: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): tier the mint cap, daily mints, and TTL by account posture (#96846)
Brandonca5a7e88282e
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 2feb12bab891..88eb3af10bfa 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -36,11 +36,14 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blockedfrom posthog.llm.wizard_gateway_token import (WizardGatewayMintError,+ WizardPosture,mint_wizard_gateway_token,wizard_gateway_base_url,wizard_gateway_configured,wizard_limit_override,+ wizard_posture,wizard_product_node,+ wizard_tier_limits,)from posthog.models import Team, Userfrom posthog.models.project import Project@@ -521,6 +524,7 @@ class SetupWizardViewSet(viewsets.ViewSet):refuse(outcome, exc, user=user)team: Team | None = None+ posture: WizardPosture | None = Noneif not wizard_gateway_configured():refuse_absent_gateway("unconfigured", "The PostHog AI gateway is not configured on this instance.")@@ -561,6 +565,7 @@ class SetupWizardViewSet(viewsets.ViewSet):if team is None:# 403: a vanished team is an authorization failure, not a missing route.refuse("team_missing", exceptions.PermissionDenied(ERROR_PROJECT_NOT_FOUND), user=user)+ posture = wizard_posture(team.organization, team)# Named ahead of the generic authorization check so the CLI can tell the user what to do.if email_verification_pending(user):@@ -615,21 +620,30 @@ class SetupWizardViewSet(viewsets.ViewSet):refuse_absent_gateway("program_unknown", "Unrecognized wizard program. Upgrade with: npx @posthog/wizard@latest", user=user)+ # The override flag outranks the tier; the tier outranks the flat rate.override = wizard_limit_override(distinct_id=distinct_id,email=user.email,organization_id=str(team.organization_id),team_id=team.id,)+ mints_per_week = override.mints_per_week+ if mints_per_week is None:+ mints_per_week = wizard_tier_limits(posture).mints_per_weektry:- reserved = reserve_wizard_mint(request, self, limit=override.mints_per_day)+ reserved = reserve_wizard_mint(request, self, limit=mints_per_week)except exceptions.Throttled as e:# The reservation raises after check_throttles ran, so the throttled()# hook never sees it.refuse("throttled", e, user=user)try:minted = mint_wizard_gateway_token(- obo=str(team.organization_id), user=distinct_id, product=product, cap_usd=override.cap_usd+ obo=str(team.organization_id),+ user=distinct_id,+ product=product,+ cap_usd=override.cap_usd,+ program=program,+ posture=posture,)except WizardGatewayMintError as e:# An ambiguous failure keeps the slot rather than risk the ceiling.diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 47363009de5c..1fd3c274e90e 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -24,11 +24,17 @@ from posthog.api.wizard.http import ()from posthog.cloud_utils import get_api_hostfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL-from posthog.llm.wizard_gateway_token import WizardGatewayMintError+from posthog.llm.wizard_gateway_token import _TIER_FLOORS, WizardGatewayMintErrorfrom posthog.models import Organization, PersonalAPIKey, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import SetupWizardGatewayTokenRateThrottle, refund_wizard_mint, reserve_wizard_mint+# Derived, not written out: these cases assert the ceiling binds, not its value.+# Every floor populates every field; the Optional is there for partial overrides.+_active_mints = _TIER_FLOORS["active"].mints_per_week+assert _active_mints is not None+_ACTIVE_MINTS_PER_WEEK: int = _active_mints+class SetupWizardTests(APIBaseTest):def setUp(self):@@ -763,6 +769,12 @@ class SetupWizardGatewayTokenTests(APIBaseTest):self.mock_blocklist = blocklist_patch.start()self.addCleanup(blocklist_patch.stop)+ def _ordinary_account(self):+ """APIBaseTest's fresh org is the `new` posture, whose weekly ceiling is+ tighter than the one these throttle-accounting cases assume."""+ self.team.ingested_event = True+ self.team.save(update_fields=["ingested_event"])+def tearDown(self):super().tearDown()cache.clear() # Clears out all DRF throttle data@@ -815,8 +827,53 @@ class SetupWizardGatewayTokenTests(APIBaseTest):"user": str(self.user.distinct_id),"product": "wizard:integration","cap_usd": None,+ "program": "integration",+ # The fixture organization is minutes old, unpaid, and has ingested nothing.+ "posture": "new",}+ @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)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_a_new_accounts_third_mint_in_a_day_is_throttled(+ self, mock_authentication, mock_flag, mock_mint, mock_authorized+ ):+ self._mock_oauth(mock_authentication)++ for _ in range(2):+ 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 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)+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_the_override_flag_outranks_the_tier_ceiling(+ self, mock_authentication, mock_flag, mock_mint, mock_authorized+ ):+ self._mock_oauth(mock_authentication)+ self.mock_limit_payload.return_value = {"mints_per_week": 3}++ for _ in range(3):+ 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++ assert mock_mint.call_count == 3+@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=False)@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")@@ -1037,7 +1094,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):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}+ self.mock_limit_payload.return_value = {"mints_per_week": 7}for _ in range(7):ok = self.client.post(@@ -1136,6 +1193,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):That is only safe while a refund is impossible on any path that hands back atoken, so the ceiling has to bind on issued tokens rather than on attempts."""+ self._ordinary_account()self._mock_oauth(mock_authentication)with patch(@@ -1151,20 +1209,20 @@ class SetupWizardGatewayTokenTests(APIBaseTest):assert self._reserved_counter_value() == 0with patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=self.MINTED) as mock_mint:- for _ in range(5):+ for _ in range(_ACTIVE_MINTS_PER_WEEK):ok = self.client.post(self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"})assert ok.status_code == status.HTTP_201_CREATED# The ceiling counts issued tokens, so the 20 refunded failures bought- # nothing: the sixth mint is refused even though 25 requests preceded it.+ # nothing: the next mint is refused on the issued count alone.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 == 5- assert self._reserved_counter_value() == 6+ assert mock_mint.call_count == _ACTIVE_MINTS_PER_WEEK+ assert self._reserved_counter_value() == _ACTIVE_MINTS_PER_WEEK + 1@patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")@patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)@@ -1260,10 +1318,11 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)@patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")def test_a_throttled_mint_is_counted(self, mock_authentication, mock_flag, mock_mint, mock_authorized):+ self._ordinary_account()self._mock_oauth(mock_authentication)before = _gateway_token_outcome("throttled")- for _ in range(5):+ for _ in range(_ACTIVE_MINTS_PER_WEEK):self.client.post(self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"})diff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.pyindex 32de29dd7f56..ce2546fb91f1 100644--- a/posthog/llm/test_wizard_gateway_token.py+++ b/posthog/llm/test_wizard_gateway_token.py@@ -1,23 +1,33 @@+from datetime import timedeltafrom decimal import Decimalimport pytestfrom unittest.mock import patchfrom django.test import override_settings+from django.utils import timezoneimport requestsfrom posthog.llm.wizard_gateway_token import (+ _TIER_FLOORS,NO_OVERRIDE,+ WIZARD_GATEWAY_CONFIG_REJECTS,WizardGatewayMintError,WizardLimitOverride,+ WizardTierLimits,mint_wizard_gateway_token,parse_limit_override,wizard_gateway_base_url,wizard_gateway_configured,wizard_limit_override,+ wizard_posture,wizard_product_node,+ wizard_program_cap,+ wizard_tier_limits,)+from posthog.models.organization import Organization+from posthog.models.team.team import TeamMINT_SETTINGS = {"WIZARD_GATEWAY_URL": "https://ai-gateway.us.posthog.com",@@ -88,7 +98,7 @@ class TestMintWizardGatewayToken: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")- assert post.call_args.kwargs["json"]["ttl_seconds"] == 3600+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 1800@pytest.mark.parametrize("response",@@ -160,7 +170,7 @@ class TestMintWizardGatewayToken:return_value=_Response(201, minted),) as post:mint_wizard_gateway_token(obo="org_1", user="user_1")- assert post.call_args.kwargs["json"]["cap_usd"] == "20.000000"+ assert post.call_args.kwargs["json"]["cap_usd"] == "7.000000"@pytest.mark.parametrize("raised,token_may_exist",@@ -221,23 +231,149 @@ class TestMintWizardGatewayToken:assert "phs_wizard_secret" not in str(raised.value)+def _organization(+ *, age: timedelta = timedelta(days=30), features: list | None = None, subscribed: bool | None = None+) -> Organization:+ # Unsaved: posture reads cached fields only, so no row is needed.+ return Organization(+ name="org",+ created_at=timezone.now() - age,+ available_product_features=features or [],+ has_active_subscription=subscribed,+ )+++class TestWizardPosture:+ def test_a_young_organization_with_no_event_is_new(self):+ assert wizard_posture(_organization(age=timedelta(days=1)), Team(ingested_event=False)) == "new"++ def test_an_ingested_event_makes_it_active_whatever_its_age(self):+ assert wizard_posture(_organization(age=timedelta(days=1)), Team(ingested_event=True)) == "active"++ def test_an_old_organization_with_no_event_is_active(self):+ assert wizard_posture(_organization(age=timedelta(days=8)), Team(ingested_event=False)) == "active"++ def test_a_subscription_outranks_the_rest(self):+ paid = _organization(age=timedelta(days=1), subscribed=True)+ assert wizard_posture(paid, Team(ingested_event=False)) == "paid"++ def test_a_cancelled_organization_keeps_its_features_but_loses_the_paid_tier(self):+ # Billing leaves the feature list populated after a cancellation, so the+ # feature-derived tier would go on handing it the widest limits.+ cancelled = _organization(features=[{"key": "alerts", "name": "Alerts"}], subscribed=False)+ assert wizard_posture(cancelled, Team(ingested_event=True)) == "active"++ def test_an_unsynced_organization_falls_back_to_its_plan_tier(self):+ licensed = _organization(features=[{"key": "alerts", "name": "Alerts"}], subscribed=None)+ assert wizard_posture(licensed, Team(ingested_event=False)) == "paid"+ assert wizard_posture(_organization(subscribed=None), Team(ingested_event=True)) == "active"+++class TestWizardTierLimits:+ @override_settings(WIZARD_GATEWAY_TIERS={"new": {"cap_usd": "5", "mints_per_week": 2, "ttl_seconds": "3600"}})+ def test_a_configured_tier_is_read_field_by_field(self):+ assert wizard_tier_limits("new") == WizardTierLimits(+ cap_usd=Decimal("5.000000"),+ max_cap_usd=_TIER_FLOORS["new"].max_cap_usd,+ mints_per_week=2,+ ttl_seconds=3600,+ )+ assert wizard_tier_limits("paid") == _TIER_FLOORS["paid"]++ @override_settings(WIZARD_GATEWAY_TIERS={"new": {"cap_usd": "5", "max_cap_usd": "3"}})+ def test_a_ceiling_under_its_own_cap_is_ignored(self):+ # Honouring it would let a program entry tighten the cap rather than size it.+ limits = wizard_tier_limits("new")+ assert limits.cap_usd == Decimal("5.000000")+ assert limits.max_cap_usd == _TIER_FLOORS["new"].max_cap_usd++ @pytest.mark.parametrize(+ "tiers",+ [+ {"new": "lots"},+ # A non-dict entry that would satisfy `"cap_usd" in raw`.+ {"new": ["cap_usd", "mints_per_week", "ttl_seconds"]},+ {"new": {"cap_usd": "999", "mints_per_week": 0, "ttl_seconds": True}},+ {"new": {"cap_usd": "NaN", "mints_per_week": "two", "ttl_seconds": -1}},+ [],+ "not a dict",+ ],+ )+ def test_an_out_of_contract_tier_degrades_to_its_own_floor(self, tiers):+ with override_settings(WIZARD_GATEWAY_TIERS=tiers):+ assert wizard_tier_limits("new") == _TIER_FLOORS["new"]++ @override_settings(WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM={"self-driving": "6", "broken": "lots"})+ def test_a_program_cap_is_read_by_program_id(self):+ assert wizard_program_cap("self-driving") == Decimal("6.000000")+ assert wizard_program_cap("broken") is None+ assert wizard_program_cap("integration") is None+ assert wizard_program_cap(["self-driving"]) is None+++class TestTieredMint:+ @pytest.fixture(autouse=True)+ def _mint_settings(self):+ with override_settings(+ **MINT_SETTINGS,+ WIZARD_GATEWAY_TIERS={+ "new": {"cap_usd": "5", "mints_per_week": 2, "ttl_seconds": 3600},+ "paid": {"cap_usd": "10", "mints_per_week": 10},+ },+ WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM={"ai-observability": "12"},+ ):+ yield++ def _mint(self, **kwargs):+ 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", **kwargs)+ return post.call_args.kwargs["json"]++ def test_the_tier_cap_and_ttl_apply(self):+ body = self._mint(program="integration", posture="new")+ assert (body["cap_usd"], body["ttl_seconds"]) == ("5.000000", 3600)++ def test_a_tier_without_a_ttl_keeps_its_floor_ttl(self):+ assert self._mint(program="integration", posture="paid")["ttl_seconds"] == _TIER_FLOORS["paid"].ttl_seconds++ def test_a_posture_without_a_tier_keeps_its_floor_cap(self):+ want = f"{_TIER_FLOORS['active'].cap_usd:f}"+ assert self._mint(program="integration", posture="active")["cap_usd"] == want++ def test_the_program_cap_is_bounded_by_the_postures_ceiling(self):+ assert self._mint(program="ai-observability", posture="new")["cap_usd"] == "6.000000"+ assert self._mint(program="ai-observability", posture="paid")["cap_usd"] == "12.000000"++ def test_no_posture_ignores_the_caller_supplied_program_cap(self):+ # The one path with no ceiling to bound it, so the program a caller+ # names must not choose the cap there.+ assert self._mint(program="ai-observability")["cap_usd"] == "25.000000"++ def test_the_override_outranks_both(self):+ assert self._mint(program="ai-observability", posture="new", cap_usd=Decimal("30"))["cap_usd"] == "30.000000"++ def test_no_posture_and_no_program_is_the_flat_cap(self):+ assert self._mint()["cap_usd"] == "25.000000"++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": "30", "mints_per_week": 100},+ WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_week=100),),(- '{"cap_usd": 12.5, "mints_per_day": "50"}',- WizardLimitOverride(cap_usd=Decimal("12.500000"), mints_per_day=50),+ '{"cap_usd": 12.5, "mints_per_week": "50"}',+ WizardLimitOverride(cap_usd=Decimal("12.500000"), mints_per_week=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)),+ ({"mints_per_week": 100}, WizardLimitOverride(cap_usd=None, mints_per_week=100)),+ ({"cap_usd": "lots", "mints_per_week": 100}, WizardLimitOverride(cap_usd=None, mints_per_week=100)),(- {"cap_usd": "30", "mints_per_day": 0},- WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_day=None),+ {"cap_usd": "30", "mints_per_week": 0},+ WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_week=None),),(None, NO_OVERRIDE),("not json", NO_OVERRIDE),@@ -254,7 +390,7 @@ class TestParseLimitOverride:@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+ assert parse_limit_override({"mints_per_week": mints}) == NO_OVERRIDEclass TestWizardLimitOverride:@@ -267,7 +403,7 @@ class TestWizardLimitOverride: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)+ assert override == WizardLimitOverride(cap_usd=Decimal("30.000000"), mints_per_week=None)get_payload.assert_called_once_with("wizard-gateway-limit-override","d1",@@ -326,3 +462,73 @@ class TestWizardProductNode:@override_settings(WIZARD_GATEWAY_PROGRAM_IDS=[])def test_no_configured_programs_refuses_every_program(self):assert wizard_product_node("audit") is None+++class TestWizardConfigRejectCounter:+ """A rejected settings value degrades the mint toward a floor, so every+ rejection leaves a counter an operator can alert on."""++ @staticmethod+ def _count(field: str) -> float:+ return WIZARD_GATEWAY_CONFIG_REJECTS.labels(field=field)._value.get()++ @override_settings(WIZARD_GATEWAY_TIERS={"new": {"cap_usd": "999", "mints_per_week": 0, "ttl_seconds": -1}})+ def test_each_rejected_tier_field_is_counted_on_its_own_label(self):+ fields = ("cap_usd", "mints_per_week", "ttl_seconds")+ before = {f: self._count(f) for f in fields}+ wizard_tier_limits("new")+ assert {f: self._count(f) for f in fields} == {f: before[f] + 1 for f in fields}++ @override_settings(WIZARD_GATEWAY_TIERS={"new": {"cap_usd": "5", "max_cap_usd": "3"}})+ def test_a_ceiling_under_its_own_cap_counts_apart_from_an_unreadable_one(self):+ before = self._count("max_cap_usd_below_cap")+ unreadable = self._count("max_cap_usd")+ wizard_tier_limits("new")+ assert self._count("max_cap_usd_below_cap") == before + 1+ assert self._count("max_cap_usd") == unreadable++ @override_settings(WIZARD_GATEWAY_TIERS={"new": {"cap_usd": "5"}})+ def test_a_readable_tier_counts_nothing(self):+ fields = ("cap_usd", "mints_per_week", "ttl_seconds", "max_cap_usd", "max_cap_usd_below_cap", "tiers_json")+ before = {f: self._count(f) for f in fields}+ wizard_tier_limits("new")+ assert {f: self._count(f) for f in fields} == before++ @override_settings(WIZARD_GATEWAY_TIERS={}, WIZARD_GATEWAY_TIERS_INVALID=True)+ def test_a_tier_map_unreadable_at_boot_is_counted_on_every_mint(self):+ # The empty dict cannot say whether the operator configured nothing or+ # configured something unparseable, which is why boot carries the flag.+ before = self._count("tiers_json")+ assert wizard_tier_limits("new") == _TIER_FLOORS["new"]+ assert self._count("tiers_json") == before + 1++ @override_settings(WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM={"broken": "lots"})+ def test_a_rejected_program_cap_is_counted(self):+ before = self._count("program_cap")+ assert wizard_program_cap("broken") is None+ assert self._count("program_cap") == before + 1++ @override_settings(WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM={}, WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM_INVALID=True)+ def test_a_program_cap_map_unreadable_at_boot_is_counted(self):+ before = self._count("program_caps_json")+ assert wizard_program_cap("self-driving") is None+ assert self._count("program_caps_json") == before + 1++ def test_an_override_payload_that_is_not_json_is_counted(self):+ before = self._count("override_payload")+ assert parse_limit_override("{not json") == NO_OVERRIDE+ assert self._count("override_payload") == before + 1++ def test_the_retired_daily_key_still_applies_and_is_counted(self):+ # The live override flag's payload still spells it mints_per_day, so+ # dropping the key outright would silently stop applying every override.+ before = self._count("mints_per_day_retired_key")+ assert parse_limit_override({"mints_per_day": 100}) == WizardLimitOverride(cap_usd=None, mints_per_week=100)+ assert self._count("mints_per_day_retired_key") == before + 1++ def test_the_weekly_key_wins_and_counts_no_retirement(self):+ before = self._count("mints_per_day_retired_key")+ assert parse_limit_override({"mints_per_week": 7, "mints_per_day": 100}) == WizardLimitOverride(+ cap_usd=None, mints_per_week=7+ )+ assert self._count("mints_per_day_retired_key") == beforediff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex 40cc1cbec8d8..cacad86cef02 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -11,10 +11,12 @@ attempt fast instead of retrying into the CLI's timeout."""import json+from datetime import timedeltafrom decimal import Decimal, InvalidOperation-from typing import Any+from typing import Any, Literalfrom django.conf import settings+from django.utils import timezoneimport requestsimport structlog@@ -22,6 +24,8 @@ import posthoganalyticsfrom prometheus_client import Counterfrom posthog.dataclasses import frozen+from posthog.models.organization import Organization+from posthog.models.team.team import Teamlogger = structlog.get_logger(__name__)@@ -29,27 +33,31 @@ _MINT_TIMEOUT_SECONDS = 10# The gateway refuses a TTL outside these bounds with a 400, so clamp locally: a# misconfigured setting should not turn every mint into a 503.-# Far above the gateway's own 60s floor: a run's holders capture the bearer once+# Well above the gateway's own 60s floor: a run's holders capture the bearer once# and cannot re-resolve, so a token must outlive the whole run. Clamping to that# floor would turn a misconfigured knob into mid-run 401s.-_MIN_TTL_SECONDS = 3600+_MIN_TTL_SECONDS = 1800_MAX_TTL_SECONDS = 86400# 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")+_DEFAULT_CAP_USD = Decimal("7")_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,+# An organization's standing at mint time, which picks its tier of limits.+WizardPosture = Literal["new", "active", "paid"]+_NEW_ORGANIZATION_AGE = timedelta(days=7)++# Payload: {"cap_usd": "30", "mints_per_week": 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+_MAX_MINTS_PER_WEEK = 150@frozen@@ -57,7 +65,7 @@ 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+ mints_per_week: int | None = NoneNO_OVERRIDE = WizardLimitOverride()@@ -84,7 +92,7 @@ def wizard_limit_override("wizard_gateway_token: limit override applied",team_id=team_id,cap_usd=str(override.cap_usd),- mints_per_day=override.mints_per_day,+ mints_per_week=override.mints_per_week,)return override@@ -96,28 +104,166 @@ def parse_limit_override(raw: object) -> WizardLimitOverride:raw = json.loads(raw)except ValueError:logger.warning("wizard_gateway_token: limit override payload is not JSON")+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="override_payload").inc()return NO_OVERRIDEif not isinstance(raw, dict):return NO_OVERRIDE+ cap, mints = _parse_limit_fields(raw, source="limit override")+ return WizardLimitOverride(cap_usd=cap, mints_per_week=mints)+++def _parse_limit_fields(raw: dict, *, source: str) -> tuple[Decimal | None, int | None]:cap = _parse_cap(raw["cap_usd"]) if "cap_usd" in raw else Noneif "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(f"wizard_gateway_token: {source} cap_usd out of contract, ignored", cap=str(raw["cap_usd"]))+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="cap_usd").inc()+ # mints_per_day is the retired spelling and is still live in the override+ # flag's payload, so it is read until that payload is updated. Counted so the+ # fallback can be retired on evidence rather than on assumption.+ key = "mints_per_week" if "mints_per_week" in raw else "mints_per_day"+ if key == "mints_per_day" and key in raw:+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="mints_per_day_retired_key").inc()+ mints = _parse_mints_per_week(raw[key]) if key in raw else None+ if key 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"]),+ f"wizard_gateway_token: {source} {key} out of contract, ignored",+ mints=str(raw[key]),)- return WizardLimitOverride(cap_usd=cap, mints_per_day=mints)+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="mints_per_week").inc()+ return cap, mints+++@frozen+class WizardTierLimits:+ """`cap_usd` applies to a program with no entry of its own; a program with+ one replaces it, up to `max_cap_usd`."""++ cap_usd: Decimal | None = None+ max_cap_usd: Decimal | None = None+ mints_per_week: int | None = None+ ttl_seconds: int | None = None+++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.+_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,+ 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,+ 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,+ ttl_seconds=_MAX_TTL_SECONDS,+ ),+}+++def wizard_posture(organization: Organization, team: Team) -> WizardPosture:+ """`paid` outranks the rest, then anything that has ingested is `active`, and+ only a young organization with no event is `new`. Reads cached fields only.++ Billing's own subscription flag decides `paid`, because a cancelled organization+ keeps its feature list and the feature-derived plan tier would go on handing it+ the widest limits. A NULL flag never synced, so it falls back to that tier.+ """+ subscribed = organization.has_active_subscription+ if subscribed if subscribed is not None else organization.get_plan_tier() != "free":+ return "paid"+ if team.ingested_event:+ return "active"+ if organization.created_at is not None and organization.created_at > timezone.now() - _NEW_ORGANIZATION_AGE:+ return "new"+ return "active"+++def wizard_tier_limits(posture: WizardPosture) -> WizardTierLimits:+ """The tier for a posture, each field validated on its own and each falling+ back to that posture's floor rather than to the flat setting."""+ floor = _TIER_FLOORS[posture]+ if getattr(settings, "WIZARD_GATEWAY_TIERS_INVALID", False):+ # Boot parsed the whole map away, so every posture silently takes its floor.+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="tiers_json").inc()+ tiers = settings.WIZARD_GATEWAY_TIERS+ raw = tiers.get(posture) if isinstance(tiers, dict) else None+ if not isinstance(raw, dict):+ return floor+ cap, mints = _parse_limit_fields(raw, source=f"{posture} tier")+ max_cap = _parse_cap(raw["max_cap_usd"]) if "max_cap_usd" in raw else None+ if "max_cap_usd" in raw and max_cap is None:+ logger.warning(+ f"wizard_gateway_token: {posture} tier max_cap_usd out of contract, ignored",+ max_cap_usd=str(raw["max_cap_usd"]),+ )+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="max_cap_usd").inc()+ if max_cap is not None and cap is not None and max_cap < cap:+ # An entry whose ceiling sits under its own cap would let a program tighten+ # rather than size. Ignored rather than absorbed, so the operator sees it.+ logger.warning(+ f"wizard_gateway_token: {posture} tier max_cap_usd below cap_usd, ignored",+ max_cap_usd=str(max_cap),+ cap_usd=str(cap),+ )+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="max_cap_usd_below_cap").inc()+ max_cap = None+ ttl = _parse_ttl(raw["ttl_seconds"]) if "ttl_seconds" in raw else None+ if "ttl_seconds" in raw and ttl is None:+ logger.warning(+ f"wizard_gateway_token: {posture} tier ttl_seconds out of contract, ignored", ttl=str(raw["ttl_seconds"])+ )+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="ttl_seconds").inc()+ return WizardTierLimits(+ cap_usd=cap if cap is not None else floor.cap_usd,+ max_cap_usd=max_cap if max_cap is not None else floor.max_cap_usd,+ mints_per_week=mints if mints is not None else floor.mints_per_week,+ ttl_seconds=ttl if ttl is not None else floor.ttl_seconds,+ )-def _parse_mints_per_day(raw: object) -> int | None:- # bool is an int subclass: True would read as one mint a day.+def wizard_program_cap(program: object) -> Decimal | None:+ """A per-program cap from WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM, keyed on the+ program id the CLI sent; None when the program has no usable entry."""+ if getattr(settings, "WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM_INVALID", False):+ # Boot parsed the map away, so no program can carry its own cap.+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="program_caps_json").inc()+ caps = settings.WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM+ if not isinstance(program, str) or not isinstance(caps, dict) or program not in caps:+ return None+ cap = _parse_cap(caps[program])+ if cap is None:+ logger.warning("wizard_gateway_token: program cap out of contract, ignored", program=program)+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="program_cap").inc()+ return cap+++def _parse_ttl(raw: object) -> int | None:+ 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:+ return None+ return raw+++def _parse_mints_per_week(raw: object) -> int | None:+ # bool is an int subclass: True would read as one mint a week.if isinstance(raw, bool):return Noneif isinstance(raw, str) and raw.strip().isdigit():raw = int(raw)- if not isinstance(raw, int) or raw < 1 or raw > _MAX_MINTS_PER_DAY:+ if not isinstance(raw, int) or raw < 1 or raw > _MAX_MINTS_PER_WEEK:return Nonereturn raw@@ -148,6 +294,14 @@ WIZARD_GATEWAY_MINTS = Counter(labelnames=["outcome"],)+# A rejected value degrades the mint quietly toward a floor, so the warning alone+# gives nothing to alert on. Labelled by field, never by the rejected value.+WIZARD_GATEWAY_CONFIG_REJECTS = Counter(+ "posthog_wizard_gateway_config_rejects_total",+ "Wizard gateway settings values rejected as out of contract, by field",+ labelnames=["field"],+)+class WizardGatewayMintError(Exception):"""The gateway refused or failed the mint; the caller answers 503.@@ -185,17 +339,25 @@ def wizard_gateway_base_url() -> str:def mint_wizard_gateway_token(- *, obo: str, user: str, product: str = WIZARD_PRODUCT, cap_usd: Decimal | None = None+ *,+ obo: str,+ user: str,+ product: str = WIZARD_PRODUCT,+ cap_usd: Decimal | None = None,+ program: object = None,+ posture: WizardPosture | 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. `cap_usd`, when set, replaces the- configured cap and must already be validated.+ appears in logs or exception text. `cap_usd`, when set, outranks every+ configured cap and must already be validated; otherwise the program's cap+ bounded by the posture's ceiling, then the posture's own, then the flat+ setting, which applies only when there is no posture."""base_url = wizard_gateway_base_url()body = {- "cap_usd": _cap_usd(cap_usd),- "ttl_seconds": _ttl_seconds(),+ "cap_usd": _cap_usd(cap_usd, program=program, posture=posture),+ "ttl_seconds": _ttl_seconds(posture),"product": product,"obo": obo,"user": user,@@ -252,23 +414,43 @@ def mint_wizard_gateway_token(}-def _ttl_seconds() -> int:+def _ttl_seconds(posture: WizardPosture | None) -> int:"""The requested token lifetime, clamped to the gateway's mint bounds."""- return max(_MIN_TTL_SECONDS, min(int(settings.WIZARD_GATEWAY_TOKEN_TTL_SECONDS), _MAX_TTL_SECONDS))+ ttl = wizard_tier_limits(posture).ttl_seconds if posture is not None else None+ if ttl is None:+ ttl = int(settings.WIZARD_GATEWAY_TOKEN_TTL_SECONDS)+ return max(_MIN_TTL_SECONDS, min(ttl, _MAX_TTL_SECONDS))++def _cap_usd(override: Decimal | None, *, program: object, posture: WizardPosture | None) -> str:+ """The cap as a fixed-point string: the override, then the program's cap+ bounded by the posture's ceiling, then the posture's, then the flat setting.-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.+ program is a caller-supplied body field, so the program cap only applies+ inside a posture; with no posture there is no ceiling to bound it and it is+ ignored, or an account would set its own cap by naming the priciest program."""if override is not None:return f"{override.quantize(_CAP_QUANTUM):f}"- raw = str(settings.WIZARD_GATEWAY_TOKEN_CAP_USD)- cap = _parse_cap(raw)+ if posture is None:+ cap = None+ else:+ tier = wizard_tier_limits(posture)+ cap = wizard_program_cap(program)+ if cap is not None:+ ceiling = tier.max_cap_usd if tier.max_cap_usd is not None else tier.cap_usd+ if ceiling is not None:+ cap = min(cap, ceiling)+ if cap is None:+ cap = tier.cap_usdif 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}"+ raw = str(settings.WIZARD_GATEWAY_TOKEN_CAP_USD)+ cap = _parse_cap(raw)+ if cap is None:+ logger.warning("wizard_gateway_token: cap_usd out of contract, using the default", cap=raw)+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="flat_cap_usd").inc()+ cap = _DEFAULT_CAP_USD+ return f"{cap.quantize(_CAP_QUANTUM):f}"def _parse_cap(raw: object) -> Decimal | None:diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 2fcba167e70a..5272f8ba72a0 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -1193,8 +1193,15 @@ class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):def get_rate(self):if settings.DEBUG:- return "1000/day"- return "5/day"+ return "1000/week"+ return "5/week"++ def parse_rate(self, rate):+ """DRF's period map stops at days. A week is spelled out rather than+ written as 7 days so the rate reads as what it is everywhere it is logged."""+ if isinstance(rate, str) and rate.endswith("/week"):+ return int(rate.split("/")[0]), 7 * 24 * 60 * 60+ return super().parse_rate(rate)def allow_request(self, request, view):"""Always admit; the ceiling is the view's atomic reservation.@@ -1238,9 +1245,9 @@ class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):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.+ """Atomically consume one of this user's weekly mints for this program, or raise.- `limit` replaces the throttle's daily count; None keeps the configured rate.+ `limit` replaces the throttle's weekly 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 ceiling@@ -1248,8 +1255,8 @@ def reserve_wizard_mint(request, view, limit: int | None = None) -> str | None:slot unless the failure proves no token was issued; see refund_wizard_mint.Returns the counter it charged so the refund targets that exact key. Recomputing- the window at refund time would decrement the next day's counter for a request- spanning 00:00 UTC, handing out a free slot.+ the window at refund time would decrement the next window's counter for a request+ spanning the boundary, handing out a free slot.Fails open on a cache error: this bounds spend that the per-token cap and thewallet also bound, and a Redis blip must not turn a minted token into a 500.@@ -1277,7 +1284,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 daily run limit. Try again tomorrow.")+ raise exceptions.Throttled(detail="This wizard program has used its weekly run limit. Try again next week.")return counter@@ -1285,7 +1292,7 @@ def refund_wizard_mint(counter: str | None) -> None:"""Return a reserved mint slot after a failure that issued no token.Only for failures that prove the gateway holds nothing: refunding one it did- mint would let a user exceed the daily ceiling. Swallows cache errors so a+ mint would let a user exceed the weekly ceiling. Swallows cache errors so arefund can never turn the 503 the caller is already answering into a 500."""if counter is None:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 44b736bf8a41..8a2a540eac3a 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1242,6 +1242,32 @@ WIZARD_GATEWAY_TOKEN_CAP_USD = get_from_env("WIZARD_GATEWAY_TOKEN_CAP_USD", "20"# is required rather than optional. Mirrors the CLI's PROGRAM_REGISTRY.WIZARD_GATEWAY_PROGRAM_IDS = get_list(get_from_env("WIZARD_GATEWAY_PROGRAM_IDS", ""))WIZARD_GATEWAY_TOKEN_TTL_SECONDS = get_from_env("WIZARD_GATEWAY_TOKEN_TTL_SECONDS", 86400, type_cast=int)+# Per-posture limits, JSON {"new"|"active"|"paid": {"cap_usd", "max_cap_usd",+# "mints_per_week", "ttl_seconds"}}, each field optional and falling back to that+# posture's floor in wizard_gateway_token, not to the flat settings above, whose+# cap is wider than every tier. Per-program caps, JSON {program id: cap}, replace a+# posture's cap_usd for that program up to its max_cap_usd. Both parsed+# defensively like AI_GATEWAY_TEAM_TIER_OVERRIDES: a malformed value must not+# take boot down.+# The _INVALID flags separate "operator configured nothing" from "operator+# configured something unreadable", which the empty dict cannot express. Each+# mint counts the second case so a malformed value is alertable, not just logged.+WIZARD_GATEWAY_TIERS_INVALID = False+WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM_INVALID = False+try:+ WIZARD_GATEWAY_TIERS = json.loads(get_from_env("WIZARD_GATEWAY_TIERS", "{}"))+except ValueError:+ # Empty means every posture keeps its in-code floor, which is the tighter+ # reading. Logged because the operator meant to configure something.+ logger.warning("WIZARD_GATEWAY_TIERS is not JSON, falling back to the in-code tier floors")+ WIZARD_GATEWAY_TIERS = {}+ WIZARD_GATEWAY_TIERS_INVALID = True+try:+ WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM = json.loads(get_from_env("WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM", "{}"))+except ValueError:+ logger.warning("WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM is not JSON, falling back to no per-program caps")+ WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM = {}+ WIZARD_GATEWAY_TOKEN_CAP_USD_BY_PROGRAM_INVALID = True# Exact MCP endpoints that operators explicitly allow the MCP Store to reach even# when normal SSRF validation rejects their private/internal address. This is an