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): project quota from enabled scanners' estimated rates (#62951)

Tue Haulundf9cd61c7d9d8
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index a253e4ebc314..c99873e442fa 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -86,6 +86,7 @@ from products.error_tracking.backend.temporal.symbol_set_cleanup.schedule import
create_error_tracking_symbol_set_cleanup_schedule,
)
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
+from products.replay_vision.backend.temporal.estimates import create_replay_vision_estimates_schedule
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedule
from products.tasks.backend.temporal.code_workstreams.schedule import create_evaluate_code_workstreams_schedule
@@ -662,6 +663,7 @@ schedules = [
create_cleanup_alert_checks_schedule,
create_signals_scout_coordinator_schedule,
create_replay_vision_reconciler_schedule,
+ create_replay_vision_estimates_schedule,
create_evaluate_code_workstreams_schedule,
]
diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.py
index 483a33d4b06c..b5ce491f4bde 100644
--- a/products/replay_vision/backend/api/quota.py
+++ b/products/replay_vision/backend/api/quota.py
@@ -39,6 +39,13 @@ class VisionQuotaSerializer(serializers.Serializer):
read_only=True,
help_text="First moment of the next quota period (UTC); the current period's exclusive upper bound.",
)
+ projected_monthly_observations = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Sum of enabled scanners' projected observations/month across the organization. "
+ "Scanners without a computed estimate contribute 0."
+ ),
+ )
class VisionQuotaViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 389b440607a9..1e6c7a8ee4d1 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -48,7 +48,12 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerProvider,
ScannerType,
)
-from products.replay_vision.backend.queries import estimate_scanner_session_volume
+from products.replay_vision.backend.queries import (
+ ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS,
+ estimate_scanner_session_volume,
+ project_monthly_observations,
+ refresh_scanner_estimate,
+)
from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
@@ -64,6 +69,14 @@ _QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")
logger = structlog.get_logger(__name__)
+def _refresh_estimate_fail_soft(scanner: ReplayScanner) -> None:
+ # The estimate is advisory — never fail a scanner save over it, and keep the save's latency tail short.
+ try:
+ refresh_scanner_estimate(scanner, max_execution_seconds=ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS)
+ except Exception:
+ logger.exception("replay_vision.estimate_refresh_failed", scanner_id=str(scanner.id))
+
+
def _scanner_config_error_message(scanner_type: ScannerType, scanner_config: Any) -> str | None:
if not isinstance(scanner_config, dict):
return "Scanner configuration must be a JSON object."
@@ -152,6 +165,11 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
read_only=True,
help_text="Increments on every config-changing save. Observations snapshot this value.",
)
+ estimated_monthly_observations = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="Latest projected observations/month for this scanner. Null until first computed.",
+ )
last_swept_at = serializers.DateTimeField(
read_only=True,
help_text="Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery.",
@@ -177,6 +195,7 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
"enabled",
"emits_signals",
"scanner_version",
+ "estimated_monthly_observations",
"last_swept_at",
"created_at",
"created_by",
@@ -185,6 +204,7 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
read_only_fields = [
"id",
"scanner_version",
+ "estimated_monthly_observations",
"last_swept_at",
"created_at",
"created_by",
@@ -251,15 +271,21 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
team = self.context["get_team"]()
user = cast(User, self.context["request"].user)
try:
- return ReplayScanner.objects.create(team=team, created_by=user, **validated_data)
+ scanner = ReplayScanner.objects.create(team=team, created_by=user, **validated_data)
except IntegrityError as e:
self._reraise_unique_name_violation(e)
+ _refresh_estimate_fail_soft(scanner)
+ return scanner
def update(self, instance: ReplayScanner, validated_data: dict[str, Any]) -> ReplayScanner:
try:
- return super().update(instance, validated_data)
+ scanner = super().update(instance, validated_data)
except IntegrityError as e:
self._reraise_unique_name_violation(e)
+ # Model save clears `estimated_at` when volume inputs change; refresh eagerly for the editor.
+ if scanner.estimated_at is None:
+ _refresh_estimate_fail_soft(scanner)
+ return scanner
@staticmethod
def _reraise_unique_name_violation(error: IntegrityError) -> NoReturn:
@@ -660,8 +686,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
recordings_query = RecordingsQuery.model_validate(query_dict)
estimate = estimate_scanner_session_volume(team=self.team, query=recordings_query)
- sessions_per_day = estimate.matched_sessions / estimate.effective_window_days
- observations_per_month = round(sessions_per_day * 30 * sampling_rate)
+ observations_per_month = project_monthly_observations(estimate, sampling_rate)
return Response(
EstimateResponseSerializer(
diff --git a/products/replay_vision/backend/migrations/0013_replayscanner_estimated_at_and_more.py b/products/replay_vision/backend/migrations/0013_replayscanner_estimated_at_and_more.py
new file mode 100644
index 000000000000..7e563f7d0cde
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0013_replayscanner_estimated_at_and_more.py
@@ -0,0 +1,30 @@
+# Generated by Django 5.2.14 on 2026-06-11 11:05
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0012_replayquotagrant"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="estimated_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="When the estimate was last computed. Refreshed on config saves and by the sweep when stale.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="estimated_monthly_observations",
+ field=models.PositiveIntegerField(
+ blank=True,
+ help_text="Latest projected observations/month for this scanner; enabled scanners are summed org-wide for the quota prognosis.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 928fab1e1ad2..8ba37f153725 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0012_replayquotagrant
+0013_replayscanner_estimated_at_and_more
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index e151b248d033..8b345f4af190 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -2,6 +2,8 @@ from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models, transaction
from django.utils import timezone
+from posthog.schema import RecordingsQuery
+
from posthog.models.utils import UUIDModel
@@ -69,6 +71,17 @@ class ReplayScanner(UUIDModel):
help_text="Keyset tiebreaker; set when the last batch saturated so the next sweep resumes past session_end ties.",
)
+ estimated_monthly_observations = models.PositiveIntegerField(
+ null=True,
+ blank=True,
+ help_text="Latest projected observations/month for this scanner; enabled scanners are summed org-wide for the quota prognosis.",
+ )
+ estimated_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="When the estimate was last computed. Refreshed on config saves and by the sweep when stale.",
+ )
+
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
updated_at = models.DateTimeField(auto_now=True)
@@ -94,26 +107,47 @@ class ReplayScanner(UUIDModel):
"model",
"emits_signals",
)
+ # Fields the persisted volume estimate is computed from; changing them marks the estimate stale.
+ _ESTIMATE_FIELDS = frozenset({"query", "sampling_rate"})
def save(self, *args, **kwargs) -> None:
update_fields = kwargs.get("update_fields")
if update_fields is not None:
relevant = [f for f in self._VERSION_TRACKED_FIELDS if f in update_fields]
+ track_enabled = "enabled" in update_fields
else:
relevant = list(self._VERSION_TRACKED_FIELDS)
- if self.pk and relevant:
+ track_enabled = True
+ if self.pk and (relevant or track_enabled):
# SELECT FOR UPDATE so concurrent saves can't both bump scanner_version from the same baseline.
with transaction.atomic():
old = (
- type(self).objects.select_for_update().filter(pk=self.pk).only("scanner_version", *relevant).first()
+ type(self)
+ .objects.select_for_update()
+ .filter(pk=self.pk)
+ .only("scanner_version", "enabled", *relevant)
+ .first()
)
- if old is not None and any(getattr(old, f) != getattr(self, f) for f in relevant):
- self.scanner_version = old.scanner_version + 1
- if update_fields is not None:
- kwargs["update_fields"] = [*update_fields, "scanner_version"]
+ if old is not None:
+ changed = {f for f in relevant if getattr(old, f) != getattr(self, f)}
+ extra_fields = []
+ if changed:
+ self.scanner_version = old.scanner_version + 1
+ extra_fields.append("scanner_version")
+ # Re-enabling resurfaces a possibly long-stale estimate in the quota sum, so it invalidates too.
+ reenabled = track_enabled and self.enabled and not old.enabled
+ if (changed & self._ESTIMATE_FIELDS) or reenabled:
+ self.estimated_at = None
+ extra_fields.append("estimated_at")
+ if update_fields is not None and extra_fields:
+ kwargs["update_fields"] = [*update_fields, *extra_fields]
super().save(*args, **kwargs)
return
super().save(*args, **kwargs)
+ def recordings_query(self) -> RecordingsQuery:
+ """The persisted candidate filter; an empty `query` parses as a bare RecordingsQuery."""
+ return RecordingsQuery.model_validate(self.query or {"kind": "RecordingsQuery"})
+
def __str__(self) -> str:
return f"{self.name} ({self.scanner_type})"
diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.py
index 80259a9acaca..d527f4128f73 100644
--- a/products/replay_vision/backend/queries/__init__.py
+++ b/products/replay_vision/backend/queries/__init__.py
@@ -7,17 +7,25 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
ScannerCandidateQuery,
)
from products.replay_vision.backend.queries.scanner_volume_estimate import (
+ ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS,
+ ESTIMATE_STALE_AFTER,
ScannerVolumeEstimate,
estimate_scanner_session_volume,
+ project_monthly_observations,
+ refresh_scanner_estimate,
)
__all__ = [
"DEFAULT_CANDIDATE_LIMIT",
"DEFAULT_MAX_EXECUTION_SECONDS",
+ "ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS",
+ "ESTIMATE_STALE_AFTER",
"SAMPLE_RATE_PRECISION",
"SETTLE_INTERVAL",
"CandidateSession",
"ScannerCandidateQuery",
"ScannerVolumeEstimate",
"estimate_scanner_session_volume",
+ "project_monthly_observations",
+ "refresh_scanner_estimate",
]
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 961240c4d672..86f74fd64e9e 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -1,6 +1,8 @@
import datetime as dt
from dataclasses import dataclass
+from django.utils import timezone
+
from posthog.schema import RecordingsQuery
from posthog.hogql import ast
@@ -11,12 +13,20 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models import Team
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+
# A pathological filter must not be able to hang the estimate request.
_ESTIMATE_MAX_EXECUTION_TIME_SECONDS = 30
+# Interactive saves get a tighter budget and fail soft; the batch refresher can afford the full cap.
+ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS = 10
+
# The estimate always projects a calendar month from a fixed 30-day lookback.
ESTIMATE_WINDOW_DAYS = 30
+# Persisted per-scanner estimates older than this are recomputed by the sweep.
+ESTIMATE_STALE_AFTER = dt.timedelta(hours=24)
+
@dataclass(frozen=True)
class ScannerVolumeEstimate:
@@ -25,7 +35,9 @@ class ScannerVolumeEstimate:
effective_window_days: int
-def estimate_scanner_session_volume(*, team: Team, query: RecordingsQuery) -> ScannerVolumeEstimate:
+def estimate_scanner_session_volume(
+ *, team: Team, query: RecordingsQuery, max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS
+) -> ScannerVolumeEstimate:
"""Count sessions matching `query` over the last 30 days, for the scanner cost preview.
Reuses `SessionRecordingListFromQuery`'s filter compilation verbatim and wraps it in a
@@ -75,7 +87,7 @@ def estimate_scanner_session_volume(*, team: Team, query: RecordingsQuery) -> Sc
query=combined_query,
team=team,
query_type="ReplayVisionScannerEstimateQuery",
- settings=HogQLGlobalSettings(max_execution_time=_ESTIMATE_MAX_EXECUTION_TIME_SECONDS),
+ settings=HogQLGlobalSettings(max_execution_time=max_execution_seconds),
)
results = response.results or []
matched = int(results[0][0]) if results else 0
@@ -87,6 +99,29 @@ def estimate_scanner_session_volume(*, team: Team, query: RecordingsQuery) -> Sc
)
+def project_monthly_observations(estimate: ScannerVolumeEstimate, sampling_rate: float) -> int:
+ """Scale matched sessions to a 30-day month and apply the sampling rate."""
+ return round(estimate.matched_sessions / estimate.effective_window_days * ESTIMATE_WINDOW_DAYS * sampling_rate)
+
+
+def refresh_scanner_estimate(
+ scanner: ReplayScanner, *, max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS
+) -> None:
+ """Recompute and persist the scanner's projected monthly volume. Raises on failure; callers decide severity."""
+ estimate = estimate_scanner_session_volume(
+ team=scanner.team, query=scanner.recordings_query(), max_execution_seconds=max_execution_seconds
+ )
+ projection = project_monthly_observations(estimate, scanner.sampling_rate)
+ estimated_at = timezone.now()
+ # Filtered write so a config edit racing the (slow) estimate query can't get stamped fresh with stale numbers.
+ updated = ReplayScanner.objects.filter(
+ pk=scanner.pk, query=scanner.query, sampling_rate=scanner.sampling_rate
+ ).update(estimated_monthly_observations=projection, estimated_at=estimated_at)
+ if updated:
+ scanner.estimated_monthly_observations = projection
+ scanner.estimated_at = estimated_at
+
+
def _clamp_window_days(earliest: object) -> int:
"""Clamp the divisor to the team's actual data span so a new team isn't under-estimated."""
if not isinstance(earliest, dt.datetime):
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index cf1d04020c3e..82af33a3cd65 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -11,6 +11,7 @@ from posthog.date_util import start_of_month
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
MONTHLY_OBSERVATION_QUOTA = 3000
@@ -24,6 +25,8 @@ class QuotaSnapshot:
usage_this_month: int
period_start: datetime
period_end: datetime
+ # Sum of enabled scanners' persisted per-scanner estimates across the org; uncomputed estimates count 0.
+ projected_monthly_observations: int
@property
def remaining(self) -> int:
@@ -57,9 +60,14 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
organization_id=organization_id,
expires_at__gt=now,
).aggregate(total=Coalesce(Sum("amount"), Value(0)))["total"]
+ projected = ReplayScanner.objects.filter(
+ team__organization_id=organization_id,
+ enabled=True,
+ ).aggregate(total=Coalesce(Sum("estimated_monthly_observations"), Value(0)))["total"]
return QuotaSnapshot(
monthly_quota=MONTHLY_OBSERVATION_QUOTA + bonus,
usage_this_month=usage,
period_start=period_start,
period_end=period_end,
+ projected_monthly_observations=projected,
)
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 215eaaf1ddac..6a5c1302bb2b 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -16,18 +16,26 @@ from products.replay_vision.backend.temporal.activities import (
find_scanner_candidates_activity,
list_enabled_scanners_activity,
list_scanner_schedules_activity,
+ list_stale_scanner_estimates_activity,
mark_observation_failed_activity,
mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
+ refresh_scanner_estimate_activity,
upload_video_to_gemini_activity,
upsert_scanner_schedule_activity,
)
+from products.replay_vision.backend.temporal.estimates import RefreshScannerEstimatesWorkflow
from products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflow
from products.replay_vision.backend.temporal.sweep_workflow import SweepScannerWorkflow
from products.replay_vision.backend.temporal.workflow import ApplyScannerWorkflow
-WORKFLOWS = [ApplyScannerWorkflow, ReconcileScannerSchedulesWorkflow, SweepScannerWorkflow]
+WORKFLOWS = [
+ ApplyScannerWorkflow,
+ ReconcileScannerSchedulesWorkflow,
+ RefreshScannerEstimatesWorkflow,
+ SweepScannerWorkflow,
+]
ACTIVITIES: list[Callable[..., Any]] = [
create_observation_activity,
mark_observation_running_activity,
@@ -49,6 +57,8 @@ ACTIVITIES: list[Callable[..., Any]] = [
list_scanner_schedules_activity,
upsert_scanner_schedule_activity,
delete_scanner_schedule_activity,
+ list_stale_scanner_estimates_activity,
+ refresh_scanner_estimate_activity,
]
__all__ = [
@@ -56,6 +66,7 @@ __all__ = [
"WORKFLOWS",
"ApplyScannerWorkflow",
"ReconcileScannerSchedulesWorkflow",
+ "RefreshScannerEstimatesWorkflow",
"SweepScannerWorkflow",
"advance_scanner_watermark_activity",
"call_scanner_provider_activity",
@@ -71,10 +82,12 @@ __all__ = [
"find_scanner_candidates_activity",
"list_enabled_scanners_activity",
"list_scanner_schedules_activity",
+ "list_stale_scanner_estimates_activity",
"mark_observation_failed_activity",
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
+ "refresh_scanner_estimate_activity",
"upload_video_to_gemini_activity",
"upsert_scanner_schedule_activity",
]
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 764ad795a51b..1fbac3c1419d 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -13,6 +13,9 @@ from products.replay_vision.backend.temporal.activities.emit_observation_event i
from products.replay_vision.backend.temporal.activities.ensure_session_asset import ensure_session_asset_activity
from products.replay_vision.backend.temporal.activities.fetch_session_events import fetch_session_events_activity
from products.replay_vision.backend.temporal.activities.find_scanner_candidates import find_scanner_candidates_activity
+from products.replay_vision.backend.temporal.activities.list_stale_scanner_estimates import (
+ list_stale_scanner_estimates_activity,
+)
from products.replay_vision.backend.temporal.activities.observation_state import (
mark_observation_failed_activity,
mark_observation_ineligible_activity,
@@ -25,6 +28,9 @@ from products.replay_vision.backend.temporal.activities.reconciler_activities im
list_scanner_schedules_activity,
upsert_scanner_schedule_activity,
)
+from products.replay_vision.backend.temporal.activities.refresh_scanner_estimate import (
+ refresh_scanner_estimate_activity,
+)
from products.replay_vision.backend.temporal.activities.upload_video_to_gemini import upload_video_to_gemini_activity
__all__ = [
@@ -42,10 +48,12 @@ __all__ = [
"find_scanner_candidates_activity",
"list_enabled_scanners_activity",
"list_scanner_schedules_activity",
+ "list_stale_scanner_estimates_activity",
"mark_observation_failed_activity",
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
+ "refresh_scanner_estimate_activity",
"upload_video_to_gemini_activity",
"upsert_scanner_schedule_activity",
]
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index c56105b43b72..c950be74c115 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -2,8 +2,6 @@ from pydantic import ValidationError
from temporalio import activity
from temporalio.exceptions import ApplicationError
-from posthog.schema import RecordingsQuery
-
from posthog.rbac.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
@@ -38,7 +36,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
return FindScannerCandidatesOutput(candidates=[], saturated=False)
try:
- query = RecordingsQuery.model_validate(scanner.query or {"kind": "RecordingsQuery"})
+ query = scanner.recordings_query()
except ValidationError as exc:
raise ApplicationError(
f"ReplayScanner {inputs.scanner_id} has malformed query: {exc}", non_retryable=True
diff --git a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
new file mode 100644
index 000000000000..aced0d3f764e
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
@@ -0,0 +1,25 @@
+from django.db.models import F, Q
+from django.utils import timezone
+
+from temporalio import activity
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER
+from products.replay_vision.backend.temporal.constants import ESTIMATES_MAX_PER_RUN
+from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.estimates_types import RefreshScannerEstimateInputs
+
+
+@track_activity()
+def list_stale_scanner_estimates_activity() -> list[RefreshScannerEstimateInputs]:
+ """Enabled scanners whose persisted estimate is missing or past the staleness window, oldest first."""
+ cutoff = timezone.now() - ESTIMATE_STALE_AFTER
+ rows = (
+ ReplayScanner.objects.filter(enabled=True)
+ .filter(Q(estimated_at__isnull=True) | Q(estimated_at__lt=cutoff))
+ # Never-estimated scanners first, then the longest-stale, so a backlog drains fairly across runs.
+ .order_by(F("estimated_at").asc(nulls_first=True))
+ .values_list("id", "team_id")[:ESTIMATES_MAX_PER_RUN]
+ )
+ return [RefreshScannerEstimateInputs(scanner_id=scanner_id, team_id=team_id) for scanner_id, team_id in rows]
diff --git a/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py
new file mode 100644
index 000000000000..7f81da4f9eda
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py
@@ -0,0 +1,25 @@
+from django.utils import timezone
+
+from temporalio import activity
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, refresh_scanner_estimate
+from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.estimates_types import RefreshScannerEstimateInputs
+
+
+@track_activity()
+def refresh_scanner_estimate_activity(inputs: RefreshScannerEstimateInputs) -> bool:
+ """Recompute the scanner's persisted estimate; the staleness re-check makes it idempotent against an interactive save racing the batch."""
+ scanner = (
+ ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id, enabled=True)
+ .select_related("team")
+ .first()
+ )
+ if scanner is None:
+ return False
+ if scanner.estimated_at is not None and timezone.now() - scanner.estimated_at < ESTIMATE_STALE_AFTER:
+ return False
+ refresh_scanner_estimate(scanner)
+ return True
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index ce3853481095..5122479879c0 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -50,6 +50,25 @@ MAX_IN_FLIGHT_APPLIES_PER_SCANNER = 50
COUNT_IN_FLIGHT_APPLIES_TIMEOUT = dt.timedelta(seconds=30)
+ESTIMATES_WORKFLOW_NAME = "replay-vision-refresh-scanner-estimates"
+ESTIMATES_WORKFLOW_ID = "replay-vision-estimate-refresher"
+ESTIMATES_SCHEDULE_ID = "replay-vision-estimate-refresher-schedule"
+
+# Quarter-hourly checks against a 24h staleness target keep estimates at most ~24h15m old.
+ESTIMATES_REFRESH_INTERVAL = dt.timedelta(minutes=15)
+# Covers the worst-case batch (MAX_PER_RUN / CONCURRENCY × the 60s activity timeout = 100 min) with margin;
+# overlap SKIP means a slow run absorbs later ticks instead of being cancelled mid-batch.
+ESTIMATES_EXECUTION_TIMEOUT = dt.timedelta(hours=2)
+
+# Each refresh is a ClickHouse count; bound the batch and parallelism so one run stays cheap.
+ESTIMATES_MAX_PER_RUN = 400
+ESTIMATE_REFRESH_CONCURRENCY = 4
+
+LIST_STALE_ESTIMATES_TIMEOUT = dt.timedelta(seconds=60)
+# Covers the estimate query's 30s ClickHouse cap plus the Postgres staleness check.
+REFRESH_SCANNER_ESTIMATE_TIMEOUT = dt.timedelta(seconds=60)
+
+
def build_apply_scanner_workflow_id(scanner_id: UUID, session_id: str) -> str:
"""Deterministic Temporal workflow id for one (scanner, session) application."""
return f"{APPLY_SCANNER_WORKFLOW_NAME}-{scanner_id}-{session_id}"
diff --git a/products/replay_vision/backend/temporal/estimates.py b/products/replay_vision/backend/temporal/estimates.py
new file mode 100644
index 000000000000..f2d05665f270
--- /dev/null
+++ b/products/replay_vision/backend/temporal/estimates.py
@@ -0,0 +1,97 @@
+"""Periodic batch refresh of persisted per-scanner volume estimates (the quota prognosis inputs)."""
+
+import asyncio
+from typing import TYPE_CHECKING
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ApplicationError
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from products.replay_vision.backend.temporal.constants import (
+ ESTIMATE_REFRESH_CONCURRENCY,
+ ESTIMATES_EXECUTION_TIMEOUT,
+ ESTIMATES_REFRESH_INTERVAL,
+ ESTIMATES_SCHEDULE_ID,
+ ESTIMATES_WORKFLOW_ID,
+ ESTIMATES_WORKFLOW_NAME,
+ LIST_STALE_ESTIMATES_TIMEOUT,
+ REFRESH_SCANNER_ESTIMATE_TIMEOUT,
+)
+from products.replay_vision.backend.temporal.estimates_types import (
+ RefreshScannerEstimateInputs,
+ RefreshScannerEstimatesInputs,
+ RefreshScannerEstimatesResult,
+)
+
+if TYPE_CHECKING:
+ from temporalio.client import Client
+
+# `activities` pulls in Django, which the workflow sandbox can't safely re-import.
+with workflow.unsafe.imports_passed_through():
+ from products.replay_vision.backend.temporal.activities import (
+ list_stale_scanner_estimates_activity,
+ refresh_scanner_estimate_activity,
+ )
+
+
[email protected](name=ESTIMATES_WORKFLOW_NAME)
+class RefreshScannerEstimatesWorkflow(PostHogWorkflow):
+ inputs_cls = RefreshScannerEstimatesInputs
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, inputs: RefreshScannerEstimatesInputs) -> RefreshScannerEstimatesResult:
+ stale = await workflow.execute_activity(
+ list_stale_scanner_estimates_activity,
+ start_to_close_timeout=LIST_STALE_ESTIMATES_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if not stale:
+ return RefreshScannerEstimatesResult()
+
+ # Each refresh runs a ClickHouse count, so bound the parallelism.
+ semaphore = asyncio.Semaphore(ESTIMATE_REFRESH_CONCURRENCY)
+
+ async def refresh(entry: RefreshScannerEstimateInputs) -> None:
+ async with semaphore:
+ await workflow.execute_activity(
+ refresh_scanner_estimate_activity,
+ entry,
+ start_to_close_timeout=REFRESH_SCANNER_ESTIMATE_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ # return_exceptions so one scanner's failure doesn't block the others.
+ outcomes = await asyncio.gather(*(refresh(entry) for entry in stale), return_exceptions=True)
+ result = RefreshScannerEstimatesResult(
+ refreshed=[e.scanner_id for e, r in zip(stale, outcomes) if not isinstance(r, BaseException)],
+ failed=[e.scanner_id for e, r in zip(stale, outcomes) if isinstance(r, BaseException)],
+ )
+ if result.failed:
+ workflow.logger.warning(
+ "replay_vision.estimate_refresh_partial_failure",
+ extra={"failed": [str(s) for s in result.failed]},
+ )
+ # Total failure is likely systemic — surface it so Temporal retries.
+ if not result.refreshed:
+ raise ApplicationError(f"estimate refresher: all {len(stale)} refresh activities failed")
+ return result
+
+
+async def create_replay_vision_estimates_schedule(client: "Client") -> None:
+ """Upsert the global estimate-refresher schedule. Called from worker startup."""
+ # Function-local: this module contains `@workflow.defn`, and the Temporal sandbox can't
+ # re-import the schedule helper's Django/temporalio.client dependencies when validating the workflow.
+ from products.replay_vision.backend.temporal.schedule import upsert_interval_schedule # noqa: PLC0415
+
+ await upsert_interval_schedule(
+ client,
+ schedule_id=ESTIMATES_SCHEDULE_ID,
+ workflow_name=ESTIMATES_WORKFLOW_NAME,
+ workflow_id=ESTIMATES_WORKFLOW_ID,
+ inputs=RefreshScannerEstimatesInputs(),
+ interval=ESTIMATES_REFRESH_INTERVAL,
+ execution_timeout=ESTIMATES_EXECUTION_TIMEOUT,
+ )
diff --git a/products/replay_vision/backend/temporal/estimates_types.py b/products/replay_vision/backend/temporal/estimates_types.py
new file mode 100644
index 000000000000..d6f22b87c74d
--- /dev/null
+++ b/products/replay_vision/backend/temporal/estimates_types.py
@@ -0,0 +1,19 @@
+"""Estimate-refresher-only Temporal types — split from `types.py` to avoid a circular import."""
+
+from uuid import UUID
+
+from pydantic import BaseModel
+
+
+class RefreshScannerEstimateInputs(BaseModel, frozen=True):
+ scanner_id: UUID
+ team_id: int
+
+
+class RefreshScannerEstimatesInputs(BaseModel, frozen=True):
+ pass
+
+
+class RefreshScannerEstimatesResult(BaseModel, frozen=True):
+ refreshed: list[UUID] = []
+ failed: list[UUID] = []
diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.py
index 5dbb35cad2e2..ca0d62797854 100644
--- a/products/replay_vision/backend/temporal/reconciler.py
+++ b/products/replay_vision/backend/temporal/reconciler.py
@@ -15,6 +15,10 @@ from products.replay_vision.backend.temporal.constants import (
LIST_ENABLED_SCANNERS_TIMEOUT,
LIST_SCANNER_SCHEDULES_TIMEOUT,
RECONCILE_SCHEDULE_OP_TIMEOUT,
+ RECONCILER_EXECUTION_TIMEOUT,
+ RECONCILER_INTERVAL,
+ RECONCILER_SCHEDULE_ID,
+ RECONCILER_WORKFLOW_ID,
RECONCILER_WORKFLOW_NAME,
)
from products.replay_vision.backend.temporal.reconciler_types import (
@@ -116,44 +120,15 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
async def create_replay_vision_reconciler_schedule(client: "Client") -> None:
"""Upsert the global reconciler schedule. Called from worker startup."""
# Function-local: this module contains `@workflow.defn`, and the Temporal sandbox can't
- # re-import django.conf or unrelated temporalio.client types when validating the workflow.
- from django.conf import settings # noqa: PLC0415
-
- from temporalio.client import ( # noqa: PLC0415
- Schedule,
- ScheduleActionStartWorkflow,
- ScheduleIntervalSpec,
- ScheduleOverlapPolicy,
- SchedulePolicy,
- ScheduleSpec,
- )
-
- from posthog.temporal.common.schedule import ( # noqa: PLC0415
- a_create_schedule,
- a_schedule_exists,
- a_update_schedule,
- )
-
- from products.replay_vision.backend.temporal.constants import ( # noqa: PLC0415
- RECONCILER_EXECUTION_TIMEOUT,
- RECONCILER_INTERVAL,
- RECONCILER_SCHEDULE_ID,
- RECONCILER_WORKFLOW_ID,
- )
-
- schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- RECONCILER_WORKFLOW_NAME,
- ReconcileScannerSchedulesInputs(),
- id=RECONCILER_WORKFLOW_ID,
- task_queue=settings.REPLAY_VISION_TASK_QUEUE,
- execution_timeout=RECONCILER_EXECUTION_TIMEOUT,
- retry_policy=RetryPolicy(maximum_attempts=1),
- ),
- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=RECONCILER_INTERVAL)]),
- policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=RECONCILER_INTERVAL),
+ # re-import the schedule helper's Django/temporalio.client dependencies when validating the workflow.
+ from products.replay_vision.backend.temporal.schedule import upsert_interval_schedule # noqa: PLC0415
+
+ await upsert_interval_schedule(
+ client,
+ schedule_id=RECONCILER_SCHEDULE_ID,
+ workflow_name=RECONCILER_WORKFLOW_NAME,
+ workflow_id=RECONCILER_WORKFLOW_ID,
+ inputs=ReconcileScannerSchedulesInputs(),
+ interval=RECONCILER_INTERVAL,
+ execution_timeout=RECONCILER_EXECUTION_TIMEOUT,
)
- if await a_schedule_exists(client, RECONCILER_SCHEDULE_ID):
- await a_update_schedule(client, RECONCILER_SCHEDULE_ID, schedule)
- else:
- await a_create_schedule(client, RECONCILER_SCHEDULE_ID, schedule, trigger_immediately=True)
diff --git a/products/replay_vision/backend/temporal/schedule.py b/products/replay_vision/backend/temporal/schedule.py
index e03400570a8b..d5c55527dd19 100644
--- a/products/replay_vision/backend/temporal/schedule.py
+++ b/products/replay_vision/backend/temporal/schedule.py
@@ -9,8 +9,10 @@ from uuid import UUID
from django.conf import settings
import structlog
+from pydantic import BaseModel
from temporalio import common
from temporalio.client import (
+ Client,
Schedule,
ScheduleActionStartWorkflow,
ScheduleIntervalSpec,
@@ -99,6 +101,35 @@ def load_enabled_scanner_fingerprints() -> dict[UUID, tuple[int, str]]:
}
+async def upsert_interval_schedule(
+ client: Client,
+ *,
+ schedule_id: str,
+ workflow_name: str,
+ workflow_id: str,
+ inputs: BaseModel,
+ interval: dt.timedelta,
+ execution_timeout: dt.timedelta,
+) -> None:
+ """Create or update a singleton interval schedule with SKIP overlap; first creation triggers immediately."""
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ workflow_name,
+ inputs,
+ id=workflow_id,
+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,
+ execution_timeout=execution_timeout,
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=interval)]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=interval),
+ )
+ if await a_schedule_exists(client, schedule_id):
+ await a_update_schedule(client, schedule_id, schedule)
+ else:
+ await a_create_schedule(client, schedule_id, schedule, trigger_immediately=True)
+
+
async def a_upsert_scanner_schedule(scanner_id: UUID, team_id: int) -> None:
"""Reflect current scanner state in Temporal: upsert when enabled, delete otherwise."""
fingerprint = await database_sync_to_async(_load_fingerprint)(scanner_id)
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index cd3dc2893134..fccd08cd2c24 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -40,8 +40,12 @@ class _VisionAPITestCase(APIBaseTest):
return_value=True,
)
self.flag_patcher.start()
+ # Scanner saves recompute the volume estimate against ClickHouse; keep CRUD tests off that path.
+ self.refresh_estimate_patcher = patch("products.replay_vision.backend.api.scanners.refresh_scanner_estimate")
+ self.mock_refresh_estimate = self.refresh_estimate_patcher.start()
def tearDown(self) -> None:
+ self.refresh_estimate_patcher.stop()
self.flag_patcher.stop()
super().tearDown()
@@ -579,6 +583,82 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(resp.status_code, 403, resp.json())
+class TestScannerEstimatePersistence(_VisionAPITestCase):
+ def _create_payload(self, **overrides: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "name": "estimate-persistence",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "p"},
+ "model": ScannerModel.GEMINI_3_FLASH,
+ }
+ payload.update(overrides)
+ return payload
+
+ def test_create_refreshes_estimate(self) -> None:
+ resp = self.client.post(self.scanners_url, data=self._create_payload(), format="json")
+ self.assertEqual(resp.status_code, 201, resp.json())
+ self.mock_refresh_estimate.assert_called_once()
+ self.assertEqual(str(self.mock_refresh_estimate.call_args.args[0].id), resp.json()["id"])
+
+ def test_create_succeeds_when_estimate_refresh_fails(self) -> None:
+ self.mock_refresh_estimate.side_effect = RuntimeError("clickhouse down")
+ resp = self.client.post(self.scanners_url, data=self._create_payload(), format="json")
+ self.assertEqual(resp.status_code, 201, resp.json())
+ self.assertIsNone(resp.json()["estimated_monthly_observations"])
+
+ def test_response_exposes_estimated_monthly_observations(self) -> None:
+ scanner = self._create_scanner()
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ estimated_monthly_observations=42, estimated_at=timezone.now()
+ )
+ resp = self.client.get(f"{self.scanners_url}{scanner.id}/")
+ self.assertEqual(resp.json()["estimated_monthly_observations"], 42)
+
+ @parameterized.expand(
+ [
+ ("sampling_rate_change", {"sampling_rate": 0.5}, True),
+ ("query_change", {"query": {"kind": "RecordingsQuery", "operand": "AND"}}, True),
+ ("rename_only", {"name": "renamed"}, False),
+ ("sampling_rate_unchanged", {"sampling_rate": 1.0}, False),
+ ("disable", {"enabled": False}, False),
+ ]
+ )
+ def test_update_refreshes_only_on_volume_affecting_changes(
+ self, _name: str, body: dict[str, Any], expect_refresh: bool
+ ) -> None:
+ scanner = self._create_scanner(sampling_rate=1.0)
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ estimated_monthly_observations=10, estimated_at=timezone.now()
+ )
+ self.mock_refresh_estimate.reset_mock()
+
+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data=body, format="json")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(self.mock_refresh_estimate.called, expect_refresh)
+
+ def test_reenabling_refreshes_a_stale_estimate(self) -> None:
+ scanner = self._create_scanner(enabled=False)
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ estimated_monthly_observations=10, estimated_at=timezone.now() - timedelta(days=30)
+ )
+ self.mock_refresh_estimate.reset_mock()
+
+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"enabled": True}, format="json")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.mock_refresh_estimate.assert_called_once()
+
+ def test_update_backfills_a_never_computed_estimate(self) -> None:
+ scanner = self._create_scanner()
+ self.mock_refresh_estimate.reset_mock()
+
+ resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"name": "renamed"}, format="json")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.mock_refresh_estimate.assert_called_once()
+
+
class TestReplayScannerViewSetFeatureFlag(APIBaseTest):
@property
def scanners_url(self) -> str:
diff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.py
new file mode 100644
index 000000000000..e1031bc7ffc4
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py
@@ -0,0 +1,325 @@
+import uuid
+import datetime as dt
+from typing import Any
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
+
+from posthog.models import Organization, Team
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.queries import (
+ ScannerVolumeEstimate,
+ project_monthly_observations,
+ refresh_scanner_estimate,
+)
+from products.replay_vision.backend.temporal.activities.list_stale_scanner_estimates import (
+ list_stale_scanner_estimates_activity,
+)
+from products.replay_vision.backend.temporal.activities.refresh_scanner_estimate import (
+ refresh_scanner_estimate_activity,
+)
+from products.replay_vision.backend.temporal.constants import ESTIMATES_SCHEDULE_ID
+from products.replay_vision.backend.temporal.estimates import (
+ RefreshScannerEstimatesWorkflow,
+ create_replay_vision_estimates_schedule,
+)
+from products.replay_vision.backend.temporal.estimates_types import (
+ RefreshScannerEstimateInputs,
+ RefreshScannerEstimatesInputs,
+ RefreshScannerEstimatesResult,
+)
+
+_ACTIVITY_HELPER = (
+ "products.replay_vision.backend.temporal.activities.refresh_scanner_estimate.refresh_scanner_estimate"
+)
+_ESTIMATE_QUERY = "products.replay_vision.backend.queries.scanner_volume_estimate.estimate_scanner_session_volume"
+
+
+def _make_scanner(**overrides: Any) -> ReplayScanner:
+ org = Organization.objects.create(name="vision-estimate-test-org")
+ team = Team.objects.create(organization=org, name="vision-estimate-test-team")
+ defaults: dict[str, Any] = {
+ "team": team,
+ "name": "estimate-scanner",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "p"},
+ "model": ScannerModel.GEMINI_3_FLASH,
+ }
+ defaults.update(overrides)
+ return ReplayScanner.objects.create(**defaults)
+
+
+def _set_estimate(scanner: ReplayScanner, value: int, hours_ago: float) -> None:
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ estimated_monthly_observations=value,
+ estimated_at=timezone.now() - dt.timedelta(hours=hours_ago),
+ )
+
+
+ "matched, window_days, sampling_rate, expected",
+ [
+ (60, 30, 1.0, 60),
+ (60, 30, 0.5, 30),
+ (0, 30, 1.0, 0),
+ (10, 1, 0.5, 150),
+ (45, 30, 0.2, 9),
+ ],
+)
+def test_project_monthly_observations(matched: int, window_days: int, sampling_rate: float, expected: int) -> None:
+ estimate = ScannerVolumeEstimate(matched_sessions=matched, effective_window_days=window_days)
+ assert project_monthly_observations(estimate, sampling_rate) == expected
+
+
[email protected]_db(transaction=True)
+class TestRefreshScannerEstimate:
+ def test_persists_projection_and_timestamp(self) -> None:
+ scanner = _make_scanner(sampling_rate=0.5)
+ with patch(
+ _ESTIMATE_QUERY,
+ return_value=ScannerVolumeEstimate(matched_sessions=60, effective_window_days=30),
+ ):
+ refresh_scanner_estimate(scanner)
+
+ scanner.refresh_from_db()
+ assert scanner.estimated_monthly_observations == 30
+ assert scanner.estimated_at is not None
+
+ def test_raises_and_leaves_fields_untouched_when_the_estimate_query_errors(self) -> None:
+ scanner = _make_scanner()
+ with patch(_ESTIMATE_QUERY, side_effect=RuntimeError("clickhouse down")):
+ with pytest.raises(RuntimeError, match="clickhouse down"):
+ refresh_scanner_estimate(scanner)
+
+ scanner.refresh_from_db()
+ assert scanner.estimated_monthly_observations is None
+ assert scanner.estimated_at is None
+
+ def test_does_not_bump_scanner_version(self) -> None:
+ scanner = _make_scanner()
+ original_version = scanner.scanner_version
+ with patch(
+ _ESTIMATE_QUERY,
+ return_value=ScannerVolumeEstimate(matched_sessions=1, effective_window_days=30),
+ ):
+ refresh_scanner_estimate(scanner)
+
+ scanner.refresh_from_db()
+ assert scanner.scanner_version == original_version
+
+ def test_discards_result_when_config_changed_mid_flight(self) -> None:
+ scanner = _make_scanner(sampling_rate=1.0)
+
+ def edit_then_estimate(**_: Any) -> ScannerVolumeEstimate:
+ ReplayScanner.objects.filter(pk=scanner.pk).update(sampling_rate=0.5)
+ return ScannerVolumeEstimate(matched_sessions=60, effective_window_days=30)
+
+ with patch(_ESTIMATE_QUERY, side_effect=edit_then_estimate):
+ refresh_scanner_estimate(scanner)
+
+ scanner.refresh_from_db()
+ # The estimate was computed against the pre-edit config, so the filtered write must not land.
+ assert scanner.estimated_monthly_observations is None
+ assert scanner.estimated_at is None
+
+
[email protected]_db(transaction=True)
+class TestEstimateInvalidationOnSave:
+ @pytest.mark.parametrize(
+ "field, value, expect_stale",
+ [
+ ("sampling_rate", 0.25, True),
+ ("query", {"kind": "RecordingsQuery", "operand": "AND"}, True),
+ ("name", "renamed", False),
+ ("scanner_config", {"prompt": "new prompt"}, False), # version-tracked but not a volume input
+ ],
+ )
+ def test_volume_input_changes_clear_estimated_at(self, field: str, value: Any, expect_stale: bool) -> None:
+ scanner = _make_scanner()
+ _set_estimate(scanner, 10, hours_ago=1)
+ scanner.refresh_from_db()
+
+ setattr(scanner, field, value)
+ scanner.save()
+
+ scanner.refresh_from_db()
+ assert (scanner.estimated_at is None) == expect_stale
+ # The last computed value sticks around until the refresher recomputes it.
+ assert scanner.estimated_monthly_observations == 10
+
+ @pytest.mark.parametrize(
+ "initial_enabled, new_enabled, expect_stale",
+ [
+ (False, True, True), # re-enable resurfaces the estimate in the quota sum → refresh needed
+ (True, False, False), # disabling keeps the last estimate for display
+ (True, True, False), # no transition
+ ],
+ )
+ def test_enabled_transitions(self, initial_enabled: bool, new_enabled: bool, expect_stale: bool) -> None:
+ scanner = _make_scanner(enabled=initial_enabled)
+ _set_estimate(scanner, 10, hours_ago=1)
+ scanner.refresh_from_db()
+
+ scanner.enabled = new_enabled
+ scanner.save(update_fields=["enabled"])
+
+ scanner.refresh_from_db()
+ assert (scanner.estimated_at is None) == expect_stale
+
+
[email protected]_db(transaction=True)
+class TestRefreshScannerEstimateActivity:
+ @pytest.mark.parametrize(
+ "enabled, estimated_hours_ago, expect_refresh",
+ [
+ (True, None, True), # never computed → refresh
+ (True, 25, True), # stale → refresh
+ (True, 1, False), # fresh → no-op
+ (False, 25, False), # disabled → no-op
+ ],
+ )
+ def test_gates_on_enabled_and_staleness(
+ self, enabled: bool, estimated_hours_ago: int | None, expect_refresh: bool
+ ) -> None:
+ scanner = _make_scanner(enabled=enabled)
+ if estimated_hours_ago is not None:
+ _set_estimate(scanner, 10, hours_ago=estimated_hours_ago)
+
+ with patch(_ACTIVITY_HELPER) as mock_refresh:
+ refreshed = refresh_scanner_estimate_activity(
+ RefreshScannerEstimateInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert refreshed == expect_refresh
+ assert mock_refresh.called == expect_refresh
+
+ def test_noop_when_scanner_missing(self) -> None:
+ with patch(_ACTIVITY_HELPER) as mock_refresh:
+ refreshed = refresh_scanner_estimate_activity(
+ RefreshScannerEstimateInputs(scanner_id=uuid.uuid4(), team_id=999)
+ )
+ assert refreshed is False
+ mock_refresh.assert_not_called()
+
+ def test_propagates_helper_errors(self) -> None:
+ scanner = _make_scanner()
+ with patch(_ACTIVITY_HELPER, side_effect=RuntimeError("boom")):
+ with pytest.raises(RuntimeError, match="boom"):
+ refresh_scanner_estimate_activity(
+ RefreshScannerEstimateInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+
[email protected]_db(transaction=True)
+class TestListStaleScannerEstimatesActivity:
+ def test_returns_stale_enabled_scanners_oldest_first(self) -> None:
+ never = _make_scanner(name="never-estimated")
+ stale = _make_scanner(name="stale")
+ _set_estimate(stale, 10, hours_ago=48)
+ very_stale = _make_scanner(name="very-stale")
+ _set_estimate(very_stale, 10, hours_ago=72)
+ fresh = _make_scanner(name="fresh")
+ _set_estimate(fresh, 10, hours_ago=1)
+ disabled = _make_scanner(name="disabled", enabled=False)
+ _set_estimate(disabled, 10, hours_ago=48)
+
+ entries = list_stale_scanner_estimates_activity()
+
+ assert [e.scanner_id for e in entries] == [never.id, very_stale.id, stale.id]
+ assert entries[0].team_id == never.team_id
+
+ def test_caps_the_batch(self) -> None:
+ for i in range(3):
+ _make_scanner(name=f"stale-{i}")
+ with patch(
+ "products.replay_vision.backend.temporal.activities.list_stale_scanner_estimates.ESTIMATES_MAX_PER_RUN",
+ 2,
+ ):
+ entries = list_stale_scanner_estimates_activity()
+ assert len(entries) == 2
+
+
+# RefreshScannerEstimatesWorkflow (mocked-Temporal)
+
+
+def _stale(*scanner_ids: uuid.UUID) -> list[RefreshScannerEstimateInputs]:
+ return [RefreshScannerEstimateInputs(scanner_id=sid, team_id=i + 1) for i, sid in enumerate(scanner_ids)]
+
+
+async def _run_estimates(
+ stale: list[RefreshScannerEstimateInputs], failing: set[uuid.UUID] | None = None
+) -> tuple[RefreshScannerEstimatesResult, list[uuid.UUID]]:
+ refreshed: list[uuid.UUID] = []
+
+ async def execute_activity(activity_fn: Any, activity_input: Any = None, **_: Any) -> Any:
+ if activity_fn is list_stale_scanner_estimates_activity:
+ return stale
+ assert activity_fn is refresh_scanner_estimate_activity
+ if activity_input.scanner_id in (failing or set()):
+ raise RuntimeError(f"refresh boom for {activity_input.scanner_id}")
+ refreshed.append(activity_input.scanner_id)
+ return True
+
+ with (
+ patch("temporalio.workflow.execute_activity", side_effect=execute_activity),
+ patch("temporalio.workflow.logger", MagicMock()),
+ ):
+ result = await RefreshScannerEstimatesWorkflow().run(RefreshScannerEstimatesInputs())
+ return result, refreshed
+
+
+async def test_workflow_skips_when_nothing_is_stale() -> None:
+ result, refreshed = await _run_estimates([])
+ assert result == RefreshScannerEstimatesResult()
+ assert refreshed == []
+
+
+async def test_workflow_refreshes_each_stale_scanner() -> None:
+ sid_a, sid_b = uuid.uuid4(), uuid.uuid4()
+ result, refreshed = await _run_estimates(_stale(sid_a, sid_b))
+ assert set(result.refreshed) == {sid_a, sid_b}
+ assert result.failed == []
+ assert set(refreshed) == {sid_a, sid_b}
+
+
+async def test_workflow_isolates_per_scanner_failures() -> None:
+ sid_ok, sid_fail = uuid.uuid4(), uuid.uuid4()
+ result, _ = await _run_estimates(_stale(sid_ok, sid_fail), failing={sid_fail})
+ assert result.refreshed == [sid_ok]
+ assert result.failed == [sid_fail]
+
+
+async def test_workflow_raises_when_all_refreshes_fail() -> None:
+ sid_a, sid_b = uuid.uuid4(), uuid.uuid4()
+ with pytest.raises(ApplicationError):
+ await _run_estimates(_stale(sid_a, sid_b), failing={sid_a, sid_b})
+
+
+def test_refresh_estimates_parse_inputs() -> None:
+ assert RefreshScannerEstimatesWorkflow.parse_inputs([]) == RefreshScannerEstimatesInputs()
+
+
[email protected]([("missing", False, "create"), ("present", True, "update")])
+async def test_create_estimates_schedule_routes_by_existence(_name: str, exists: bool, expected: str) -> None:
+ schedule_mod = "products.replay_vision.backend.temporal.schedule"
+ with (
+ patch(f"{schedule_mod}.a_schedule_exists", AsyncMock(return_value=exists)),
+ patch(f"{schedule_mod}.a_create_schedule", AsyncMock()) as create,
+ patch(f"{schedule_mod}.a_update_schedule", AsyncMock()) as update,
+ ):
+ await create_replay_vision_estimates_schedule(AsyncMock())
+ called, skipped = (create, update) if expected == "create" else (update, create)
+ called.assert_awaited_once()
+ skipped.assert_not_awaited()
+ assert called.call_args.args[1] == ESTIMATES_SCHEDULE_ID
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index 84556314a711..691f933d8af5 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -150,6 +150,42 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
assert snapshot.remaining == 0
+class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
+ def _make_scanner(self, *, team: Team, name: str, enabled: bool = True, estimate: int | None = None) -> None:
+ scanner = ReplayScanner.objects.create(
+ team=team,
+ name=name,
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ enabled=enabled,
+ )
+ if estimate is not None:
+ ReplayScanner.objects.filter(pk=scanner.pk).update(
+ estimated_monthly_observations=estimate, estimated_at=timezone.now()
+ )
+
+ def test_sums_enabled_scanners_across_org_teams(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="second-team")
+ self._make_scanner(team=self.team, name="a", estimate=100)
+ self._make_scanner(team=other_team, name="b", estimate=250)
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.projected_monthly_observations == 350
+
+ def test_disabled_and_unestimated_scanners_contribute_zero(self) -> None:
+ self._make_scanner(team=self.team, name="disabled", enabled=False, estimate=500)
+ self._make_scanner(team=self.team, name="unestimated", estimate=None)
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.projected_monthly_observations == 0
+
+ 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")
+ self._make_scanner(team=other_team, name="other", estimate=999)
+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ assert snapshot.projected_monthly_observations == 0
+
+
class TestQuotaGrants(_VisionQuotaTestCase):
def test_active_grant_adds_to_monthly_quota(self) -> None:
ReplayQuotaGrant.objects.create(
@@ -263,9 +299,17 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):
assert body["usage_this_month"] == 0
assert body["remaining"] == MONTHLY_OBSERVATION_QUOTA
assert body["exhausted"] is False
+ assert body["projected_monthly_observations"] == 0
assert "period_start" in body
assert "period_end" in body
+ def test_returns_fleet_projection(self) -> None:
+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(
+ estimated_monthly_observations=120, estimated_at=timezone.now()
+ )
+ resp = self.client.get(self.quota_url)
+ assert resp.json()["projected_monthly_observations"] == 120
+
def test_reflects_recent_succeeded_observations(self) -> None:
for _ in range(3):
self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.py
index e5643faadcd1..2f95d9755237 100644
--- a/products/replay_vision/backend/tests/test_reconciler.py
+++ b/products/replay_vision/backend/tests/test_reconciler.py
@@ -360,7 +360,7 @@ def test_reconcile_parse_inputs() -> None:
@pytest.mark.asyncio
@parameterized.expand([("missing", False, "create"), ("present", True, "update")])
async def test_create_reconciler_schedule_routes_by_existence(_name: str, exists: bool, expected: str) -> None:
- schedule_mod = "posthog.temporal.common.schedule"
+ schedule_mod = "products.replay_vision.backend.temporal.schedule"
with (
patch(f"{schedule_mod}.a_schedule_exists", AsyncMock(return_value=exists)),
patch(f"{schedule_mod}.a_create_schedule", AsyncMock()) as create,
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 4c3a97187478..e8d2b4ad1666 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -280,6 +280,7 @@ class TestCreateObservationActivity:
usage_this_month=1,
period_start=dt.datetime.now(dt.UTC),
period_end=dt.datetime.now(dt.UTC),
+ projected_monthly_observations=0,
)
result = create_observation_activity(
CreateObservationInputs(
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index ab8f50ab5540..be5b35bd44ee 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -226,6 +226,8 @@ export interface VisionQuotaApi {
readonly period_start: string
/** First moment of the next quota period (UTC); the current period's exclusive upper bound. */
readonly period_end: string
+ /** Sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
+ readonly projected_monthly_observations: number
}
export interface ReplayScannerApi {
@@ -269,6 +271,11 @@ export interface ReplayScannerApi {
emits_signals?: boolean
/** Increments on every config-changing save. Observations snapshot this value. */
readonly scanner_version: number
+ /**
+ * Latest projected observations/month for this scanner. Null until first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_observations: number | null
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at: string
readonly created_at: string
@@ -327,6 +334,11 @@ export interface PatchedReplayScannerApi {
emits_signals?: boolean
/** Increments on every config-changing save. Observations snapshot this value. */
readonly scanner_version?: number
+ /**
+ * Latest projected observations/month for this scanner. Null until first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_observations?: number | null
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at?: string
readonly created_at?: string
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index e430144072f8..8af2c561be2b 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -92,6 +92,7 @@ const quota: VisionQuotaApi = {
usage_this_month: 2400,
remaining: 7600,
exhausted: false,
+ projected_monthly_observations: 5200,
period_start: '2026-05-01T00:00:00Z',
period_end: '2026-06-01T00:00:00Z',
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
index 71244a072d0f..dc414237fa9a 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
@@ -32,19 +32,11 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
const used = quota?.usage_this_month ?? 0
const cap = quota?.monthly_quota ?? 0
- // Always include the scanner's projection — on edit we slightly double-count the scanner's existing
- // contribution to `usage_this_month`, but that's a small over-report. Missing an over-cap config
- // (e.g., 15 obs/month projected against a 10 cap) is the bigger UX hazard.
- const projection = projectQuota(quota, projected)
- const {
- status,
- capReachDate,
- projectionConfident,
- projectedPeriodEndRatio,
- resetsOn,
- daysRemaining,
- combinedDailyRate,
- } = projection
+ // The fleet sum already contains this scanner's stored estimate when it's enabled, so only the
+ // delta between the proposed config and that stored contribution is added on top.
+ const storedContribution = scanner.enabled ? (scanner.estimated_monthly_observations ?? 0) : 0
+ const projection = projectQuota(quota, projected !== null ? projected - storedContribution : 0)
+ const { status, capReachDate, projectedPeriodEndRatio, resetsOn, daysRemaining, combinedDailyRate } = projection
const effectiveStatus: QuotaStatus = projected === null ? 'safe' : status
const styles = STATUS_STYLES[effectiveStatus]
@@ -71,7 +63,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
const renderStatusLine = (): JSX.Element | string => {
if (effectiveStatus === 'danger') {
- if (capReachDate && projectionConfident) {
+ if (capReachDate) {
return (
<span className="text-danger">
You'll run out of observations on <strong>{capReachDate.format('MMMM D')}</strong> at this rate.
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
index c009063000b3..04824039fa8a 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
@@ -113,6 +113,12 @@ export function VisionMetrics(): JSX.Element {
<div>
Used this month: <strong>{quota.usage_this_month.toLocaleString()}</strong>
</div>
+ <div>
+ Projected from enabled scanners:{' '}
+ <strong>
+ ~{quota.projected_monthly_observations.toLocaleString()}/month
+ </strong>
+ </div>
<div>
Monthly quota: <strong>{quota.monthly_quota.toLocaleString()}</strong>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 8eac2f9edba9..6d1614feab68 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -20,6 +20,7 @@ import {
} from '../generated/api'
import type { EstimateResponseApi, ObservationStatsApi, ReplayObservationApi } from '../generated/api.schemas'
import { scheduleObservationPoll } from '../logics/observationPolling'
+import { visionQuotaLogic } from '../logics/visionQuotaLogic'
import type { replayScannerLogicType } from './replayScannerLogicType'
import { findScannerTemplate, newScanner } from './scannerTemplates'
import {
@@ -632,7 +633,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// and rapid filter edits don't fire one request per tick.
setScannerValue: () => actions.requestScannerEstimate(),
setScannerValues: () => actions.requestScannerEstimate(),
- submitScannerSuccess: () => actions.requestScannerEstimate(),
+ submitScannerSuccess: () => {
+ actions.requestScannerEstimate()
+ // Saving recomputes the persisted estimate, which shifts the org-wide fleet sum.
+ visionQuotaLogic.findMounted()?.actions.loadQuota()
+ },
requestScannerEstimate: () => {
cache.disposables.add(() => {
@@ -707,6 +712,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
try {
await visionScannersPartialUpdate(String(teamId), props.id, { enabled: next })
actions.toggleEnabledSuccess(next)
+ visionQuotaLogic.findMounted()?.actions.loadQuota()
} catch (error: any) {
actions.setScannerValue('enabled', !next)
const verb = next ? 'enable' : 'disable'
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
index 9bd63610d00a..616487ca8d91 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
@@ -15,6 +15,7 @@ import {
visionScannersStatsRetrieve,
} from '../generated/api'
import type { ScannerStatsResponseApi, UserBasicApi, VisionScannersListParams } from '../generated/api.schemas'
+import { visionQuotaLogic } from '../logics/visionQuotaLogic'
import type { replayScannersLogicType } from './replayScannersLogicType'
import {
ENABLED_OPTIONS,
@@ -322,14 +323,16 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
}
},
- // Refetch after any mutation so the page + creator dropdown + team-wide stats stay accurate.
+ // Refetch after any mutation so the page + creator dropdown + team-wide stats + quota meter stay accurate.
deleteScannerSuccess: () => {
actions.loadScanners()
actions.loadCreators()
actions.loadScannerStats()
+ visionQuotaLogic.findMounted()?.actions.loadQuota()
},
toggleScannerEnabledDone: () => {
actions.loadScannerStats()
+ visionQuotaLogic.findMounted()?.actions.loadQuota()
},
toggleScannerEnabled: async ({ id }) => {
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index 40cf52f04725..abba2fbf872a 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -196,6 +196,7 @@ export interface BaseReplayScanner {
model: string
emits_signals: boolean
scanner_version: number
+ estimated_monthly_observations?: number | null
last_swept_at: string
created_at: string
updated_at: string
diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.ts
index 0a18de74a9f4..133ade0be048 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts
@@ -10,6 +10,7 @@ function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaApi {
usage_this_month: 0,
remaining: 10_000,
exhausted: false,
+ projected_monthly_observations: 0,
period_start: now.subtract(10, 'day').toISOString(),
period_end: now.add(20, 'day').toISOString(),
...overrides,
@@ -22,48 +23,56 @@ describe('projectQuota', () => {
expect(projectQuota(makeQuota({ monthly_quota: 0 }))).toMatchObject({ status: 'safe', combinedDailyRate: 0 })
})
- it('safe when current burn projects well under the cap', () => {
- const proj = projectQuota(makeQuota({ usage_this_month: 1_000, remaining: 9_000 }))
+ it('safe when the fleet rate projects well under the cap', () => {
+ // 3,000/month fleet → 100/day → ends at 3,000 of 10,000.
+ const proj = projectQuota(makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }))
expect(proj.status).toBe('safe')
expect(proj.projectedPeriodEndRatio).toBeLessThan(QUOTA_WARN_THRESHOLD)
})
- it('warning when projection crosses the warn threshold but stays under cap', () => {
- // 3,000 used over 10 days → 300/day. Projected to end at 9,000 (90% of cap) without exhausting.
- const proj = projectQuota(makeQuota({ usage_this_month: 3_000, remaining: 7_000 }))
+ it('zero fleet rate projects flat usage to period end', () => {
+ const proj = projectQuota(makeQuota({ usage_this_month: 4_000 }))
+ expect(proj.combinedDailyRate).toBe(0)
+ expect(proj.projectedPeriodEndRatio).toBeCloseTo(0.4)
+ expect(proj.capReachDate).toBeNull()
+ })
+
+ it('warning when the fleet projection crosses the warn threshold but stays under cap', () => {
+ // 3,000 used + 9,000/month fleet → 300/day × 20 days → ends at 9,000 (90% of cap).
+ const proj = projectQuota(makeQuota({ usage_this_month: 3_000, projected_monthly_observations: 9_000 }))
expect(proj.status).toBe('warning')
expect(proj.projectedPeriodEndRatio).toBeGreaterThanOrEqual(QUOTA_WARN_THRESHOLD)
expect(proj.capReachInPeriod).toBe(false)
})
it('danger when projected to exhaust before period end', () => {
- const proj = projectQuota(makeQuota({ usage_this_month: 9_000, remaining: 1_000 }))
+ // 9,000 used + 100/day → cap reached in 10 days, 20 days left in the period.
+ const proj = projectQuota(makeQuota({ usage_this_month: 9_000, projected_monthly_observations: 3_000 }))
expect(proj.status).toBe('danger')
expect(proj.capReachInPeriod).toBe(true)
expect(proj.capReachDate).not.toBeNull()
})
- it('danger when explicitly exhausted regardless of historical burn', () => {
+ it('danger when explicitly exhausted regardless of the fleet rate', () => {
const proj = projectQuota(makeQuota({ usage_this_month: 10_000, remaining: 0, exhausted: true }))
expect(proj.status).toBe('danger')
})
- it('projection is unconfident before 3 days have elapsed', () => {
- const now = dayjs()
- const proj = projectQuota(
- makeQuota({
- period_start: now.subtract(1, 'day').toISOString(),
- period_end: now.add(29, 'day').toISOString(),
- })
+ it('a positive scanner delta raises the projection on top of the fleet sum', () => {
+ const base = projectQuota(makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }))
+ const withDelta = projectQuota(
+ makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }),
+ 6_000
)
- expect(proj.projectionConfident).toBe(false)
+ expect(withDelta.combinedDailyRate).toBeGreaterThan(base.combinedDailyRate)
+ expect(withDelta.projectedPeriodEndRatio).toBeGreaterThan(base.projectedPeriodEndRatio)
})
- it('adds scanner projected monthly on top of historical burn', () => {
- const noScanner = projectQuota(makeQuota({ usage_this_month: 1_000, remaining: 9_000 }))
- const withScanner = projectQuota(makeQuota({ usage_this_month: 1_000, remaining: 9_000 }), 6_000)
- expect(withScanner.combinedDailyRate).toBeGreaterThan(noScanner.combinedDailyRate)
- expect(withScanner.projectedPeriodEndRatio).toBeGreaterThan(noScanner.projectedPeriodEndRatio)
+ it('a negative scanner delta lowers the projection and clamps at zero', () => {
+ const lowered = projectQuota(makeQuota({ projected_monthly_observations: 3_000 }), -1_000)
+ expect(lowered.combinedDailyRate).toBeCloseTo(2_000 / 30)
+ const clamped = projectQuota(makeQuota({ projected_monthly_observations: 3_000 }), -9_000)
+ expect(clamped.combinedDailyRate).toBe(0)
})
})
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
index f5d5e07e43bd..f813e2abb90a 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -4,15 +4,12 @@ import type { VisionQuotaApi } from '../generated/api.schemas'
export const QUOTA_WARN_THRESHOLD = 0.85
-const MIN_DAYS_FOR_PROJECTED_DATE = 3
-
export type QuotaStatus = 'safe' | 'warning' | 'danger'
export interface QuotaProjection {
status: QuotaStatus
capReachDate: dayjs.Dayjs | null
capReachInPeriod: boolean
- projectionConfident: boolean
projectedPeriodEndRatio: number
resetsOn: string | null
daysRemaining: number
@@ -23,17 +20,18 @@ const EMPTY: QuotaProjection = {
status: 'safe',
capReachDate: null,
capReachInPeriod: false,
- projectionConfident: false,
projectedPeriodEndRatio: 0,
resetsOn: null,
daysRemaining: 0,
combinedDailyRate: 0,
}
-export function projectQuota(
- quota: VisionQuotaApi | null,
- scannerProjectedMonthly: number | null = null
-): QuotaProjection {
+/**
+ * Project quota usage to period end from the enabled fleet's summed per-scanner estimates.
+ * `scannerProjectedMonthlyDelta` adjusts the fleet sum for a scanner being edited:
+ * its proposed monthly estimate minus the stored contribution already in the sum.
+ */
+export function projectQuota(quota: VisionQuotaApi | null, scannerProjectedMonthlyDelta: number = 0): QuotaProjection {
if (!quota || quota.monthly_quota <= 0) {
return EMPTY
}
@@ -43,14 +41,11 @@ export function projectQuota(
const periodStart = quota.period_start ? dayjs(quota.period_start) : null
const periodEnd = quota.period_end ? dayjs(quota.period_end) : null
const periodLengthDays = periodStart && periodEnd ? Math.max(periodEnd.diff(periodStart, 'day', true), 1) : 30
- const daysElapsed = periodStart ? Math.max(now.diff(periodStart, 'day', true), 0) : 0
const daysRemaining = periodEnd ? Math.max(periodEnd.diff(now, 'day', true), 0) : 0
const resetsOn = periodEnd ? periodEnd.format('MMMM D') : null
- const projectionConfident = daysElapsed >= MIN_DAYS_FOR_PROJECTED_DATE
- const historicalDailyBurn = daysElapsed > 0 ? used / daysElapsed : 0
- const scannerDailyRate = scannerProjectedMonthly !== null ? scannerProjectedMonthly / periodLengthDays : 0
- const combinedDailyRate = historicalDailyBurn + scannerDailyRate
+ const projectedMonthly = Math.max(quota.projected_monthly_observations + scannerProjectedMonthlyDelta, 0)
+ const combinedDailyRate = projectedMonthly / periodLengthDays
const projectedPeriodEndRatio = (used + combinedDailyRate * daysRemaining) / cap
const capReachDate = combinedDailyRate > 0 && used < cap ? now.add((cap - used) / combinedDailyRate, 'day') : null
@@ -67,7 +62,6 @@ export function projectQuota(
status,
capReachDate,
capReachInPeriod,
- projectionConfident,
projectedPeriodEndRatio,
resetsOn,
daysRemaining,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5d77eb40f910..ad3988e8f053 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26074,6 +26074,11 @@ export namespace Schemas {
emits_signals?: boolean;
/** Increments on every config-changing save. Observations snapshot this value. */
readonly scanner_version: number;
+ /**
+ * Latest projected observations/month for this scanner. Null until first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_observations: number | null;
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at: string;
readonly created_at: string;
@@ -32801,6 +32806,11 @@ export namespace Schemas {
emits_signals?: boolean;
/** Increments on every config-changing save. Observations snapshot this value. */
readonly scanner_version?: number;
+ /**
+ * Latest projected observations/month for this scanner. Null until first computed.
+ * @nullable
+ */
+ readonly estimated_monthly_observations?: number | null;
/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
readonly last_swept_at?: string;
readonly created_at?: string;
@@ -42244,6 +42254,8 @@ export namespace Schemas {
readonly period_start: string;
/** First moment of the next quota period (UTC); the current period's exclusive upper bound. */
readonly period_end: string;
+ /** Sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
+ readonly projected_monthly_observations: number;
}
/**