Skip to content

: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.

fix(wizard): read the gateway prompt flag with the sdk (#117340)

Vincent (Wen Yu) Ge3b39f480b753
diff --git a/docs/internal/wizard-gateway-mint.md b/docs/internal/wizard-gateway-mint.md
index 02044220facf..b88f863d5364 100644
--- a/docs/internal/wizard-gateway-mint.md
+++ b/docs/internal/wizard-gateway-mint.md
@@ -31,22 +31,15 @@ Django posts to `{WIZARD_GATEWAY_URL}/v1/tokens` with
| `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,
+The pins come from two 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.
+- `wizard-ai-gateway-system-prompt` is read from local evaluation only, so the read adds no network time to the mint.
+ The read sends `$feature_flag_called`.
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.
@@ -57,8 +50,7 @@ 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.
+ `system_prompt`. The operator kill switch is turning the flag off, 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
diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.py
index 966c1f48f8e8..27d19cc04ef6 100644
--- a/posthog/api/wizard/test/test_http.py
+++ b/posthog/api/wizard/test/test_http.py
@@ -271,11 +271,6 @@ class SetupWizardGatewayTokenTests(APIBaseTest):
)
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.
@@ -284,8 +279,7 @@ class SetupWizardGatewayTokenTests(APIBaseTest):
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]
+ return [call for call in self.mock_flag_payload.call_args_list if call.args[0] == key]
def _ordinary_account(self):
"""APIBaseTest's fresh org is the `new` posture, whose weekly ceiling is
diff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.py
index 2cfa986594ca..f969db68caa6 100644
--- a/posthog/llm/test_wizard_gateway_token.py
+++ b/posthog/llm/test_wizard_gateway_token.py
@@ -1,13 +1,10 @@
import json
-import threading
-import http.server
from contextlib import contextmanager
from datetime import timedelta
from decimal import Decimal
-from types import SimpleNamespace
import pytest
-from unittest.mock import patch
+from unittest.mock import call, patch
from django.test import override_settings
from django.utils import timezone
@@ -523,20 +520,14 @@ class TestWizardGatewayPolicy:
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
+ with patch(
+ "posthog.llm.wizard_gateway_token.posthoganalytics.get_feature_flag_payload",
+ side_effect=reader({WIZARD_SYSTEM_PROMPT_FLAG: prompt, WIZARD_GATEWAY_ALLOWLIST_FLAG: allowlist}),
+ ) as evaluated:
+ yield evaluated
def test_both_flags_make_the_policy(self):
- with self._flags() as (remote_config, evaluated):
+ with self._flags():
policy = _policy()
assert policy == WizardGatewayPolicy(
@@ -545,10 +536,6 @@ class TestWizardGatewayPolicy:
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"
@@ -557,17 +544,28 @@ class TestWizardGatewayPolicy:
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):
+ def test_both_flags_are_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,
- )
+ properties = {"email": "[email protected]", "organization_id": "org_1", "team_id": "7"}
+ assert evaluated.call_args_list == [
+ # The prompt read sends its flag event and adds no network time to the mint.
+ call(
+ WIZARD_SYSTEM_PROMPT_FLAG,
+ "d1",
+ person_properties=properties,
+ only_evaluate_locally=True,
+ send_feature_flag_events=True,
+ ),
+ call(
+ WIZARD_GATEWAY_ALLOWLIST_FLAG,
+ "d1",
+ person_properties=properties,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ ),
+ ]
@pytest.mark.parametrize("missing", [None, RuntimeError("flags down")])
@pytest.mark.parametrize(
@@ -588,53 +586,6 @@ class TestWizardGatewayPolicy:
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 = {
@@ -710,8 +661,6 @@ class TestWizardGatewayPolicy:
# 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):
diff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.py
index cea0fa777c0d..7effa6e98058 100644
--- a/posthog/llm/wizard_gateway_token.py
+++ b/posthog/llm/wizard_gateway_token.py
@@ -155,12 +155,7 @@ def _parse_limit_fields(raw: dict, *, source: str) -> tuple[Decimal | None, int
return 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
+# Two flags in the PostHog internal project, read for their payloads 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:
@@ -246,7 +241,14 @@ def wizard_gateway_policy(
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),
+ # Local evaluation only, so the prompt read adds no network time to the mint.
+ lambda: posthoganalytics.get_feature_flag_payload(
+ WIZARD_SYSTEM_PROMPT_FLAG,
+ distinct_id,
+ person_properties=properties,
+ only_evaluate_locally=True,
+ send_feature_flag_events=True,
+ ),
source="system prompt",
field="system_prompt",
)
@@ -297,36 +299,6 @@ def _policy_payload(read: Callable[[], object], *, source: str, field: str) -> d
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")