: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): org-level credit limit override (#81738)
Tue Haulund25d2e1898864
diff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex b38651a5e576..f3dae5ebb16a 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -64,7 +64,7 @@ The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` a- `backend/api/` — DRF viewsets and serializers (scanners, observations, backfills, prompt suggestions, quota, vision actions, stats, live progress over SSE).- `backend/queries/` — ClickHouse candidate selection (watermark + settle window + eligibility + sampling), the backfill's bounded descending walk and its exact count, and volume estimates.- `backend/temporal/` — the apply workflow and its activities, per-scanner sweep, per-backfill tick, schedule reconciler (+ observation and backfill-schedule reapers), estimate refresher, prompt evaluation, vision actions, and the Gemini file cleanup sweep.-- `backend/quota.py` + `backend/billing.py` — credit accounting: the per-model price table, the receipt ledger, and the quota snapshot the meter reads.+- `backend/quota.py` + `backend/billing.py` — credit accounting: the per-model price table, the receipt ledger, the quota snapshot the meter reads, and the per-org credit-limit override described below.- `backend/enqueue_claims.py` — atomic slot claims that keep on-demand scans inside the in-flight caps.- `backend/embeddings.py` — the embedding identity shared by the write and search sides.- `backend/prompt_suggestions.py` + `backend/proposers/` — rating-driven prompt rewrites, one proposer per scanner type. `backend/prompt_evaluation.py` re-runs a suggestion against rated sessions before it's applied, and `backend/feedback_themes.py` clusters written thumbs-down feedback.@@ -76,3 +76,26 @@ The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` a- `backend/admin.py` — Django admin registrations.- `backend/temporal/vision_actions/` + `backend/api/vision_actions.py` — scheduled follow-up actions over observations: group summaries and alerts, including the built-in daily digest.- `frontend/` — kea-first scenes and logics for the scanner management UI; `frontend/generated/` carries the generated API types.++## Per-org credit limit override++`REPLAY_VISION_ORG_CREDIT_LIMIT_OVERRIDES` caps monthly credit spend for named organizations, on top+of whatever billing reports. It exists for organizations on unlimited plans, where billing correctly+syncs no limit but spend still needs a ceiling — our own internal org being the case it was built for.++The value is a JSON object of organization id to monthly credit cap:++```json+{ "01234567-89ab-cdef-0123-456789abcdef": 500000 }+```++- The tighter of billing's limit and the override wins, so it can only ever reduce credits.+- Every gate and spend surface reads it, because they all resolve through `quota_state`. An org at its+ override behaves exactly like an org at a billing limit: observations stop, and the quota UI and the+ cost preview both price against what is left.+- Keys are normalized through `UUID`, so uppercase or unhyphenated ids still match the org they name.+- Values clamp at zero, and booleans are rejected. A malformed entry is dropped on its own and logged;+ the rest of the map still applies. Unparseable JSON yields no overrides rather than failing startup.+- Applied org ids are logged at startup, so a cap that silently failed to match is visible.++Changing it takes a deploy, since it is read once at import.diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex fde6cd5f8113..3363e1654554 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -1,3 +1,4 @@+import jsonfrom collections import Counterfrom dataclasses import dataclass, replacefrom datetime import UTC, datetime@@ -33,6 +34,46 @@ logger = structlog.get_logger(__name__)# free-tier org; self-hosted deployments raise it via the env var.MONTHLY_CREDIT_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_CREDIT_QUOTA", FREE_TIER_MONTHLY_CREDITS, type_cast=int)++def _parse_org_credit_limit_overrides(raw: str) -> dict[str, int]:+ """JSON org-id -> monthly credit cap; malformed config fails toward no override, never toward a crash.++ Keys are normalized through `UUID`, so an id written in uppercase or without hyphens still caps the+ org it names. Matching the raw string would leave the cap silently unapplied, which is the state+ this setting exists to prevent. A bad entry is dropped on its own rather than voiding the rest.+ """+ try:+ parsed = json.loads(raw)+ if not isinstance(parsed, dict):+ raise ValueError(f"expected an object, got {type(parsed).__name__}")+ except (ValueError, TypeError):+ logger.exception("replay_vision.malformed_org_credit_limit_overrides")+ return {}++ overrides: dict[str, int] = {}+ for org_id, limit in parsed.items():+ try:+ key = str(UUID(str(org_id)))+ # `int(True)` is 1, which would cap an org at a single credit. Billing's own limit parser+ # rejects bools for the same reason.+ if isinstance(limit, bool):+ raise ValueError(f"credit limit must be a number, got {limit!r}")+ # A negative cap would read as "already over", so the worst a typo can do is block the org.+ overrides[key] = max(0, int(limit))+ except (ValueError, TypeError):+ logger.exception("replay_vision.invalid_org_credit_limit_override", org_id=str(org_id))+ if overrides:+ logger.info("replay_vision.org_credit_limit_overrides_applied", org_ids=sorted(overrides))+ return overrides+++# Per-org monthly credit caps applied on top of billing's limit (the tighter one wins). For internal+# orgs on unlimited plans, where billing correctly syncs no limit but dogfooding spend still needs a+# ceiling. Enforcement and every spend surface treat it exactly like a billing limit.+ORG_CREDIT_LIMIT_OVERRIDES: dict[str, int] = get_from_env(+ "REPLAY_VISION_ORG_CREDIT_LIMIT_OVERRIDES", {}, type_cast=_parse_org_credit_limit_overrides+)+# Billing's usage_key for this product; see ee/billing/quota_limiting.QuotaResource.REPLAY_VISION_CREDITS.USAGE_KEY = "replay_vision_credits"@@ -403,6 +444,11 @@ def quota_state(organization_id: UUID) -> QuotaState:synced, credit_limit = _billing_synced_limit(organization)if not synced:credit_limit = MONTHLY_CREDIT_QUOTA+ # The tighter of billing's limit and the override, so a config mistake can only reduce credits;+ # this is how an internal org on an unlimited plan still gets a spend ceiling.+ override = ORG_CREDIT_LIMIT_OVERRIDES.get(str(organization_id))+ if override is not None:+ credit_limit = override if credit_limit is None else min(credit_limit, override)return QuotaState(credit_limit=credit_limit,credits_used=usage,diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.pyindex 53613c70136f..153da5d55b4a 100644--- a/products/replay_vision/backend/tests/test_quota.py+++ b/products/replay_vision/backend/tests/test_quota.py@@ -1,3 +1,4 @@+import uuidfrom datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTest@@ -25,12 +26,15 @@ from products.replay_vision.backend.quota import (MONTHLY_CREDIT_QUOTA,BillingPeriod,ScannerBudget,+ _parse_org_credit_limit_overrides,compute_quota_snapshot,compute_scanner_budget,compute_scanner_budgets,)from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for+_ORG_ID = "01234567-89ab-cdef-0123-456789abcdef"+class _VisionQuotaTestCase(APIBaseTest):def setUp(self) -> None:@@ -606,6 +610,58 @@ class TestBillingSyncedQuota(_VisionQuotaTestCase):snapshot = compute_quota_snapshot(organization_id=self.organization.id)assert snapshot.credit_limit == expected_quota+ @parameterized.expand(+ [+ # An unlimited plan (billing syncs no limit) gets the override as its cap.+ ("caps_an_uncapped_org", {"replay_vision_credits": {"limit": None, "usage": 0}}, 500, 500),+ ("tighter_override_wins", {"replay_vision_credits": {"limit": 42, "usage": 0}}, 10, 10),+ # The override can only reduce credits; a looser value never overrides billing.+ ("looser_override_ignored", {"replay_vision_credits": {"limit": 42, "usage": 0}}, 9000, 42),+ ]+ )+ def test_org_credit_limit_override(self, _name: str, usage: dict, override: int, expected_quota: int) -> None:+ self.organization.usage = usage+ self.organization.save()+ with patch.dict(+ "products.replay_vision.backend.quota.ORG_CREDIT_LIMIT_OVERRIDES",+ {str(self.organization.id): override},+ ):+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.credit_limit == expected_quota++ def test_override_for_another_org_changes_nothing(self) -> None:+ self.organization.usage = {"replay_vision_credits": {"limit": None, "usage": 0}}+ self.organization.save()+ with patch.dict(+ "products.replay_vision.backend.quota.ORG_CREDIT_LIMIT_OVERRIDES",+ {str(uuid.uuid4()): 500},+ ):+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ assert snapshot.credit_limit is None++ @parameterized.expand(+ [+ ("canonical_id", '{"01234567-89ab-cdef-0123-456789abcdef": 500000}', {_ORG_ID: 500000}),+ # Written another way, the same org must still be capped rather than silently uncapped.+ ("uppercase_id", '{"01234567-89AB-CDEF-0123-456789ABCDEF": 500000}', {_ORG_ID: 500000}),+ ("unhyphenated_id", '{"0123456789abcdef0123456789abcdef": 500000}', {_ORG_ID: 500000}),+ # A negative cap would read as already over, so a typo blocks the org rather than freeing it.+ ("negative_value_clamped", '{"01234567-89ab-cdef-0123-456789abcdef": -5}', {_ORG_ID: 0}),+ ("not_an_object", "[1, 2]", {}),+ ("non_int_value", '{"01234567-89ab-cdef-0123-456789abcdef": "lots"}', {}),+ ("non_uuid_key", '{"not-an-org": 500000}', {}),+ # int(True) is 1, which would cap the org at a single credit rather than not at all.+ ("boolean_value", '{"01234567-89ab-cdef-0123-456789abcdef": true}', {}),+ ("invalid_json", "{nope", {}),+ ]+ )+ def test_parse_org_credit_limit_overrides(self, _name: str, raw: str, expected: dict) -> None:+ assert _parse_org_credit_limit_overrides(raw) == expected++ def test_one_bad_entry_does_not_void_the_others(self) -> None:+ raw = '{"not-an-org": 1, "01234567-89ab-cdef-0123-456789abcdef": 500000}'+ assert _parse_org_credit_limit_overrides(raw) == {_ORG_ID: 500000}+def test_uncapped_org_is_never_exhausted(self) -> None:self.organization.usage = {"replay_vision_credits": {"limit": None, "usage": 0}}self.organization.save()