: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
chore(replay-vision): reset closed-beta state for launch (#75876)
Tue Haulundb3910ab5e976
diff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.pyindex 06abb2caf5c2..9c35771d44e9 100644--- a/products/replay_vision/backend/admin.py+++ b/products/replay_vision/backend/admin.py@@ -1,17 +1,7 @@-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,- ReplayQuotaGrant,- ReplayScanner,- VisionAction,- VisionActionRun,-)-from products.replay_vision.backend.quota import next_month_start+from products.replay_vision.backend.models import ReplayObservation, ReplayScanner, VisionAction, VisionActionRun@admin.register(ReplayScanner)@@ -51,24 +41,6 @@ class ReplayObservationAdmin(admin.ModelAdmin):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.- # Pass native types (not strings): the admin's SplitDateTimeWidget calls- # `to_current_timezone(value)` on initial, which AttributeErrors on a str.- initial.setdefault("expires_at", next_month_start(datetime.now(UTC)))- initial.setdefault("granted_by", request.user.pk)- return initial--@admin.register(VisionAction)class VisionActionAdmin(admin.ModelAdmin):list_display = (diff --git a/products/replay_vision/backend/migrations/0057_closed_beta_launch_reset.py b/products/replay_vision/backend/migrations/0057_closed_beta_launch_reset.pynew file mode 100644index 000000000000..bf83cbc53443--- /dev/null+++ b/products/replay_vision/backend/migrations/0057_closed_beta_launch_reset.py@@ -0,0 +1,46 @@+from django.conf import settings+from django.db import migrations+from django.utils import timezone++INTERNAL_TEAM_ID = 2 # PostHog's dogfooding team on US Cloud; the id means nothing on other instances.+_BATCH_SIZE = 2000+++def reset_closed_beta_state(apps, schema_editor):+ # Cloud-only: launch pricing doesn't apply to self-hosted instances, so leave their scanners alone.+ deployment = (settings.CLOUD_DEPLOYMENT or "").upper()+ if deployment not in ("US", "EU"):+ return++ ReplayScanner = apps.get_model("replay_vision", "ReplayScanner")+ ReplayObservationUsage = apps.get_model("replay_vision", "ReplayObservationUsage")++ # Cutoff comes first so receipts written mid-migration by still-enabled scanners are never zeroed.+ cutoff = timezone.now()++ # Bulk update skips save() on purpose: no config change means no version bump, and the reconciler tears down schedules for disabled scanners.+ scanners = ReplayScanner.objects.filter(enabled=True)+ if deployment == "US":+ scanners = scanners.exclude(team_id=INTERNAL_TEAM_ID)+ scanners.update(enabled=False)++ # Zeroed receipts make the quota meter, usage reports, and quota limiting all read 0.+ while True:+ chunk = list(+ ReplayObservationUsage.objects.filter(credits__gt=0, created_at__lt=cutoff).values_list("pk", flat=True)[+ :_BATCH_SIZE+ ]+ )+ if not chunk:+ break+ ReplayObservationUsage.objects.filter(pk__in=chunk).update(credits=0)+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0056_alter_replayobservation_help_texts"),+ ]++ operations = [+ migrations.RunPython(reset_closed_beta_state, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/replay_vision/backend/migrations/0058_delete_replayquotagrant.py b/products/replay_vision/backend/migrations/0058_delete_replayquotagrant.pynew file mode 100644index 000000000000..8dc36ae13fa4--- /dev/null+++ b/products/replay_vision/backend/migrations/0058_delete_replayquotagrant.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.14 on 2026-07-31 08:42++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0057_closed_beta_launch_reset"),+ ]++ # State-only delete per the safe-migrations table-drop pattern; the table is dropped in a later migration.+ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.DeleteModel(+ name="ReplayQuotaGrant",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex fde6cd028dfc..557b3b4cb1e5 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0056_alter_replayobservation_help_texts+0058_delete_replayquotagrantdiff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.pyindex 16434f52b453..1093a2814ea5 100644--- a/products/replay_vision/backend/models/__init__.py+++ b/products/replay_vision/backend/models/__init__.py@@ -1,7 +1,6 @@from products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabelfrom products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage-from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrantfrom products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.models.replay_scanner_prompt_suggestion import ReplayScannerPromptSuggestionfrom products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun@@ -10,7 +9,6 @@ __all__ = ["ReplayObservation","ReplayObservationLabel","ReplayObservationUsage",- "ReplayQuotaGrant","ReplayScanner","ReplayScannerPromptSuggestion","VisionAction",diff --git a/products/replay_vision/backend/models/replay_quota_grant.py b/products/replay_vision/backend/models/replay_quota_grant.pydeleted file mode 100644index e2883dfd7b45..000000000000--- a/products/replay_vision/backend/models/replay_quota_grant.py+++ /dev/null@@ -1,59 +0,0 @@-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 credit budget for an organization, valid until `expires_at`.-- Active grants are summed into the organization's effective credit limit; 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 credits granted on top of the base monthly credit limit (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 fde5393e46dc..7e0cb24805d1 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -20,7 +20,6 @@ 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 ReplayQuotaGrantfrom products.replay_vision.backend.models.replay_scanner import ReplayScannerlogger = structlog.get_logger(__name__)@@ -167,7 +166,7 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:# this module — deferring breaks the quota -> prompt_evaluation -> temporal -> quota cycle.from products.replay_vision.backend.prompt_evaluation import in_flight_evaluation_credits # noqa: PLC0415- # Single `now` so the usage window, bonus expiry, and any caller comparisons are computed from one instant.+ # Single `now` so the usage window and any caller comparisons are computed from one instant.now = datetime.now(UTC)organization = Organization.objects.filter(pk=organization_id).only("usage").first()# Billing is the source of truth once synced, falling back to the env cap and calendar months otherwise.@@ -193,16 +192,10 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:in_flight = sum(observation_credits_for_model(model or "") * count for model, count in in_flight_models.items())# Prompt tests have no observation rows. Their unsettled sessions are committed spend too.usage = consumed + in_flight + in_flight_evaluation_credits(organization_id)- bonus = ReplayQuotaGrant.objects.filter(- organization_id=organization_id,- expires_at__gt=now,- ).aggregate(total=Coalesce(Sum("amount"), Value(0)))["total"]projected = sum_enabled_scanner_estimated_credits(organization_id)- synced, base_limit = _billing_synced_limit(organization)+ synced, credit_limit = _billing_synced_limit(organization)if not synced:- base_limit = MONTHLY_CREDIT_QUOTA- # An uncapped synced org stays uncapped: bonuses only extend a real limit.- credit_limit = base_limit + bonus if base_limit is not None else None+ credit_limit = MONTHLY_CREDIT_QUOTAreturn QuotaSnapshot(credit_limit=credit_limit,credits_used=usage,diff --git a/products/replay_vision/backend/tests/test_migration_backfill.py b/products/replay_vision/backend/tests/test_migration_backfill.pyindex 88a0ed5ce678..49140fd246e9 100644--- a/products/replay_vision/backend/tests/test_migration_backfill.py+++ b/products/replay_vision/backend/tests/test_migration_backfill.py@@ -4,8 +4,13 @@ import importlibfrom posthog.test.base import APIBaseTestfrom django.apps import apps+from django.test import override_settingsfrom django.utils import timezone+from parameterized import parameterized++from posthog.models import Team+from products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,@@ -16,6 +21,7 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,m33 = importlib.import_module("products.replay_vision.backend.migrations.0033_backfill_replayobservationusage_team_id")m37 = importlib.import_module("products.replay_vision.backend.migrations.0037_backfill_replayobservationusage_credits")+m56 = importlib.import_module("products.replay_vision.backend.migrations.0057_closed_beta_launch_reset")class TestReceiptBackfillMigrations(APIBaseTest):@@ -65,3 +71,83 @@ class TestReceiptBackfillMigrations(APIBaseTest):orphan.refresh_from_db()assert (live.team_id, live.model, live.credits) == (self.team.id, "gemini-3.1-flash-lite-preview", 2)assert (orphan.team_id, orphan.model, orphan.credits) == (None, None, 5)+++class TestClosedBetaLaunchReset(APIBaseTest):+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_us_disables_scanners_except_internal_and_zeroes_receipts(self) -> None:+ internal_team = (+ self.team+ if self.team.id == m56.INTERNAL_TEAM_ID+ else Team.objects.create(id=m56.INTERNAL_TEAM_ID, organization=self.organization, name="internal")+ )+ beta_team = Team.objects.create(organization=self.organization, name="beta")+ internal_scanner = ReplayScanner.objects.create(+ team=internal_team,+ name="internal",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ beta_scanner = ReplayScanner.objects.create(+ team=beta_team,+ name="beta",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ receipt = ReplayObservationUsage.objects.create(+ observation_id=uuid.uuid4(),+ organization_id=self.organization.id,+ team_id=beta_team.id,+ observation_created_at=timezone.now(),+ model=ScannerModel.GEMINI_3_6_FLASH,+ credits=15,+ )++ m56.reset_closed_beta_state(apps, None)++ internal_scanner.refresh_from_db()+ beta_scanner.refresh_from_db()+ receipt.refresh_from_db()+ assert internal_scanner.enabled+ assert not beta_scanner.enabled+ assert receipt.credits == 0++ @parameterized.expand(+ [+ ("eu_team_2_not_exempt", "EU", False, 0),+ ("self_hosted_untouched", None, True, 15),+ ]+ )+ def test_reset_outside_us(+ self, _name: str, deployment: str | None, expect_enabled: bool, expect_credits: int+ ) -> None:+ team_2 = (+ self.team+ if self.team.id == m56.INTERNAL_TEAM_ID+ else Team.objects.create(id=m56.INTERNAL_TEAM_ID, organization=self.organization, name="two")+ )+ scanner = ReplayScanner.objects.create(+ team=team_2,+ name="s",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ receipt = ReplayObservationUsage.objects.create(+ observation_id=uuid.uuid4(),+ organization_id=self.organization.id,+ team_id=team_2.id,+ observation_created_at=timezone.now(),+ model=ScannerModel.GEMINI_3_6_FLASH,+ credits=15,+ )++ with override_settings(CLOUD_DEPLOYMENT=deployment):+ m56.reset_closed_beta_state(apps, None)++ scanner.refresh_from_db()+ receipt.refresh_from_db()+ assert scanner.enabled is expect_enabled+ assert receipt.credits == expect_creditsdiff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.pyindex c55ff21d6aa4..ef01b0b0e30d 100644--- a/products/replay_vision/backend/tests/test_quota.py+++ b/products/replay_vision/backend/tests/test_quota.py@@ -3,7 +3,6 @@ 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@@ -18,7 +17,6 @@ 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 ReplayQuotaGrantfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.models.replay_scanner_prompt_suggestion import ReplayScannerPromptSuggestionfrom products.replay_vision.backend.quota import MONTHLY_CREDIT_QUOTA, compute_quota_snapshot@@ -281,14 +279,6 @@ class TestBillingSyncedQuota(_VisionQuotaTestCase):assert snapshot.remaining is Noneassert not snapshot.exhausted- def test_grants_stack_on_billing_limit(self) -> None:- self.organization.usage = {"replay_vision_credits": {"limit": 42, "usage": 0}}- self.organization.save()- ReplayQuotaGrant.objects.create(- organization=self.organization, amount=8, expires_at=timezone.now() + timedelta(days=10)- )- assert compute_quota_snapshot(organization_id=self.organization.id).credit_limit == 50-def test_billing_period_bounds_used_when_current(self) -> None:now = datetime.now(UTC)start = now - timedelta(days=10)@@ -372,106 +362,6 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):assert snapshot.projected_monthly_credits == 0-class TestQuotaGrants(_VisionQuotaTestCase):- def test_active_grant_adds_to_credit_limit(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.credit_limit == MONTHLY_CREDIT_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.credit_limit == MONTHLY_CREDIT_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.credit_limit == MONTHLY_CREDIT_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.credit_limit == MONTHLY_CREDIT_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_CREDIT_QUOTA", 30):- 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 TestReplayQuotaGrantAdmin(_VisionQuotaTestCase):- def test_initial_form_renders(self) -> None:- # Regression: `expires_at` initial must be a datetime, not a str. The admin's- # SplitDateTimeWidget.decompress runs `to_current_timezone` → `is_aware` →- # `value.utcoffset()`, which AttributeErrors on a str and 500s the add page in prod.- # We render the form directly instead of GETting /admin/...add/ because the admin- # URLs are gated on ADMIN_PORTAL_ENABLED, which defaults False in product test env.- from django.contrib import admin as django_admin- from django.test import RequestFactory-- from products.replay_vision.backend.admin import ReplayQuotaGrantAdmin-- self.user.is_staff = True- self.user.save()- request = RequestFactory().get("/admin/replay_vision/replayquotagrant/add/")- request.user = self.user-- grant_admin = ReplayQuotaGrantAdmin(ReplayQuotaGrant, django_admin.site)- form_class = grant_admin.get_form(request)- form = form_class(initial=grant_admin.get_changeform_initial_data(request))- # `as_p()` triggers widget render, which is where the bug fires.- html = form.as_p()- assert 'name="expires_at_0"' in html- assert 'name="granted_by"' in html--class TestVisionQuotaEndpoint(_VisionQuotaTestCase):@propertydef quota_url(self) -> str: