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): add free-only scanners that stop at the org's free credits (#116150)

Tue Haulundbc92c3098fe6
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 090cb75f1dff..0f5a37d28d84 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -344,6 +344,9 @@ def scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:
# True when the prompt is a stock template's word for word, so a creation-flow experiment can
# tell a scanner tailored to the team from a template saved with its defaults.
"uses_template_prompt": template_question(scanner.scanner_config) is not None,
+ # Spend choices, so the goal-flow experiment can count free-only scanners and capped ones.
+ "free_only": scanner.free_only,
+ "has_credit_limit": scanner.credit_limit is not None,
"estimated_monthly_observations": estimate,
"estimated_monthly_credits": (
estimate * observation_credits_for_model(scanner.model) if estimate is not None else None
@@ -597,14 +600,23 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
"Credits counted against `credit_limit` for the current billing period: settled receipts plus "
"in-flight observations, priced from their frozen snapshot model. This "
"is what the limit gate measures, so it includes work still in progress. It is not the same as "
- "`credits_this_month`, which counts only succeeded observations."
+ "`credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the "
+ "organization's free credits, this is the organization's usage, not the scanner's own."
+ ),
+ )
+ limit_from_free_credits = serializers.SerializerMethodField(
+ help_text=(
+ "True when the organization's free credits bind this `free_only` scanner rather than its own "
+ "`credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against "
+ "its free credits."
),
)
limit_reached = serializers.SerializerMethodField(
help_text=(
- "Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is "
- "set and the budget left cannot cover one more observation, which is the same test the scanner's "
- "enforcement gates apply. Always false when no limit is set."
+ "Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, "
+ "because the organization has used its free credits. True when the budget left cannot cover one "
+ "more observation, which is the same test the scanner's enforcement gates apply. Always false when "
+ "no limit is set and `free_only` is false."
),
)
sweep_throttle_factor = serializers.SerializerMethodField(
@@ -653,6 +665,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
"sampling_rate",
"sampling_mode",
"credit_limit",
+ "free_only",
"provider",
"model",
"enabled",
@@ -666,6 +679,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
"credits_this_month",
"observations_this_month",
"credits_used_against_limit",
+ "limit_from_free_credits",
"limit_reached",
"sweep_throttle_factor",
"dashboard_id",
@@ -687,6 +701,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
"credits_this_month",
"observations_this_month",
"credits_used_against_limit",
+ "limit_from_free_credits",
"limit_reached",
"sweep_throttle_factor",
"dashboard_id",
@@ -757,6 +772,10 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
def get_credits_used_against_limit(self, scanner: ReplayScanner) -> int:
return self._scanner_budget(scanner).credits_used
+ @extend_schema_field(serializers.BooleanField())
+ def get_limit_from_free_credits(self, scanner: ReplayScanner) -> bool:
+ return self._scanner_budget(scanner).free_credits_bound
+
@extend_schema_field(serializers.IntegerField())
def get_sweep_throttle_factor(self, scanner: ReplayScanner) -> int:
return current_sweep_throttle_factor(
@@ -1097,7 +1116,10 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
# The UI PATCHes the whole form on save, so edits are detected by comparing values, not keys.
before = {field: getattr(instance, field) for field in validated_data}
was_enabled = instance.enabled
- limit_changed = "credit_limit" in validated_data and validated_data["credit_limit"] != instance.credit_limit
+ limit_changed = any(
+ field in validated_data and validated_data[field] != getattr(instance, field)
+ for field in ("credit_limit", "free_only")
+ )
# After `before`, so the question is not reported as an edit. A model call, so before the transaction.
if "scanner_config" in validated_data:
validated_data.update(
@@ -1904,6 +1926,13 @@ class EstimateResponseSerializer(serializers.Serializer):
"segment instead of adding it to a per-month total."
),
)
+ free_only_monthly_credits_left = serializers.IntegerField(
+ help_text=(
+ "The monthly credit rate the organization's free credits still cover for one more free-only scanner, "
+ "after the other free-only scanners and backfills. The forecast caps a free-only scanner at this rate, "
+ "because free-only scanners share one pool."
+ ),
+ )
sampling_rate = serializers.FloatField(
help_text="Sampling rate applied to the projection. Echoed from the request.",
)
@@ -2408,6 +2437,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
sampling_rate=source.sampling_rate,
sampling_mode=source.sampling_mode,
credit_limit=source.credit_limit,
+ free_only=source.free_only,
provider=source.provider,
model=source.model,
emits_signals=source.emits_signals,
@@ -2651,13 +2681,13 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
)
try:
- check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))
+ org_state = check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))
except QuotaLimitExceeded:
self._report_quota_exhausted(scanner, "on_demand")
raise
# Deliberately outside the analytics wrapper above: that event means "the org ran out of
# credits", and firing it for a self-imposed per-scanner cap would corrupt that metric.
- check_scanner_quota(scanner)
+ check_scanner_quota(scanner, org_state)
check_team_in_flight_capacity(self.team.id)
body = ObserveRequestSerializer(data=request.data)
@@ -3138,7 +3168,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
# One projection read, excluding the scanner being edited, so the editor adds this estimate on top of a
# consistent snapshot instead of subtracting a possibly-stale per-scanner field.
- projection = spend_projection(self.team.organization_id, exclude_scanner_id=scanner_id)
+ projection = spend_projection(
+ self.team.organization_id, exclude_scanner_id=scanner_id, include_free_headroom=True
+ )
return Response(
EstimateResponseSerializer(
@@ -3150,6 +3182,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
"estimated_credits_per_month": observations_per_month * credits_per_observation,
"other_enabled_scanners_monthly_credits": projection.scanners_monthly_credits,
"active_backfill_credits": projection.backfills_committed_credits,
+ "free_only_monthly_credits_left": projection.free_only_monthly_credits_left or 0,
"sampling_rate": sampling_rate,
}
).data
diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.py
index 6f0b1093301f..73f2d513197b 100644
--- a/products/replay_vision/backend/api/trigger.py
+++ b/products/replay_vision/backend/api/trigger.py
@@ -31,7 +31,7 @@ from products.replay_vision.backend.models.replay_observation import (
ReplayObservation,
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
-from products.replay_vision.backend.quota import compute_scanner_budget, quota_state
+from products.replay_vision.backend.quota import QuotaState, compute_scanner_budget, quota_state
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
@@ -64,8 +64,11 @@ def check_team_in_flight_capacity(team_id: int) -> None:
raise Throttled(detail=f"This team already has {count} observations running. Try again in a few minutes.")
-def check_observation_quota(organization_id: UUID, observation_credits: int) -> None:
- """Raise 402 when starting an observation of this credit cost would exceed the org's monthly limit."""
+def check_observation_quota(organization_id: UUID, observation_credits: int) -> QuotaState:
+ """Raise 402 when starting an observation of this credit cost would exceed the org's monthly limit.
+
+ Returns the org's spend, so a free-only scanner's check can reuse it instead of reading the ledger again.
+ """
snapshot = quota_state(organization_id=organization_id)
if snapshot.would_exceed(observation_credits):
# would_exceed is only ever true when a limit is set, so credit_limit is non-None here.
@@ -77,16 +80,25 @@ def check_observation_quota(organization_id: UUID, observation_credits: int) ->
f"{snapshot.period_end.day}."
)
)
+ return snapshot
-def check_scanner_quota(scanner: ReplayScanner) -> None:
- """Raise 402 when this scanner's own credit limit leaves no room for another observation."""
- if scanner.credit_limit is None:
+def check_scanner_quota(scanner: ReplayScanner, org_state: QuotaState | None = None) -> None:
+ """Raise 402 when the scanner's own limit, or a free-only scanner's free credits, leave no room for another observation."""
+ if not scanner.has_spend_ceiling:
return
- budget = compute_scanner_budget(scanner)
+ budget = compute_scanner_budget(scanner, org_state=org_state)
# blocked is only true when a limit is set; the direct check narrows without an assert.
if budget.credit_limit is not None and budget.blocked:
record_scanner_limit_reached("on_demand")
+ if budget.free_credits_bound:
+ raise QuotaLimitExceeded(
+ detail=(
+ f"This scanner only uses free credits, and your organization has used all {budget.credit_limit:,} "
+ f'for this billing period. To keep scanning now, turn off "Free credits only" in its settings.'
+ ),
+ code="scanner_free_credits_used",
+ )
raise QuotaLimitExceeded(
detail=(
f"This scanner has {budget.remaining:,} of its {budget.credit_limit:,} credit limit left "
diff --git a/products/replay_vision/backend/migrations/0124_replayscanner_free_only.py b/products/replay_vision/backend/migrations/0124_replayscanner_free_only.py
new file mode 100644
index 000000000000..2667d9211686
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0124_replayscanner_free_only.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.18 on 2026-10-13 12:42
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0123_rlou_org_created_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="free_only",
+ field=models.BooleanField(
+ db_default=False,
+ default=False,
+ help_text="Run only while the organization has free credits left this billing period, so the scanner never adds spend.",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 7618995540a1..3f448009d002 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0123_rlou_org_created_idx
+0124_replayscanner_free_only
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 45fef74dd0c9..9f2445537d35 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -334,6 +334,11 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):
validators=[MinValueValidator(1)],
help_text="Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap.",
)
+ free_only = models.BooleanField(
+ default=False,
+ db_default=False,
+ help_text="Run only while the organization has free credits left this billing period, so the scanner never adds spend.",
+ )
limit_notified_period_start = models.DateTimeField(
null=True,
blank=True,
@@ -546,5 +551,9 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):
"""
return apply_experiment_targeting(self.recordings_query(), self.experiment_scope())
+ @property
+ def has_spend_ceiling(self) -> bool:
+ return self.credit_limit is not None or self.free_only
+
def __str__(self) -> str:
return f"{self.name} ({self.scanner_type})"
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 308d3a897ef6..8b343b5ec0e8 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -1,5 +1,8 @@
import json
+import math
+import functools
from collections import Counter
+from collections.abc import Callable
from dataclasses import dataclass, replace
from datetime import UTC, date, datetime, timedelta
from uuid import UUID
@@ -139,6 +142,9 @@ class SpendProjection:
scanners_monthly_credits: int
# Committed-but-unspent credits of active backfills. A one-off charge, not a rate.
backfills_committed_credits: int
+ # The monthly rate the free credits still cover after the other free-only scanners and backfills.
+ # Only the editor's forecast asks for it, so it is None unless requested.
+ free_only_monthly_credits_left: int | None = None
@property
def total(self) -> int:
@@ -277,6 +283,10 @@ class ScannerBudget(QuotaState):
"""
credits_per_observation: int = 0
+ # True when the org's free credits bind a free-only scanner, rather than its own limit.
+ free_credits_bound: bool = False
+ # A free-only scanner's other ceiling is full of posted spend, though this one leaves less room.
+ other_ceiling_settled_blocked: bool = False
@property
def blocked(self) -> bool:
@@ -295,7 +305,15 @@ class ScannerBudget(QuotaState):
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.credits_settled).blocked
+ return self.other_ceiling_settled_blocked or replace(self, credits_used=self.credits_settled).blocked
+
+ @property
+ def settled_block_from_free_credits(self) -> bool:
+ """Whether the org's free credits, rather than the scanner's own limit, are the ceiling posted spend fills."""
+ if replace(self, credits_used=self.credits_settled).blocked:
+ return self.free_credits_bound
+ # The other ceiling of a free-only scanner is the own limit when this one is the free credits, and back.
+ return self.other_ceiling_settled_blocked and not self.free_credits_bound
def _scanner_in_flight_credits(
@@ -318,7 +336,12 @@ def _scanner_in_flight_credits(
def compute_scanner_budgets(
- organization_id: UUID, scanner_ids: list[UUID], period: BillingPeriod | None = None
+ organization_id: UUID,
+ scanner_ids: list[UUID],
+ period: BillingPeriod | None = None,
+ *,
+ include_free_credits: bool = True,
+ org_state: QuotaState | None = None,
) -> dict[UUID, ScannerBudget]:
"""Per-scanner budgets for the org's current billing period, with an entry for every requested scanner.
@@ -344,8 +367,13 @@ def compute_scanner_budgets(
# 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.all_origins.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}
+ ).values_list("id", "credit_limit", "model", "free_only")
+ configs: dict[UUID, tuple[int | None, str]] = {}
+ free_only_ids: set[UUID] = set()
+ for scanner_id, limit, model, free_only in scanner_rows:
+ configs[scanner_id] = (limit, model)
+ if free_only:
+ free_only_ids.add(scanner_id)
# 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]
@@ -381,44 +409,111 @@ def compute_scanner_budgets(
credits_settled=settled_credits,
credits_reserved=reserved,
)
+ if free_only_ids and include_free_credits:
+ # A caller that already read the org's spend passes it, so the ledger is not read twice.
+ free_budget = (
+ _free_credits_budget_from_state(org_state)
+ if org_state is not None
+ else _free_credits_budget(organization_id, period)
+ )
+ for scanner_id in free_only_ids:
+ own = result[scanner_id]
+ free = replace(free_budget, credits_per_observation=own.credits_per_observation)
+ # A free-only scanner can carry its own cap too; whichever leaves less room binds.
+ tighter, other = sorted((own, free), key=lambda b: b.remaining if b.remaining is not None else math.inf)
+ # The sweep's settled-only check still has to see a ceiling that posted spend already fills.
+ result[scanner_id] = replace(tighter, other_ceiling_settled_blocked=other.blocked_by_settled_spend)
return result
-def compute_scanner_budget(scanner: ReplayScanner, period: BillingPeriod | None = None) -> ScannerBudget:
+def compute_scanner_budget(
+ scanner: ReplayScanner,
+ period: BillingPeriod | None = None,
+ *,
+ include_free_credits: bool = True,
+ org_state: QuotaState | 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)
+ budgets = compute_scanner_budgets(
+ scanner.team.organization_id,
+ [scanner.id],
+ period,
+ include_free_credits=include_free_credits,
+ org_state=org_state,
+ )
return budgets[scanner.id]
-def _sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:
+def _remaining_as_monthly_rate(budget: ScannerBudget | None, now: datetime) -> float:
+ """The 30-day rate whose share of the days left lands exactly on what the budget has left."""
+ if budget is None or budget.remaining is None:
+ return math.inf
+ days_left = max((budget.period_end - now).total_seconds() / 86400, 0)
+ return budget.remaining * ESTIMATE_MONTH_DAYS / days_left if days_left > 0 else math.inf
+
+
+@frozen
+class ScannerRates:
+ total: int
+ # The share of `total` that free-only scanners draw from the org's free credits.
+ free_only: int
+
+
+def _sum_enabled_scanner_estimated_credits(
+ organization_id: UUID,
+ free_budget: Callable[[], ScannerBudget],
+ exclude_scanner_id: UUID | None = None,
+ free_credits_claimed: int = 0,
+) -> ScannerRates:
"""Projected monthly credit spend of the org's enabled scanners' cached estimates.
A capped scanner can only spend what its limit has left this period. Surfaces pro-rate this
30-day rate over the days left, so that headroom is folded back into a rate: the pro-rated
- share then lands on exactly the remaining cap, never past it.
+ share then lands on exactly the remaining cap, never past it. Free-only scanners share one
+ pool, the org's free credits left, so their rates are capped together rather than each in full.
"""
scanners = ReplayScanner.objects.filter(team__organization_id=organization_id, enabled=True)
if exclude_scanner_id is not None:
scanners = scanners.exclude(pk=exclude_scanner_id)
# Credit weighting happens in Python: the per-model price table lives in code, and orgs have few scanners.
- rows = list(scanners.values_list("id", "model", "estimated_monthly_observations", "credit_limit"))
- capped_ids = [scanner_id for scanner_id, _, _, credit_limit in rows if credit_limit is not None]
- budgets = compute_scanner_budgets(organization_id, capped_ids) if capped_ids else {}
+ rows = list(scanners.values_list("id", "model", "estimated_monthly_observations", "credit_limit", "free_only"))
+ capped_ids = [scanner_id for scanner_id, _, _, credit_limit, _ in rows if credit_limit is not None]
+ has_free_only = any(free_only for *_, free_only in rows)
+ period = current_period_bounds(organization_id) if capped_ids or has_free_only else None
+ budgets = (
+ compute_scanner_budgets(organization_id, capped_ids, period, include_free_credits=False) if capped_ids else {}
+ )
now = datetime.now(UTC)
+
+ def capped_rate(rate: float, budget: ScannerBudget | None) -> float:
+ return min(rate, _remaining_as_monthly_rate(budget, now))
+
total = 0.0
- for scanner_id, model, estimate, _credit_limit in rows:
- rate = observation_credits_for_model(model) * (estimate or 0)
- budget = budgets.get(scanner_id)
- if budget is None or budget.remaining is None:
+ free_only_total = 0.0
+ for scanner_id, model, estimate, _credit_limit, free_only in rows:
+ rate = capped_rate(observation_credits_for_model(model) * (estimate or 0), budgets.get(scanner_id))
+ if free_only:
+ free_only_total += rate
+ else:
total += rate
- continue
- days_left = max((budget.period_end - now).total_seconds() / 86400, 0)
- headroom_rate = budget.remaining * ESTIMATE_MONTH_DAYS / days_left if days_left > 0 else rate
- total += min(rate, headroom_rate)
- return round(total)
+ free_only_rate = 0.0
+ if has_free_only and period is not None:
+ # Free-only backfills already claim part of the pool, so the sweep rate gets only the rest.
+ free = free_budget()
+ free_only_rate = capped_rate(
+ free_only_total, replace(free, credits_used=free.credits_used + free_credits_claimed)
+ )
+ return ScannerRates(total=round(total + free_only_rate), free_only=round(free_only_rate))
-def _sum_active_backfill_remaining_credits(organization_id: UUID) -> int:
+@frozen
+class BackfillCommitments:
+ paid: int
+ # Committed by free-only scanners, which pause when the org's free credits run out.
+ free_only: int
+
+
+def _sum_active_backfill_remaining_credits(organization_id: UUID) -> BackfillCommitments:
"""Committed-but-unspent credits of the org's active backfills, priced at each backfill's frozen rate.
Projection only: enforcement stays the per-observation creation check, identical for live and
@@ -428,11 +523,20 @@ def _sum_active_backfill_remaining_credits(organization_id: UUID) -> int:
rows = (
ReplayScannerBackfill.objects.unscoped()
.filter(team__organization_id=organization_id, status__in=ACTIVE_BACKFILL_STATUSES)
- .values_list("total_count", "dispatched_count", "skipped_count", "credits_per_observation")
+ .values_list(
+ "total_count", "dispatched_count", "skipped_count", "credits_per_observation", "scanner__free_only"
+ )
)
# Skipped candidates were quoted and then scanned by the live sweep first, so the backfill no longer
# owes their credits. Leaving them in strands phantom commitment for the rest of the run.
- return sum(max(0, total - dispatched - skipped) * price for total, dispatched, skipped, price in rows)
+ committed = [
+ (max(0, total - dispatched - skipped) * price, free_only)
+ for total, dispatched, skipped, price, free_only in rows
+ ]
+ return BackfillCommitments(
+ paid=sum(c for c, free_only in committed if not free_only),
+ free_only=sum(c for c, free_only in committed if free_only),
+ )
def _billing_synced_limit(organization: Organization | None) -> tuple[bool, int | None]:
@@ -459,15 +563,48 @@ def _billing_synced_limit(organization: Organization | None) -> tuple[bool, int
return False, None
-def spend_projection(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> SpendProjection:
+def spend_projection(
+ organization_id: UUID,
+ exclude_scanner_id: UUID | None = None,
+ *,
+ org_state: QuotaState | None = None,
+ include_free_headroom: bool = False,
+) -> SpendProjection:
"""The org's rest-of-period commitments, priced.
- `exclude_scanner_id` drops one scanner's stored estimate, for the editor's "others plus this
- proposal" forecast. Callers never touch the underlying scanner or backfill rows.
+ `exclude_scanner_id` drops one scanner's stored estimate, for the editor's "others plus
+ proposal" forecast. `org_state` is the org's spend when the caller already read it.
+ `include_free_headroom` adds the free-credit rate left for one more free-only scanner. Callers
+ never touch the underlying scanner or backfill rows.
"""
+
+ @functools.cache
+ def free_budget() -> ScannerBudget:
+ state = org_state or quota_state(organization_id)
+ return _free_credits_budget_from_state(state)
+
+ backfills = _sum_active_backfill_remaining_credits(organization_id)
+ free_only_backfills = backfills.free_only
+ if free_only_backfills:
+ # A free-only backfill pauses when the free credits run out, so it commits only what is left of them.
+ credits_left = free_budget().remaining
+ free_only_backfills = min(
+ free_only_backfills, credits_left if credits_left is not None else free_only_backfills
+ )
+ rates = _sum_enabled_scanner_estimated_credits(
+ organization_id, free_budget, exclude_scanner_id, free_credits_claimed=free_only_backfills
+ )
+ free_left: int | None = None
+ if include_free_headroom:
+ free = free_budget()
+ pool = replace(free, credits_used=free.credits_used + free_only_backfills)
+ pool_rate = _remaining_as_monthly_rate(pool, datetime.now(UTC))
+ # Past the period end there is no rate to share, and an unbounded rate leaves nothing to cap.
+ free_left = max(0, round(pool_rate - rates.free_only)) if math.isfinite(pool_rate) else 0
return SpendProjection(
- scanners_monthly_credits=_sum_enabled_scanner_estimated_credits(organization_id, exclude_scanner_id),
- backfills_committed_credits=_sum_active_backfill_remaining_credits(organization_id),
+ scanners_monthly_credits=rates.total,
+ backfills_committed_credits=backfills.paid + free_only_backfills,
+ free_only_monthly_credits_left=free_left,
)
@@ -541,13 +678,39 @@ def quota_state_for_cap(organization_id: UUID, cap: OrgCreditCap) -> QuotaState:
)
+def free_credits_ceiling(cap: OrgCreditCap) -> int:
+ """The most a free-only scanner lets the org spend this period: the free credits, or less if billing caps lower."""
+ if cap.credit_limit is None:
+ return FREE_TIER_MONTHLY_CREDITS
+ return min(cap.credit_limit, FREE_TIER_MONTHLY_CREDITS)
+
+
+def _free_credits_budget(organization_id: UUID, period: BillingPeriod) -> ScannerBudget:
+ cap = replace(org_credit_cap(organization_id), period=period)
+ return _free_credits_budget_from_state(quota_state_for_cap(organization_id, cap))
+
+
+def _free_credits_budget_from_state(state: QuotaState) -> ScannerBudget:
+ return ScannerBudget(
+ credit_limit=FREE_TIER_MONTHLY_CREDITS
+ if state.credit_limit is None
+ else min(state.credit_limit, FREE_TIER_MONTHLY_CREDITS),
+ credits_used=state.credits_used,
+ period_start=state.period_start,
+ period_end=state.period_end,
+ credits_settled=state.credits_settled,
+ credits_reserved=state.credits_reserved,
+ free_credits_bound=True,
+ )
+
+
def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
"""Enforcement state plus the projection.
Prefer `quota_state` wherever only the caps matter: this pays for two aggregates no gate reads.
"""
state = quota_state(organization_id)
- projection = spend_projection(organization_id)
+ projection = spend_projection(organization_id, org_state=state)
return QuotaSnapshot(
credit_limit=state.credit_limit,
credits_used=state.credits_used,
diff --git a/products/replay_vision/backend/scanning.py b/products/replay_vision/backend/scanning.py
index f7e7d811c304..48de0ac1f497 100644
--- a/products/replay_vision/backend/scanning.py
+++ b/products/replay_vision/backend/scanning.py
@@ -117,7 +117,9 @@ def scan_headroom(*, team: Team, model: str, scanner: ReplayScanner | None) -> S
# None means nothing binds: an uncapped org (or scanner), or a free model that spends nothing.
affordable = snapshot.affordable_count(cost)
quota_limit = in_flight_limit if affordable is None else affordable
- scanner_affordable = compute_scanner_budget(scanner).affordable_count(cost) if scanner is not None else None
+ scanner_affordable = (
+ compute_scanner_budget(scanner, org_state=snapshot).affordable_count(cost) if scanner is not None else None
+ )
scanner_limit = in_flight_limit if scanner_affordable is None else scanner_affordable
# Report whichever limit is strictly tighter, so the user knows which one to raise.
if scanner_limit < in_flight_limit and scanner_limit <= quota_limit:
@@ -331,8 +333,8 @@ def retry_observation(*, observation: ReplayObservation, user: User) -> tuple[Re
# these two read enough to be worth keeping off a held row lock.
# Raises QuotaLimitExceeded / Throttled, which callers already know how to render. Kept as
# exceptions rather than outcomes so the API's existing 402 and 429 messages are unchanged.
- check_observation_quota(scanner.team.organization_id, observation_credits_for_model(scanner.model))
- check_scanner_quota(scanner)
+ org_state = check_observation_quota(scanner.team.organization_id, observation_credits_for_model(scanner.model))
+ check_scanner_quota(scanner, org_state)
check_team_in_flight_capacity(scanner.team_id)
# Locked so two concurrent retries can't both pass the status check and both delete the row.
diff --git a/products/replay_vision/backend/scout_writes.py b/products/replay_vision/backend/scout_writes.py
index 2dcbbcdff0ac..8bcf3a0ef28c 100644
--- a/products/replay_vision/backend/scout_writes.py
+++ b/products/replay_vision/backend/scout_writes.py
@@ -24,6 +24,10 @@ CREDIT_LIMIT_REQUIRED = (
"`vision-scanners-estimate` projects what a scanner will spend per month."
)
+FREE_ONLY_NOT_CLEARABLE = (
+ "Scouts cannot turn off free credits only on a scanner without its own credit limit. Set a credit limit "
+ "first, or set `enabled: false` to stop the scanner."
+)
CREDIT_LIMIT_NOT_CLEARABLE = (
"Scouts cannot remove a scanner's credit limit. Raise the limit instead, or set "
"`enabled: false` to stop the scanner."
@@ -93,6 +97,13 @@ def check_scout_scanner_credit_limit(
return
if "credit_limit" in attrs and attrs["credit_limit"] is None:
raise ValidationError({"credit_limit": CREDIT_LIMIT_NOT_CLEARABLE})
+ # Free-only is a spend ceiling too, so a scout cannot drop it unless the scanner keeps its own limit.
+ if (
+ instance.free_only
+ and attrs.get("free_only") is False
+ and attrs.get("credit_limit", instance.credit_limit) is None
+ ):
+ raise ValidationError({"free_only": FREE_ONLY_NOT_CLEARABLE})
# Arming a disabled experiment scanner to start on launch is a deferred enable.
arms_start_on_launch = (
instance.scanner_type == ScannerType.EXPERIMENT
@@ -119,5 +130,14 @@ def check_scout_scanner_credit_limit(
)
return
raises_limit = "credit_limit" in attrs and (instance.credit_limit is None or credit_limit > instance.credit_limit)
- if turning_on or changes_enabled_cost or raises_limit:
+ # Without free-only, a running scanner bills up to its own limit, so that limit has to fit the org quota.
+ # One armed to start on launch is about to run, so it counts as running here.
+ config = attrs.get("scanner_config", instance.scanner_config) or {}
+ armed_for_launch = instance.scanner_type == ScannerType.EXPERIMENT and config.get("start_on_launch") is True
+ starts_billing = (
+ instance.free_only
+ and attrs.get("free_only") is False
+ and (attrs.get("enabled", instance.enabled) or armed_for_launch)
+ )
+ if turning_on or changes_enabled_cost or raises_limit or starts_billing:
_check_credit_ceiling(credit_limit, max_credit_limit)
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index 99a49d1e6002..6448ccaf6fc2 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -114,7 +114,9 @@ def prepare_backfill_tick_activity(inputs: BackfillTickInputs) -> PrepareBackfil
record_backfill_tick_outcome("paused_quota")
return PrepareBackfillTickOutput(action=BackfillTickAction.PAUSE)
- scanner_budget = compute_scanner_budget(backfill.scanner) if backfill.scanner.credit_limit is not None else None
+ scanner_budget = (
+ compute_scanner_budget(backfill.scanner, org_state=quota) if backfill.scanner.has_spend_ceiling else None
+ )
if scanner_budget is not None and scanner_budget.would_exceed(backfill.credits_per_observation):
# Children would decline at create while the cursor walks past their sessions; the hold lets
# the backfill resume when the period resets or the limit rises.
diff --git a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
index 596bb8487114..008d1086415e 100644
--- a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
+++ b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
@@ -10,7 +10,7 @@ from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.sweep_types import CheckScannerBudgetInputs, CheckScannerBudgetOutput
-def _notify_limit_reached(scanner: ReplayScanner) -> bool:
+def _notify_limit_reached(scanner: ReplayScanner, free_credits_bound: bool = False) -> bool:
"""Best-effort notification; False only when the send raised. A deliberate skip inside the
pipeline (flag off, nobody to notify) counts as sent so it is not retried every tick."""
try:
@@ -55,8 +55,10 @@ def _notify_limit_reached(scanner: ReplayScanner) -> bool:
]
body = (
- "It stopped scanning until its billing period resets. Sessions skipped while capped are not scanned later."
- )
+ "It only uses free credits, and your organization has used them for this billing period. "
+ if free_credits_bound
+ else ""
+ ) + "It stopped scanning until its billing period resets. Sessions skipped while capped are not scanned later."
# The cap also holds a running backfill without changing its status; without this line the
# notification leaves that backfill looking stalled for no reason.
if (
@@ -72,7 +74,9 @@ def _notify_limit_reached(scanner: ReplayScanner) -> bool:
# A cap is a usage event, not breakage; it must not surface as a pipeline failure.
notification_type=NotificationType.USAGE_SPIKE,
priority=Priority.NORMAL,
- title=f'"{scanner.name}" reached its credit limit',
+ title=f'"{scanner.name}" used its free credits'
+ if free_credits_bound
+ else f'"{scanner.name}" reached its credit limit',
body=body,
target_type=TargetType.TEAM,
target_id=str(scanner.team_id),
@@ -107,7 +111,7 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
if scanner is None:
# The reconciler removes schedules for deleted scanners. A racing tick just stops here.
return CheckScannerBudgetOutput(capped=False)
- if scanner.credit_limit is None:
+ if not scanner.has_spend_ceiling:
return CheckScannerBudgetOutput(capped=False)
# Resolve the period once so the cap decision and the notification stamp cannot straddle a rollover.
period = current_period_bounds(scanner.team.organization_id)
@@ -159,7 +163,7 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
},
)
# Sent only after the stamp commits: a push can't be un-sent, so it must never precede its record.
- if stamped and not _notify_limit_reached(scanner):
+ if stamped and not _notify_limit_reached(scanner, budget.settled_block_from_free_credits):
# Hand the claim back so a transient outage delays the notification instead of consuming it.
ReplayScanner.objects.filter(pk=scanner.pk, limit_notified_period_start=period.start).update(
limit_notified_period_start=None
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 653e531b1e9e..d707db294bab 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -1,8 +1,10 @@
+from dataclasses import replace
from typing import Any, Literal
from uuid import UUID
from django.db import IntegrityError, OperationalError, connection, transaction
from django.db.models import F
+from django.db.models.lookups import LessThanOrEqual
from django.utils import timezone
import psycopg.errors
@@ -32,6 +34,7 @@ from products.replay_vision.backend.quota import (
QuotaState,
ScannerBudget,
compute_scanner_budget,
+ free_credits_ceiling,
org_credit_cap_for,
quota_state_for_cap,
)
@@ -65,7 +68,7 @@ def _build_scanner_snapshot(
def _capture_scan_blocked(
*,
scanner: ReplayScanner,
- reason: Literal["quota", "consent"],
+ reason: Literal["quota", "free_credits", "consent"],
triggered_by: ObservationTrigger,
quota: QuotaState | None = None,
) -> None:
@@ -171,7 +174,8 @@ def _admit_within_cap(scanner: ReplayScanner, cost: int, period: BillingPeriod)
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)
+ # The org admission enforces a free-only ceiling, so this cache holds the scanner's own spend only.
+ budget = compute_scanner_budget(scanner, period, include_free_credits=False)
admitted = not budget.would_exceed(cost)
ReplayScanner.all_origins.filter(pk=scanner.pk).update(
admission_budget_used=budget.credits_used,
@@ -192,11 +196,15 @@ class _OrgLimitRefused(Exception):
def _skip_for_quota(
- scanner: ReplayScanner, inputs: CreateObservationInputs, quota: QuotaState
+ scanner: ReplayScanner, inputs: CreateObservationInputs, quota: QuotaState, *, free_credits: bool = False
) -> CreateObservationOutput:
- record_quota_exhausted_skip(scanner.scanner_type)
+ # Free credits running out pauses one free-only scanner, so it counts as a scanner limit, not an org block.
+ if free_credits:
+ record_scanner_limit_reached("admission")
+ else:
+ record_quota_exhausted_skip(scanner.scanner_type)
activity.logger.info(
- "Skipping observation: monthly quota exhausted",
+ "Skipping observation: free credits used" if free_credits else "Skipping observation: monthly quota exhausted",
extra={
"scanner_id": str(inputs.scanner_id),
"team_id": inputs.team_id,
@@ -205,37 +213,43 @@ def _skip_for_quota(
"credits_used": quota.credits_used,
},
)
- _capture_scan_blocked(scanner=scanner, reason="quota", triggered_by=inputs.triggered_by, quota=quota)
+ _capture_scan_blocked(
+ scanner=scanner,
+ reason="free_credits" if free_credits else "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:
+def _try_cached_org_admission(organization_id: UUID, cost: int, cap: OrgCreditCap, ceiling: int | None) -> 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)
+ budget = ReplayVisionOrgAdmissionBudget.objects.filter(
+ organization_id=organization_id,
+ period_start=cap.period.start,
+ credit_limit=cap.credit_limit,
+ refreshed_at__gte=fresh_after,
)
+ if ceiling is not None:
+ budget = budget.filter(LessThanOrEqual(F("credits_used") + F("credits_since_refresh") + cost, ceiling))
+ return bool(budget.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.
+def _admit_within_org_limit(
+ organization_id: UUID, cost: int, cap: OrgCreditCap, ceiling: int | None
+) -> QuotaState | None:
+ """Admit `cost` against `ceiling`, the org limit or a free-only scanner's free credits; None on admission, else the refusing state.
One conditional UPDATE on the org's row, so concurrent applies across its scanners cannot overshoot.
+ With no ceiling the admission still records its spend here, so a free-only scanner's check sees it.
"""
- if cap.credit_limit is None:
- return None
- if _try_cached_org_admission(organization_id, cost, cap):
+ if _try_cached_org_admission(organization_id, cost, cap, ceiling):
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):
+ if _try_cached_org_admission(organization_id, cost, cap, ceiling):
return None
else:
# A racing creator waits on the unique key and then takes the row lock below.
@@ -252,7 +266,7 @@ def _admit_within_org_limit(organization_id: UUID, cost: int, cap: OrgCreditCap)
ignore_conflicts=True,
)
locked.first()
- quota = quota_state_for_cap(organization_id, cap)
+ quota = replace(quota_state_for_cap(organization_id, cap), credit_limit=ceiling)
admitted = not quota.would_exceed(cost)
ReplayVisionOrgAdmissionBudget.objects.filter(organization_id=organization_id).update(
period_start=cap.period.start,
@@ -365,13 +379,23 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
organization_id = scanner.team.organization_id
cap = org_credit_cap_for(scanner.team.organization, organization_id)
+ # A free-only scanner stops at the org's free credits, below any billing limit.
+ ceiling = free_credits_ceiling(cap) if scanner.free_only else cap.credit_limit
+ # The free credits, not the org's own limit, are what stops the scanner when they sit below that limit.
+ free_credits_bound = scanner.free_only and (
+ cap.credit_limit is None or free_credits_ceiling(cap) < cap.credit_limit
+ )
# Unlocked pre-check, so an exhausted org skips the snapshot and admission work.
- if cap.credit_limit is not None:
+ if ceiling is not None:
with bounded_queries(CREATE_OBSERVATION_TIMEOUT):
quota = quota_state_for_cap(organization_id, cap)
+ if scanner.free_only:
+ quota = replace(quota, credit_limit=ceiling)
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)
+ return _reclaim_own_pending_insert(inputs) or _skip_for_quota(
+ scanner, inputs, quota, free_credits=free_credits_bound
+ )
# 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)
@@ -431,7 +455,7 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
was_created=False,
scanner_type=scanner.scanner_type,
)
- refused_quota = _admit_within_org_limit(organization_id, cost, cap)
+ refused_quota = _admit_within_org_limit(organization_id, cost, cap, ceiling)
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:
@@ -468,7 +492,7 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
reclaimed_output = _reclaim_own_pending_insert(inputs)
if reclaimed_output is not None:
return reclaimed_output
- return _skip_for_quota(scanner, inputs, refused.quota)
+ return _skip_for_quota(scanner, inputs, refused.quota, free_credits=free_credits_bound)
except IntegrityError as e:
# Only swallow the dedup case; FK / CHECK violations should fail the activity.
if not isinstance(e.__cause__, psycopg.errors.UniqueViolation):
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 8a720f4acc52..83b2b4190038 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -1087,15 +1087,54 @@ class TestScannerScoutCallerRules(_VisionAPITestCase):
self.assertEqual(resp.status_code, expected_status, resp.json())
self.assertEqual(ReplayScanner.objects.filter(team=self.team, name="capped").exists(), expected_status == 201)
- def test_scout_cannot_clear_a_credit_limit(self) -> None:
- scanner = self._create_scanner(name="capped", credit_limit=500)
+ @parameterized.expand(
+ [
+ ("credit_limit", {"credit_limit": 500}, {"credit_limit": None}, 1000, 400),
+ ("free_only_without_own_limit", {"free_only": True}, {"free_only": False}, 1000, 400),
+ ("free_only_with_own_limit", {"free_only": True, "credit_limit": 500}, {"free_only": False}, 1000, 200),
+ (
+ "free_only_with_own_limit_in_an_uncapped_org",
+ {"free_only": True, "credit_limit": 500},
+ {"free_only": False},
+ None,
+ 400,
+ ),
+ # Disabled, but armed to start when its experiment launches, so it is about to bill.
+ (
+ "armed_for_launch_in_an_uncapped_org",
+ {"free_only": True, "credit_limit": 500, "enabled": False, "armed_for_launch": True},
+ {"free_only": False},
+ None,
+ 400,
+ ),
+ ]
+ )
+ def test_scout_cannot_remove_a_spend_ceiling(
+ self,
+ _name: str,
+ ceiling: dict[str, Any],
+ patch_body: dict[str, Any],
+ organization_limit: int | None,
+ expected_status: int,
+ ) -> None:
+ self.organization.usage = {"replay_vision_credits": {"limit": organization_limit}}
+ self.organization.save(update_fields=["usage"])
+ ceiling = dict(ceiling)
+ if ceiling.pop("armed_for_launch", False):
+ experiment = create_experiment(self.team, "armed-launch", variants=["control", "test"])
+ ceiling = {
+ **ceiling,
+ "scanner_type": ScannerType.EXPERIMENT,
+ "scanner_config": {"prompt": "p", "experiment_id": experiment.id, "start_on_launch": True},
+ }
+ scanner = self._create_scanner(name="capped", **ceiling)
self._authenticate_as_scout()
- resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"credit_limit": None}, format="json")
+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data=patch_body, format="json")
- self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertEqual(resp.status_code, expected_status, resp.json())
scanner.refresh_from_db()
- self.assertEqual(scanner.credit_limit, 500)
+ self.assertEqual(scanner.has_spend_ceiling, True)
def test_scout_delete_is_refused_and_the_scanner_survives(self) -> None:
scanner = self._create_scanner(name="keep-me")
@@ -1463,6 +1502,7 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):
"model": ScannerModel.GEMINI_3_8_FLASH,
"sampling_rate": 0.25,
"query": {"kind": "RecordingsQuery", "events": [{"id": "$pageview"}]},
+ "free_only": True,
},
format="json",
)
@@ -1480,6 +1520,8 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):
self.assertTrue(properties["has_filters"])
self.assertFalse(properties["has_experiment_targeting"])
self.assertFalse(properties["uses_template_prompt"])
+ self.assertTrue(properties["free_only"])
+ self.assertFalse(properties["has_credit_limit"])
self.assertTrue(properties["enabled"])
self.assertEqual(properties["organization_id"], str(self.team.organization_id))
# Session auth resolves to "web" (the app UI), MCP callers to "mcp".
@@ -4271,8 +4313,10 @@ class TestScannerSpend(_VisionAPITestCase):
# keyed on the wrong scanner would give every row the first row's answer.
capped = self._create_scanner(name="capped")
self._create_scanner(name="uncapped")
+ free = self._create_scanner(name="free")
cost = observation_credits_for_model(capped.model)
ReplayScanner.objects.filter(pk=capped.pk).update(credit_limit=cost)
+ ReplayScanner.objects.filter(pk=free.pk).update(free_only=True)
self._spend_against_limit(capped, "capped-spend")
resp = self.client.get(self.scanners_url)
@@ -4282,6 +4326,10 @@ class TestScannerSpend(_VisionAPITestCase):
self.assertIs(by_name["uncapped"]["limit_reached"], False)
self.assertEqual(by_name["capped"]["credits_used_against_limit"], cost)
self.assertEqual(by_name["uncapped"]["credits_used_against_limit"], 0)
+ self.assertEqual(
+ {name: row["limit_from_free_credits"] for name, row in by_name.items()},
+ {"capped": False, "uncapped": False, "free": True},
+ )
def test_limit_below_one_observation_reports_reached_before_any_spend(self) -> None:
# `limit_reached` answers "can this scanner run again", not "has it spent its limit". A cap
diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.py
index b200a3e0bf1c..670f2cc95456 100644
--- a/products/replay_vision/backend/tests/test_backfills.py
+++ b/products/replay_vision/backend/tests/test_backfills.py
@@ -18,12 +18,13 @@ from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counte
_stuck_key,
)
+from products.replay_vision.backend import quota
from products.replay_vision.backend.api.backfills import (
MAX_BACKFILL_WINDOW_DAYS,
BackfillEnumerationThrottle,
ReplayScannerBackfillViewSet,
)
-from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.billing import FREE_TIER_MONTHLY_CREDITS, observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -144,6 +145,15 @@ class TestBackfillQuotaCommitment:
assert spend_projection(org_id).backfills_committed_credits == 60 * 5
assert compute_quota_snapshot(org_id).projected_monthly_credits == 60 * 5
+ def test_free_only_backfill_commits_only_the_free_credits_left(self) -> None:
+ scanner = _make_scanner()
+ ReplayScanner.objects.filter(pk=scanner.pk).update(free_only=True)
+ org_id = scanner.team.organization_id
+ seed_scanner_spend(scanner, FREE_TIER_MONTHLY_CREDITS - 100)
+ _make_backfill(scanner, total_count=100, credits_per_observation=5)
+ with patch.object(quota, "MONTHLY_CREDIT_QUOTA", 1_000_000):
+ assert spend_projection(org_id).backfills_committed_credits == 100
+
def test_paused_backfill_still_counts_as_committed(self) -> None:
scanner = _make_scanner()
_make_backfill(
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index a1e1d23d62ee..149c3386be87 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -14,7 +14,7 @@ from posthog.date_util import start_of_month
from posthog.models import Organization, Team
from products.replay_vision.backend import quota
-from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.billing import FREE_TIER_MONTHLY_CREDITS, observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -31,8 +31,12 @@ from products.replay_vision.backend.quota import (
compute_quota_snapshot,
compute_scanner_budget,
compute_scanner_budgets,
+ spend_projection,
+)
+from products.replay_vision.backend.tests.helpers import (
+ seed_scanner_spend,
+ snapshot_for as _snapshot_for,
)
-from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for
_ORG_ID = "01234567-89ab-cdef-0123-456789abcdef"
@@ -499,6 +503,100 @@ class TestComputeScannerBudgets(_VisionQuotaTestCase):
assert result[other_scanner.id].credits_used == 0
assert result[other_scanner.id].credit_limit is None
+ @parameterized.expand(
+ [
+ ("no_own_cap_free_credits_bind", None, 1_000_000, FREE_TIER_MONTHLY_CREDITS, True, False, True),
+ ("larger_own_cap_free_credits_bind", 100_000, 1_000_000, FREE_TIER_MONTHLY_CREDITS, True, False, True),
+ ("tighter_own_cap_binds", 5, 1_000_000, 5, True, False, False),
+ ("no_org_limit_free_credits_still_bind", None, None, FREE_TIER_MONTHLY_CREDITS, True, False, True),
+ ("org_limit_below_free_credits_binds", None, 1_000, 1_000, True, False, True),
+ # In-flight work fills the own cap, but only the free credits are full of posted spend.
+ (
+ "settled_free_credits_still_block_under_in_flight_own_cap",
+ "one_observation",
+ 1_000_000,
+ "one_observation",
+ True,
+ True,
+ True,
+ ),
+ ]
+ )
+ def test_free_only_scanner_draws_on_the_orgs_free_credits(
+ self,
+ _name: str,
+ own_cap: int | str | None,
+ org_limit: int | None,
+ expected_limit: int | str,
+ expected_blocked: bool,
+ in_flight: bool,
+ expected_free_credits_copy: bool,
+ ) -> None:
+ cost = observation_credits_for_model(ScannerModel.GEMINI_3_8_FLASH)
+ own_cap = cost if own_cap == "one_observation" else own_cap
+ expected_limit = cost if expected_limit == "one_observation" else expected_limit
+ # Another scanner's spend leaves less than one observation of free credits.
+ seed_scanner_spend(self.scanner, FREE_TIER_MONTHLY_CREDITS - 10)
+ free = ReplayScanner.objects.create(
+ team=self.team,
+ name="free-scanner",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ credit_limit=own_cap,
+ free_only=True,
+ )
+ if in_flight:
+ ReplayObservation.objects.create(
+ scanner=free,
+ team=self.team,
+ session_id="free-in-flight",
+ status=ObservationStatus.RUNNING,
+ scanner_snapshot=_snapshot_for(free),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ )
+ with patch.object(quota, "MONTHLY_CREDIT_QUOTA", org_limit):
+ budget = compute_scanner_budgets(self.organization.id, [free.id])[free.id]
+ assert (
+ budget.credit_limit,
+ budget.blocked,
+ budget.blocked_by_settled_spend,
+ budget.settled_block_from_free_credits,
+ ) == (expected_limit, expected_blocked, True, expected_free_credits_copy)
+
+ def test_free_only_scanner_keeps_the_tighter_headroom_when_its_own_cap_is_settled_full(self) -> None:
+ cost = observation_credits_for_model(ScannerModel.GEMINI_3_8_FLASH)
+ free = ReplayScanner.objects.create(
+ team=self.team,
+ name="free-scanner",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ credit_limit=2 * cost - 1,
+ free_only=True,
+ )
+ # The own cap has posted spend that leaves less than one observation, but some room.
+ seed_scanner_spend(free, cost)
+ # The free credits have room for one more posted observation, but in-flight work takes it.
+ seed_scanner_spend(self.scanner, FREE_TIER_MONTHLY_CREDITS - 2 * cost)
+ ReplayObservation.objects.create(
+ scanner=self.scanner,
+ team=self.team,
+ session_id="other-in-flight",
+ status=ObservationStatus.RUNNING,
+ scanner_snapshot=_snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ )
+ reserved = observation_credits_for_model(self.scanner.model)
+ with patch.object(quota, "MONTHLY_CREDIT_QUOTA", 1_000_000):
+ budget = compute_scanner_budgets(self.organization.id, [free.id])[free.id]
+ # The own cap is what posted spend fills, so the notification must not blame the free credits.
+ assert (budget.remaining, budget.blocked_by_settled_spend, budget.settled_block_from_free_credits) == (
+ max(0, cost - reserved),
+ True,
+ False,
+ )
+
class TestBillingSyncedQuota(_VisionQuotaTestCase):
@parameterized.expand(
@@ -671,6 +769,7 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
estimate: int | None = None,
model: ScannerModel = ScannerModel.GEMINI_3_8_FLASH,
credit_limit: int | None = None,
+ free_only: bool = False,
) -> None:
scanner = ReplayScanner.objects.create(
team=team,
@@ -680,6 +779,7 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
model=model,
enabled=enabled,
credit_limit=credit_limit,
+ free_only=free_only,
)
if estimate is not None:
ReplayScanner.objects.filter(pk=scanner.pk).update(
@@ -707,6 +807,33 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
# 15 of 30 days left: the 200 headroom pro-rated back to a 30-day rate is 400.
assert snapshot.projected_monthly_credits == 400 + 150
+ @time_machine.travel("2026-09-16T00:00:00Z", tick=False)
+ def test_free_only_scanners_share_the_orgs_free_credits_left(self) -> None:
+ seed_scanner_spend(self.scanner, FREE_TIER_MONTHLY_CREDITS - 500)
+ self._make_scanner(team=self.team, name="free-a", estimate=100, free_only=True) # 1500 uncapped
+ self._make_scanner(team=self.team, name="free-b", estimate=100, free_only=True) # 1500 uncapped
+ with patch.object(quota, "MONTHLY_CREDIT_QUOTA", 1_000_000):
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ # 15 of 30 days left: the 500 free credits left, pro-rated back to a 30-day rate, cover both scanners.
+ assert snapshot.projected_monthly_credits == 1000
+
+ @parameterized.expand(
+ [
+ ("room_left_after_the_other", 20, 1000 - 300),
+ ("other_uses_it_all", 100, 0),
+ ]
+ )
+ @time_machine.travel("2026-09-16T00:00:00Z", tick=False)
+ def test_free_headroom_is_what_other_free_only_scanners_leave(
+ self, _name: str, other_estimate: int, expected_left: int
+ ) -> None:
+ seed_scanner_spend(self.scanner, FREE_TIER_MONTHLY_CREDITS - 500)
+ self._make_scanner(team=self.team, name="free-other", estimate=other_estimate, free_only=True)
+ with patch.object(quota, "MONTHLY_CREDIT_QUOTA", 1_000_000):
+ projection = spend_projection(self.organization.id, include_free_headroom=True)
+ # The 500 free credits left over 15 days are a 1000-credit monthly rate, shared with the other scanner.
+ assert projection.free_only_monthly_credits_left == expected_left
+
def test_other_orgs_scanners_not_counted(self) -> None:
other_org = Organization.objects.create(name="other-projection-org")
other_team = Team.objects.create(organization=other_org, name="other-projection-team")
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index 57a65f15b7da..9bdb3c72fb3d 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -1171,25 +1171,28 @@ class TestAdvanceScannerWatermarkActivity:
@pytest.mark.parametrize(
- "limit, spent_observations, expect_capped",
+ "limit, spent_observations, free_only, expect_capped",
[
- (None, 0, False),
+ (None, 0, False, False),
# No limit set, and heavy spend: never capped, watermark never touched.
- (None, 100, False),
- (20 * _OBSERVATION_CREDITS, 0, False),
- (20 * _OBSERVATION_CREDITS, 10, False),
+ (None, 100, False, False),
+ (20 * _OBSERVATION_CREDITS, 0, False, False),
+ (20 * _OBSERVATION_CREDITS, 10, False, False),
# Exactly one observation's worth of room left.
- (20 * _OBSERVATION_CREDITS, 19, False),
+ (20 * _OBSERVATION_CREDITS, 19, False, False),
# Credits left, but not enough for one more observation.
- (20 * _OBSERVATION_CREDITS - 1, 19, True),
- (20 * _OBSERVATION_CREDITS, 20, True),
+ (20 * _OBSERVATION_CREDITS - 1, 19, False, True),
+ (20 * _OBSERVATION_CREDITS, 20, False, True),
+ # No scanner limit, but free-only: the org's free credits cap it while billing allows more.
+ (None, 100, True, False),
+ (None, 200, True, True),
],
)
@pytest.mark.django_db(transaction=True)
def test_check_scanner_budget_activity_caps_and_advances_the_watermark(
- limit: int | None, spent_observations: int, expect_capped: bool
+ limit: int | None, spent_observations: int, free_only: bool, expect_capped: bool
) -> None:
- scanner = _make_scanner(credit_limit=limit)
+ scanner = _make_scanner(credit_limit=limit, free_only=free_only)
stale = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)
ReplayScanner.objects.filter(pk=scanner.pk).update(
last_swept_at=stale,
@@ -1198,7 +1201,8 @@ def test_check_scanner_budget_activity_caps_and_advances_the_watermark(
)
seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=spent_observations)
- output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000):
+ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))
scanner.refresh_from_db()
assert output.capped is expect_capped
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 5fea218a5290..575568eb6ba5 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -43,7 +43,7 @@ from posthog.session_recordings.session_recording_v2_service import RecordingBlo
from products.exports.backend.models.exported_asset import ExportedAsset
from products.replay_vision.backend.api.observation_progress import _ObservationState, stream_observation_progress
-from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.billing import FREE_TIER_MONTHLY_CREDITS, observation_credits_for_model
from products.replay_vision.backend.enqueue_claims import (
_RELEASE_GRACE_SECONDS,
pending_enqueue_claims_for_scanner,
@@ -547,6 +547,28 @@ class TestCreateObservationActivity:
)
assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-no-consent").exists()
+ @parameterized.expand(
+ [
+ # Billing allows far more spend, so only the free credits stop the scanner.
+ ("free_credits_bind", 1_000_000, FREE_TIER_MONTHLY_CREDITS, "free_credits"),
+ # The org's own limit sits below the free credits, so it is the org that is out.
+ ("org_limit_binds", 1_000, 1_000, "quota"),
+ ]
+ )
+ def test_free_only_refusal_names_what_stopped_it(
+ self, _name: str, org_limit: int, spent: int, expected_reason: str
+ ) -> None:
+ scanner = _make_scanner(free_only=True)
+ seed_scanner_spend(_make_scanner(team=scanner.team, name="spender"), spent)
+ with (
+ patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", org_limit),
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.posthoganalytics.capture"
+ ) as capture,
+ ):
+ assert self._admit(scanner, "sess-free").was_created is False
+ assert [c.kwargs["properties"]["reason"] for c in capture.call_args_list] == [expected_reason]
+
@parameterized.expand(
[
("quota", 5, 5),
@@ -926,14 +948,21 @@ class TestCreateObservationActivity:
assert created == {"sibling-a": True, "sibling-b": True}
- @parameterized.expand([("uncapped", None), ("capped", 1_000)])
+ @parameterized.expand([("uncapped", None, False), ("capped", 1_000, False), ("free_only", None, True)])
def test_concurrent_admissions_across_scanners_cannot_exceed_org_credit_limit(
- self, _name: str, scanner_limit: int | None
+ self, _name: str, scanner_limit: int | None, free_only: bool
) -> 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)
+ scanner_a = _make_scanner(credit_limit=scanner_limit, free_only=free_only)
+ scanner_b = _make_scanner(
+ team=scanner_a.team, name="org-sibling", credit_limit=scanner_limit, free_only=free_only
+ )
+ # Free-only scanners race for the last free credits while billing still allows far more spend.
+ org_limit = credits
+ if free_only:
+ seed_scanner_spend(_make_scanner(team=scanner_a.team, name="spender"), FREE_TIER_MONTHLY_CREDITS - credits)
+ org_limit = 1_000_000
barrier = threading.Barrier(2)
created: dict[str, bool] = {}
@@ -948,7 +977,7 @@ class TestCreateObservationActivity:
finally:
connections.close_all()
- with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", credits):
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", org_limit):
threads = [
threading.Thread(target=admit, args=(scanner_a, "org-race-a")),
threading.Thread(target=admit, args=(scanner_b, "org-race-b")),
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index a1bc78a87d1a..9badd80e7948 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1267,6 +1267,8 @@ export interface ReplayScannerApi {
* @nullable
*/
credit_limit?: number | null
+ /** Run only while the organization has free credits left this billing period, so the scanner never adds spend. */
+ free_only?: boolean
/** LLM provider. v1 is Google-only.
*
* * `google` - Google */
@@ -1306,9 +1308,11 @@ export interface ReplayScannerApi {
readonly credits_this_month: number
/** Succeeded observations this scanner produced in the current billing period. */
readonly observations_this_month: number
- /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */
+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the organization's free credits, this is the organization's usage, not the scanner's own. */
readonly credits_used_against_limit: number
- /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */
+ /** True when the organization's free credits bind this `free_only` scanner rather than its own `credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against its free credits. */
+ readonly limit_from_free_credits: boolean
+ /** Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, because the organization has used its free credits. True when the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set and `free_only` is false. */
readonly limit_reached: boolean
/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */
readonly sweep_throttle_factor: number
@@ -1407,6 +1411,8 @@ export interface PatchedReplayScannerApi {
* @nullable
*/
credit_limit?: number | null
+ /** Run only while the organization has free credits left this billing period, so the scanner never adds spend. */
+ free_only?: boolean
/** LLM provider. v1 is Google-only.
*
* * `google` - Google */
@@ -1446,9 +1452,11 @@ export interface PatchedReplayScannerApi {
readonly credits_this_month?: number
/** Succeeded observations this scanner produced in the current billing period. */
readonly observations_this_month?: number
- /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */
+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the organization's free credits, this is the organization's usage, not the scanner's own. */
readonly credits_used_against_limit?: number
- /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */
+ /** True when the organization's free credits bind this `free_only` scanner rather than its own `credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against its free credits. */
+ readonly limit_from_free_credits?: boolean
+ /** Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, because the organization has used its free credits. True when the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set and `free_only` is false. */
readonly limit_reached?: boolean
/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */
readonly sweep_throttle_factor?: number
@@ -2731,6 +2739,8 @@ export interface EstimateResponseApi {
other_enabled_scanners_monthly_credits: number
/** Committed-but-unspent credits of the org's active backfills, the same figure the quota snapshot's projection carries. A one-off charge rather than a monthly rate, so the forecast shows it as its own segment instead of adding it to a per-month total. */
active_backfill_credits: number
+ /** The monthly credit rate the organization's free credits still cover for one more free-only scanner, after the other free-only scanners and backfills. The forecast caps a free-only scanner at this rate, because free-only scanners share one pool. */
+ free_only_monthly_credits_left: number
/** Sampling rate applied to the projection. Echoed from the request. */
sampling_rate: number
}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 496f6aa159a8..abec59022cec 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -662,6 +662,12 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod
.describe(
"Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."
),
+ free_only: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Run only while the organization has free credits left this billing period, so the scanner never adds spend.'
+ ),
provider: zod
.enum(['google'])
.describe('\* `google` - Google')
@@ -814,6 +820,12 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."
),
+ free_only: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Run only while the organization has free credits left this billing period, so the scanner never adds spend.'
+ ),
provider: zod
.enum(['google'])
.describe('\* `google` - Google')
diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
index baa2cd42dd7e..18abef5e0586 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
@@ -168,6 +168,7 @@ export function newScanner(templateKey?: string | null, teamName?: string | null
credit_limit_enabled: false,
// An unsaved scanner has no spend yet, so it can't have hit a limit it doesn't have.
credits_used_against_limit: 0,
+ limit_from_free_credits: false,
limit_reached: false,
sweep_throttle_factor: 1,
dashboard_id: null,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c95007598aa2..165b06ec388b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42148,6 +42148,8 @@ export namespace Schemas {
other_enabled_scanners_monthly_credits: number;
/** Committed-but-unspent credits of the org's active backfills, the same figure the quota snapshot's projection carries. A one-off charge rather than a monthly rate, so the forecast shows it as its own segment instead of adding it to a per-month total. */
active_backfill_credits: number;
+ /** The monthly credit rate the organization's free credits still cover for one more free-only scanner, after the other free-only scanners and backfills. The forecast caps a free-only scanner at this rate, because free-only scanners share one pool. */
+ free_only_monthly_credits_left: number;
/** Sampling rate applied to the projection. Echoed from the request. */
sampling_rate: number;
}
@@ -71814,6 +71816,8 @@ export namespace Schemas {
* @nullable
*/
credit_limit?: number | null;
+ /** Run only while the organization has free credits left this billing period, so the scanner never adds spend. */
+ free_only?: boolean;
/** LLM provider. v1 is Google-only.
*
* * `google` - Google */
@@ -71853,9 +71857,11 @@ export namespace Schemas {
readonly credits_this_month: number;
/** Succeeded observations this scanner produced in the current billing period. */
readonly observations_this_month: number;
- /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */
+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the organization's free credits, this is the organization's usage, not the scanner's own. */
readonly credits_used_against_limit: number;
- /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */
+ /** True when the organization's free credits bind this `free_only` scanner rather than its own `credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against its free credits. */
+ readonly limit_from_free_credits: boolean;
+ /** Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, because the organization has used its free credits. True when the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set and `free_only` is false. */
readonly limit_reached: boolean;
/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */
readonly sweep_throttle_factor: number;
@@ -83773,6 +83779,8 @@ export namespace Schemas {
* @nullable
*/
credit_limit?: number | null;
+ /** Run only while the organization has free credits left this billing period, so the scanner never adds spend. */
+ free_only?: boolean;
/** LLM provider. v1 is Google-only.
*
* * `google` - Google */
@@ -83812,9 +83820,11 @@ export namespace Schemas {
readonly credits_this_month?: number;
/** Succeeded observations this scanner produced in the current billing period. */
readonly observations_this_month?: number;
- /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */
+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the organization's free credits, this is the organization's usage, not the scanner's own. */
readonly credits_used_against_limit?: number;
- /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */
+ /** True when the organization's free credits bind this `free_only` scanner rather than its own `credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against its free credits. */
+ readonly limit_from_free_credits?: boolean;
+ /** Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, because the organization has used its free credits. True when the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set and `free_only` is false. */
readonly limit_reached?: boolean;
/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */
readonly sweep_throttle_factor?: number;
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 22df6720f397..84c479dca879 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -928,6 +928,12 @@ export const VisionScannersCreateBody = () => zod
.describe(
"Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."
),
+ free_only: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Run only while the organization has free credits left this billing period, so the scanner never adds spend.'
+ ),
provider: zod
.enum(['google'])
.describe('\* `google` - Google')
@@ -1101,6 +1107,12 @@ export const VisionScannersPartialUpdateBody = () => zod
.describe(
"Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."
),
+ free_only: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Run only while the organization has free credits left this billing period, so the scanner never adds spend.'
+ ),
provider: zod
.enum(['google'])
.describe('\* `google` - Google')
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index eeec5b354871..109b01d5d69c 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -934,6 +934,9 @@ const visionScannersCreate = (): ToolBase<
if (params.credit_limit !== undefined) {
body['credit_limit'] = params.credit_limit
}
+ if (params.free_only !== undefined) {
+ body['free_only'] = params.free_only
+ }
if (params.provider !== undefined) {
body['provider'] = params.provider
}
@@ -1610,6 +1613,9 @@ const visionScannersUpdate = (): ToolBase<ReturnType<typeof VisionScannersUpdate
if (params.credit_limit !== undefined) {
body['credit_limit'] = params.credit_limit
}
+ if (params.free_only !== undefined) {
+ body['free_only'] = params.free_only
+ }
if (params.provider !== undefined) {
body['provider'] = params.provider
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
index b8841820c157..197766d5b015 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
@@ -76,6 +76,10 @@
],
"description": "The experiment this scanner's targeting watches, if any. Set null when the experiment targeting is removed."
},
+ "free_only": {
+ "description": "Run only while the organization has free credits left this billing period, so the scanner never adds spend.",
+ "type": "boolean"
+ },
"goal": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
index 2668a6ac0a9e..5520343c8ec1 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
@@ -75,6 +75,10 @@
],
"description": "The experiment this scanner's targeting watches, if any. Set null when the experiment targeting is removed."
},
+ "free_only": {
+ "description": "Run only while the organization has free credits left this billing period, so the scanner never adds spend.",
+ "type": "boolean"
+ },
"goal": {
"anyOf": [
{