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): say which teams lose scans to quota and consent (#96100)

Arno Hillen3d5091435957
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index be04628b4189..613980ca0428 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal
from uuid import UUID
from django.db import IntegrityError, OperationalError, connection, transaction
@@ -6,24 +6,32 @@ from django.db.models import F
from django.utils import timezone
import psycopg.errors
+import posthoganalytics
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog import redis
+from posthog.event_usage import groups
from posthog.models.organization import OrganizationMembership
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.enqueue_claims import release_enqueue_claim
-from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill
from products.replay_vision.backend.quota import (
BillingPeriod,
+ QuotaState,
ScannerBudget,
compute_scanner_budget,
current_period_bounds,
quota_state,
)
-from products.replay_vision.backend.temporal.constants import ADMISSION_BUDGET_TTL
+from products.replay_vision.backend.temporal.constants import ADMISSION_BUDGET_TTL, replay_vision_distinct_id
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import SCANNER_ADMISSION_BUSY_ERROR_TYPE
from products.replay_vision.backend.temporal.metrics import (
@@ -35,11 +43,57 @@ from products.replay_vision.backend.temporal.metrics import (
from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot, ScannerSnapshot
from products.replay_vision.backend.temporal.types import CreateObservationInputs, CreateObservationOutput
+# One event per scanner and reason per hour. Without a gate, an org past its limit emits one event
+# for every session it refuses, which is its entire scan volume.
+_SCAN_BLOCKED_DEDUP_TTL_SECONDS = 60 * 60
+
def _build_scanner_snapshot(scanner: ReplayScanner) -> dict[str, Any]:
return ScannerSnapshot.from_scanner(scanner).model_dump(mode="json")
+def _capture_scan_blocked(
+ *,
+ scanner: ReplayScanner,
+ reason: Literal["quota", "consent"],
+ triggered_by: ObservationTrigger,
+ quota: QuotaState | None = None,
+) -> None:
+ """Internal cross-customer telemetry for a scan refused before it created a row.
+
+ The Prometheus skip counters carry no team label, so this event is the only per-team record of a
+ refused scan.
+ """
+ dedup_key = f"@posthog/replay-vision/scan-blocked/{reason}/{scanner.pk}"
+ try:
+ # Also the retry gate: an activity retry re-enters this branch and the key is already held.
+ if not redis.get_client().set(dedup_key, b"1", nx=True, ex=_SCAN_BLOCKED_DEDUP_TTL_SECONDS):
+ return
+ posthoganalytics.capture(
+ distinct_id=replay_vision_distinct_id(scanner.team_id),
+ event="replay_vision_scan_blocked",
+ properties={
+ "reason": reason,
+ "scanner_id": str(scanner.pk),
+ "scanner_type": scanner.scanner_type,
+ "triggered_by": str(triggered_by),
+ # None for a reason that has no cap behind it, such as missing consent.
+ "credit_limit": quota.credit_limit if quota else None,
+ "credits_used": quota.credits_used if quota else None,
+ "team_id": scanner.team_id,
+ "organization_id": str(scanner.team.organization_id),
+ },
+ groups=groups(scanner.team.organization, scanner.team),
+ )
+ except Exception:
+ # Fail-soft: the scan is already refused and the caller returns next, so raising here would
+ # retry an activity whose decision cannot change.
+ activity.logger.exception(
+ "replay_vision.scan_blocked_capture_failed",
+ extra={"scanner_id": str(scanner.pk), "reason": reason},
+ )
+
+
@activity.defn
@track_activity()
def create_observation_activity(inputs: CreateObservationInputs) -> CreateObservationOutput:
@@ -189,6 +243,7 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
"Skipping observation: AI data processing not approved for organization",
extra={"scanner_id": str(inputs.scanner_id), "team_id": inputs.team_id, "session_id": inputs.session_id},
)
+ _capture_scan_blocked(scanner=scanner, reason="consent", triggered_by=inputs.triggered_by)
return CreateObservationOutput(
observation_id=None,
was_created=False,
@@ -217,12 +272,14 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
# Deliberately check-then-act: the snapshot doesn't count enqueue claims, so a concurrent burst can
# overshoot by at most the in-flight caps allow, which is accepted.
- if quota_state(scanner.team.organization_id).would_exceed(observation_credits_for_model(priced_model)):
+ quota = quota_state(scanner.team.organization_id)
+ if quota.would_exceed(observation_credits_for_model(priced_model)):
record_quota_exhausted_skip(scanner.scanner_type)
activity.logger.info(
"Skipping observation: monthly quota exhausted",
extra={"scanner_id": str(inputs.scanner_id), "team_id": inputs.team_id, "session_id": inputs.session_id},
)
+ _capture_scan_blocked(scanner=scanner, reason="quota", triggered_by=inputs.triggered_by, quota=quota)
return CreateObservationOutput(
observation_id=None,
was_created=False,
@@ -265,6 +322,8 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
reclaimed_output = _reclaim_own_pending_insert(inputs)
if reclaimed_output is not None:
return reclaimed_output
+ # No blocked event here: this refusal holds the admission row lock, which cannot
+ # wait on a Redis and an analytics round trip.
record_scanner_limit_reached("admission")
activity.logger.info(
"Skipping observation: scanner credit limit reached",
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 7debdc5e64f7..f61e89ae8965 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -505,6 +505,98 @@ class TestCreateObservationActivity:
)
assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-no-consent").exists()
+ @parameterized.expand(
+ [
+ ("quota", 5, 5),
+ ("consent", None, None),
+ ]
+ )
+ def test_blocked_scan_emits_one_event_per_scanner_and_reason(
+ self, reason: str, expected_credit_limit: int | None, expected_credits_used: int | None
+ ) -> None:
+ # A refused scan writes no observation row, so this event is the only thing that can count it.
+ scanner = _make_scanner()
+ sibling = _make_scanner(team=scanner.team, name="sibling")
+ if reason == "consent":
+ org = scanner.team.organization
+ org.is_ai_data_processing_approved = False
+ org.save()
+
+ # Both gates would refuse, so the consent case reporting no credit figures is what proves
+ # consent is checked first.
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.quota_state",
+ return_value=QuotaSnapshot(
+ credit_limit=5,
+ credits_used=5,
+ period_start=dt.datetime.now(dt.UTC),
+ period_end=dt.datetime.now(dt.UTC),
+ projected_monthly_credits=0,
+ ),
+ ),
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.posthoganalytics.capture"
+ ) as capture,
+ ):
+ for session_id in ("sess-a", "sess-b"):
+ assert self._admit(scanner, session_id).was_created is False
+ assert self._admit(sibling, "sess-c").was_created is False
+ # Flip consent so the same scanner is now refused for the other reason, which the dedup
+ # key holds separately.
+ org = scanner.team.organization
+ org.is_ai_data_processing_approved = reason == "consent"
+ org.save()
+ assert self._admit(scanner, "sess-d").was_created is False
+
+ emitted = [
+ (c.kwargs["properties"]["scanner_id"], c.kwargs["properties"]["reason"]) for c in capture.call_args_list
+ ]
+ # Two sessions on one scanner share an event; another scanner, or another reason, reports on
+ # its own.
+ assert emitted == [
+ (str(scanner.id), reason),
+ (str(sibling.id), reason),
+ (str(scanner.id), "quota" if reason == "consent" else "consent"),
+ ]
+ kwargs = capture.call_args_list[0].kwargs
+ assert kwargs["event"] == "replay_vision_scan_blocked"
+ assert kwargs["distinct_id"] == f"replay-vision:{scanner.team_id}"
+ properties = kwargs["properties"]
+ assert properties["reason"] == reason
+ assert properties["scanner_type"] == "monitor"
+ # The enum's value, not its repr: a dashboard filters on the string the event carries.
+ assert properties["triggered_by"] == "schedule"
+ assert properties["credit_limit"] == expected_credit_limit
+ assert properties["credits_used"] == expected_credits_used
+ assert properties["team_id"] == scanner.team_id
+ assert properties["organization_id"] == str(scanner.team.organization_id)
+ assert kwargs["groups"]["project"] == str(scanner.team.uuid)
+
+ def test_blocked_scan_settles_and_stays_quiet_when_the_dedup_store_fails(self) -> None:
+ # The scan is already refused, so a Redis outage must neither fail the activity into a retry
+ # that reaches the same decision, nor emit the per-session flood the dedup gate exists to stop.
+ scanner = _make_scanner()
+ org = scanner.team.organization
+ org.is_ai_data_processing_approved = False
+ org.save()
+
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.redis.get_client",
+ side_effect=RuntimeError("redis unreachable"),
+ ),
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.posthoganalytics.capture"
+ ) as capture,
+ ):
+ result = self._admit(scanner, "sess-redis-down")
+
+ assert result == CreateObservationOutput(
+ observation_id=None, was_created=False, scanner_type=scanner.scanner_type
+ )
+ capture.assert_not_called()
+
@parameterized.expand(
[
(None, 0, True),