: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): read the wizard gateway policy from flags and pin the prompt (#115782)
Vincent (Wen Yu) Ge8b1387ae119e
diff --git a/docs/internal/wizard-gateway-mint.md b/docs/internal/wizard-gateway-mint.mdindex 8e1ee40207ee..02044220facf 100644--- a/docs/internal/wizard-gateway-mint.md+++ b/docs/internal/wizard-gateway-mint.md@@ -12,24 +12,62 @@ Code: `posthog/api/wizard/http.py` (the endpoint and its gates),## Mint request+The CLI sends `program` and `reads_refusal_reason: true` to `POST /api/wizard/gateway_token/`.+`reads_refusal_reason` controls whether a refusal that an older CLI absorbed uses 403 with a reason or the legacy 404 response.+Django attaches the operator system prompt to the token whenever the prompt flag is usable.+The client never sees the prompt and sends none: the gateway injects it into every model request.+Django posts to `{WIZARD_GATEWAY_URL}/v1/tokens` with`Authorization: Bearer {WIZARD_GATEWAY_MINT_KEY}`:-| Field | Meaning |-| ----------------- | ------------------------------------------- |-| `cap_usd` | Fixed-point spend ceiling for this token |-| `ttl_seconds` | Token lifetime, clamped to 1800-86400 |-| `product` | Product node, `wizard:<program id>` |-| `obo` | The organization the spend is attributed to |-| `user` | The user the run belongs to |-| `allowed_models` | Models this token may reach |-| `allowed_efforts` | Reasoning efforts this token may declare |--`allowed_models` and `allowed_efforts` come from `WIZARD_MODEL_ALLOWLIST`, which-is the canonical table. The wizard CLI's own model constants follow that table-rather than the other way round. A gateway that predates either field ignores it-and mints an unpinned token, so Django can send both before the gateway enforces-them.+| Field | Meaning |+| ----------------- | ------------------------------------------------------------------ |+| `cap_usd` | Fixed-point spend ceiling for this token |+| `ttl_seconds` | Token lifetime, clamped to 1800-86400 |+| `product` | Product node, `wizard:<program id>` |+| `obo` | The organization the spend is attributed to |+| `user` | The user the run belongs to |+| `allowed_models` | Models this token may reach |+| `allowed_efforts` | Reasoning efforts this token may declare |+| `system_prompt` | The operator prompt text, sent only when the prompt flag is usable |++The pins come from two remote-config flags in the PostHog internal project,+read once per mint request after authentication.++- `wizard-ai-gateway-system-prompt` must be a remote-config flag with an encrypted payload.+ `/flags` returns an unencrypted payload to anyone with the public project token, so an unencrypted prompt is public.+ `/flags` drops an encrypted flag, so Django reads this one from the `remote_config` endpoint with the SDK's host and+ Django's `POSTHOG_PERSONAL_API_KEY`, the request the SDK's `get_remote_config_payload` makes.+ The read makes one attempt with a 1 second connect and a 1 second read timeout, and no retry.+ A timeout, a 429 or a 503 mints unpinned at once, because the SDK's own retries sleep for `Retry-After` on the mint worker.+ That endpoint decrypts only for a personal API key with `feature_flag:read` on the project.+ A project secret key gets the redacted marker back, and the mint treats it as out of contract.+ The payload is `{"text": "<prompt>"}`, plus an optional `"version"` that is the operator's own label and that nothing reads.+ The text is non-empty, at most 16384 bytes, valid UTF-8 without U+FFFD, and contains `[posthog:abort]`.+ It goes to the gateway as `system_prompt`, byte for byte.+- `wizard-gateway-allowlist`: `{"models": [...], "efforts": [...], "programs": [...]}`.+ The allowlist is not secret, and its payload must stay unencrypted, because Django reads it through `/flags`.+ All three lists are non-empty, and `efforts` come from the gateway's effort vocabulary.+ `models` holds at most 32 entries, and each one must still name a model after the mint strips the `openai/` prefix.+ The read carries the `email`, `organization_id` and `team_id` person properties the limit-override flag gets.+ They matter only if the allowlist is a regular boolean flag with release conditions instead.++The mint response carries no prompt field at all, pinned or not: no text and no version.+Nothing logs the prompt text, and no error returns it.+A policy flag never refuses a mint:++- A prompt flag that is missing, unreadable or out of contract mints an unpinned token. The mint body omits+ `system_prompt`. The `remote_config` endpoint ignores the flag's on/off switch, so the operator kill switch is+ clearing the payload or deleting the flag.+- An allowlist flag that is unreadable or out of contract falls back to `WIZARD_DEFAULT_MODELS`,+ `WIZARD_DEFAULT_EFFORTS` and `WIZARD_DEFAULT_PROGRAMS` in `wizard_gateway_token.py`.+- Unreadable payloads, flags that return no payload, and out-of-contract payloads log a warning. The PostHog SDK+ swallows its own errors and returns no payload, so an outage reads the same as a flag with no payload.+ Out-of-contract ones also count on+ `posthog_wizard_gateway_config_rejects_total{field="system_prompt"|"allowlist"}`.++A gateway that predates a field ignores it and mints a token without it.+The `programs` list is authoritative: a program absent from it is refused as `program_unknown`.## Limitsdiff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex e75a5a58f5cb..2489a58c010f 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -1,7 +1,7 @@from __future__ import annotationsimport time-from typing import NoReturn, cast+from typing import Any, NoReturn, castfrom django.conf import settingsfrom django.core.cache import cache@@ -27,6 +27,7 @@ from posthog.llm.wizard_gateway_token import (mint_wizard_gateway_token,wizard_gateway_base_url,wizard_gateway_configured,+ wizard_gateway_policy,wizard_limit_override,wizard_posture,wizard_product_node,@@ -168,10 +169,11 @@ class SetupWizardViewSet(viewsets.ViewSet):no other gateway: every refusal ends the run, with the body's `detail`shown to the user and its `code` naming the outcome."""- # Resolved above the first gate so every refusal names the program.+ # Resolved above the first gate so every refusal names the program. The+ # product node waits for the policy, which is read after authentication.body = request.data if isinstance(request.data, dict) else {}program = body.get("program")- product = wizard_product_node(program)+ product: str | None = None# Only a literal true: any other truthy shape keeps the 404 a fallback needs.reads_reason = body.get("reads_refusal_reason") is True@@ -299,7 +301,18 @@ class SetupWizardViewSet(viewsets.ViewSet):"not_rolled_out", "Wizard gateway tokens are switched off for this organization.", user=user)+ # Read once, after every gate that needs no flag, so an unauthenticated or+ # refused request costs no flag read. A policy flag that is off or broken+ # degrades the pin and never refuses the mint.+ policy = wizard_gateway_policy(+ distinct_id=distinct_id,+ email=user.email,+ organization_id=str(team.organization_id),+ team_id=team.id,+ )+# A closed set: refusing keeps every pinned node one that carries a budget.+ product = wizard_product_node(program, policy)if product is None:refuse_absent_gateway("program_unknown", "Unrecognized wizard program. Upgrade with: npx @posthog/wizard@latest", user=user@@ -324,6 +337,7 @@ class SetupWizardViewSet(viewsets.ViewSet):minted = mint_wizard_gateway_token(obo=str(team.id),user=distinct_id,+ policy=policy,product=product,cap_usd=override.cap_usd,program=program,@@ -338,17 +352,15 @@ class SetupWizardViewSet(viewsets.ViewSet):return Response({"error": "Gateway token mint failed."}, status=status.HTTP_503_SERVICE_UNAVAILABLE)WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="minted").inc()- return Response(- {- "token": minted["token"],- "expires_at": minted["expires_at"],- "cap_usd": minted.get("cap_usd"),- "gateway_url": wizard_gateway_base_url(),- # The CLI stamps this on each generation as `team_id`.- "team_id": team.id,- },- status=status.HTTP_201_CREATED,- )+ payload: dict[str, Any] = {+ "token": minted["token"],+ "expires_at": minted["expires_at"],+ "cap_usd": minted.get("cap_usd"),+ "gateway_url": wizard_gateway_base_url(),+ # The CLI stamps this on each generation as `team_id`.+ "team_id": team.id,+ }+ return Response(payload, status=status.HTTP_201_CREATED)@extend_schema(request=SetupWizardCloudRunSerializer,diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 27bfb28d114f..966c1f48f8e8 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -4,7 +4,7 @@ from decimal import Decimalimport pytestfrom posthog.test.base import APIBaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.core.cache import cachefrom django.test import override_settings@@ -19,7 +19,15 @@ from rest_framework.test import APIRequestFactoryfrom posthog.api.wizard.http import WIZARD_EMAIL_UNVERIFIED_DETAILfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL-from posthog.llm.wizard_gateway_token import _TIER_FLOORS, WizardGatewayMintError+from posthog.llm.wizard_gateway_token import (+ _TIER_FLOORS,+ WIZARD_DEFAULT_EFFORTS,+ WIZARD_DEFAULT_MODELS,+ WIZARD_GATEWAY_ALLOWLIST_FLAG,+ WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG,+ WIZARD_SYSTEM_PROMPT_FLAG,+ WizardGatewayMintError,+)from 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@@ -231,21 +239,43 @@ class SetupWizardGatewayTokenThrottleTests(APIBaseTest):WIZARD_GATEWAY_MINT_KEY="phs_wizard_mint",WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com",WIZARD_GATEWAY_CLIENT_IDS=["wizard-client-id"],- WIZARD_GATEWAY_PROGRAM_IDS=["integration"],)class SetupWizardGatewayTokenTests(APIBaseTest):GATEWAY_TOKEN_URL = "/api/wizard/gateway_token"MINTED = {"token": "phe_test_token", "expires_at": "2026-08-22T00:00:00Z", "cap_usd": "50"}+ PROMPT_TEXT = "You are the wizard. [posthog:abort] é"def setUp(self):super().setUp()- # Keeps the SDK off the network; a test sets a payload to opt in.+ # Keeps the SDK off the network. A test changes what a flag returns by+ # setting its entry here; an Exception value is raised instead.+ self.flag_payloads: dict[str, object] = {+ WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG: None,+ WIZARD_SYSTEM_PROMPT_FLAG: {"version": 4, "text": self.PROMPT_TEXT},+ WIZARD_GATEWAY_ALLOWLIST_FLAG: {+ "models": ["openai/gpt-5.6-luna", "claude-sonnet-5"],+ "efforts": ["none", "low"],+ "programs": ["integration", "ai-observability", "events-audit"],+ },+ }++ def read_payload(key, *args, **kwargs):+ value = self.flag_payloads[key]+ if isinstance(value, Exception):+ raise value+ return value+payload_patch = patch(- "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload", return_value=None+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload", side_effect=read_payload)- self.mock_limit_payload = payload_patch.start()+ self.mock_flag_payload = payload_patch.start()self.addCleanup(payload_patch.stop)+ remote_config_patch = patch(+ "posthog.llm.wizard_gateway_token._read_remote_config_payload", side_effect=read_payload+ )+ self.mock_remote_config = remote_config_patch.start()+ self.addCleanup(remote_config_patch.stop)# Patched at the endpoint's seam: the feature_enabled patches below land on# the shared module object, so an SDK-level patch would read the rollout# flag's value as a ban.@@ -253,6 +283,10 @@ class SetupWizardGatewayTokenTests(APIBaseTest):self.mock_blocklist = blocklist_patch.start()self.addCleanup(blocklist_patch.stop)+ def _flag_reads(self, key: str) -> list:+ calls = self.mock_flag_payload.call_args_list + self.mock_remote_config.call_args_list+ return [call for call in calls if call.args[0] == key]+def _ordinary_account(self):"""APIBaseTest's fresh org is the `new` posture, whose weekly ceiling istighter than the one these throttle-accounting cases assume."""@@ -314,6 +348,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):"program": "integration",# The fixture organization is minutes old, unpaid, and has ingested nothing."posture": "new",+ "policy": ANY,}@parameterized.expand([("allowed", False, status.HTTP_201_CREATED), ("refused", True, status.HTTP_403_FORBIDDEN)])@@ -376,7 +411,6 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@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)@@ -411,7 +445,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):self, mock_authentication, mock_flag, mock_mint, mock_authorized):self._mock_oauth(mock_authentication)- self.mock_limit_payload.return_value = {"mints_per_week": 3}+ self.flag_payloads[WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG] = {"mints_per_week": 3}for _ in range(3):ok = self.client.post(@@ -598,6 +632,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):self._mock_oauth(mock_authentication)response = self.client.post(self.GATEWAY_TOKEN_URL, headers={"authorization": "Bearer pha_test"})assert response.status_code == status.HTTP_403_FORBIDDEN+ assert response.json()["code"] == "unauthorized"def test_unauthenticated_request_is_rejected(self):# No authenticator mock: the real one must refuse a request with no@@ -641,7 +676,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_week": 7}+ self.flag_payloads[WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG] = {"mints_per_week": 7}for _ in range(7):ok = self.client.post(@@ -661,7 +696,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@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"})+ self.flag_payloads[WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG] = json.dumps({"cap_usd": "30"})response = self.client.post(self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}@@ -669,7 +704,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):assert response.status_code == status.HTTP_201_CREATED, response.contentassert mock_mint.call_args.kwargs["cap_usd"] == Decimal("30.000000")- self.mock_limit_payload.assert_called_once_with(+ self.mock_flag_payload.assert_any_call("wizard-gateway-limit-override",str(self.user.distinct_id),person_properties={@@ -687,7 +722,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):@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")+ self.flag_payloads[WIZARD_GATEWAY_LIMIT_OVERRIDE_FLAG] = RuntimeError("flags unavailable")response = self.client.post(self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}@@ -847,8 +882,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):def test_a_non_string_program_is_refused_not_a_500(self, mock_authentication, mock_flag, mock_authorized, mock_mint):- # An unhashable value raises on the set membership, inside a throttle that- # runs before authentication.+ # An unhashable value must be refused, not raise on the membership test.self._mock_oauth(mock_authentication)response = self.client.post(self.GATEWAY_TOKEN_URL,@@ -880,6 +914,174 @@ class SetupWizardGatewayTokenTests(APIBaseTest):assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTSassert _gateway_token_outcome("throttled") == before + 1+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.llm.wizard_gateway_token.requests.post")+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_the_flags_set_the_token_pins_and_the_prompt_stays_off_the_client(+ self, mock_authentication, mock_flag, mock_post, mock_authorized+ ):+ self._mock_oauth(mock_authentication)+ mock_post.return_value.status_code = 201+ mock_post.return_value.json.return_value = self.MINTED++ 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+ body = mock_post.call_args.kwargs["json"]+ assert body["allowed_models"] == ["gpt-5.6-luna", "claude-sonnet-5"]+ assert body["allowed_efforts"] == ["none", "low"]+ assert body["system_prompt"] == self.PROMPT_TEXT+ # The client gets no prompt metadata at all: no text, no version.+ assert not any("prompt" in key for key in response.json())+ assert self.PROMPT_TEXT not in response.content.decode()+ # One read per flag per request, however many places use the policy.+ assert len(self._flag_reads(WIZARD_SYSTEM_PROMPT_FLAG)) == 1+ assert len(self._flag_reads(WIZARD_GATEWAY_ALLOWLIST_FLAG)) == 1++ @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_program_the_allowlist_flag_drops_is_refused(+ self, mock_authentication, mock_flag, mock_authorized, mock_mint+ ):+ self._mock_oauth(mock_authentication)+ self.flag_payloads[WIZARD_GATEWAY_ALLOWLIST_FLAG] = {+ "models": ["claude-sonnet-5"],+ "efforts": ["none"],+ "programs": ["integration"],+ }++ for program, expected in (("integration", 201), ("ai-observability", 403)):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL,+ {"program": program, "reads_refusal_reason": True},+ headers={"authorization": "Bearer pha_test"},+ )+ assert response.status_code == expected, (program, response.content)+ assert response.json()["code"] == "program_unknown"+ assert mock_mint.call_count == 1++ @parameterized.expand(+ [+ ("unreadable", RuntimeError("flags down")),+ ("no_payload", None),+ ("out_of_contract", {"version": 1, "text": "no marker"}),+ ]+ )+ @patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.llm.wizard_gateway_token.requests.post")+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_a_prompt_flag_that_is_not_usable_mints_an_unpinned_token(+ self, _name, payload, mock_authentication, mock_flag, mock_post, mock_authorized, mock_key+ ):+ self._mock_oauth(mock_authentication)+ mock_post.return_value.status_code = 201+ mock_post.return_value.json.return_value = self.MINTED+ self.flag_payloads[WIZARD_SYSTEM_PROMPT_FLAG] = payload++ 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+ body = mock_post.call_args.kwargs["json"]+ assert "system_prompt" not in body+ assert not any("prompt" in key for key in response.json())+ # The allowlist is untouched.+ assert body["allowed_models"] == ["gpt-5.6-luna", "claude-sonnet-5"]++ @parameterized.expand(+ [+ ("unreadable", RuntimeError("flags down")),+ ("off", None),+ ("out_of_contract", {"models": [], "efforts": ["none"], "programs": ["integration"]}),+ ]+ )+ @patch.object(SetupWizardGatewayTokenRateThrottle, "get_cache_key", return_value="refund-test-key")+ @patch("posthog.api.wizard.http.oauth_credential_authorized", return_value=True)+ @patch("posthog.llm.wizard_gateway_token.requests.post")+ @patch("posthog.api.wizard.http.posthoganalytics.feature_enabled", return_value=True)+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ def test_an_allowlist_flag_that_is_not_usable_mints_with_the_defaults(+ self, _name, payload, mock_authentication, mock_flag, mock_post, mock_authorized, mock_key+ ):+ self._mock_oauth(mock_authentication)+ mock_post.return_value.status_code = 201+ mock_post.return_value.json.return_value = self.MINTED+ self.flag_payloads[WIZARD_GATEWAY_ALLOWLIST_FLAG] = payload++ # One default program, so the refused program is known to be outside the defaults.+ with patch("posthog.llm.wizard_gateway_token.WIZARD_DEFAULT_PROGRAMS", ("integration",)):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL,+ {"program": "integration"},+ headers={"authorization": "Bearer pha_test"},+ )+ refused = self.client.post(+ self.GATEWAY_TOKEN_URL,+ {"program": "events-audit", "reads_refusal_reason": True},+ headers={"authorization": "Bearer pha_test"},+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ body = mock_post.call_args.kwargs["json"]+ assert body["allowed_models"] == list(WIZARD_DEFAULT_MODELS)+ assert body["allowed_efforts"] == list(WIZARD_DEFAULT_EFFORTS)+ # The program check runs against the default programs, not the flag's.+ assert refused.status_code == status.HTTP_403_FORBIDDEN+ assert refused.json()["code"] == "program_unknown"+ assert mock_post.call_count == 1++ @patch("posthog.api.wizard.http.mint_wizard_gateway_token", return_value=MINTED)+ def test_the_policy_is_not_read_before_the_caller_is_authenticated(self, mock_mint):+ response = self.client.post(+ self.GATEWAY_TOKEN_URL,+ {"program": "integration"},+ headers={"authorization": "Bearer pha_unknown"},+ )++ assert response.status_code == status.HTTP_401_UNAUTHORIZED+ assert self._flag_reads(WIZARD_SYSTEM_PROMPT_FLAG) == []+ assert self._flag_reads(WIZARD_GATEWAY_ALLOWLIST_FLAG) == []+ mock_mint.assert_not_called()++ @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_refusal_after_authentication_never_reads_the_policy(+ self, mock_authentication, mock_flag, mock_mint, mock_authorized+ ):+ self._mock_oauth(mock_authentication)++ self.mock_blocklist.return_value = True+ blocked = self.client.post(+ self.GATEWAY_TOKEN_URL, {"program": "integration"}, headers={"authorization": "Bearer pha_test"}+ )+ self.mock_blocklist.return_value = False+ mock_flag.return_value = False+ switched_off = self.client.post(+ self.GATEWAY_TOKEN_URL,+ {"program": "integration", "reads_refusal_reason": True},+ headers={"authorization": "Bearer pha_test"},+ )++ assert blocked.status_code == status.HTTP_403_FORBIDDEN, blocked.content+ assert switched_off.json()["code"] == "not_rolled_out"+ assert self._flag_reads(WIZARD_SYSTEM_PROMPT_FLAG) == []+ assert self._flag_reads(WIZARD_GATEWAY_ALLOWLIST_FLAG) == []+ mock_mint.assert_not_called()+def test_an_unresolvable_bearer_is_counted(self):before = _gateway_token_outcome("invalid_token")@@ -901,7 +1103,7 @@ class TestReserveWizardMint:@pytest.fixture(autouse=True)def _settings(self):- with override_settings(WIZARD_GATEWAY_PROGRAM_IDS=["integration"], DEBUG=False):+ with override_settings(DEBUG=False):yielddef _request(self):diff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.pyindex 2b7f80eee65e..2cfa986594ca 100644--- a/posthog/llm/test_wizard_gateway_token.py+++ b/posthog/llm/test_wizard_gateway_token.py@@ -1,5 +1,10 @@+import json+import threading+import http.server+from contextlib import contextmanagerfrom datetime import timedeltafrom decimal import Decimal+from types import SimpleNamespaceimport pytestfrom unittest.mock import patch@@ -12,20 +17,24 @@ import requestsfrom posthog.llm.wizard_gateway_token import (_TIER_FLOORS,NO_OVERRIDE,- WIZARD_DECLARABLE_EFFORTS,+ WIZARD_DEFAULT_EFFORTS,+ WIZARD_DEFAULT_MODELS,+ WIZARD_DEFAULT_PROGRAMS,WIZARD_EFFORT_LEVELS,+ WIZARD_GATEWAY_ALLOWLIST_FLAG,WIZARD_GATEWAY_CONFIG_REJECTS,- WIZARD_MODEL_ALLOWLIST,+ WIZARD_SYSTEM_PROMPT_FLAG,WizardGatewayMintError,+ WizardGatewayPolicy,WizardLimitOverride,+ WizardSystemPrompt,WizardTierLimits,- allowed_efforts,- allowed_models,mint_wizard_gateway_token,normalize_model,parse_limit_override,wizard_gateway_base_url,wizard_gateway_configured,+ wizard_gateway_policy,wizard_limit_override,wizard_posture,wizard_product_node,@@ -44,7 +53,24 @@ MINT_SETTINGS = {# assertions indistinguishable."WIZARD_GATEWAY_TOKEN_CAP_USD": "25","WIZARD_GATEWAY_TOKEN_TTL_SECONDS": 86400,- "WIZARD_GATEWAY_PROGRAM_IDS": ["integration"],+}++# Trailing whitespace and an accent: the mint must carry the text byte for byte.+PROMPT_TEXT = "You are the wizard. [posthog:abort]\n é"++POLICY = WizardGatewayPolicy(+ # Mixed case, a provider prefix, a duplicate and stray spaces: the mint sends the gateway's spelling.+ models=("OpenAI/GPT-5.6-Luna", "gpt-5.6-luna", " Claude-Sonnet-5 "),+ efforts=("none", "high"),+ programs=("integration", "audit"),+ prompt=WizardSystemPrompt(text=PROMPT_TEXT),+)++PROMPT_PAYLOAD = {"version": 4, "text": PROMPT_TEXT}+ALLOWLIST_PAYLOAD = {+ "models": ["OpenAI/GPT-5.6-Luna", "claude-sonnet-5"],+ "efforts": ["high", "none"],+ "programs": ["integration", "audit"],}@@ -81,7 +107,7 @@ class TestMintWizardGatewayToken:override_settings(WIZARD_GATEWAY_MINT_URL=mint_url),patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post,):- assert mint_wizard_gateway_token(obo="7", user="user_1") == minted+ assert mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY) == mintedassert wizard_gateway_base_url() == "https://ai-gateway.us.posthog.com"assert post.call_args[0][0] == expected_url@@ -91,44 +117,15 @@ class TestMintWizardGatewayToken:"product": "wizard","obo": "7","user": "user_1",- # Derived: this case pins that the mint carries the pins, not which- # models are on the table. TestWizardModelAllowlist owns the contents.- "allowed_models": allowed_models(),- "allowed_efforts": allowed_efforts(),+ "allowed_models": ["gpt-5.6-luna", "claude-sonnet-5"],+ "allowed_efforts": ["none", "high"],+ "system_prompt": PROMPT_TEXT,}assert post.call_args.kwargs["headers"] == {"Authorization": "Bearer phs_wizard_secret"}assert post.call_args.kwargs["timeout"] > 0-class TestWizardModelAllowlist:- def test_the_allowlist_is_never_empty(self):- # The gateway refuses an explicit [] at mint, so an empty table would- # refuse every wizard run rather than pin nothing.- assert allowed_models()- assert allowed_efforts()- assert all(efforts for efforts in WIZARD_MODEL_ALLOWLIST.values())-- def test_models_are_sent_lowercased_and_stripped_of_the_openai_prefix(self):- table = {"OpenAI/GPT-5.6-Luna": ("low",), "gpt-5.6-luna": ("medium",), " Claude-Sonnet-5 ": ("none",)}- with patch("posthog.llm.wizard_gateway_token.WIZARD_MODEL_ALLOWLIST", table):- assert allowed_models() == ["gpt-5.6-luna", "claude-sonnet-5"]-- def test_efforts_cover_what_the_cli_can_declare_not_what_the_table_measured(self):- # A flag payload or a remote prompt can name any declarable level with- # no deploy here, so a pin built from the table would refuse those runs.- table = {"a": ("high", "none")}- with patch("posthog.llm.wizard_gateway_token.WIZARD_MODEL_ALLOWLIST", table):- assert allowed_efforts() == ["none", "minimal", "low", "medium", "high", "xhigh"]-- def test_the_effort_pin_withholds_the_level_the_cli_cannot_send(self):- assert "max" not in allowed_efforts()- assert set(WIZARD_DECLARABLE_EFFORTS) <= set(WIZARD_EFFORT_LEVELS)-- def test_every_effort_in_the_table_is_gateway_vocabulary(self):- for model, efforts in WIZARD_MODEL_ALLOWLIST.items():- assert set(efforts) <= set(WIZARD_EFFORT_LEVELS), model- assert normalize_model(model) == model, model-+class TestWizardMintRequest:@override_settings(WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com/v1/", WIZARD_GATEWAY_MINT_URL="")def test_version_suffixed_setting_does_not_double_up(self):# The setting may carry /v1; both the mint path and the base handed to the@@ -136,21 +133,21 @@ class TestWizardModelAllowlist:assert wizard_gateway_base_url() == "https://ai-gateway.us.posthog.com"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="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert post.call_args[0][0] == "https://ai-gateway.us.posthog.com/v1/tokens"@override_settings(WIZARD_GATEWAY_TOKEN_TTL_SECONDS=172800)def test_ttl_clamped_to_gateway_ceiling(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="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert post.call_args.kwargs["json"]["ttl_seconds"] == 86400@override_settings(WIZARD_GATEWAY_TOKEN_TTL_SECONDS=5)def test_ttl_clamped_to_a_ttl_that_outlives_a_run(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="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert post.call_args.kwargs["json"]["ttl_seconds"] == 1800@pytest.mark.parametrize(@@ -164,7 +161,7 @@ class TestWizardModelAllowlist:def test_non_201_raises(self, response):with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=response):with pytest.raises(WizardGatewayMintError):- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)def test_transport_failure_raises(self):with patch(@@ -172,7 +169,7 @@ class TestWizardModelAllowlist:side_effect=requests.RequestException("connection reset"),):with pytest.raises(WizardGatewayMintError):- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)def test_non_json_body_raises(self):with patch(@@ -180,7 +177,7 @@ class TestWizardModelAllowlist:return_value=_Response(201, raise_on_json=True),):with pytest.raises(WizardGatewayMintError):- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)@pytest.mark.parametrize("payload",@@ -193,7 +190,7 @@ class TestWizardModelAllowlist:def test_incomplete_payload_raises(self, payload):with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, payload)):with pytest.raises(WizardGatewayMintError):- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)@pytest.mark.parametrize("configured",@@ -222,7 +219,7 @@ class TestWizardModelAllowlist:"posthog.llm.wizard_gateway_token.requests.post",return_value=_Response(201, minted),) as post:- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert post.call_args.kwargs["json"]["cap_usd"] == "7.000000"@pytest.mark.parametrize(@@ -238,7 +235,7 @@ class TestWizardModelAllowlist:def test_transport_failures_report_whether_a_token_may_exist(self, raised, token_may_exist):with patch("posthog.llm.wizard_gateway_token.requests.post", side_effect=raised):with pytest.raises(WizardGatewayMintError) as excinfo:- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert excinfo.value.token_may_exist is token_may_existdef test_a_refusal_reports_that_no_token_exists(self):@@ -247,7 +244,7 @@ class TestWizardModelAllowlist:return_value=_Response(400, {"error": "bad request"}),):with pytest.raises(WizardGatewayMintError) as excinfo:- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert excinfo.value.token_may_exist is Falsedef test_an_unreadable_201_reports_that_a_token_may_exist(self):@@ -258,7 +255,7 @@ class TestWizardModelAllowlist:return_value=_Response(201, {"not": "a token"}),):with pytest.raises(WizardGatewayMintError) as excinfo:- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert excinfo.value.token_may_exist is True@override_settings(WIZARD_GATEWAY_TOKEN_CAP_USD="12.5")@@ -268,19 +265,19 @@ class TestWizardModelAllowlist:"posthog.llm.wizard_gateway_token.requests.post",return_value=_Response(201, minted),) as post:- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)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="7", user="user_1", cap_usd=Decimal("30"))+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY, 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:- mint_wizard_gateway_token(obo="7", user="user_1")+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY)assert "phs_wizard_secret" not in str(raised.value)@@ -380,7 +377,7 @@ class TestTieredMint: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="7", user="user_1", **kwargs)+ mint_wizard_gateway_token(obo="7", user="user_1", policy=POLICY, **kwargs)return post.call_args.kwargs["json"]def test_the_tier_cap_and_ttl_apply(self):@@ -476,7 +473,7 @@ class TestWizardLimitOverride:class TestWizardGatewayConfigured:- def test_all_four_present(self):+ def test_all_three_present(self):with override_settings(**MINT_SETTINGS):assert wizard_gateway_configured() is True@@ -486,35 +483,308 @@ class TestWizardGatewayConfigured:"WIZARD_GATEWAY_URL","WIZARD_GATEWAY_MINT_KEY","WIZARD_GATEWAY_CLIENT_IDS",- # An empty program list refuses every program, so leaving it out is an- # unconfigured deploy, not a fleet of callers sending bad names.- "WIZARD_GATEWAY_PROGRAM_IDS",],)def test_any_missing_piece_disables(self, missing):blank: dict = {**MINT_SETTINGS,- missing: [] if missing in ("WIZARD_GATEWAY_CLIENT_IDS", "WIZARD_GATEWAY_PROGRAM_IDS") else "",+ missing: [] if missing == "WIZARD_GATEWAY_CLIENT_IDS" else "",}with override_settings(**blank):assert wizard_gateway_configured() is Falseclass TestWizardProductNode:- @override_settings(WIZARD_GATEWAY_PROGRAM_IDS=["integration", "audit"])- def test_a_configured_program_gets_its_own_node(self):- assert wizard_product_node("audit") == "wizard:audit"-- @override_settings(WIZARD_GATEWAY_PROGRAM_IDS=["integration"])- def test_an_unknown_program_is_refused(self):- assert wizard_product_node("../../etc") is None- assert wizard_product_node("not-a-program") is None- assert wizard_product_node("") is None- assert wizard_product_node(None) is None-- @override_settings(WIZARD_GATEWAY_PROGRAM_IDS=[])- def test_no_configured_programs_refuses_every_program(self):- assert wizard_product_node("audit") is None+ def test_a_program_on_the_allowlist_gets_its_own_node(self):+ assert wizard_product_node("audit", POLICY) == "wizard:audit"++ def test_a_program_off_the_allowlist_is_refused(self):+ assert wizard_product_node("../../etc", POLICY) is None+ assert wizard_product_node("not-a-program", POLICY) is None+ assert wizard_product_node("", POLICY) is None+ assert wizard_product_node(None, POLICY) is None+ assert wizard_product_node(["integration"], POLICY) is None+++def _policy() -> WizardGatewayPolicy:+ return wizard_gateway_policy(distinct_id="d1", email="[email protected]", organization_id="org_1", team_id=7)+++class TestWizardGatewayPolicy:+ @staticmethod+ @contextmanager+ def _flags(prompt=PROMPT_PAYLOAD, allowlist=ALLOWLIST_PAYLOAD):+ def reader(payloads):+ def read(key, *args, **kwargs):+ value = payloads.get(key)+ if isinstance(value, Exception):+ raise value+ return value++ return read++ with (+ patch(+ "posthog.llm.wizard_gateway_token._read_remote_config_payload",+ side_effect=reader({WIZARD_SYSTEM_PROMPT_FLAG: prompt}),+ ) as remote_config,+ patch(+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload",+ side_effect=reader({WIZARD_GATEWAY_ALLOWLIST_FLAG: allowlist}),+ ) as evaluated,+ ):+ yield remote_config, evaluated++ def test_both_flags_make_the_policy(self):+ with self._flags() as (remote_config, evaluated):+ policy = _policy()++ assert policy == WizardGatewayPolicy(+ models=("OpenAI/GPT-5.6-Luna", "claude-sonnet-5"),+ efforts=("none", "high"),+ programs=("integration", "audit"),+ prompt=WizardSystemPrompt(text=PROMPT_TEXT),+ )+ # `/flags` serves an unencrypted payload to anyone with the public project+ # token, so the prompt must come only from the decrypting remote-config read.+ remote_config.assert_called_once_with(WIZARD_SYSTEM_PROMPT_FLAG)+ assert [call.args[0] for call in evaluated.call_args_list] == [WIZARD_GATEWAY_ALLOWLIST_FLAG]++ def test_the_prompt_text_is_kept_untrimmed(self):+ text = " [posthog:abort] \n"+ with self._flags(prompt={"version": 1, "text": text}):+ policy = _policy()+ assert policy.prompt is not None+ assert policy.prompt.text == text++ def test_the_allowlist_is_read_with_the_override_flags_targeting_properties(self):+ with self._flags() as (_, evaluated):+ _policy()++ evaluated.assert_called_once_with(+ WIZARD_GATEWAY_ALLOWLIST_FLAG,+ "d1",+ person_properties={"email": "[email protected]", "organization_id": "org_1", "team_id": "7"},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )++ @pytest.mark.parametrize("missing", [None, RuntimeError("flags down")])+ @pytest.mark.parametrize(+ "flag,message",+ [+ (WIZARD_SYSTEM_PROMPT_FLAG, "system prompt flag"),+ (WIZARD_GATEWAY_ALLOWLIST_FLAG, "allowlist flag"),+ ],+ )+ def test_a_flag_that_returns_nothing_is_logged(self, flag, message, missing):+ # The SDK swallows its own errors and returns None, so None is the outage a+ # production mint sees; the exception is the same outage in a client that raises.+ kwargs = {"prompt": missing} if flag == WIZARD_SYSTEM_PROMPT_FLAG else {"allowlist": missing}+ with self._flags(**kwargs), patch("posthog.llm.wizard_gateway_token.logger") as log:+ _policy()++ logged = [call.args[0] for call in log.warning.call_args_list]+ expected = f"wizard_gateway_token: {message} " + ("returned no payload" if missing is None else "unavailable")+ assert logged == [expected]++ @pytest.mark.parametrize("status", [429, 503])+ def test_a_throttled_prompt_read_mints_unpinned_after_one_attempt(self, status):+ hits = []++ class Throttled(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ hits.append(self.path)+ self.send_response(status)+ self.send_header("Retry-After", "1")+ self.send_header("Content-Length", "0")+ self.end_headers()++ def log_message(self, *args):+ pass++ server = http.server.HTTPServer(("127.0.0.1", 0), Throttled)+ thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)+ thread.start()+ sdk = SimpleNamespace(+ disabled=False,+ personal_api_key="phx_test",+ api_key="phc_test",+ host=f"http://127.0.0.1:{server.server_port}",+ )+ try:+ with (+ patch("posthog.llm.wizard_gateway_token.posthoganalytics.setup", return_value=sdk),+ patch(+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload",+ return_value=ALLOWLIST_PAYLOAD,+ ),+ patch("posthog.llm.wizard_gateway_token.logger") as log,+ ):+ policy = _policy()+ finally:+ server.shutdown()+ server.server_close()++ assert policy.prompt is None+ assert policy.programs == ("integration", "audit")+ # A retry that honored Retry-After would sleep on the mint worker and hit again.+ assert len(hits) == 1+ assert hits[0].startswith(f"/api/projects/@current/feature_flags/{WIZARD_SYSTEM_PROMPT_FLAG}/remote_config?")+ assert [call.args[0] for call in log.warning.call_args_list] == [+ "wizard_gateway_token: system prompt flag unavailable"+ ]++ def test_models_that_spell_one_model_do_not_count_twice_against_the_gateways_cap(self):+ names = [f"m{i}" for i in range(31)]+ allowlist = {+ "models": [*names, "gpt-x", "openai/gpt-x", "GPT-X"],+ "efforts": ["high"],+ "programs": ["integration"],+ }+ with self._flags(allowlist=allowlist):+ policy = _policy()++ assert policy.programs == ("integration",)++ def test_a_program_id_saved_with_stray_spaces_is_stored_stripped(self):+ allowlist = {**ALLOWLIST_PAYLOAD, "programs": ["posthog-integration ", " audit"]}+ with self._flags(allowlist=allowlist):+ policy = _policy()++ assert policy.programs == ("posthog-integration", "audit")+ assert wizard_product_node("posthog-integration", policy) == "wizard:posthog-integration"++ def test_the_defaults_stay_inside_what_the_gateway_and_the_cli_accept(self):+ # The fallback pins every run when the allowlist flag is unreadable, so a+ # level the gateway does not know, or a model it spells differently,+ # would refuse them all.+ assert set(WIZARD_DEFAULT_EFFORTS) <= set(WIZARD_EFFORT_LEVELS)+ assert "max" not in WIZARD_DEFAULT_EFFORTS+ for model in WIZARD_DEFAULT_MODELS:+ assert normalize_model(model) == model, model++ @pytest.mark.parametrize(+ "payload",+ [+ {"text": PROMPT_TEXT},+ {"version": 4, "text": PROMPT_TEXT},+ {"version": "not a number", "text": PROMPT_TEXT},+ {"version": None, "text": PROMPT_TEXT},+ ],+ )+ def test_a_version_in_the_payload_is_tolerated_and_ignored(self, payload):+ with self._flags(prompt=payload):+ policy = _policy()+ assert policy.prompt == WizardSystemPrompt(text=PROMPT_TEXT)++ def test_the_prompt_text_stays_out_of_a_repr(self):+ assert PROMPT_TEXT not in repr(POLICY)+ assert PROMPT_TEXT not in repr(POLICY.prompt)++ def test_a_json_string_payload_reads_like_an_object(self):+ with self._flags(prompt=json.dumps(PROMPT_PAYLOAD), allowlist=json.dumps(ALLOWLIST_PAYLOAD)):+ policy = _policy()+ assert policy.prompt is not None+ assert policy.prompt.text == PROMPT_TEXT+ assert policy.programs == ("integration", "audit")++ @staticmethod+ def _rejects(field: str) -> float:+ return WIZARD_GATEWAY_CONFIG_REJECTS.labels(field=field)._value.get()++ @pytest.mark.parametrize(+ "prompt,counted",+ [+ # Off or unreadable is quiet: a flag outage is not a bad payload.+ (None, False),+ (RuntimeError("flags down"), False),+ ("not json", True),+ ([], True),+ ({"version": 4}, True),+ ({"version": 4, "text": ""}, True),+ ({"version": 4, "text": 7}, True),+ ({"version": 4, "text": "no marker here"}, True),+ # 16385 bytes: the cap counts bytes, not characters.+ ({"version": 4, "text": "[posthog:abort]" + "é" * 8185}, True),+ # The gateway refuses these two, so they must never reach it.+ ({"version": 4, "text": "[posthog:abort] \ud800"}, True),+ ({"version": 4, "text": "[posthog:abort] \ufffd"}, True),+ # remote_config's answer for an encrypted payload when the SDK holds a project secret key.+ ('"********* (encrypted)"', True),+ ],+ )+ def test_an_unusable_prompt_flag_leaves_the_token_unpinned(self, prompt, counted):+ before = self._rejects("system_prompt")+ with self._flags(prompt=prompt):+ policy = _policy()++ assert policy.prompt is None+ # The allowlist is read on its own and is untouched.+ assert policy.programs == ("integration", "audit")+ assert self._rejects("system_prompt") == before + (1 if counted else 0)++ def test_a_prompt_of_exactly_the_gateways_byte_cap_is_carried(self):+ text = "[posthog:abort]" + "é" * 8184 # 15 + 16368 = 16383 bytes+ text += "a"+ assert len(text.encode("utf-8")) == 16384+ with self._flags(prompt={"text": text}):+ policy = _policy()+ assert policy.prompt is not None+ assert policy.prompt.text == text++ @pytest.mark.parametrize(+ "allowlist,counted",+ [+ (None, False),+ (RuntimeError("flags down"), False),+ ("not json", True),+ ([], True),+ ({}, True),+ ({"models": [], "efforts": ["high"], "programs": ["integration"]}, True),+ ({"models": ["a"], "efforts": [], "programs": ["integration"]}, True),+ ({"models": ["a"], "efforts": ["high"], "programs": []}, True),+ ({"models": ["a"], "efforts": ["high"]}, True),+ ({"models": "a", "efforts": ["high"], "programs": ["integration"]}, True),+ ({"models": [7], "efforts": ["high"], "programs": ["integration"]}, True),+ ({"models": [" "], "efforts": ["high"], "programs": ["integration"]}, True),+ # Non-empty as saved, but empty once the mint strips the provider prefix.+ ({"models": ["gpt-x", "OpenAI/"], "efforts": ["high"], "programs": ["integration"]}, True),+ ({"models": ["a"], "efforts": ["extreme"], "programs": ["integration"]}, True),+ ({"models": ["a"], "efforts": ["high"], "programs": [""]}, True),+ # The gateway refuses more than 32 models, after it reads them in its own spelling.+ ({"models": [f"m{i}" for i in range(33)], "efforts": ["high"], "programs": ["integration"]}, True),+ ],+ )+ def test_an_unusable_allowlist_flag_falls_back_to_the_defaults(self, allowlist, counted):+ before = self._rejects("allowlist")+ with self._flags(allowlist=allowlist):+ policy = _policy()++ # All three lists fall back together, never a mix of flag and default.+ assert (policy.models, policy.efforts, policy.programs) == (+ WIZARD_DEFAULT_MODELS,+ WIZARD_DEFAULT_EFFORTS,+ WIZARD_DEFAULT_PROGRAMS,+ )+ # The prompt is read on its own and is untouched.+ assert policy.prompt is not None+ assert self._rejects("allowlist") == before + (1 if counted else 0)++ def test_a_mint_without_a_prompt_omits_the_prompt(self):+ unpinned = WizardGatewayPolicy(+ models=POLICY.models, efforts=POLICY.efforts, programs=POLICY.programs, prompt=None+ )+ minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z"}+ with (+ override_settings(**MINT_SETTINGS),+ patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post,+ ):+ mint_wizard_gateway_token(obo="7", user="user_1", policy=unpinned)++ body = post.call_args.kwargs["json"]+ assert "system_prompt" not in body+ assert body["allowed_models"] == ["gpt-5.6-luna", "claude-sonnet-5"]class TestWizardConfigRejectCounter:diff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex cc954a1bd745..cea0fa777c0d 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -11,6 +11,8 @@ attempt fast instead of retrying into the CLI's timeout."""import json+import dataclasses+from collections.abc import Callablefrom datetime import timedeltafrom decimal import Decimal, InvalidOperationfrom typing import Any, Literal@@ -50,27 +52,6 @@ WIZARD_PRODUCT = "wizard"# The gateway's effort vocabulary, in order; the pin sent at mint is a subset.WIZARD_EFFORT_LEVELS: tuple[str, ...] = ("none", "minimal", "low", "medium", "high", "xhigh", "max")-# What the CLI can ask for, not what it was measured asking for: a flag payload-# or a remote prompt's frontmatter can name any of these with no deploy here,-# while widening this needs one. "none" is a call with no effort parameter,-# which is also the CLI's "off". "max" is absent because the CLI cannot send it,-# so the pin refuses it and the escalation stays out of reach.-WIZARD_DECLARABLE_EFFORTS: tuple[str, ...] = ("none", "minimal", "low", "medium", "high", "xhigh")--# Every (model, effort) pair the wizard CLI dispatches; "none" is a request with-# no effort parameter. Wizard-wide rather than per program: the CLI picks models-# per switchboard flag. The keys mirror the CLI's own model constants (wizard-# src/lib/constants.ts, the *_MODEL exports), so widen here when one is added.-WIZARD_MODEL_ALLOWLIST: dict[str, tuple[str, ...]] = {- "claude-sonnet-5": ("none", "high"),- "claude-haiku-4-5": ("none",),- "gpt-5.6-luna": ("low",),- "gpt-5.6-sol": ("medium",),- "gpt-5.6-terra": ("low", "medium", "high"),- "gpt-6-luna": ("low", "medium"),- "gpt-6-sol": ("low", "medium", "high"),-}-# pi sends the provider-prefixed id for OpenAI models; the gateway pins the bare model._STRIPPED_MODEL_PREFIXES = ("openai/",)@@ -83,17 +64,6 @@ def normalize_model(model: str) -> str:return normalized-def allowed_models() -> list[str]:- """The allowlist's models as the gateway spells them, deduplicated, in table order."""- return list(dict.fromkeys(normalize_model(model) for model in WIZARD_MODEL_ALLOWLIST))---def allowed_efforts() -> list[str]:- """Every effort the CLI can declare, in vocabulary order. Flat per token: a- per-model pin is a gateway follow-up."""- return [level for level in WIZARD_EFFORT_LEVELS if level in WIZARD_DECLARABLE_EFFORTS]--# An organization's standing at mint time, which picks its tier of limits.WizardPosture = Literal["new", "active", "paid"]_NEW_ORGANIZATION_AGE = timedelta(days=7)@@ -118,6 +88,11 @@ class WizardLimitOverride:NO_OVERRIDE = WizardLimitOverride()+def _targeting_properties(*, email: str | None, organization_id: str, team_id: int) -> dict[str, str]:+ """The person properties every wizard flag read carries, so a flag can target by them."""+ return {"email": email or "", "organization_id": organization_id, "team_id": str(team_id)}++def wizard_limit_override(*, distinct_id: str, email: str | None, organization_id: str, team_id: int) -> WizardLimitOverride:@@ -126,7 +101,7 @@ def wizard_limit_override(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)},+ person_properties=_targeting_properties(email=email, organization_id=organization_id, team_id=team_id),only_evaluate_locally=False,send_feature_flag_events=False,)@@ -180,6 +155,246 @@ def _parse_limit_fields(raw: dict, *, source: str) -> tuple[Decimal | None, intreturn cap, mints+# Two remote-config flags in the PostHog internal project, read for their payloads.+# `/flags` serves an unencrypted payload to anyone with the public project token,+# and drops an encrypted one. So the prompt flag is encrypted and read through the+# remote_config endpoint, which decrypts only for a personal API key and ignores the+# on/off switch: an operator clears the payload or deletes the flag to stop pinning.+# The allowlist is not secret, so it stays unencrypted on `/flags`, with the limit+# override's person properties for targeting. The payloads are {"version": 4,+# "text": "..."} (nothing reads the version) and {"models", "efforts", "programs"}.+# A flag that is off, missing, unreadable or out of contract never refuses a mint:+# no prompt mints unpinned, and no allowlist falls back to the defaults below. The+# prompt text goes to the gateway in the mint body and never to the wizard.+WIZARD_SYSTEM_PROMPT_FLAG = "wizard-ai-gateway-system-prompt"+WIZARD_GATEWAY_ALLOWLIST_FLAG = "wizard-gateway-allowlist"++# The wizard ends a run on the abort marker, so a prompt without it would give+# every token a prompt that run cannot end on.+_ABORT_MARKER = "[posthog:abort]"+# The gateway's own limits, mirrored so a payload it would refuse mints unpinned+# here instead of failing every mint. `canonicalSystemPrompt` (principal.ValidSystemPrompt)+# takes a non-empty string of at most 16384 bytes of valid UTF-8, and refuses U+FFFD, which+# its JSON decoder writes for invalid UTF-8. `canonicalModels` takes at most 32 models.+_MAX_PROMPT_BYTES = 16384+_MAX_ALLOWED_MODELS = 32++# What the allowlist falls back to: the pins the mint sent before the flag existed.+# The models are every one the wizard CLI dispatches (its *_MODEL constants in+# src/lib/constants.ts), so widen them here when one is added. The efforts are+# every one the CLI can declare; "max" is absent because the CLI cannot send it.+# The programs match the deploy's former WIZARD_GATEWAY_PROGRAM_IDS, so older wizards+# that mint for a tool keep working when the allowlist is unreadable.+WIZARD_DEFAULT_MODELS: tuple[str, ...] = (+ "claude-sonnet-5",+ "claude-haiku-4-5",+ "gpt-5.6-luna",+ "gpt-5.6-sol",+ "gpt-5.6-terra",+ "gpt-6-luna",+ "gpt-6-sol",+)+WIZARD_DEFAULT_EFFORTS: tuple[str, ...] = ("none", "minimal", "low", "medium", "high", "xhigh")+WIZARD_DEFAULT_PROGRAMS: tuple[str, ...] = (+ "posthog-integration",+ "revenue-analytics-setup",+ "warehouse-source",+ "error-tracking-upload-source-maps",+ "error-tracking",+ "audit",+ "events-audit",+ "posthog-doctor",+ "web-analytics-doctor",+ "migration",+ "self-driving",+ "agent-skill",+ "mcp-add",+ "mcp-remove",+ "mcp-tutorial",+ "mcp-analytics",+ "replay-vision",+ "ai-observability",+ "metrics",+ "slack",+)+++@frozen+class WizardSystemPrompt:+ """The operator prompt a token carries. `text` goes to the gateway only, in+ the mint body, and is never logged or returned to the wizard."""++ text: str = dataclasses.field(repr=False)+++@frozen+class WizardGatewayPolicy:+ """What one mint pins, read from the two flags. `prompt` is None when the+ prompt flag is off or unusable, and the token is then minted unpinned."""++ models: tuple[str, ...]+ efforts: tuple[str, ...]+ programs: tuple[str, ...]+ prompt: WizardSystemPrompt | None+++def wizard_gateway_policy(+ *, distinct_id: str, email: str | None, organization_id: str, team_id: int+) -> WizardGatewayPolicy:+ """Read both policy flags once. Never raises: an unreadable or invalid flag+ degrades that half of the policy and leaves the other alone. The allowlist sees+ the same person properties as the limit override, so it can be targeted."""+ properties = _targeting_properties(email=email, organization_id=organization_id, team_id=team_id)+ prompt_raw = _policy_payload(+ lambda: _read_remote_config_payload(WIZARD_SYSTEM_PROMPT_FLAG),+ source="system prompt",+ field="system_prompt",+ )+ allowlist_raw = _policy_payload(+ lambda: posthoganalytics.get_feature_flag_payload(+ WIZARD_GATEWAY_ALLOWLIST_FLAG,+ distinct_id,+ person_properties=properties,+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ ),+ source="allowlist",+ field="allowlist",+ )+ prompt = _parse_system_prompt(prompt_raw) if prompt_raw is not None else None+ allowlist = _parse_allowlist(allowlist_raw) if allowlist_raw is not None else None+ allowlist = allowlist or _Allowlist(+ models=WIZARD_DEFAULT_MODELS, efforts=WIZARD_DEFAULT_EFFORTS, programs=WIZARD_DEFAULT_PROGRAMS+ )+ return WizardGatewayPolicy(+ models=allowlist.models, efforts=allowlist.efforts, programs=allowlist.programs, prompt=prompt+ )+++def _policy_payload(read: Callable[[], object], *, source: str, field: str) -> dict | None:+ """The flag's payload object, or None when it is off, unreadable, or not an object."""+ try:+ raw = read()+ except Exception as e:+ logger.warning(f"wizard_gateway_token: {source} flag unavailable", error=str(e))+ return None+ if raw is None:+ # The SDK swallows its own errors and returns None, so an outage looks the+ # same as a flag with no payload: say so, as the rollout flag read does.+ logger.warning(f"wizard_gateway_token: {source} flag returned no payload")+ return None+ if isinstance(raw, str):+ try:+ raw = json.loads(raw)+ except ValueError:+ logger.warning(f"wizard_gateway_token: {source} payload is not JSON")+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field=field).inc()+ return None+ if not isinstance(raw, dict):+ logger.warning(f"wizard_gateway_token: {source} payload out of contract, ignored")+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field=field).inc()+ return None+ return raw+++# The read runs on the mint request, so it makes one attempt in about 2 seconds and then+# mints unpinned. The SDK's get_remote_config_payload retries, and sleeps for a 429 or 503+# Retry-After outside its timeout, which can hold a worker for minutes.+# A plain requests session makes no retries.+_PROMPT_READ_TIMEOUT_SECONDS = (1.0, 1.0)+_PROMPT_READ_SESSION = requests.Session()+++def _read_remote_config_payload(key: str) -> object:+ """What the SDK's get_remote_config_payload returns, from one bounded request with+ the SDK's host and keys. None when the SDK is off or holds no personal API key."""+ client = posthoganalytics.setup()+ if client.disabled or not client.personal_api_key:+ return None+ try:+ response = _PROMPT_READ_SESSION.get(+ f"{client.host.rstrip('/')}/api/projects/@current/feature_flags/{key}/remote_config",+ params={"token": client.api_key},+ headers={"Authorization": f"Bearer {client.personal_api_key}"},+ timeout=_PROMPT_READ_TIMEOUT_SECONDS,+ )+ except requests.RequestException as e:+ # The exception text holds the request URL, so only the type goes to the log.+ raise RuntimeError(f"remote_config request failed: {type(e).__name__}") from e+ if response.status_code != 200:+ raise RuntimeError(f"remote_config answered HTTP {response.status_code}")+ # The endpoint answers an empty body for a cleared payload.+ return response.json() if response.content else None+++def _parse_system_prompt(raw: dict) -> WizardSystemPrompt | None:+ # The payload may carry a `version` for the operator's own bookkeeping. Nothing reads it.+ text = raw.get("text")+ if not isinstance(text, str) or not text or _ABORT_MARKER not in text:+ _reject_system_prompt("text must be non-empty and hold the abort marker")+ return None+ # A lone surrogate is a str Python cannot encode, and U+FFFD is what the gateway's+ # decoder makes of invalid UTF-8, so the gateway refuses both.+ try:+ size = len(text.encode("utf-8"))+ except UnicodeEncodeError:+ _reject_system_prompt("text is not valid UTF-8")+ return None+ if "\ufffd" in text:+ _reject_system_prompt("text holds U+FFFD")+ return None+ if size > _MAX_PROMPT_BYTES:+ _reject_system_prompt(f"text is over {_MAX_PROMPT_BYTES} bytes")+ return None+ return WizardSystemPrompt(text=text)+++def _reject_system_prompt(problem: str) -> None:+ logger.warning("wizard_gateway_token: system prompt out of contract, ignored", problem=problem)+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="system_prompt").inc()+++@frozen+class _Allowlist:+ models: tuple[str, ...]+ efforts: tuple[str, ...]+ programs: tuple[str, ...]+++def _parse_allowlist(raw: dict) -> _Allowlist | None:+ """All three lists or none: a half-applied allowlist would pin a mix nobody wrote."""+ try:+ models = _string_list(raw, "models")+ efforts = _string_list(raw, "efforts")+ programs = _string_list(raw, "programs")+ if not set(efforts) <= set(WIZARD_EFFORT_LEVELS):+ raise ValueError("efforts outside the gateway vocabulary")+ # Checked in the gateway's spelling, which the mint sends: "openai/" becomes an empty id.+ pinned = {normalize_model(model) for model in models}+ if not all(pinned):+ raise ValueError("models must hold a model id after the provider prefix")+ if len(pinned) > _MAX_ALLOWED_MODELS:+ raise ValueError(f"models is over {_MAX_ALLOWED_MODELS} entries")+ except ValueError as e:+ logger.warning("wizard_gateway_token: allowlist out of contract, ignored", problem=str(e))+ WIZARD_GATEWAY_CONFIG_REJECTS.labels(field="allowlist").inc()+ return None+ # Vocabulary order, so the pin reads the same whatever order the payload used.+ return _Allowlist(+ models=models, efforts=tuple(level for level in WIZARD_EFFORT_LEVELS if level in efforts), programs=programs+ )+++def _string_list(payload: dict, key: str) -> tuple[str, ...]:+ values = payload.get(key)+ if not isinstance(values, list) or not values:+ raise ValueError(f"{key} must be a non-empty list")+ if not all(isinstance(value, str) and value.strip() for value in values):+ raise ValueError(f"{key} must hold only non-empty strings")+ # Stored stripped, as validated: an id saved as "audit " must match "audit".+ return tuple(dict.fromkeys(value.strip() for value in values))++@frozenclass WizardTierLimits:"""`cap_usd` applies to a program with no entry of its own; a program with@@ -318,22 +533,20 @@ def _parse_mints_per_week(raw: object) -> int | None:return raw-def wizard_product_node(program: str | None) -> str | None:+def wizard_product_node(program: object, policy: WizardGatewayPolicy) -> str | None:"""The product node to pin for a run, or None when this is not a program- Django knows.+ the allowlist flag lists.- The setting is authoritative: an unrecognized program is refused rather than+ The flag is authoritative: an unrecognized program is refused rather thanfolded into a generic node. Gateway budgets match a node value exactly, sofolding would report a new program's spend as plain wizard spend and leave theprogram itself with no budget of its own, and the drift would be silent.A refusal ends the run with an upgrade message and shows in the mint outcome- counter as `program_unknown`; a new program is registered in the CLI, this- setting, and a budget row.+ counter as `program_unknown`; a new program is registered in the CLI, the+ allowlist flag, and a budget row."""- # isinstance first: the value is caller JSON, and an unhashable one (a list- # or object) raises on the set membership below, inside a throttle that runs- # before authentication.- if isinstance(program, str) and program in set(settings.WIZARD_GATEWAY_PROGRAM_IDS):+ # isinstance first: the value is caller JSON, and a list or object is not a program id.+ if isinstance(program, str) and program in policy.programs:return f"{WIZARD_PRODUCT}:{program}"return None@@ -367,19 +580,9 @@ class WizardGatewayMintError(Exception):def wizard_gateway_configured() -> bool:- """Every one of the four is required; any missing piece refuses every mint- as `unconfigured`.-- The program list is a hard requirement, not a refinement: an empty one- refuses every program, so without it the deploy would report itself- configured and 400 every request as though the callers were at fault.- """- return bool(- settings.WIZARD_GATEWAY_MINT_KEY- and settings.WIZARD_GATEWAY_URL- and settings.WIZARD_GATEWAY_CLIENT_IDS- and settings.WIZARD_GATEWAY_PROGRAM_IDS- )+ """Every one of the three is required; any missing piece refuses every mint+ as `unconfigured`."""+ return bool(settings.WIZARD_GATEWAY_MINT_KEY and settings.WIZARD_GATEWAY_URL and settings.WIZARD_GATEWAY_CLIENT_IDS)def wizard_gateway_base_url() -> str:@@ -391,6 +594,7 @@ def mint_wizard_gateway_token(*,obo: str,user: str,+ policy: WizardGatewayPolicy,product: str = WIZARD_PRODUCT,cap_usd: Decimal | None = None,program: object = None,@@ -404,16 +608,19 @@ def mint_wizard_gateway_token(setting, which applies only when there is no posture."""base_url = (settings.WIZARD_GATEWAY_MINT_URL or settings.WIZARD_GATEWAY_URL).rstrip("/").removesuffix("/v1")- body = {+ body: dict[str, Any] = {"cap_usd": _cap_usd(cap_usd, program=program, posture=posture),"ttl_seconds": _ttl_seconds(posture),"product": product,"obo": obo,"user": user,- # A gateway that predates either field ignores it and mints unpinned.- "allowed_models": allowed_models(),- "allowed_efforts": allowed_efforts(),+ # A gateway that predates a pin ignores it and mints unpinned.+ "allowed_models": list(dict.fromkeys(normalize_model(model) for model in policy.models)),+ "allowed_efforts": list(policy.efforts),}+ if policy.prompt is not None:+ # The gateway stores the text on the token and injects it into every call.+ body["system_prompt"] = policy.prompt.texttry:response = requests.post(f"{base_url}/v1/tokens",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e32d1f7b07ec..1a9431ad0cb8 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1351,11 +1351,6 @@ WIZARD_GATEWAY_CLIENT_IDS = [client_id for client_id in get_list(get_from_env("WIZARD_GATEWAY_CLIENT_IDS", "")) if client_id]WIZARD_GATEWAY_TOKEN_CAP_USD = get_from_env("WIZARD_GATEWAY_TOKEN_CAP_USD", "20")-# Wizard programs that may mint, each getting its own pinned product node and so-# its own per-program budget and mint quota. The list is authoritative: a program-# absent here is refused, not folded into a generic node, so listing a new program-# 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