: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(wizard): flag-driven override of gateway token cap and daily mints (#92888)
Brandonaf2971b8c49e
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 1befbbd91fd2..4eb36fddbc24 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -36,6 +36,7 @@ from posthog.llm.wizard_gateway_token import (mint_wizard_gateway_token,wizard_gateway_base_url,wizard_gateway_configured,+ wizard_limit_override,wizard_product_node,)from posthog.models import Team, User@@ -491,15 +492,23 @@ class SetupWizardViewSet(viewsets.ViewSet):# program keeps running on legacy instead of dying. It still cannot mint.WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="program_unknown").inc()raise exceptions.NotFound("Unrecognized wizard program.")+ override = wizard_limit_override(+ distinct_id=distinct_id,+ email=user.email,+ organization_id=str(team.organization_id),+ team_id=team.id,+ )try:- reserved = reserve_wizard_mint(request, self)+ reserved = reserve_wizard_mint(request, self, limit=override.mints_per_day)except exceptions.Throttled:# The reservation raises after check_throttles ran, so the throttled()# hook never sees it.WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="throttled").inc()raisetry:- minted = mint_wizard_gateway_token(obo=str(team.organization_id), user=distinct_id, product=product)+ minted = mint_wizard_gateway_token(+ obo=str(team.organization_id), user=distinct_id, product=product, cap_usd=override.cap_usd+ )except WizardGatewayMintError as e:# An ambiguous failure keeps the slot rather than risk the ceiling.if not e.token_may_exist:diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 61ec3b039e6a..b3115bf827ea 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -1,5 +1,6 @@import jsonfrom datetime import timedelta+from decimal import Decimalimport pytestfrom posthog.test.base import APIBaseTest@@ -670,6 +671,15 @@ class SetupWizardGatewayTokenTests(APIBaseTest):MINTED = {"token": "phe_test_token", "expires_at": "2026-08-22T00:00:00Z", "cap_usd": "50"}+ def setUp(self):+ super().setUp()+ # Keeps the SDK off the network; a test sets a payload to opt in.+ payload_patch = patch(+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload", return_value=None+ )+ self.mock_limit_payload = payload_patch.start()+ self.addCleanup(payload_patch.stop)+def tearDown(self):super().tearDown()cache.clear() # Clears out all DRF throttle data@@ -708,6 +718,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):"obo": str(self.team.organization_id),"user": str(self.user.distinct_id),"product": "wizard:integration",+ "cap_usd": None,}@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@@ -772,6 +783,71 @@ class SetupWizardGatewayTokenTests(APIBaseTest):)assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ @override_settings(DEBUG=False)+ @patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")+ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_limit_override_raises_the_daily_ceiling(+ self, mock_authentication, mock_flag, mock_authorized, mock_mint, mock_key+ ):+ self._mock_oauth(mock_authentication)+ self.mock_limit_payload.return_value = {"mints_per_day": 7}++ for _ in range(7):+ ok = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ assert ok.status_code == status.HTTP_201_CREATED, ok.content+ refused = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert refused.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert mock_mint.call_count == 7++ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_limit_override_cap_reaches_the_mint(self, mock_authentication, mock_flag, mock_authorized, mock_mint):+ self._mock_oauth(mock_authentication)+ self.mock_limit_payload.return_value = json.dumps({"cap_usd": "30"})++ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ assert mock_mint.call_args.kwargs["cap_usd"] == Decimal("30.000000")+ self.mock_limit_payload.assert_called_once_with(+ "wizard-gateway-limit-override",+ str(self.user.distinct_id),+ person_properties={+ "email": self.user.email,+ "organization_id": str(self.team.organization_id),+ "team_id": str(self.team.id),+ },+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )++ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_a_flag_outage_keeps_the_default_limits(self, mock_authentication, mock_flag, mock_authorized, mock_mint):+ self._mock_oauth(mock_authentication)+ self.mock_limit_payload.side_effect = RuntimeError("flags unavailable")++ response = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ assert mock_mint.call_args.kwargs["cap_usd"] is None+def _reserved_counter_value(self, key="refund-test-key"):"""The live value of the reservation counter for a pinned cache key."""import timediff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.pyindex d0aa5caae103..32de29dd7f56 100644--- a/posthog/llm/test_wizard_gateway_token.py+++ b/posthog/llm/test_wizard_gateway_token.py@@ -1,3 +1,5 @@+from decimal import Decimal+import pytestfrom unittest.mock import patch@@ -6,10 +8,14 @@ from django.test import override_settingsimport requestsfrom posthog.llm.wizard_gateway_token import (+ NO_OVERRIDE,WizardGatewayMintError,+ WizardLimitOverride,mint_wizard_gateway_token,+ parse_limit_override,wizard_gateway_base_url,wizard_gateway_configured,+ wizard_limit_override,wizard_product_node,)@@ -202,6 +208,12 @@ class TestMintWizardGatewayToken:mint_wizard_gateway_token(obo="org_1", user="user_1")assert post.call_args.kwargs["json"]["cap_usd"] == "12.500000"+ def test_an_override_cap_replaces_the_setting(self):+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post:+ mint_wizard_gateway_token(obo="org_1", user="user_1", cap_usd=Decimal("30"))+ assert post.call_args.kwargs["json"]["cap_usd"] == "30.000000"+def test_secret_never_appears_in_the_error(self):with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(403)):with pytest.raises(WizardGatewayMintError) as raised:@@ -209,6 +221,71 @@ class TestMintWizardGatewayToken:assert "phs_wizard_secret" not in str(raised.value)+class TestParseLimitOverride:+ @pytest.mark.parametrize(+ "raw,expected",+ [+ (+ {"cap_usd": "30", "mints_per_day": 100},+ WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_day=100),+ ),+ (+ '{"cap_usd": 12.5, "mints_per_day": "50"}',+ WizardLimitOverride(cap_usd=Decimal("12.500000"), mints_per_day=50),+ ),+ ({"mints_per_day": 100}, WizardLimitOverride(cap_usd=None, mints_per_day=100)),+ ({"cap_usd": "lots", "mints_per_day": 100}, WizardLimitOverride(cap_usd=None, mints_per_day=100)),+ (+ {"cap_usd": "30", "mints_per_day": 0},+ WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_day=None),+ ),+ (None, NO_OVERRIDE),+ ("not json", NO_OVERRIDE),+ ([], NO_OVERRIDE),+ ({}, NO_OVERRIDE),+ ],+ )+ def test_payload_is_validated_field_by_field(self, raw, expected):+ assert parse_limit_override(raw) == expected++ @pytest.mark.parametrize("cap", ["0", "-5", "31", "20000", "NaN", "Infinity", "1e100000", "0.0000001", True, None])+ def test_a_cap_outside_the_gateway_contract_is_ignored(self, cap):+ assert parse_limit_override({"cap_usd": cap}) == NO_OVERRIDE++ @pytest.mark.parametrize("mints", [0, -1, 151, 2.5, "2.5", "abc", True, None])+ def test_mints_outside_the_bounds_are_ignored(self, mints):+ assert parse_limit_override({"mints_per_day": mints}) == NO_OVERRIDE+++class TestWizardLimitOverride:+ def test_evaluates_the_flag_for_the_user_org_and_project(self):+ with patch(+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload",+ return_value={"cap_usd": "30"},+ ) as get_payload:+ override = wizard_limit_override(+ distinct_id="d1", email="[email protected]", organization_id="org_1", team_id=7+ )++ assert override == WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_day=None)+ get_payload.assert_called_once_with(+ "wizard-gateway-limit-override",+ "d1",+ person_properties={"email": "[email protected]", "organization_id": "org_1", "team_id": "7"},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )++ def test_a_flag_outage_fails_closed(self):+ with patch(+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload",+ side_effect=RuntimeError("down"),+ ):+ assert (+ wizard_limit_override(distinct_id="d1", email=None, organization_id="org_1", team_id=7) == NO_OVERRIDE+ )++class TestWizardGatewayConfigured:def test_all_four_present(self):with override_settings(**MINT_SETTINGS):diff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex 7580259f0c94..fd0292ae1750 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -10,6 +10,7 @@ products/tasks' sandbox mint (ai_gateway_token.py): the wizard needsattempt fast instead of retrying into the CLI's timeout."""+import jsonfrom decimal import Decimal, InvalidOperationfrom typing import Any@@ -17,8 +18,11 @@ from django.conf import settingsimport requestsimport structlog+import posthoganalyticsfrom prometheus_client import Counter+from posthog.dataclasses import frozen+logger = structlog.get_logger(__name__)_MINT_TIMEOUT_SECONDS = 10@@ -31,14 +35,92 @@ _MINT_TIMEOUT_SECONDS = 10_MIN_TTL_SECONDS = 3600_MAX_TTL_SECONDS = 86400-# The gateway 400s a cap that is non-positive, over 6dp, or above its top-up-# ceiling, so a bad knob falls back locally instead of 503ing every mint.+# A bad knob or payload falls back locally instead of 503ing every mint. The+# cap ceiling is a wizard-run backstop, well under the gateway's own._DEFAULT_CAP_USD = Decimal("20")-_MAX_CAP_USD = Decimal("10000")+_MAX_CAP_USD = Decimal("30")_CAP_QUANTUM = Decimal("0.000001")WIZARD_PRODUCT = "wizard"+# Payload: {"cap_usd": "30", "mints_per_day": 100}. A person flag: email,+# organization_id, and team_id ride as person properties so one flag can target+# engineers by email and candidates by org id.+WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG = "wizard-gateway-limit-override"++# Above this a value only widens a fat-finger; the gateway's mint rate bounds the fleet.+_MAX_MINTS_PER_DAY = 150+++@frozen+class WizardLimitOverride:+ """Limits the override flag grants a user; None keeps the configured default."""++ cap_usd: Decimal | None = None+ mints_per_day: int | None = None+++NO_OVERRIDE = WizardLimitOverride()+++def wizard_limit_override(+ *, distinct_id: str, email: str | None, organization_id: str, team_id: int+) -> WizardLimitOverride:+ """Read the override flag for this mint; a flag outage fails closed to the defaults."""+ try:+ raw = posthoganalytics.get_feature_flag_payload(+ WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG,+ distinct_id,+ person_properties={"email": email or "", "organization_id": organization_id, "team_id": str(team_id)},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception as e:+ logger.warning("wizard_gateway_token: limit override flag unavailable", error=str(e))+ return NO_OVERRIDE+ override = parse_limit_override(raw)+ if override != NO_OVERRIDE:+ logger.info(+ "wizard_gateway_token: limit override applied",+ team_id=team_id,+ cap_usd=str(override.cap_usd),+ mints_per_day=override.mints_per_day,+ )+ return override+++def parse_limit_override(raw: object) -> WizardLimitOverride:+ """Validate field by field so a typo in one value cannot zero the other."""+ if isinstance(raw, str):+ try:+ raw = json.loads(raw)+ except ValueError:+ logger.warning("wizard_gateway_token: limit override payload is not JSON")+ return NO_OVERRIDE+ if not isinstance(raw, dict):+ return NO_OVERRIDE+ cap = _parse_cap(raw["cap_usd"]) if "cap_usd" in raw else None+ if "cap_usd" in raw and cap is None:+ logger.warning("wizard_gateway_token: limit override cap_usd out of contract, ignored", cap=str(raw["cap_usd"]))+ mints = _parse_mints_per_day(raw["mints_per_day"]) if "mints_per_day" in raw else None+ if "mints_per_day" in raw and mints is None:+ logger.warning(+ "wizard_gateway_token: limit override mints_per_day out of contract, ignored",+ mints_per_day=str(raw["mints_per_day"]),+ )+ return WizardLimitOverride(cap_usd=cap, mints_per_day=mints)+++def _parse_mints_per_day(raw: object) -> int | None:+ # bool is an int subclass: True would read as one mint a day.+ if isinstance(raw, bool):+ return None+ if isinstance(raw, str) and raw.strip().isdigit():+ raw = int(raw)+ if not isinstance(raw, int) or raw < 1 or raw > _MAX_MINTS_PER_DAY:+ return None+ return raw+def wizard_product_node(program: str | None) -> str | None:"""The product node to pin for a run, or None when this is not a program@@ -102,14 +184,17 @@ def wizard_gateway_base_url() -> str:return settings.WIZARD_GATEWAY_URL.rstrip("/").removesuffix("/v1")-def mint_wizard_gateway_token(*, obo: str, user: str, product: str = WIZARD_PRODUCT) -> dict[str, Any]:+def mint_wizard_gateway_token(+ *, obo: str, user: str, product: str = WIZARD_PRODUCT, cap_usd: Decimal | None = None+) -> dict[str, Any]:"""Mint one run's token; returns {token, expires_at, cap_usd}. RaisesWizardGatewayMintError on any refusal or transport failure; the bearer never- appears in logs or exception text.+ appears in logs or exception text. `cap_usd`, when set, replaces the+ configured cap and must already be validated."""base_url = wizard_gateway_base_url()body = {- "cap_usd": _cap_usd(),+ "cap_usd": _cap_usd(cap_usd),"ttl_seconds": _ttl_seconds(),"product": product,"obo": obo,@@ -172,28 +257,37 @@ def _ttl_seconds() -> int:return max(_MIN_TTL_SECONDS, min(int(settings.WIZARD_GATEWAY_TOKEN_TTL_SECONDS), _MAX_TTL_SECONDS))-def _cap_usd() -> str:- """The per-token cap as a fixed-point string the gateway accepts. An- unparseable, non-positive, or over-ceiling setting falls back to the default- rather than making every mint a 503.+def _cap_usd(override: Decimal | None) -> str:+ """The cap as a fixed-point string: the override when set, else the setting,+ which falls back to the default rather than 503ing every mint."""+ if override is not None:+ return f"{override.quantize(_CAP_QUANTUM):f}"raw = str(settings.WIZARD_GATEWAY_TOKEN_CAP_USD)- try:- cap = Decimal(raw)- except (InvalidOperation, ValueError):- logger.warning("wizard_gateway_token: cap_usd is not a decimal, using the default", cap=raw)- cap = _DEFAULT_CAP_USD- # Quantize before the range check: a positive value below a microdollar- # rounds to 0.000000, which the gateway rejects as non-positive. Guarded- # because quantize raises once the result needs more digits than the decimal- # context allows, and this function's contract is to fall back, never raise.- if cap.is_finite():- try:- cap = cap.quantize(_CAP_QUANTUM)- except InvalidOperation:- logger.warning("wizard_gateway_token: cap_usd is out of representable range, using the default", cap=raw)- cap = _DEFAULT_CAP_USD.quantize(_CAP_QUANTUM)- if not cap.is_finite() or cap <= 0 or cap > _MAX_CAP_USD:- logger.warning("wizard_gateway_token: cap_usd out of range, using the default", cap=raw)+ cap = _parse_cap(raw)+ if cap is None:+ logger.warning("wizard_gateway_token: cap_usd out of contract, using the default", cap=raw)cap = _DEFAULT_CAP_USD.quantize(_CAP_QUANTUM)return f"{cap:f}"+++def _parse_cap(raw: object) -> Decimal | None:+ """A cap inside the gateway's contract, quantized to 6dp, or None. Quantize+ before the range check (a sub-microdollar value rounds to 0, which the gateway+ rejects) and guard it: quantize raises past the decimal context's precision.+ """+ if isinstance(raw, bool):+ return None+ try:+ cap = Decimal(str(raw))+ except (InvalidOperation, ValueError):+ return None+ if not cap.is_finite():+ return None+ try:+ cap = cap.quantize(_CAP_QUANTUM)+ except InvalidOperation:+ return None+ if cap <= 0 or cap > _MAX_CAP_USD:+ return None+ return capdiff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 58e4a0f00adf..c603c3ab409f 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -1192,9 +1192,11 @@ class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):return f"throttle_wizard_gateway_token_{hashlib.sha256(ident.encode()).hexdigest()}"-def reserve_wizard_mint(request, view) -> str | None:+def reserve_wizard_mint(request, view, limit: int | None = None) -> str | None:"""Atomically consume one of this user's daily mints for this program, or raise.+ `limit` replaces the throttle's daily count; None keeps the configured rate.+Called immediately before the mint, after every gate, so a request refused by agate spends nothing, while parallel requests cannot all slip under the ceilingthe way a read-then-charge throttle lets them. A mint that then fails keeps its@@ -1229,7 +1231,7 @@ def reserve_wizard_mint(request, view) -> str | None:except Exception as e:capture_exception(e)return None- if count > throttle.num_requests:+ if count > (throttle.num_requests if limit is None else limit):raise exceptions.Throttled(detail="This wizard program has used its daily run limit. Try again tomorrow.")return counter