: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(signals): raise the per-run gateway token cap to $15 for implementation runs (#91411)
Andrew Maguire644701eb7903
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex df8e7e154e62..b547977ebbe9 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -161,6 +161,20 @@ Funnel exposes these services to anyone on the internet who learns the URL, so t`SANDBOX_MCP_URL` overrides the `host.docker.internal` default (which only resolves from local Docker sandboxes, not Modal). Without it, sandbox agents can't reach the MCP server and lose access to the PostHog `execute-sql`, query, and tool-calling stack.+### AI gateway token caps++Scoped AI gateway tokens use `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD` as their default+per-run dollar cap. Two JSON object settings can override it:++- `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES` maps team IDs to caps.+- `SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES` maps AI product names to+ caps and defaults to `{"signals_implementation": "15"}`.++A product override takes precedence over a team override, which takes precedence+over the default cap. Set the product override to `{}` to disable the built-in+implementation override. An empty environment value is treated as unset and+restores the built-in map.+### Agent run telemetry (optional)To ship agent-server run metadata to PostHog Logs, set both of the first two; the third additionally produces one APM trace per run (root `task_run` span, a `turn` span per prompt, a `tool_call:<kind>` span per tool call) with trace/span ids stamped on the log records:diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex b03e9b639960..56309e7a044f 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -77,6 +77,12 @@ SANDBOX_AI_GATEWAY_MINT_KEY: str | None = get_from_env("SANDBOX_AI_GATEWAY_MINT_SANDBOX_AI_GATEWAY_TOKEN_CAP_USD: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD", "10")# Per-team per-run cap overrides as a JSON object of team id to dollars, e.g. {"2": "10"}.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES", "")+# Per-product per-run cap overrides as a JSON object of ai_product to dollars. A product+# entry beats the team override and the default: run cost tracks the kind of work, and+# implementation runs regularly outspend every other stage.+SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES: str = get_from_env(+ "SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES", '{"signals_implementation": "15"}'+)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/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex 756cfc4d1229..1cdc5a541f91 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -12,6 +12,7 @@ import jsonimport timeimport randomimport logging+from decimal import Decimal, InvalidOperationfrom typing import Anyfrom django.conf import settings@@ -42,6 +43,9 @@ _ORIGIN_TO_GATEWAY_PRODUCT: dict[str, str] = {_SIGNALS_STAGE_PRODUCTS = frozenset({"scout", "research", "implementation", "repo_selection", "custom_agent"})_SCOUT_STAGE_PREFIX = "scout:"+_MAX_CAP_USD = Decimal("10000")+_MAX_CAP_DECIMAL_PLACES = 6+# Products whose runs may mint an internally funded token. Mint scope needs# server-side provenance: `internal` and some origin_product values are# API-settable, so an unmapped origin marked internal resolves to@@ -104,21 +108,51 @@ def _token_ttl_seconds() -> int:return max(60, min(configured, 86400))-def _token_cap_usd(team_id: int) -> str:- """Per-run cap, with per-team overrides (JSON map of team id to dollars).+def _cap_override(raw: str, key: str, setting_name: str) -> str | None:+ if not raw:+ return None+ try:+ override = json.loads(raw).get(key)+ except (ValueError, AttributeError):+ logger.warning("Ignoring invalid JSON object for %s", setting_name)+ return None+ if override is None:+ return None+ try:+ cap = Decimal(str(override))+ except (InvalidOperation, ValueError):+ logger.warning("Ignoring invalid cap for %s", setting_name)+ return None+ if not cap.is_finite():+ logger.warning("Ignoring invalid cap for %s", setting_name)+ return None+ exponent = cap.as_tuple().exponent+ if not isinstance(exponent, int):+ logger.warning("Ignoring invalid cap for %s", setting_name)+ return None+ decimal_places = max(0, -exponent)+ if cap <= 0 or cap > _MAX_CAP_USD or decimal_places > _MAX_CAP_DECIMAL_PLACES:+ logger.warning("Ignoring invalid cap for %s", setting_name)+ return None+ return f"{cap:f}"+++def _token_cap_usd(team_id: int, ai_product: str) -> str:+ """Per-run cap: the product override, else the team override, else the default.- Team 2's custom scouts run hotter than the external fleet, so it carries a- higher cap than the default without raising everyone's ceiling.+ The product override wins because run cost tracks the kind of work, not who+ it runs for — implementation runs regularly outspend every other stage. The+ team override raises a single team (team 2's custom scouts run hotter than+ the external fleet) without raising everyone's ceiling."""- raw = settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES- if raw:- try:- override = json.loads(raw).get(str(team_id))- except (ValueError, AttributeError):- override = None- logger.warning("ai_gateway_token: cap overrides setting is not a JSON object; using the default cap")- if override is not None:- return str(override)+ product_cap = _cap_override(+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES, ai_product, "product cap overrides"+ )+ if product_cap is not None:+ return product_cap+ team_cap = _cap_override(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES, str(team_id), "cap overrides")+ if team_cap is not None:+ return team_capreturn str(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD)@@ -136,7 +170,7 @@ def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None)return Nonebody: dict[str, Any] = {- "cap_usd": _token_cap_usd(team_id),+ "cap_usd": _token_cap_usd(team_id, ai_product),"ttl_seconds": _token_ttl_seconds(),"product": ai_product,"obo": str(team_id),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 7bdc612244eb..4b33e0717ed4 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@@ -99,6 +99,7 @@ def mint_settings(settings):settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD = "3"settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 14400settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = ""+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = ""return settings@@ -365,6 +366,27 @@ class TestUserPinAndCapOverride:assert post.call_args_list[0].kwargs["json"]["cap_usd"] == "10"assert post.call_args_list[1].kwargs["json"]["cap_usd"] == "3"+ def test_cap_product_override_beats_team_override(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = '{"2": "10"}'+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = '{"signals_implementation": "15"}'+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product="signals_implementation", team_id=2)+ mint_scoped_token(ai_product="signals_scout", team_id=2)+ assert post.call_args_list[0].kwargs["json"]["cap_usd"] == "15"+ assert post.call_args_list[1].kwargs["json"]["cap_usd"] == "10"++ @pytest.mark.parametrize("invalid_product_cap", ["", True, 0, -1, "0.0000001", "10000.000001", "NaN"])+ def test_invalid_product_cap_falls_back_to_team_override(self, mint_settings, invalid_product_cap):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = '{"2": "10"}'+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_PRODUCT_OVERRIDES = json.dumps(+ {"signals_implementation": invalid_product_cap}+ )+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product="signals_implementation", team_id=2)+ assert post.call_args.kwargs["json"]["cap_usd"] == "10"+def test_malformed_overrides_fall_back_to_default(self, mint_settings):mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = "not json"with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post: