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): immutable usage ledger so deletes don't refund quota (#65316)

Tue Haulundb12393b19a5f
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 8c5829898be6..802dc0c55763 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -621,6 +621,7 @@ rules:
|Plugin
|Project
|ProxyRecord
+ |ReplayObservationUsage
|ReplayQuotaGrant
|Role
|RoleExternalReference
@@ -689,6 +690,7 @@ rules:
|Plugin
|Project
|ProxyRecord
+ |ReplayObservationUsage
|ReplayQuotaGrant
|Role
|RoleExternalReference
diff --git a/products/replay_vision/backend/migrations/0017_replayobservationusage.py b/products/replay_vision/backend/migrations/0017_replayobservationusage.py
new file mode 100644
index 000000000000..5ab166a23160
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0017_replayobservationusage.py
@@ -0,0 +1,60 @@
+# Generated by Django 5.2.14 on 2026-06-22 20:05
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1231_duckgresserverteam"),
+ ("replay_vision", "0016_alter_visionaction_selection"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ReplayObservationUsage",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "observation_id",
+ models.UUIDField(
+ help_text="The observation this receipt accounts for (plain id, no FK).",
+ unique=True,
+ ),
+ ),
+ (
+ "observation_created_at",
+ models.DateTimeField(
+ help_text="The observation's created_at; the monthly quota window filters on this."
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "organization",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="replay_observation_usage",
+ to="posthog.organization",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["organization", "observation_created_at"],
+ name="replay_visi_organiz_a84ed4_idx",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0018_backfill_replay_observation_usage.py b/products/replay_vision/backend/migrations/0018_backfill_replay_observation_usage.py
new file mode 100644
index 000000000000..182bb724308b
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0018_backfill_replay_observation_usage.py
@@ -0,0 +1,53 @@
+from datetime import UTC, datetime
+
+from django.db import migrations
+
+from dateutil.relativedelta import relativedelta
+
+from posthog.date_util import start_of_month
+
+_BATCH = 1000
+
+
+def backfill_current_period(apps, schema_editor):
+ """Seed receipts for the current month's already-succeeded observations (idempotent via ignore_conflicts)."""
+ ReplayObservation = apps.get_model("replay_vision", "ReplayObservation")
+ ReplayObservationUsage = apps.get_model("replay_vision", "ReplayObservationUsage")
+
+ now = datetime.now(UTC)
+ period_start = start_of_month(now) # same window helper compute_quota_snapshot reads with
+ period_end = period_start + relativedelta(months=1)
+
+ rows = (
+ ReplayObservation.objects.filter(
+ status="succeeded",
+ created_at__gte=period_start,
+ created_at__lt=period_end,
+ )
+ .values_list("id", "team__organization_id", "created_at")
+ .iterator(chunk_size=_BATCH) # stream the read; the whole succeeded-set could be large across orgs
+ )
+
+ ReplayObservationUsage.objects.bulk_create(
+ (
+ ReplayObservationUsage(
+ observation_id=obs_id,
+ organization_id=org_id,
+ observation_created_at=created_at,
+ created_at=now,
+ )
+ for obs_id, org_id, created_at in rows
+ ),
+ ignore_conflicts=True,
+ batch_size=_BATCH,
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0017_replayobservationusage"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_current_period, migrations.RunPython.noop),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index e6d194dfffc6..4a92f3fe048c 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0016_alter_visionaction_selection
+0018_backfill_replay_observation_usage
diff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.py
index 294c9cfaa815..3d8ee05ee46f 100644
--- a/products/replay_vision/backend/models/__init__.py
+++ b/products/replay_vision/backend/models/__init__.py
@@ -1,6 +1,14 @@
from products.replay_vision.backend.models.replay_observation import ReplayObservation
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun
-__all__ = ["ReplayObservation", "ReplayQuotaGrant", "ReplayScanner", "VisionAction", "VisionActionRun"]
+__all__ = [
+ "ReplayObservation",
+ "ReplayObservationUsage",
+ "ReplayQuotaGrant",
+ "ReplayScanner",
+ "VisionAction",
+ "VisionActionRun",
+]
diff --git a/products/replay_vision/backend/models/replay_observation_usage.py b/products/replay_vision/backend/models/replay_observation_usage.py
new file mode 100644
index 000000000000..5eb4a00db60f
--- /dev/null
+++ b/products/replay_vision/backend/models/replay_observation_usage.py
@@ -0,0 +1,29 @@
+from django.db import models
+
+from posthog.models.utils import UUIDModel
+
+
+class ReplayObservationUsage(UUIDModel):
+ """Immutable per-observation usage receipt — decoupled from the observation row so deletes can't refund spent quota."""
+
+ organization = models.ForeignKey(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ related_name="replay_observation_usage",
+ )
+ observation_id = models.UUIDField(
+ unique=True,
+ help_text="The observation this receipt accounts for (plain id, no FK).",
+ )
+ observation_created_at = models.DateTimeField(
+ help_text="The observation's created_at; the monthly quota window filters on this.",
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["organization", "observation_created_at"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"usage {self.observation_id} ({self.organization_id})"
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index c4148c392017..fc42df484f3c 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -11,13 +11,14 @@ from posthog.date_util import start_of_month
from posthog.settings.utils import get_from_env
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
MONTHLY_OBSERVATION_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_OBSERVATION_QUOTA", 3000, type_cast=int)
-# In-flight rows count against the quota so concurrent on-demand triggers can't all race past the gate before any complete.
-_COUNTED_STATUSES = (ObservationStatus.SUCCEEDED, ObservationStatus.PENDING, ObservationStatus.RUNNING)
+# usage = ledger(succeeded) + live(in-flight); every quota-counting status must belong to exactly one source.
+_IN_FLIGHT_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)
@dataclass(frozen=True)
@@ -51,12 +52,20 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
# Single `now` so the usage window, bonus expiry, and any caller comparisons are computed from one instant.
now = datetime.now(UTC)
period_start, period_end = _current_month_bounds(now)
- usage = ReplayObservation.objects.filter(
+ # Permanently-spent (succeeded) from the immutable ledger; deletes can't refund it.
+ consumed = ReplayObservationUsage.objects.filter(
+ organization_id=organization_id,
+ observation_created_at__gte=period_start,
+ observation_created_at__lt=period_end,
+ ).count()
+ # In-flight rows aren't in the ledger yet (receipt is written on success), so add them live.
+ in_flight = ReplayObservation.objects.filter(
team__organization_id=organization_id,
- status__in=_COUNTED_STATUSES,
+ status__in=_IN_FLIGHT_STATUSES,
created_at__gte=period_start,
created_at__lt=period_end,
).count()
+ usage = consumed + in_flight
bonus = ReplayQuotaGrant.objects.filter(
organization_id=organization_id,
expires_at__gt=now,
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index 3f6ea9479ff7..a557b6afc165 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -1,11 +1,13 @@
from collections.abc import Container
+from django.db import transaction
from django.utils import timezone
import structlog
from temporalio import activity
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import FailureKind, IneligibleSessionKind
from products.replay_vision.backend.temporal.metrics import (
@@ -105,16 +107,26 @@ def mark_observation_ineligible_activity(inputs: MarkObservationIneligibleInputs
@track_activity()
def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs) -> None:
"""Flip pending/running → succeeded and persist the scanner result. Idempotent: SUCCEEDED is not in the source filter."""
- updated = ReplayObservation.objects.filter(
- pk=inputs.observation_id,
- status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],
- ).update(
- status=ObservationStatus.SUCCEEDED,
- completed_at=timezone.now(),
- scanner_result=inputs.scanner_result.model_dump(mode="json"),
- )
- if not updated:
- return # No state transition — retry against an already-terminal row.
+ with transaction.atomic():
+ updated = ReplayObservation.objects.filter(
+ pk=inputs.observation_id,
+ status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],
+ ).update(
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ scanner_result=inputs.scanner_result.model_dump(mode="json"),
+ )
+ if not updated:
+ return # No state transition — retry against an already-terminal row.
+ # Write the usage receipt in the same transaction as the transition so a crash can't undercount.
+ obs = ReplayObservation.objects.values("team__organization_id", "created_at").get(pk=inputs.observation_id)
+ ReplayObservationUsage.objects.get_or_create(
+ observation_id=inputs.observation_id,
+ defaults={
+ "organization_id": obs["team__organization_id"],
+ "observation_created_at": obs["created_at"],
+ },
+ )
REPLAY_VISION_OBSERVATIONS.labels(status="succeeded", scanner_type=inputs.scanner_type).inc()
logger.info(
"replay_vision.observation.succeeded",
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index 691f933d8af5..2d9a6b60cff1 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -15,6 +15,7 @@ from products.replay_vision.backend.models.replay_observation import (
ObservationTrigger,
ReplayObservation,
)
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.quota import MONTHLY_OBSERVATION_QUOTA, compute_quota_snapshot
@@ -60,8 +61,21 @@ class _VisionQuotaTestCase(APIBaseTest):
if created_at is not None:
ReplayObservation.objects.filter(pk=observation.pk).update(created_at=created_at)
observation.refresh_from_db()
+ if status == ObservationStatus.SUCCEEDED:
+ # Mirror production: a succeeded observation has a usage receipt, which is what quota counts.
+ self._make_receipt(observation)
return observation
+ @staticmethod
+ def _make_receipt(observation: ReplayObservation) -> None:
+ ReplayObservationUsage.objects.get_or_create(
+ observation_id=observation.id,
+ defaults={
+ "organization_id": observation.team.organization_id,
+ "observation_created_at": observation.created_at,
+ },
+ )
+
class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
@parameterized.expand(
@@ -125,7 +139,7 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
scanner_config={"prompt": "p"},
model=ScannerModel.GEMINI_3_FLASH,
)
- ReplayObservation.objects.create(
+ other_obs = ReplayObservation.objects.create(
scanner=other_scanner,
team=other_team,
session_id="other-sess",
@@ -134,6 +148,7 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
triggered_by=ObservationTrigger.ON_DEMAND,
completed_at=timezone.now(),
)
+ self._make_receipt(other_obs)
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
assert snapshot.usage_this_month == 0
@@ -149,6 +164,36 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
assert snapshot.exhausted is True
assert snapshot.remaining == 0
+ def test_deleting_scanner_does_not_refund_spent_usage(self) -> None:
+ # Deleting a scanner cascade-deletes its observations, but the usage they spent must not be refunded.
+ for _ in range(3):
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+ assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 3
+
+ self.scanner.delete()
+
+ assert ReplayObservation.objects.filter(team=self.team).count() == 0 # observations cascade-deleted
+ assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 3 # receipts survive
+
+ def test_deleting_observation_does_not_refund_spent_usage(self) -> None:
+ observation = self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())
+ assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+
+ observation.delete() # e.g. the admin recording-delete flow
+
+ assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+
+ def test_no_double_count_across_pending_to_succeeded(self) -> None:
+ observation = self._make_observation(status=ObservationStatus.PENDING)
+ assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1 # counted in-flight
+
+ # The success transition flips status and writes the receipt, so the total stays 1.
+ ReplayObservation.objects.filter(pk=observation.pk).update(
+ status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()
+ )
+ self._make_receipt(observation)
+ assert compute_quota_snapshot(organization_id=self.organization.id).usage_this_month == 1
+
class TestProjectedMonthlyObservations(_VisionQuotaTestCase):
def _make_scanner(self, *, team: Team, name: str, enabled: bool = True, estimate: int | None = None) -> None:
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index edb34a3a84a3..aaa64dc5c57b 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -29,6 +29,7 @@ from products.replay_vision.backend.models.replay_observation import (
ObservationTrigger,
ReplayObservation,
)
+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.quota import QuotaSnapshot
from products.replay_vision.backend.temporal import ApplyScannerWorkflow
@@ -437,6 +438,50 @@ class TestObservationStateActivities:
assert observation.completed_at is not None
assert observation.scanner_result == {} # not overwritten
+ def test_mark_succeeded_writes_usage_receipt(self) -> None:
+ scanner = _make_scanner()
+ observation = _make_observation(scanner, status=ObservationStatus.RUNNING, started_at=timezone.now())
+ result = ScannerResult(model_output=MonitorOutput(verdict="yes", reasoning="ok", confidence=0.9))
+
+ mark_observation_succeeded_activity(
+ MarkObservationSucceededInputs(
+ observation_id=observation.id, scanner_result=result, scanner_type=ScannerType.MONITOR
+ )
+ )
+
+ receipts = ReplayObservationUsage.objects.filter(observation_id=observation.id)
+ assert receipts.count() == 1
+ receipt = receipts.get()
+ assert receipt.organization_id == observation.team.organization_id
+ assert receipt.observation_created_at == observation.created_at
+
+ def test_mark_succeeded_usage_receipt_is_idempotent(self) -> None:
+ scanner = _make_scanner()
+ observation = _make_observation(scanner, status=ObservationStatus.RUNNING, started_at=timezone.now())
+ result = ScannerResult(model_output=MonitorOutput(verdict="yes", reasoning="ok", confidence=0.9))
+ inputs = MarkObservationSucceededInputs(
+ observation_id=observation.id, scanner_result=result, scanner_type=ScannerType.MONITOR
+ )
+
+ mark_observation_succeeded_activity(inputs)
+ mark_observation_succeeded_activity(inputs) # retry: the transition is sticky, so no second receipt
+
+ assert ReplayObservationUsage.objects.filter(observation_id=observation.id).count() == 1
+
+ def test_mark_failed_writes_no_usage_receipt(self) -> None:
+ scanner = _make_scanner()
+ observation = _make_observation(scanner, status=ObservationStatus.RUNNING, started_at=timezone.now())
+
+ mark_observation_failed_activity(
+ MarkObservationFailedInputs(
+ observation_id=observation.id,
+ error_reason="provider_rejected:nope",
+ scanner_type=ScannerType.MONITOR,
+ )
+ )
+
+ assert ReplayObservationUsage.objects.filter(observation_id=observation.id).count() == 0
+
def _counter_value(metric_name: str, **labels: str) -> float:
return REGISTRY.get_sample_value(metric_name, labels) or 0.0