: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): admin-grantable bonus observation quota (#62090)
Tue Haulund9e5aaebb0c82
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 4c58c413b6d7..a4443ea9f595 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -568,6 +568,7 @@ rules:|Plugin|Project|ProxyRecord+ |ReplayQuotaGrant|Role|RoleExternalReference|RoleMembership@@ -634,6 +635,7 @@ rules:|Plugin|Project|ProxyRecord+ |ReplayQuotaGrant|Role|RoleExternalReference|RoleMembershipdiff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.pyindex 4bdac7a6faa3..2f5817f27bd2 100644--- a/products/replay_vision/backend/admin.py+++ b/products/replay_vision/backend/admin.py@@ -1,7 +1,11 @@+from datetime import UTC, datetime+from typing import Any+from django.contrib import adminfrom django.http import HttpRequest-from products.replay_vision.backend.models import ReplayObservation, ReplayScanner+from products.replay_vision.backend.models import ReplayObservation, ReplayQuotaGrant, ReplayScanner+from products.replay_vision.backend.quota import next_month_start@admin.register(ReplayScanner)@@ -37,3 +41,19 @@ class ReplayObservationAdmin(admin.ModelAdmin):def has_add_permission(self, request: HttpRequest) -> bool:# Created by workflow/consumer, never via admin.return False++[email protected](ReplayQuotaGrant)+class ReplayQuotaGrantAdmin(admin.ModelAdmin):+ list_display = ("organization", "amount", "granted_at", "expires_at", "granted_by", "reason")+ list_filter = ("granted_at", "expires_at")+ search_fields = ("organization__name", "reason")+ raw_id_fields = ("organization", "granted_by")+ readonly_fields = ("id", "granted_at")++ def get_changeform_initial_data(self, request: HttpRequest) -> dict[str, Any]:+ initial: dict[str, Any] = super().get_changeform_initial_data(request)+ # Pre-fill but don't force — admins can clear either field on the add form.+ initial.setdefault("expires_at", next_month_start(datetime.now(UTC)).isoformat())+ initial.setdefault("granted_by", str(request.user.pk))+ return initialdiff --git a/products/replay_vision/backend/migrations/0012_replayquotagrant.py b/products/replay_vision/backend/migrations/0012_replayquotagrant.pynew file mode 100644index 000000000000..caffe09b68d7--- /dev/null+++ b/products/replay_vision/backend/migrations/0012_replayquotagrant.py@@ -0,0 +1,86 @@+# Generated by Django 5.2.14 on 2026-06-08 09:03++import django.core.validators+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1213_filesystemfolderinstructions"),+ ("replay_vision", "0011_backfill_monitor_verdict"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="ReplayQuotaGrant",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "amount",+ models.PositiveIntegerField(+ help_text="Extra observations granted on top of the base monthly quota (1–1,000,000).",+ validators=[+ django.core.validators.MinValueValidator(1),+ django.core.validators.MaxValueValidator(1000000),+ ],+ ),+ ),+ (+ "expires_at",+ models.DateTimeField(+ help_text="Grant is valid up to but not including this timestamp. Defaults to the start of next month."+ ),+ ),+ ("granted_at", models.DateTimeField(auto_now_add=True)),+ (+ "reason",+ models.TextField(+ blank=True,+ default="",+ help_text="Free-form note explaining why the bonus was granted.",+ ),+ ),+ (+ "granted_by",+ models.ForeignKey(+ blank=True,+ help_text="Staff user who granted this bonus.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="replay_quota_grants",+ to="posthog.organization",+ ),+ ),+ ],+ options={+ "ordering": ["-granted_at"],+ "indexes": [+ models.Index(+ fields=["organization", "expires_at"],+ name="replay_visi_organiz_e1d489_idx",+ )+ ],+ },+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 4e8137b7f7b4..928fab1e1ad2 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0011_backfill_monitor_verdict+0012_replayquotagrantdiff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.pyindex c5505936bd28..0e64f93e98f5 100644--- a/products/replay_vision/backend/models/__init__.py+++ b/products/replay_vision/backend/models/__init__.py@@ -1,4 +1,5 @@from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrantfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner-__all__ = ["ReplayScanner", "ReplayObservation"]+__all__ = ["ReplayObservation", "ReplayQuotaGrant", "ReplayScanner"]diff --git a/products/replay_vision/backend/models/replay_quota_grant.py b/products/replay_vision/backend/models/replay_quota_grant.pynew file mode 100644index 000000000000..2a79ae824b9b--- /dev/null+++ b/products/replay_vision/backend/models/replay_quota_grant.py@@ -0,0 +1,59 @@+from django.core.exceptions import ValidationError+from django.core.validators import MaxValueValidator, MinValueValidator+from django.db import models+from django.utils import timezone++from posthog.models.utils import UUIDModel++# Generous upper bound — catches admin typos (5000 vs 5000000) without rejecting any plausible grant.+MAX_GRANT_AMOUNT = 1_000_000+++class ReplayQuotaGrant(UUIDModel):+ """Bonus observation budget for an organization, valid until `expires_at`.++ Active grants are summed into the organization's effective `monthly_quota` — see+ `products.replay_vision.backend.quota.compute_quota_snapshot`. At and after `expires_at`, grants stop counting.+ """++ organization = models.ForeignKey(+ "posthog.Organization",+ on_delete=models.CASCADE,+ related_name="replay_quota_grants",+ )+ amount = models.PositiveIntegerField(+ validators=[MinValueValidator(1), MaxValueValidator(MAX_GRANT_AMOUNT)],+ help_text=f"Extra observations granted on top of the base monthly quota (1–{MAX_GRANT_AMOUNT:,}).",+ )+ expires_at = models.DateTimeField(+ help_text="Grant is valid up to but not including this timestamp. Defaults to the start of next month.",+ )+ granted_at = models.DateTimeField(auto_now_add=True)+ granted_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ help_text="Staff user who granted this bonus.",+ )+ reason = models.TextField(+ blank=True,+ default="",+ help_text="Free-form note explaining why the bonus was granted.",+ )++ class Meta:+ ordering = ["-granted_at"]+ indexes = [+ # Active-grant lookup: filter by organization, then by `expires_at > now`.+ models.Index(fields=["organization", "expires_at"]),+ ]++ def __str__(self) -> str:+ return f"+{self.amount} for {self.organization_id}"++ def clean(self) -> None:+ super().clean()+ if self.expires_at and self.expires_at <= timezone.now():+ raise ValidationError({"expires_at": "Expiry must be in the future."})diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex bbca59ea7465..cf1d04020c3e 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -2,11 +2,15 @@ from dataclasses import dataclassfrom datetime import UTC, datetimefrom uuid import UUID+from django.db.models import Sum, Value+from django.db.models.functions import Coalesce+from dateutil.relativedelta import relativedeltafrom posthog.date_util import start_of_monthfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation+from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrantMONTHLY_OBSERVATION_QUOTA = 3000@@ -30,21 +34,31 @@ class QuotaSnapshot:return self.usage_this_month >= self.monthly_quota-def _current_month_bounds() -> tuple[datetime, datetime]:- period_start = start_of_month(datetime.now(UTC))- return period_start, period_start + relativedelta(months=1)+def next_month_start(now: datetime) -> datetime:+ """First moment (UTC) of the calendar month following the month containing `now`."""+ return start_of_month(now) + relativedelta(months=1)+++def _current_month_bounds(now: datetime) -> tuple[datetime, datetime]:+ return start_of_month(now), next_month_start(now)def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:- period_start, period_end = _current_month_bounds()+ # 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(team__organization_id=organization_id,status__in=_COUNTED_STATUSES,created_at__gte=period_start,created_at__lt=period_end,).count()+ bonus = ReplayQuotaGrant.objects.filter(+ organization_id=organization_id,+ expires_at__gt=now,+ ).aggregate(total=Coalesce(Sum("amount"), Value(0)))["total"]return QuotaSnapshot(- monthly_quota=MONTHLY_OBSERVATION_QUOTA,+ monthly_quota=MONTHLY_OBSERVATION_QUOTA + bonus,usage_this_month=usage,period_start=period_start,period_end=period_end,diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.pyindex 2cd6e9e0e82e..6e875a64753d 100644--- a/products/replay_vision/backend/tests/test_quota.py+++ b/products/replay_vision/backend/tests/test_quota.py@@ -3,6 +3,7 @@ from datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.core.exceptions import ValidationErrorfrom django.utils import timezonefrom parameterized import parameterized@@ -14,6 +15,7 @@ from products.replay_vision.backend.models.replay_observation import (ObservationTrigger,ReplayObservation,)+from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrantfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.quota import MONTHLY_OBSERVATION_QUOTA, compute_quota_snapshotfrom products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for@@ -148,6 +150,80 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):assert snapshot.remaining == 0+class TestQuotaGrants(_VisionQuotaTestCase):+ def test_active_grant_adds_to_monthly_quota(self) -> None:+ ReplayQuotaGrant.objects.create(+ organization=self.organization,+ amount=500,+ expires_at=timezone.now() + timedelta(days=10),+ )+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA + 500++ def test_multiple_active_grants_stack(self) -> None:+ for amount in (100, 200, 700):+ ReplayQuotaGrant.objects.create(+ organization=self.organization,+ amount=amount,+ expires_at=timezone.now() + timedelta(days=10),+ )+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA + 1000++ def test_expired_grant_does_not_count(self) -> None:+ grant = ReplayQuotaGrant(+ organization=self.organization,+ amount=500,+ expires_at=timezone.now() - timedelta(seconds=1),+ )+ grant.save() # bypass full_clean — simulate the case where a grant has aged past its expiry+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA++ def test_other_orgs_grants_not_counted(self) -> None:+ other_org = Organization.objects.create(name="other-grant-org")+ ReplayQuotaGrant.objects.create(+ organization=other_org,+ amount=500,+ expires_at=timezone.now() + timedelta(days=10),+ )+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.monthly_quota == MONTHLY_OBSERVATION_QUOTA++ @parameterized.expand(+ [+ ("past_expires_at", 500, timedelta(seconds=-1), "expires_at"),+ ("amount_zero", 0, timedelta(days=10), "amount"),+ ("amount_above_cap", 10_000_000, timedelta(days=10), "amount"),+ ]+ )+ def test_full_clean_rejects(self, _name: str, amount: int, expires_offset: timedelta, expected_field: str) -> None:+ # timezone.now() resolves inside the test body so we don't freeze it at import time.+ grant = ReplayQuotaGrant(+ organization=self.organization,+ amount=amount,+ expires_at=timezone.now() + expires_offset,+ )+ with self.assertRaises(ValidationError) as cm:+ grant.full_clean()+ assert expected_field in cm.exception.message_dict++ def test_grant_pushes_exhaustion_back(self) -> None:+ with patch("products.replay_vision.backend.quota.MONTHLY_OBSERVATION_QUOTA", 2):+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ assert compute_quota_snapshot(organization_id=self.organization.id).exhausted is True++ ReplayQuotaGrant.objects.create(+ organization=self.organization,+ amount=1,+ expires_at=timezone.now() + timedelta(days=10),+ )+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.exhausted is False+ assert snapshot.remaining == 1++class TestVisionQuotaEndpoint(_VisionQuotaTestCase):@propertydef quota_url(self) -> str: