: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(tasks): mint ai gateway tokens for posthog_ai sandbox runs (#105244)
Brandonaec9d4d4937b
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 79bb426e9f06..54a06bd67900 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -88,7 +88,7 @@ SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES: str = get_from_env("SANDBOX_AI_GATEW# retries behind a cap that binds mid-run. Suggestion runs stay on the default.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES",- '{"signals_implementation": "20", "signals_inbox": "75", "signals_chat": "30", "slack_app": "75", "workflows": "75"}',+ '{"signals_implementation": "20", "signals_inbox": "75", "signals_chat": "30", "slack_app": "75", "workflows": "75", "posthog_ai": "75"}',)SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS: int = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS", 0, type_cast=int)SANDBOX_MCP_URL: str | None = get_from_env("SANDBOX_MCP_URL", None, optional=True)diff --git a/products/tasks/backend/logic/services/gateway_model_pin.py b/products/tasks/backend/logic/services/gateway_model_pin.pyindex c5eb93f6c771..377d730890b9 100644--- a/products/tasks/backend/logic/services/gateway_model_pin.py+++ b/products/tasks/backend/logic/services/gateway_model_pin.py@@ -18,6 +18,7 @@ _FIRST_PARTY_AGENT_MODELS: list[str] = list()PRODUCT_ALLOWED_MODELS: dict[str, list[str]] = {+ "posthog_ai": _FIRST_PARTY_AGENT_MODELS,"review_hog": _FIRST_PARTY_AGENT_MODELS,"slack_app": _FIRST_PARTY_AGENT_MODELS,"workflows": _FIRST_PARTY_AGENT_MODELS,diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex 6e6ff7643c5e..5ca543d246d4 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -68,9 +68,11 @@ _MAX_CAP_DECIMAL_PLACES = 6# reservation resolve to posthog_code and cannot mint. slack_app needs server# provenance too (has_slack_provenance), older rows included.# workflows qualifies because validate_origin_product reserves its origin for the-# workflow_tasks endpoint.+# workflow_tasks endpoint. posthog_ai is API-settable but not internally funded: its token+# bills the run's own team to AI credits, and the mint refuses an exhausted balance.MINTABLE_PRODUCTS = frozenset({+ "posthog_ai","review_hog","slack_app","signals_scout",@@ -90,11 +92,11 @@ MINTABLE_PRODUCTS = frozenset(INTERACTIVE_MINTABLE_PRODUCTS = frozenset({"signals_inbox", "signals_chat"})# Interactive runs with no wall-clock cap; their tokens last the sandbox lifetime.-SANDBOX_BOUND_MINTABLE_PRODUCTS = frozenset({"slack_app"})+SANDBOX_BOUND_MINTABLE_PRODUCTS = frozenset({"posthog_ai", "slack_app"})# The Python gateway bills these mintable products to AI credits and stops them at zero.# The Go gateway has no credit check, so the mint checks the balance when the run starts.-AI_CREDITS_BILLED_PRODUCTS = frozenset({"slack_app", "workflows"})+AI_CREDITS_BILLED_PRODUCTS = frozenset({"posthog_ai", "slack_app", "workflows"})_PRODUCT_ALLOWED_MODELS = PRODUCT_ALLOWED_MODELSdiff --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 a606b6e8b899..a268d3ec2148 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@@ -161,7 +161,7 @@ class TestMintScopedToken:assert body["product"] == "review_hog"assert body["allowed_models"] == _PRODUCT_ALLOWED_MODELS["review_hog"]- @pytest.mark.parametrize("product", ["review_hog", "slack_app", "workflows"])+ @pytest.mark.parametrize("product", ["posthog_ai", "review_hog", "slack_app", "workflows"])def test_model_pin_follows_the_catalog(self, product):from products.tasks.backend.facade.run_config import RuntimeAdapter, get_models_for_runtime_adapterfrom products.tasks.backend.logic.services.gateway_model_pin import SDK_IMPLICIT_MODELS@@ -658,6 +658,7 @@ class TestUserPinAndCapOverride:("signals_chat", "30"),("slack_app", "75"),("workflows", "75"),+ ("posthog_ai", "75"),("signals_scout_suggestions", "10"),],)@@ -888,7 +889,7 @@ _CREDIT_LOOKUP = "products.tasks.backend.temporal.process_task.ai_gateway_token.class TestMintRefusalScope:def test_ai_credits_billed_products(self):- assert AI_CREDITS_BILLED_PRODUCTS == {"slack_app", "workflows"}+ assert AI_CREDITS_BILLED_PRODUCTS == {"posthog_ai", "slack_app", "workflows"}assert AI_CREDITS_BILLED_PRODUCTS <= MINTABLE_PRODUCTS@pytest.mark.parametrize("product", ["workflows", "review_hog", "signals_scout"])@@ -900,7 +901,7 @@ class TestMintRefusalScope:def test_pi_runs_never_mint(self, product):assert mint_refusal(product, team_id=2, state=None, model=None, runtime="pi") == "pi_runtime"- @pytest.mark.parametrize("product", ["workflows", "review_hog"])+ @pytest.mark.parametrize("product", ["posthog_ai", "workflows", "review_hog"])def test_pinned_products_refuse_an_off_pin_model(self, product):refusal = mint_refusal(product, team_id=2, state=None, model="zai-org/glm-5.3", runtime="acp")assert refusal == "model_outside_pin"@@ -979,3 +980,66 @@ class TestWorkflowsMint:post.return_value = responsemint_scoped_token(ai_product="workflows", team_id=2)assert post.call_args.kwargs["json"]["ttl_seconds"] == 4 * 60 * 60+++class TestPosthogAiMint:+ def _env(self, mint_settings, *, over_quota=False, **overrides):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "posthog_ai"+ kwargs: dict = {+ "team_id": 123,+ "origin_product": "posthog_ai",+ "state": None,+ "model": "claude-opus-4-8",+ "runtime": "acp",+ **overrides,+ }+ with (+ patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_abc"+ ) as mint,+ patch(_CREDIT_LOOKUP, return_value=over_quota),+ ):+ env = ai_gateway_env_vars(**kwargs)+ return env, mint++ def test_posthog_ai_run_mints_a_posthog_ai_token(self, mint_settings):+ env, mint = self._env(mint_settings)+ assert env["AI_GATEWAY_TOKEN"] == "phe_abc"+ assert env["AI_GATEWAY_PRODUCT"] == "posthog_ai"+ mint.assert_called_once_with(ai_product="posthog_ai", team_id=123, user=None)++ def test_unrouted_posthog_ai_run_does_not_mint(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "workflows"+ with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="posthog_ai", model="claude-opus-4-8", runtime="acp")+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ @pytest.mark.parametrize("model", ["zai-org/glm-5.3", "moonshotai/kimi-k3"])+ def test_model_outside_the_pin_does_not_mint(self, mint_settings, model):+ env, mint = self._env(mint_settings, model=model)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ def test_team_out_of_ai_credits_does_not_mint(self, mint_settings):+ env, mint = self._env(mint_settings, over_quota=True)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ def test_mint_carries_the_first_party_pin(self, mint_settings):+ response = MagicMock(status_code=201, json=MagicMock(return_value={"token": "phe_abc"}), text="")+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = response+ assert mint_scoped_token(ai_product="posthog_ai", team_id=2) == "phe_abc"+ body = post.call_args.kwargs["json"]+ assert body["product"] == "posthog_ai"+ assert body["allowed_models"] == _PRODUCT_ALLOWED_MODELS["posthog_ai"]++ def test_ttl_covers_the_sandbox_lifetime(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0+ mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 3 * 60 * 60+ response = MagicMock(status_code=201, json=MagicMock(return_value={"token": "phe_abc"}), text="")+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = response+ mint_scoped_token(ai_product="posthog_ai", team_id=2)+ assert post.call_args.kwargs["json"]["ttl_seconds"] == MAX_SANDBOX_TTL_SECONDS + 3600