: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
fix(wizard): bound gateway mints per account, tighten tier limits (#100469)
Vincent (Wen Yu) Ge5ce0b30ec077
diff --git a/docs/internal/wizard-gateway-mint.md b/docs/internal/wizard-gateway-mint.mdindex 2bb98133d10e..8e1ee40207ee 100644--- a/docs/internal/wizard-gateway-mint.md+++ b/docs/internal/wizard-gateway-mint.md@@ -44,7 +44,8 @@ bounded by the posture's ceiling, then the posture's cap, then`WIZARD_GATEWAY_TOKEN_CAP_USD`. The flat setting applies only when no postureresolved. Every value passes a contract check bounded by `_MAX_CAP_USD`.-Mints are metered per user, per program, per week. The reservation is atomic and+Mints are metered per user, per week — one bucket across every program, so the+tier's count is the hard per-account ceiling. The reservation is atomic andcharged immediately before the mint, so a run refused by an earlier gate spendsnothing, and a failure that proves no token was issued returns the slot.diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 6a1801db7a78..cc7843cec2a5 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -311,6 +311,35 @@ class SetupWizardGatewayTokenTests(APIBaseTest):assert refused.json()["code"] == "throttled"assert mock_mint.call_count == 2+ @override_settings(+ DEBUG=False,+ WIZARD_GATEWAY_TIERS={"new": {"mints_per_week": 2}},+ WIZARD_GATEWAY_PROGRAM_IDS=["integration", "ai-observability", "events-audit"],+ )+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_the_mint_bucket_is_shared_across_programs(+ self, mock_authentication, mock_flag, mock_mint, mock_authorized+ ):+ """The ceiling is per account, not per program: a second program does not+ get a fresh quota, or the per-account bound would scale with the program count."""+ self._mock_oauth(mock_authentication)++ for program in ("integration", "ai-observability"):+ ok = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": program}, headers={"authorization": "Bearer pha_test"}+ )+ assert ok.status_code == status.HTTP_201_CREATED, ok.content+ refused = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "events-audit"}, headers={"authorization": "Bearer pha_test"}+ )++ assert refused.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert refused.json()["code"] == "throttled"+ assert mock_mint.call_count == 2+@override_settings(DEBUG=False, WIZARD_GATEWAY_TIERS={"new": {"mints_per_week": 2}})@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)diff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex 7083cf1b3e96..725f4b4717e2 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -193,23 +193,26 @@ NO_TIER_LIMITS = WizardTierLimits()# In code so a malformed WIZARD_GATEWAY_TIERS degrades toward the tier the# operator meant, not toward the flat setting, whose cap is wider than all three.+# Caps do not pool across a run's tokens and the mint throttle is one bucket per+# account, so mints_per_week is the hard per-account ceiling: keep the counts+# low, since the weekly window can be spent in a day._TIER_FLOORS: dict[str, WizardTierLimits] = {"new": WizardTierLimits(cap_usd=Decimal("6").quantize(_CAP_QUANTUM),max_cap_usd=Decimal("6").quantize(_CAP_QUANTUM),- mints_per_week=5,+ mints_per_week=3,ttl_seconds=_MAX_TTL_SECONDS,),"active": WizardTierLimits(cap_usd=Decimal("7").quantize(_CAP_QUANTUM),max_cap_usd=Decimal("12").quantize(_CAP_QUANTUM),- mints_per_week=15,+ mints_per_week=6,ttl_seconds=_MAX_TTL_SECONDS,),"paid": WizardTierLimits(cap_usd=Decimal("10").quantize(_CAP_QUANTUM),max_cap_usd=Decimal("12").quantize(_CAP_QUANTUM),- mints_per_week=30,+ mints_per_week=12,ttl_seconds=_MAX_TTL_SECONDS,),}diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 15d12de0026d..3c270b573eaf 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -27,7 +27,6 @@ if TYPE_CHECKING:from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, ProjectSecretAPIKeyAuthenticationfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exception-from posthog.llm.wizard_gateway_token import wizard_product_nodefrom posthog.metrics import LABEL_PATH, LABEL_ROUTE, LABEL_TEAM_IDfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.team.team import Team@@ -1199,7 +1198,15 @@ class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):return Truedef get_cache_key(self, request, view):- """The per-user, per-program bucket identity. Read by the view's reservation."""+ """The per-user bucket identity. Read by the view's reservation.++ Keyed on the user alone, not (user, program): caps do not pool across a+ run's tokens, so a per-program key hands each program its own quota and+ the per-account ceiling becomes the tier times the program count. One+ bucket per account is the only aggregate bound. Spray is unaffected:+ program_unknown is refused before the reservation, so invented names+ never reach this counter.+ """# request.user is anonymous here: the viewset authenticates sessions only and# the bearer is checked in the action body, after throttling. get_ident would# then key on the caller-chosen X-Forwarded-For, so resolve the token and fall@@ -1216,21 +1223,12 @@ class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):ident = f"user:{user.pk}"if ident is None:ident = f"ip:{get_trusted_client_ip(request) or 'unknown'}"- # Bucket per program, on the resolved node rather than the raw field: keying- # on what the caller sent would hand out a fresh quota per invented name.- try:- program = request.data.get("program") if isinstance(request.data, dict) else None- except Exception:- program = None- # One shared bucket for anything unrecognized: a per-name bucket would hand- # out a fresh quota for every invented program, even though each is refused.- ident = f"{ident}|{wizard_product_node(program) or 'unknown-program'}"# nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-stringreturn f"throttle_wizard_gateway_token_{hashlib.sha256(ident.encode()).hexdigest()}"def reserve_wizard_mint(request, view, limit: int | None = None) -> str | None:- """Atomically consume one of this user's weekly mints for this program, or raise.+ """Atomically consume one of this user's weekly mints across all programs, or raise.`limit` replaces the throttle's weekly count; None keeps the configured rate.@@ -1269,7 +1267,7 @@ def reserve_wizard_mint(request, view, limit: int | None = None) -> str | None:capture_exception(e)return Noneif count > (throttle.num_requests if limit is None else limit):- raise exceptions.Throttled(detail="This wizard program has used its weekly run limit. Try again next week.")+ raise exceptions.Throttled(detail="This account has used its weekly wizard run limit. Try again next week.")return counter