:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): fail tokenless posthog_code runs; count token refusals (#118187)
Brandon54bc1f3486bf
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 2c75627f93db..48dc61ccf9bf 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1387,10 +1387,8 @@ DESKTOP_GATEWAY_TOKEN_CAP_USD = get_from_env("DESKTOP_GATEWAY_TOKEN_CAP_USD", "2DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES = get_from_env("DESKTOP_GATEWAY_TOKEN_CAP_USD_OVERRIDES", "")# A plan, access or membership change outlives a token by at most this long. All mints share the# gateway's relay-key mint ceiling, so a shorter TTL supports fewer concurrent sessions; past it the-# gateway answers 429 and the app stays on the legacy gateway.+# gateway answers 429 and the mint fails.DESKTOP_GATEWAY_TOKEN_TTL_SECONDS = get_from_env("DESKTOP_GATEWAY_TOKEN_TTL_SECONDS", 300, type_cast=int)-# Org-targeted; gates the desktop mint and the sandbox worker's posthog_code mint alike.-DESKTOP_GATEWAY_ROLLOUT_FLAG = get_from_env("DESKTOP_GATEWAY_ROLLOUT_FLAG", "posthog-desktop-ai-gateway")# Per-user mint ceiling because OAuth callers skip DRF's default throttles. At the default TTL each# open project on each device mints about 13 times an hour.DESKTOP_GATEWAY_MINTS_PER_HOUR = get_from_env("DESKTOP_GATEWAY_MINTS_PER_HOUR", 120, type_cast=int)diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.pyindex ba5234103326..e4a9915e4cc4 100644--- a/products/tasks/backend/exceptions.py+++ b/products/tasks/backend/exceptions.py@@ -295,6 +295,14 @@ class CredentialUnavailableError(ProcessTaskFatalError):ProcessTaskError.__init__(self, message, context, cause, capture=False, non_retryable=True)+class GatewayTokenUnavailableError(ProcessTaskFatalError):+ """No Go token for a posthog_code run, for a reason a retry won't change. Expected customer+ state, so not captured."""++ def __init__(self, message: str, context: dict[str, Any]):+ ProcessTaskError.__init__(self, message, context, None, capture=False, non_retryable=True)++class PersonalAPIKeyError(ProcessTaskTransientError):"""Failed to create or inject personal API key."""diff --git a/products/tasks/backend/facade/desktop_gateway.py b/products/tasks/backend/facade/desktop_gateway.pyindex 333100c4fb8d..6f2672449bf6 100644--- a/products/tasks/backend/facade/desktop_gateway.py+++ b/products/tasks/backend/facade/desktop_gateway.py@@ -8,11 +8,11 @@ from products.tasks.backend.logic.services.desktop_gateway_token import (desktop_gateway_base_url,desktop_gateway_configured,desktop_limit_tier,- desktop_rollout_enabled,desktop_token_ttl_seconds,mint_desktop_gateway_token,plan_allowed_models,posthog_code_plan,+ record_gateway_token_refusal,)__all__ = [@@ -24,10 +24,10 @@ __all__ = ["desktop_gateway_base_url","desktop_gateway_configured","desktop_limit_tier",- "desktop_rollout_enabled","desktop_token_ttl_seconds","mint_desktop_gateway_token","plan_allowed_models","posthog_code_plan",+ "record_gateway_token_refusal","team_credit_refusal",]diff --git a/products/tasks/backend/logic/services/desktop_gateway_token.py b/products/tasks/backend/logic/services/desktop_gateway_token.pyindex 8ed931f44fb3..f72dd2633973 100644--- a/products/tasks/backend/logic/services/desktop_gateway_token.py+++ b/products/tasks/backend/logic/services/desktop_gateway_token.py@@ -22,7 +22,6 @@ from prometheus_client import Counterfrom posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exception-from posthog.ph_client import feature_enabled_or_falsefrom products.tasks.backend.logic.services.gateway_model_pin import DESKTOP_AGENT_MODELS, FREE_TIER_MODELS@@ -83,6 +82,23 @@ DESKTOP_GATEWAY_MINTS = Counter(labelnames=["outcome"],)+# Which mint refused: the Desktop endpoint or a sandbox run's.+GatewayRefusalSurface = Literal["desktop", "sandbox"]+++def record_gateway_token_refusal(surface: GatewayRefusalSurface, reason: str, *, ai_product: str) -> None:+ try:+ client = posthoganalytics.default_client+ if client is None:+ return+ client.metrics.count(+ "tasks.gateway_token.refused",+ 1,+ attributes={"surface": surface, "ai_product": ai_product, "reason": reason},+ )+ except Exception:+ pass+def _team_credit_refusal(team_id: int, bucket: str) -> str | None:from posthog.models import Team # noqa: PLC0415@@ -170,27 +186,6 @@ def plan_allowed_models(plan: PosthogCodePlan) -> list[str]:return list(DESKTOP_AGENT_MODELS) if plan == "paid" else list(FREE_TIER_MODELS)-def desktop_rollout_enabled(- organization: "Organization", team: "Team", distinct_id: str | None = None, email: str | None = None-) -> bool:- """The rollout flag, targeted on the org. A flag outage reads as off, which keeps both legs on legacy."""- organization_id = str(organization.id)- try:- return feature_enabled_or_false(- settings.DESKTOP_GATEWAY_ROLLOUT_FLAG,- distinct_id or organization_id,- groups={"organization": organization_id, "project": str(team.id)},- # Always sent: the stored person email is client-writable ($set).- person_properties={"email": email or ""},- group_properties={"organization": {"id": organization_id}},- only_evaluate_locally=False,- send_feature_flag_events=False,- )- except Exception:- logger.warning("desktop_gateway_token: rollout flag unavailable, treating as off", exc_info=True)- return False--def posthog_code_billing_synced(organization: "Organization") -> bool:"""True once billing has synced posthog_code_credits usage and a period: the inputs quotalimiting needs before it can limit the org (ee/billing/quota_limiting.py). Billing writes andiff --git a/products/tasks/backend/presentation/views/desktop_access.py b/products/tasks/backend/presentation/views/desktop_access.pyindex 26fa60b1d9cd..975ff25bff64 100644--- a/products/tasks/backend/presentation/views/desktop_access.py+++ b/products/tasks/backend/presentation/views/desktop_access.py@@ -1,3 +1,4 @@+import loggingfrom datetime import UTC, datetime, timedeltafrom typing import Any, cast@@ -43,11 +44,11 @@ from products.tasks.backend.facade.desktop_gateway import (desktop_gateway_base_url,desktop_gateway_configured,desktop_limit_tier,- desktop_rollout_enabled,desktop_token_ttl_seconds,mint_desktop_gateway_token,plan_allowed_models,posthog_code_plan,+ record_gateway_token_refusal,team_credit_refusal,)from products.tasks.backend.presentation.serializers import (@@ -60,6 +61,8 @@ from products.tasks.backend.presentation.serializers import (from ee.billing.quota_limiting import team_quota_snapshot+logger = logging.getLogger(__name__)+# The legacy gateway's usage windows for posthog_code, which its cost throttles exempt._BURST_WINDOW_SECONDS = 86400_SUSTAINED_WINDOW_SECONDS = 2592000@@ -116,6 +119,16 @@ def _desktop_oauth_credential(request: Request) -> tuple[OAuthAccessToken | Nonereturn access_token, None+def _refusal_reason(response: Response) -> str:+ """The same order the Desktop client reads, so the metric names what the app saw."""+ data = response.data if isinstance(response.data, dict) else {}+ for key in ("reason", "code"):+ value = data.get(key)+ if isinstance(value, str) and value:+ return value+ return f"http_{response.status_code}"++def _iso(value: datetime) -> str:return value.astimezone(UTC).isoformat().replace("+00:00", "Z")@@ -207,8 +220,15 @@ class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(exclude=True)@action(detail=False, methods=["post"], url_path="gateway_token", required_scopes=["llm_gateway:read"])def gateway_token(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Mints a `phe_` pinned to this team, the user and the plan's models. Any non-201 keeps the- app on the legacy gateway."""+ """Mints a `phe_` pinned to this team, the user and the plan's models. Any non-201 is a refusal."""+ response = self._gateway_token(request)+ if response.status_code != status.HTTP_201_CREATED:+ reason = _refusal_reason(response)+ record_gateway_token_refusal("desktop", reason, ai_product=POSTHOG_CODE_PRODUCT)+ logger.info("desktop gateway mint refused (team_id=%s reason=%s)", self.team_id, reason)+ return response++ def _gateway_token(self, request: Request) -> Response:access_token, refusal = _desktop_oauth_credential(request)if refusal is not None or access_token is None:return refusal or _disabled("oauth_required", status.HTTP_403_FORBIDDEN)@@ -261,8 +281,6 @@ class DesktopAccessViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if not desktop_gateway_configured():return _disabled("unconfigured")- if not desktop_rollout_enabled(organization, team, distinct_id, user.email):- return _disabled("not_rolled_out")try:# Cache funding for one token lifetime: the app re-mints that often, so staleness stays within a token.diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex b7f4ce24ddfb..d074e7c9d798 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -28,7 +28,6 @@ from products.tasks.backend.logic.services.desktop_gateway_token import (_team_credit_refusal,_valid_cap,desktop_limit_tier,- desktop_rollout_enabled,posthog_code_plan,valid_caps,)@@ -191,15 +190,13 @@ def _posthog_code_team(team_id: int) -> "Team | None":return Team.objects.select_related("organization").filter(id=team_id).first()-def _posthog_code_refusal(team_id: int, model: str | None, distinct_id: str | None) -> str | None:- """The rollout flag is the switch for the product; a free plan's pin has no model an- unpinned or paid-model run could fall back to."""+def _posthog_code_refusal(team_id: int, model: str | None) -> str | None:+ """A free plan's pin has no model an unpinned or paid-model run could fall back to."""team = _posthog_code_team(team_id)- # The run's user, so a person-targeted flag moves cloud runs with that person's desktop sessions.- if team is None or not desktop_rollout_enabled(team.organization, team, distinct_id, _account_email(distinct_id)):- return "not_rolled_out"+ if team is None:+ return "team_not_found"if posthog_code_plan(team) == "free" and not model_allowed_by_pin(FREE_TIER_MODELS, model):- return "model_outside_pin"+ return "model_outside_free_pin"return None@@ -239,9 +236,8 @@ def mint_refusal(internal: bool = False,prior_slack_run: bool = False,origin_product: str | None = None,- distinct_id: str | None = None,) -> str | None:- """Why a routed run must not mint; a run without a token stays on the Python gateway."""+ """Why a routed run must not mint."""if ai_product == "account_audit" and (origin_product != "account_audit" or not internal):return "no_account_audit_provenance"if ai_product == "slack_app" and not has_slack_provenance(@@ -249,7 +245,7 @@ def mint_refusal():return "no_slack_provenance"if ai_product == POSTHOG_CODE_PRODUCT:- refusal = _posthog_code_refusal(team_id, model, distinct_id)+ refusal = _posthog_code_refusal(team_id, model)if refusal:return refusal# Pi reaches Go only for posthog_code.diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.pyindex 494c19634044..515a4dbfe0e3 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py@@ -22,6 +22,7 @@ from posthog.security.outbound_proxy import internal_requestsfrom products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGEfrom products.tasks.backend import model_catalogfrom products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS+from products.tasks.backend.exceptions import GatewayTokenUnavailableError, ProcessTaskTransientErrorfrom products.tasks.backend.facade.billing import get_task_run_costfrom products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_tokenfrom products.tasks.backend.logic.services.desktop_gateway_token import valid_caps@@ -435,7 +436,7 @@ class TestAiGatewayEnvVars:def test_unrouted_run_gets_no_token(self, mint_settings):with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:- env = ai_gateway_env_vars(team_id=123, origin_product="loop")+ env = ai_gateway_env_vars(team_id=123, origin_product="workflow")assert "AI_GATEWAY_TOKEN" not in envassert "AI_GATEWAY_PRODUCT" not in envassert "AI_GATEWAY_AI_STAGE" not in env@@ -533,9 +534,12 @@ class TestMintableGate:def test_non_internal_review_hog_does_not_mint(self, mint_settings):mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "review_hog"- with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:- env = ai_gateway_env_vars(team_id=2, origin_product="review_hog", ai_stage="validation-c1", internal=False)- assert "AI_GATEWAY_TOKEN" not in env+ # Resolves to posthog_code, which is unrouted here.+ with (+ patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint,+ pytest.raises(GatewayTokenUnavailableError),+ ):+ ai_gateway_env_vars(team_id=2, origin_product="review_hog", ai_stage="validation-c1", internal=False)mint.assert_not_called()def test_stageless_signal_report_cannot_mint_for_bare_signals(self, mint_settings):@@ -900,6 +904,36 @@ class TestProvisioningBoundaries:assert "AI_GATEWAY_TOKEN_CAP_USD" not in outassert out["AI_GATEWAY_URL"] == "url"+ def test_a_posthog_code_token_the_stamp_could_not_record_fails_the_attempt(self, mint_settings):+ ctx = self._ctx()+ ctx.origin_product = "user_created"+ task = self._task()+ task.internal = False+ env = {"AI_GATEWAY_URL": "url", "AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "posthog_code"}+ with (+ patch.object(utils, "ai_gateway_env_vars", return_value=env),+ patch.object(utils, "record_gateway_routing"),+ patch(+ "products.tasks.backend.models.TaskRun.update_state_atomic",+ side_effect=RuntimeError("postgres is down"),+ ),+ pytest.raises(ProcessTaskTransientError, match="pin_unrecorded"),+ ):+ utils.run_gateway_env_vars(ctx, task)++ def test_a_posthog_code_refusal_keeps_its_class_and_message_through_the_wrapper(self, mint_settings):+ ctx = self._ctx()+ ctx.origin_product = "user_created"+ task = self._task()+ task.internal = False+ refusal = GatewayTokenUnavailableError("This organization is deactivated.", {})+ with (+ patch.object(utils, "ai_gateway_env_vars", side_effect=refusal),+ patch.object(utils, "record_gateway_routing"),+ pytest.raises(GatewayTokenUnavailableError, match="This organization is deactivated."),+ ):+ utils.run_gateway_env_vars(ctx, task)+def test_an_unpinned_token_survives_a_failed_stamp_removal(self, mint_settings):ctx = self._ctx()ctx.state = {"ai_stage": "scout:logs", "ai_gateway_product": "slack_app"}@@ -1129,11 +1163,21 @@ class TestSlackAppMint:mint.assert_not_called()def test_mint_outcomes_name_their_reason_in_the_message(self, mint_settings, caplog):- with caplog.at_level(logging.INFO):+ with (+ caplog.at_level(logging.INFO),+ patch(+ "products.tasks.backend.logic.services.desktop_gateway_token.posthoganalytics.default_client"+ ) as client,+ ):self._env(mint_settings, state={"run_source": "manual"})skipped = [r for r in caplog.records if "mint skipped" in r.getMessage()]assert skipped, "no mint-skipped line was logged"assert "no_slack_provenance" in skipped[0].getMessage()+ client.metrics.count.assert_called_once_with(+ "tasks.gateway_token.refused",+ 1,+ attributes={"surface": "sandbox", "ai_product": "slack_app", "reason": "no_slack_provenance"},+ )assert "slack_app" in skipped[0].getMessage()def test_mint_failure_names_its_error_in_the_message(self, mint_settings, caplog):@@ -1221,7 +1265,6 @@ class TestSlackAppMint:_CREDIT_LOOKUP = "products.tasks.backend.temporal.process_task.ai_gateway_token._team_credit_refusal"_POSTHOG_CODE_GATE = "products.tasks.backend.temporal.process_task.ai_gateway_token._posthog_code_refusal"-_ROLLOUT = "products.tasks.backend.temporal.process_task.ai_gateway_token.desktop_rollout_enabled"class TestMintRefusalScope:@@ -1438,10 +1481,17 @@ def test_account_audit_cost_routing_requires_server_provenance() -> None:settings.SANDBOX_AI_GATEWAY_URL = "https://ai-gateway.example.com"settings.SANDBOX_AI_GATEWAY_PRODUCTS = "account_audit,onboarding"+ # A non-internal account_audit origin resolves to posthog_code, which is unrouted here.+ resolves_to_posthog_code = origin == "account_audit" and not internalwith patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_test") as mint:- env = ai_gateway_env_vars(- team_id=123, origin_product=origin, internal=internal, model="claude-sonnet-5", runtime="acp"- )+ refused = False+ try:+ env = ai_gateway_env_vars(+ team_id=123, origin_product=origin, internal=internal, model="claude-sonnet-5", runtime="acp"+ )+ except GatewayTokenUnavailableError:+ refused, env = True, {}+ assert refused is resolves_to_posthog_codeassert ("AI_GATEWAY_TOKEN" in env) is mintsassert mint.called is mintsif mints:@@ -1558,77 +1608,146 @@ class TestPosthogCodeSandboxMint:assert post.call_args_list[1].kwargs["json"]["allowed_models"] == FREE_TIER_MODELS@pytest.mark.django_db- def test_flag_off_skips_as_not_rolled_out(self, mint_settings):- team = self._team(paid=True)- mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"+ @pytest.mark.parametrize(+ "paid,model,routed_products,credit,token,error_type,message,counted_reason",+ [+ (+ False,+ "claude-opus-5",+ "posthog_code",+ None,+ "phe_abc",+ GatewayTokenUnavailableError,+ "free plan",+ "model_outside_free_pin",+ ),+ (+ True,+ "gpt-5.5-codex",+ "posthog_code",+ None,+ "phe_abc",+ GatewayTokenUnavailableError,+ "isn't available for PostHog Code",+ "model_outside_pin",+ ),+ (+ True,+ "claude-opus-5",+ "posthog_code",+ "posthog_code_credits_exhausted",+ "phe_abc",+ GatewayTokenUnavailableError,+ "limit",+ "posthog_code_credits_exhausted",+ ),+ (+ True,+ "claude-opus-5",+ "posthog_code",+ RuntimeError("redis down"),+ "phe_abc",+ ProcessTaskTransientError,+ "Try again in a few minutes",+ "posthog_code_credits_unknown",+ ),+ (+ True,+ "claude-opus-5",+ "posthog_code",+ None,+ None,+ ProcessTaskTransientError,+ "mint_failed",+ "mint_failed",+ ),+ (+ True,+ "claude-opus-5",+ "signals_scout",+ None,+ "phe_abc",+ GatewayTokenUnavailableError,+ "isn't configured",+ "not_configured",+ ),+ ],+ ids=[+ "free_off_pin_model",+ "paid_off_pin_model",+ "credits_exhausted",+ "credits_unknown",+ "mint_failed",+ "not_routed",+ ],+ )+ def test_a_posthog_code_run_without_a_token_fails_with_the_reason(+ self, mint_settings, paid, model, routed_products, credit, token, error_type, message, counted_reason+ ):+ team = self._team(paid=paid)+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = routed_products+ credit_patch = (+ patch(_CREDIT_LOOKUP, side_effect=credit)+ if isinstance(credit, Exception)+ else patch(_CREDIT_LOOKUP, return_value=credit)+ )with (- patch(_ROLLOUT, return_value=False),- patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint,- patch.object(utils, "logger") as log,- ):- env = ai_gateway_env_vars(team_id=team.id, origin_product="user_created", model="claude-opus-5")- assert "AI_GATEWAY_TOKEN" not in env- mint.assert_not_called()- assert log.info.call_args.kwargs["extra"]["reason"] == "not_rolled_out"-- @pytest.mark.django_db- def test_flag_outage_reads_as_off(self):- team = self._team(paid=True)- with patch(- "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",- side_effect=RuntimeError("flags down"),+ credit_patch,+ patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value=token),+ patch(+ "products.tasks.backend.logic.services.desktop_gateway_token.posthoganalytics.default_client"+ ) as client,+ pytest.raises(error_type) as raised,):- assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="acp") == (- "not_rolled_out"- )+ ai_gateway_env_vars(team_id=team.id, origin_product="user_created", model=model)+ assert message in str(raised.value)+ assert "Retrying" not in str(raised.value)+ client.metrics.count.assert_called_once_with(+ "tasks.gateway_token.refused",+ 1,+ attributes={"surface": "sandbox", "ai_product": "posthog_code", "reason": counted_reason},+ )@pytest.mark.django_db- def test_a_rolled_out_pi_run_mints(self):+ @pytest.mark.parametrize("setting", ["SANDBOX_AI_GATEWAY_URL", "SANDBOX_AI_GATEWAY_MINT_KEY"])+ def test_a_posthog_code_run_with_the_gateway_unconfigured_fails_and_logs(self, mint_settings, setting):team = self._team(paid=True)+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"+ setattr(mint_settings, setting, "")with (- patch(- "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",- return_value=True,- ),- patch(_CREDIT_LOOKUP, return_value=None),+ patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint,+ patch.object(utils, "logger") as log,+ pytest.raises(GatewayTokenUnavailableError, match="isn't configured"),):- assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="pi") is None+ ai_gateway_env_vars(team_id=team.id, origin_product="user_created", model="claude-opus-5")+ mint.assert_not_called()+ log.error.assert_called_once()- @pytest.mark.django_db- def test_flag_is_evaluated_for_the_team_org(self):- team = self._team(paid=True)+ def test_a_routing_crash_fails_a_posthog_code_run_and_degrades_other_products(self, mint_settings):+ ctx = MagicMock(+ claude_model_access="gateway", codex_model_access="gateway", state={}, team_id=2, run_id="run-1"+ )+ task = MagicMock(is_scout_experiment=False, internal=False)with (- patch(- "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",- return_value=True,- ) as flag,- patch(_CREDIT_LOOKUP, return_value=None),+ patch.object(utils, "ai_gateway_env_vars", side_effect=RuntimeError("boom")),+ patch.object(utils, "record_gateway_routing"),):- assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="acp") is None- assert flag.call_args.args[0] == "posthog-desktop-ai-gateway"- assert flag.call_args.kwargs["groups"]["organization"] == str(team.organization_id)+ ctx.origin_product = "user_created"+ with pytest.raises(ProcessTaskTransientError):+ utils.run_gateway_env_vars(ctx, task)+ ctx.origin_product = "workflow"+ assert utils.run_gateway_env_vars(ctx, task) == {}@pytest.mark.django_db- def test_flag_is_evaluated_for_the_run_user(self, mint_settings):+ def test_a_pi_run_mints(self):team = self._team(paid=True)- mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"- with (- patch(- "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",- return_value=False,- ) as flag,- patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token"),- ):- User.objects.create(email="[email protected]", distinct_id="run-user-distinct-id")- ai_gateway_env_vars(team_id=team.id, origin_product="user_created", distinct_id="run-user-distinct-id")- assert flag.call_args.args[1] == "run-user-distinct-id"- # The account email, never the person's stored one.- assert flag.call_args.kwargs["person_properties"] == {"email": "[email protected]"}+ with patch(_CREDIT_LOOKUP, return_value=None):+ assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="pi") is None@pytest.mark.django_dbdef test_off_pin_model_refuses(self):team = self._team(paid=True)- with patch(_ROLLOUT, return_value=True), patch(_CREDIT_LOOKUP, return_value=None):+ with patch(_CREDIT_LOOKUP, return_value=None):refusal = mint_refusal("posthog_code", team_id=team.id, state=None, model="gpt-5.5-codex", runtime="acp")assert refusal == "model_outside_pin"@@ -1636,16 +1755,15 @@ class TestPosthogCodeSandboxMint:@pytest.mark.parametrize("model", [None, "claude-opus-5", "zai-org/glm-5.3"])def test_free_plan_refuses_a_model_outside_the_free_pin(self, model):team = self._team(paid=False)- with patch(_ROLLOUT, return_value=True), patch(_CREDIT_LOOKUP, return_value=None):+ with patch(_CREDIT_LOOKUP, return_value=None):refusal = mint_refusal("posthog_code", team_id=team.id, state=None, model=model, runtime="acp")- assert refusal == "model_outside_pin"+ assert refusal == "model_outside_free_pin"@pytest.mark.django_dbdef test_free_plan_mints_the_free_pin_and_stamps_it(self, mint_settings):team = self._team(paid=False)mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"with (- patch(_ROLLOUT, return_value=True),patch(_CREDIT_LOOKUP, return_value=None),patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"@@ -1668,7 +1786,6 @@ class TestPosthogCodeSandboxMint:team = self._team(paid=True)mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"with (- patch(_ROLLOUT, return_value=True),patch(_CREDIT_LOOKUP, return_value=None),patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"@@ -1684,7 +1801,6 @@ class TestPosthogCodeSandboxMint:team = self._team(paid=True)mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_code"with (- patch(_ROLLOUT, return_value=True),patch(_CREDIT_LOOKUP, return_value=None),patch("products.tasks.backend.temporal.process_task.utils.posthog_code_limit_tier", return_value="power"diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 71329c7ea7b5..adce0ab119a4 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -38,10 +38,19 @@ from products.tasks.backend.constants import (is_same_run_resume_idle_state,is_same_run_resume_state,)-from products.tasks.backend.exceptions import CredentialUnavailableError+from products.tasks.backend.exceptions import (+ CredentialUnavailableError,+ GatewayTokenUnavailableError,+ ProcessTaskError,+ ProcessTaskTransientError,+)from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_tokenfrom products.tasks.backend.feature_flags import is_mcp_exec_skills_enabledfrom products.tasks.backend.logic.model_access import ModelAccess, resolve_model_access+from products.tasks.backend.logic.services.desktop_gateway_token import (+ POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL,+ record_gateway_token_refusal,+)from products.tasks.backend.logic.services.gateway_model_pin import (FREE_TIER_PIN_KEY,GATEWAY_PRODUCT_STATE_KEY,@@ -1471,11 +1480,15 @@ def run_gateway_env_vars(ctx: TaskProcessingContext, task: Task) -> dict[str, stif "own-subscription" in (ctx.claude_model_access, ctx.codex_model_access):record_gateway_routing(run_id=ctx.run_id, team_id=ctx.team_id, uses_gateway=False)return {}+ ai_stage = (ctx.state or {}).get("ai_stage")+ requires_go = resolve_sandbox_ai_product(ctx.origin_product, ai_stage, internal=task.internal) == (+ POSTHOG_CODE_PRODUCT+ )try:env_vars = ai_gateway_env_vars(team_id=ctx.team_id,origin_product=ctx.origin_product,- ai_stage=(ctx.state or {}).get("ai_stage"),+ ai_stage=ai_stage,internal=task.internal,prior_slack_run=_task_has_stamped_slack_run(task, ctx.origin_product, ctx.state),distinct_id=ctx.distinct_id,@@ -1485,10 +1498,16 @@ def run_gateway_env_vars(ctx: TaskProcessingContext, task: Task) -> dict[str, st)pinned = env_vars.pop(_PIN_KEY_ENV, None) or env_vars.get("AI_GATEWAY_PRODUCT")if not _record_pinned_gateway_product(ctx.run_id, ctx.state, pinned):+ if requires_go:+ raise posthog_code_token_unavailable("pin_unrecorded", ctx.team_id)# The model-change guard reads that stamp; unstamped, a run can move off its pin with no fallback.for key in _TOKEN_ENV_KEYS:env_vars.pop(key, None)- except Exception:+ except ProcessTaskError:+ raise+ except Exception as e:+ if requires_go:+ raise posthog_code_token_unavailable("mint_failed", ctx.team_id) from e# Degrading to the Python gateway beats failing the provisioning activity and the run.AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()logger.warning(@@ -1566,19 +1585,32 @@ def ai_gateway_env_vars(treats its own task-run fetch as the fallback. The agent server routes to theGo gateway only when the token is present, so a missing token (mint failure,or a caller that cannot supply run context) degrades the run to the Python- gateway.+ gateway, except a `posthog_code` run, which raises: the Python gateway+ refuses `posthog_code`."""+ ai_product = (+ resolve_sandbox_ai_product(origin_product, ai_stage, internal=internal) if team_id is not None else None+ )+ requires_go = ai_product == POSTHOG_CODE_PRODUCTif not (settings.SANDBOX_AI_GATEWAY_URL and settings.SANDBOX_AI_GATEWAY_PRODUCTS):+ if requires_go:+ raise posthog_code_token_unavailable("not_configured", team_id)return {}+ # Without a mint key no attempt can mint.+ if requires_go and not settings.SANDBOX_AI_GATEWAY_MINT_KEY:+ raise posthog_code_token_unavailable("not_configured", team_id)env_vars = {"AI_GATEWAY_URL": settings.SANDBOX_AI_GATEWAY_URL,"AI_GATEWAY_PRODUCTS": settings.SANDBOX_AI_GATEWAY_PRODUCTS,}- if team_id is not None:- ai_product = resolve_sandbox_ai_product(origin_product, ai_stage, internal=internal)- if ai_product in MINTABLE_PRODUCTS and sandbox_product_routed(- ai_product, ai_stage, settings.SANDBOX_AI_GATEWAY_PRODUCTS+ if team_id is not None and ai_product is not None:+ if not (+ ai_product in MINTABLE_PRODUCTS+ and sandbox_product_routed(ai_product, ai_stage, settings.SANDBOX_AI_GATEWAY_PRODUCTS)):+ if requires_go:+ raise posthog_code_token_unavailable("not_configured", team_id)+ else:refusal = mint_refusal(ai_product,team_id=team_id,@@ -1588,10 +1620,12 @@ def ai_gateway_env_vars(internal=internal,prior_slack_run=prior_slack_run,origin_product=origin_product,- distinct_id=distinct_id,)if refusal:AI_GATEWAY_TOKEN_MINTS.labels(result="skipped").inc()+ # posthog_code_token_unavailable counts posthog_code refusals.+ if not requires_go:+ record_gateway_token_refusal("sandbox", refusal, ai_product=ai_product)# The deploy's log formatter drops `extra`, so the message carries the fields.# nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs product, team id and a refusal code, no credential presentlogger.info(@@ -1601,6 +1635,8 @@ def ai_gateway_env_vars(refusal,extra={"ai_product": ai_product, "team_id": team_id, "reason": refusal},)+ if requires_go:+ raise posthog_code_token_unavailable(refusal, team_id)return env_varsmint_kwargs: dict[str, Any] = {}if ai_product == POSTHOG_CODE_PRODUCT:@@ -1617,9 +1653,41 @@ def ai_gateway_env_vars(env_vars[_PIN_KEY_ENV] = FREE_TIER_PIN_KEYif ai_stage:env_vars["AI_GATEWAY_AI_STAGE"] = ai_stage+ elif requires_go:+ raise posthog_code_token_unavailable("mint_failed", team_id)return env_vars+# Messages for reasons a retry won't change.+_POSTHOG_CODE_REFUSAL_MESSAGES = {+ "model_outside_free_pin": "This run's model isn't included in the free plan. Choose a free-plan model or upgrade.",+ "model_outside_pin": "This run's model isn't available for PostHog Code cloud runs. Choose another model.",+ "posthog_code_credits_exhausted": POSTHOG_CODE_CREDITS_EXHAUSTED_DETAIL,+ "org_deactivated": "This organization is deactivated.",+ "team_not_found": "This run's project no longer exists.",+ "not_configured": "Cloud runs can't reach PostHog AI: the AI gateway isn't configured for posthog_code.",+}+# A credit lookup or mint can succeed on the next attempt.+_POSTHOG_CODE_TRANSIENT_REFUSALS = frozenset({"posthog_code_credits_unknown", "mint_failed", "pin_unrecorded"})+++def posthog_code_token_unavailable(reason: str, team_id: int | None) -> ProcessTaskError:+ record_gateway_token_refusal("sandbox", reason, ai_product=POSTHOG_CODE_PRODUCT)+ context: dict[str, Any] = {"team_id": team_id, "reason": reason}+ if reason in _POSTHOG_CODE_TRANSIENT_REFUSALS:+ # Also the run's final error after the last retry, so it can't promise one.+ return ProcessTaskTransientError(+ f"Couldn't get a PostHog AI token for this run (reason: {reason}). Try again in a few minutes.",+ context,+ RuntimeError(reason),+ capture=False,+ )+ message = _POSTHOG_CODE_REFUSAL_MESSAGES.get(reason, f"PostHog AI refused this run (reason: {reason}).")+ if reason == "not_configured":+ logger.error("ai_gateway: posthog_code run with no gateway configured (team_id=%s)", team_id)+ return GatewayTokenUnavailableError(message, context)++def get_pr_authorship_mode(task: Task, state: dict[str, Any] | None = None) -> PrAuthorshipMode:"""Return the effective PR authorship mode for a run.diff --git a/products/tasks/backend/tests/test_desktop_gateway_token.py b/products/tasks/backend/tests/test_desktop_gateway_token.pyindex 58d5d0b63516..7ad57f945d82 100644--- a/products/tasks/backend/tests/test_desktop_gateway_token.py+++ b/products/tasks/backend/tests/test_desktop_gateway_token.py@@ -101,7 +101,6 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):def setUp(self) -> None:super().setUp()self.gates = {- "rollout": patch(f"{_VIEW}.desktop_rollout_enabled", return_value=True),"access": patch(f"{_VIEW}.get_desktop_access_decision", return_value=DesktopAccessDecision.ALLOWED),"credit": patch(f"{_VIEW}.team_credit_refusal", return_value=None),"blocked": patch(f"{_VIEW}.wizard_identity_blocked", return_value=False),@@ -190,12 +189,12 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):assert response.json()["reason"] == "unauthorized"post.assert_not_called()- def test_blocklisted_identity_is_refused_before_the_flag(self) -> None:+ def test_blocklisted_identity_is_refused_before_access(self) -> None:self.mocks["blocked"].return_value = Trueresponse, post = self._mint()assert response.status_code == status.HTTP_403_FORBIDDENassert response.json()["reason"] == "blocked"- self.mocks["rollout"].assert_not_called()+ self.mocks["access"].assert_not_called()post.assert_not_called()self.mocks["blocked"].assert_called_once_with(distinct_id=str(self.user.distinct_id),@@ -206,7 +205,7 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):surface="desktop_gateway_token",)- def test_an_access_rule_refusal_is_refused_before_the_rollout(self) -> None:+ def test_an_access_rule_refusal_is_refused_before_access(self) -> None:self.mocks["rules"].return_value = Trueresponse, post = self._mint()assert response.status_code == status.HTTP_403_FORBIDDEN@@ -215,7 +214,7 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):"reason": "blocked","detail": "This account cannot use the AI gateway.",}- self.mocks["rollout"].assert_not_called()+ self.mocks["access"].assert_not_called()post.assert_not_called()subject, surface = self.mocks["rules"].call_args.argsassert surface.value == "ai_gateway"@@ -227,29 +226,9 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):response, post = self._mint()assert response.status_code == status.HTTP_200_OKassert response.json() == {"enabled": False, "reason": "unconfigured"}- self.mocks["rollout"].assert_not_called()- post.assert_not_called()-- def test_flag_off_is_not_rolled_out_before_access_and_billing(self) -> None:- self.mocks["rollout"].return_value = False- self.mocks["credit"].return_value = "posthog_code_credits_exhausted"- response, post = self._mint()- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"enabled": False, "reason": "not_rolled_out"}self.mocks["access"].assert_not_called()- self.mocks["credit"].assert_not_called()post.assert_not_called()- def test_flag_is_evaluated_for_the_org_and_user(self) -> None:- self._mint()- organization, team, distinct_id, email = self.mocks["rollout"].call_args.args- assert (organization.id, team.id, distinct_id, email) == (- self.organization.id,- self.team.id,- self.user.distinct_id,- self.user.email,- )-def test_blocked_desktop_access_is_refused_before_billing(self) -> None:self.mocks["access"].return_value = DesktopAccessDecision.STARTUP_PLANresponse, post = self._mint()@@ -294,6 +273,29 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):self.mocks["credit"].assert_called_once_with(self.team.id, "posthog_code_credits")post.assert_not_called()+ @parameterized.expand(+ [+ ("reason_field", "credit", "posthog_code_credits_exhausted", "credit_bucket_exhausted"),+ ("code_field", "credit", "org_deactivated", "organization_deactivated"),+ ("minted", "credit", None, None),+ ]+ )+ def test_a_refusal_is_counted_by_the_code_the_app_reads(self, _name, gate, value, expected_reason) -> None:+ self.mocks[gate].return_value = value+ with patch(+ "products.tasks.backend.logic.services.desktop_gateway_token.posthoganalytics.default_client"+ ) as client:+ self._mint()+ count = client.metrics.count+ if expected_reason is None:+ count.assert_not_called()+ else:+ count.assert_called_once_with(+ "tasks.gateway_token.refused",+ 1,+ attributes={"surface": "desktop", "ai_product": "posthog_code", "reason": expected_reason},+ )+def test_unknown_credit_state_is_disabled(self) -> None:self.mocks["credit"].side_effect = RuntimeError("redis down")with patch(f"{_VIEW}.capture_exception") as capture:@@ -495,7 +497,7 @@ class TestDesktopGatewayTokenMint(_GatewayTestBase):assert refused.status_code == status.HTTP_402_PAYMENT_REQUIREDassert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS# The throttled request reached no gate past the credential shape check.- for gate in (email_pending, authorized, self.mocks["blocked"], self.mocks["rollout"]):+ for gate in (email_pending, authorized, self.mocks["blocked"], self.mocks["access"]):assert gate.call_count == 1post.assert_not_called()diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex 44dbb4d65313..d8231b999ea1 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -47,7 +47,7 @@ Existing Django callers should use `build_openai_client`, `build_async_openai_cl| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |The `posthog_code` product is retired on this gateway.-PostHog Desktop and PostHog Code mint scoped tokens on the Go gateway, and a `posthog_code` call here answers 403 with reason `product_retired` and a message that tells the user to update PostHog Desktop.+PostHog Desktop and PostHog Code mint scoped tokens on the Go gateway, and a `posthog_code` call here answers 403 with reason `product_retired` and a message that names the token refusals that send a client here.The desktop access gate and the Code-only per-user spend caps stay in the code, but no request reaches them.The retirement also closes the gap where the `posthog_code_credits` quota check failed open: Django's quota endpoint requires `project:read`, a Code OAuth token carries only `llm_gateway:read`, so every check answered 403 and the gateway let the request through.diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 6c134b3efb06..cd6961ee82e6 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -70,8 +70,11 @@ WIZARD_US_APP_ID = "019a0c79-b69d-0000-f31b-b41345208c9d"WIZARD_EU_APP_ID = "019a12d0-6edd-0000-0458-86616af3a3db"# What a retired wizard product answers every caller with.WIZARD_RETIRED_MESSAGE = "The wizard now runs on the PostHog AI gateway. Upgrade with: npx @posthog/wizard@latest"+# posthog_code reaches this gateway only after a PostHog AI token refusal, so the advice names+# the common refusals.POSTHOG_CODE_RETIRED_MESSAGE = (- "PostHog Code no longer runs on this gateway. Update PostHog Desktop to the latest version and try again."+ "PostHog Code no longer runs on this gateway. This request arrived here because the app couldn't get "+ "a PostHog AI token: sign in again and confirm your email is verified. Contact support if this continues.")POSTHOG_AI_US_APP_ID = "019ee060-3a0e-0000-7e9c-4e6b48dfae66"POSTHOG_AI_EU_APP_ID = "019ee061-5620-0000-1a0d-ab1160fceeb1"