: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(llm-gateway): add targeted per-user caps for posthog code (#109055)
Alessandro Pogliaghie93604b6c514
diff --git a/docs/internal/task-run-api.md b/docs/internal/task-run-api.mdindex 397c380a81e8..4a48821d8771 100644--- a/docs/internal/task-run-api.md+++ b/docs/internal/task-run-api.md@@ -8,6 +8,7 @@ This restriction also applies to warm creation, warm activation, warm resumes, aRequests through a PostHog connection keep the sandbox origin and the same run restrictions.The origin marker does not grant sandbox access.PostHog Desktop access, runtime access, and usage limits still apply.+PostHog Code's per-user gateway caps are disabled by default and apply only to configured users when enabled.Repository-backed report discussions also require Desktop access.Opening Ask AI on a Self-driving inbox report warms a task sandbox for the discussion.diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex cec26d9d0624..1b379b434977 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -48,6 +48,12 @@ Existing Django callers should use `build_openai_client`, `build_async_openai_clFor PostHog Desktop, the Python gateway maps Django credential rejections to generic access denials. Transport, server, and malformed-response failures remain retryable service errors.+PostHog Code's per-user spend caps remain in Python while its callers depend on the product authorization and billing policy above.+The Code-only switch enables the existing burst and sustained caps only for configured authenticated user IDs, whether billed or unbilled; it defaults to disabled with an empty list.+A Go-only change would not limit these callers before migration.+This blocker was checked on 2026-09-30 against PostHog master at `255ec0a4db39d9081fd194b2ac8ae57fdc75de32` and Go main at `da39202d10768336abd7a21fd9f27d5c8e7f2c27`.+Go's [`GatewayCredential`](https://github.com/PostHog/ai-gateway/blob/da39202d10768336abd7a21fd9f27d5c8e7f2c27/internal/auth/gateway_credential.go) resolves a fixed team and caller-asserted attribution; it does not apply Desktop's request-selected project or Django product policy.+Open-weight models added to the Python gateway under the freeze stay there for the same reason.`zai-org/glm-5.3-flash` is Baseten-exclusive and reachable only by the `posthog_code` and `review_hog` products.Its callers are PostHog Desktop and PostHog Code, so the model depends on the OAuth application allowlists, the request-selected project validated against OAuth scope and live organization membership, and the billing policy.diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex 983d9503a535..e7fd1e2934a7 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -226,6 +226,8 @@ class Settings(BaseSettings):user_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITSuser_cost_limits_disabled: bool = False+ posthog_code_user_cost_limits_enabled: bool = False+ posthog_code_capped_user_ids: set[int] = set()# Per-sandbox-run ceiling, keyed on the task the token was minted for. Product and user# budgets are windowed, so neither bounds one runaway conversation inside its window.diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.pyindex 851e19c752cd..8008a1d1833c 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py@@ -253,15 +253,12 @@ class _UserCostThrottleBase(CostThrottle):return configdef _is_exempt(self, context: ThrottleContext) -> bool:- """Whether this request meters against the posthog_code budget, which billable credits- cover instead of a per-user cost limit.-- Keyed on the resolved cost key rather than the declared product, for the same reason- `_cost_key` is: a Signals run holding an Array-app token declares `posthog_code`, and- reading the declaration here would hand it this exemption and leave the interactive- budget its spend is keyed to unenforced.- """- return self._cost_key(context) == POSTHOG_CODE_PRODUCT+ """Use the resolved budget so Signals runs declaring Code cannot claim the Code exemption."""+ settings = get_settings()+ return self._cost_key(context) == POSTHOG_CODE_PRODUCT and (+ not settings.posthog_code_user_cost_limits_enabled+ or context.user.user_id not in settings.posthog_code_capped_user_ids+ )async def allow_request(self, context: ThrottleContext) -> ThrottleResult:if not context.end_user_id or self._is_exempt(context):@@ -291,7 +288,7 @@ class _UserCostThrottleBase(CostThrottle):return await super().get_status(context)async def record_cost(self, context: ThrottleContext, cost: float) -> None:- if not context.end_user_id or self._is_exempt(context):+ if not context.end_user_id:returnawait super().record_cost(context, cost)diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.pyindex a7e22706b81a..13ff3ca8e151 100644--- a/services/llm-gateway/tests/test_cost_throttles.py+++ b/services/llm-gateway/tests/test_cost_throttles.py@@ -1170,18 +1170,81 @@ class TestRateLimitPoisoningPrevention:class TestPostHogCodeUserThrottling:@pytest.mark.asyncio- @pytest.mark.parametrize("throttle_type", [UserCostBurstThrottle, UserCostSustainedThrottle])- async def test_posthog_code_has_no_user_cost_limit(self, throttle_type: type[_UserCostThrottleBase]) -> None:+ @pytest.mark.parametrize(+ ("throttle_type", "limit_usd"), [(UserCostBurstThrottle, 100.0), (UserCostSustainedThrottle, 1000.0)]+ )+ @pytest.mark.parametrize("code_usage_billed", [False, True])+ async def test_posthog_code_user_cost_limit(+ self,+ throttle_type: type[_UserCostThrottleBase],+ limit_usd: float,+ code_usage_billed: bool,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.setattr(get_settings(), "posthog_code_user_cost_limits_enabled", True)+ monkeypatch.setattr(get_settings(), "posthog_code_capped_user_ids", {42})throttle = throttle_type(redis=None)- context = make_context(product="posthog_code")+ context = make_context(user=make_user(user_id=42), product="posthog_code", code_usage_billed=code_usage_billed)- await throttle.record_cost(context, 600.0)+ await throttle.record_cost(context, limit_usd - 1.0)- result = await throttle.allow_request(context)+ assert (await throttle.allow_request(context)).allowed is Truestatus = await throttle.get_status(context)- assert result.allowed is True+ assert status.used_usd == limit_usd - 1.0+ assert status.remaining_usd == 1.0assert status.exceeded is False- assert status.limit_usd == float("inf")++ await throttle.record_cost(context, 1.0)++ result = await throttle.allow_request(context)+ status = await throttle.get_status(context)+ assert result.allowed is False+ assert result.status_code == 429+ assert result.used_usd == limit_usd+ assert result.limit_usd == limit_usd+ assert status.exceeded is True+ assert status.used_usd == limit_usd+ assert status.limit_usd == limit_usd+ assert status.remaining_usd == 0.0++ @pytest.mark.asyncio+ @pytest.mark.parametrize("throttle_type", [UserCostBurstThrottle, UserCostSustainedThrottle])+ async def test_code_selection_preserves_spend_and_other_product_limits(+ self, throttle_type: type[_UserCostThrottleBase], monkeypatch: pytest.MonkeyPatch+ ) -> None:+ settings = get_settings()+ monkeypatch.setattr(settings, "posthog_code_user_cost_limits_enabled", False)+ monkeypatch.setattr(settings, "posthog_code_capped_user_ids", set())+ throttle = throttle_type(redis=None)+ code = make_context(user=make_user(user_id=42), product="posthog_code", code_usage_billed=True)+ other_code = make_context(user=make_user(user_id=43), product="posthog_code", code_usage_billed=True)+ wizard = make_context(product="wizard")++ for context in (code, other_code, wizard):+ await throttle.record_cost(context, 10_000.0)++ for enabled, selected, code_denied, other_denied in (+ (False, {42}, False, False),+ (True, set(), False, False),+ (True, {42}, True, False),+ (True, {43}, False, True),+ (True, {42, 43}, True, True),+ (False, {42, 43}, False, False),+ ):+ monkeypatch.setattr(settings, "posthog_code_user_cost_limits_enabled", enabled)+ monkeypatch.setattr(settings, "posthog_code_capped_user_ids", selected)++ for context, denied in ((code, code_denied), (other_code, other_denied)):+ assert (await throttle.allow_request(context)).allowed is not denied+ status = await throttle.get_status(context)+ assert status.exceeded is denied+ if denied:+ assert status.used_usd == 10_000.0+ else:+ assert status.used_usd == 0.0+ assert status.limit_usd == float("inf")+ assert (await throttle.allow_request(wizard)).allowed is False+ assert (await throttle.get_status(wizard)).exceeded is True@pytest.mark.asyncioasync def test_non_code_product_allows_normal_spend(self) -> None:@@ -1287,9 +1350,7 @@ class TestProvenanceCostKey:@pytest.mark.asyncioasync def test_marked_run_declaring_posthog_code_keeps_its_user_budget(self) -> None:- # posthog_code is exempt from per-user cost limits because billable credits meter it- # instead. Reading that exemption off the declared product would hand it to a marked run- # on an Array-app token, which spends against `signals_interactive`.+ # A Signals run with a Code token must keep its signals_interactive budget even when it declares posthog_code.throttle = UserCostBurstThrottle(redis=None)context = make_context(product="posthog_code", user=make_signals_user(interactive=True))limit, _ = throttle._get_limit_and_window(context)