: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(llm-gateway): lift posthog_code per-user caps for orgs billed for Code usage (#70946)
Adam Bowker5ec77d26d4ed
diff --git a/ee/api/quota_limits.py b/ee/api/quota_limits.pyindex 718e5a88c556..80327e13ea9d 100644--- a/ee/api/quota_limits.py+++ b/ee/api/quota_limits.py@@ -18,6 +18,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.constants import AvailableFeaturefrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited@@ -31,9 +32,14 @@ class QuotaResourceLimitSerializer(serializers.Serializer):class QuotaLimitsResponseSerializer(serializers.Serializer):limited = serializers.DictField(child=QuotaResourceLimitSerializer(),+ help_text="Per-resource limit state for every `QuotaResource` value, e.g. `ai_credits`, `posthog_code_credits`.",+ )+ code_usage_billing_active = serializers.BooleanField(help_text=(- "Per-resource limit state keyed by `QuotaResource` value. "- "Currently only `ai_credits` is reported; additional resources may be added."+ "Whether the team's organization pays for PostHog Code usage: billing grants the "+ "`posthog_code_usage` product feature only on the Code usage product's paid plan, "+ "synced into the organization's available features. Consumers gate paid-tier Code "+ "behavior on this; an org unknown to billing reads as not paying."),)@@ -66,4 +72,13 @@ class QuotaLimitsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):}for resource in QuotaResource}- return Response(QuotaLimitsResponseSerializer({"limited": limited}).data)+ return Response(+ QuotaLimitsResponseSerializer(+ {+ "limited": limited,+ "code_usage_billing_active": self.team.organization.is_feature_available(+ AvailableFeature.POSTHOG_CODE_USAGE+ ),+ }+ ).data+ )diff --git a/ee/api/test/test_quota_limits.py b/ee/api/test/test_quota_limits.pyindex 2042bcd77a7e..81ec1bf9ad45 100644--- a/ee/api/test/test_quota_limits.py+++ b/ee/api/test/test_quota_limits.py@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.models.organization import Organizationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team@@ -53,6 +54,22 @@ class TestQuotaLimitsAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()self.assertEqual(data["limited"]["ai_credits"], {"limited": False})+ # Org holds no billing-granted Code usage feature -> reads as not paying+ self.assertIs(data["code_usage_billing_active"], False)++ def test_reports_code_usage_billing_state(self) -> None:+ # The LLM gateway keys posthog_code per-user cap bypass and model gating+ # on this field - dropping it (or resolving the wrong org) silently+ # re-caps paying users.+ self.organization.available_product_features = [+ {"key": AvailableFeature.POSTHOG_CODE_USAGE, "name": "PostHog Code usage billing"}+ ]+ self.organization.save()++ response = self.client.get(self._url())++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIs(response.json()["code_usage_billing_active"], True)def test_returns_limited_when_team_is_over_quota(self) -> None:self._set_ai_credits_limit(self.team.api_token, 9_999_999_999)diff --git a/posthog/constants.py b/posthog/constants.pyindex 1e99db77696c..3bed294c2f53 100644--- a/posthog/constants.py+++ b/posthog/constants.py@@ -52,6 +52,7 @@ class AvailableFeature(StrEnum):AUDIT_LOGS = "audit_logs"APPROVALS = "approvals"XAA_AUTHENTICATION = "xaa_authentication"+ POSTHOG_CODE_USAGE = "posthog_code_usage"TREND_FILTER_TYPE_ACTIONS = "actions"diff --git a/services/llm-gateway/src/llm_gateway/api/usage.py b/services/llm-gateway/src/llm_gateway/api/usage.pyindex 71ea7311c1e3..0c5cb31ddb82 100644--- a/services/llm-gateway/src/llm_gateway/api/usage.py+++ b/services/llm-gateway/src/llm_gateway/api/usage.py@@ -78,13 +78,6 @@ async def get_usage(product=product,)now = datetime.now(tz=UTC)- # The product's own credit bucket (resolve_plan_and_quota resolves per bucket;- # always unlimited for unbilled products), reported under the legacy `ai_credits`- # response field — clients read `ai_credits.exhausted` regardless of bucket. Run- # through the same credit_bucket_scope check as the request-path throttle: clients- # gate on this response, so reporting the raw bucket state would disable the product- # for seat-covered users the gateway itself would allow.- credits_exhausted = bucket_block_applies(product, plan_info.plan_key, quota_status.limited)context = ThrottleContext(user=user,@@ -93,9 +86,16 @@ async def get_usage(plan_key=plan_info.plan_key,seat_created_at=plan_info.seat_created_at,seat_missing=plan_info.seat_missing,+ code_usage_billed=quota_status.code_usage_billing_active,billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,credits_exhausted=quota_status.limited,)+ # The product's own credit bucket (resolve_plan_and_quota resolves per bucket;+ # always unlimited for unbilled products), reported under the legacy `ai_credits`+ # response field — clients read `ai_credits.exhausted` regardless of bucket. Run+ # through the same decision as the request-path throttle: clients gate on this+ # response, so it must never disagree with what enforcement would do.+ credits_exhausted = bucket_block_applies(context)burst_status: CostLimitStatus | None = Nonesustained_status: CostLimitStatus | None = Nonediff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex f26933a67279..77ec22445f0f 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -69,6 +69,13 @@ FREE_PLAN_COST_LIMIT = UserCostLimit(sustained_window_seconds=2592000,)+ORG_BILLED_USER_COST_LIMIT = UserCostLimit(+ burst_limit_usd=float("inf"),+ burst_window_seconds=86400,+ sustained_limit_usd=float("inf"),+ sustained_window_seconds=2592000,+)+_COST_LIMIT_KEY_ALIASES: dict[str, str] = {"array": "posthog_code",@@ -177,12 +184,6 @@ class Settings(BaseSettings):user_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITSuser_cost_limits_disabled: bool = False- # Plan-key prefixes that bill usage-based. These plans get the usage-based- # PostHog Code user cost limit instead of the subscription-era default.- # Placeholder prefix until billing finalizes the plan key; override by env var- # without a deploy if the name differs.- usage_based_plan_prefixes: list[str] = ["posthog-code-usage"]-default_fallback_cost_usd: float = 0.01posthog_api_base_url: str = "https://us.posthog.com"diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.pyindex 4aeda4fb1bf2..496e37850180 100644--- a/services/llm-gateway/src/llm_gateway/dependencies.py+++ b/services/llm-gateway/src/llm_gateway/dependencies.py@@ -169,6 +169,10 @@ async def resolve_plan_and_quota(billing into a credit bucket we overlap them. Unbilled products short-circuitthe throttle stack regardless of quota state, so we skip the resolver entirelyrather than paying for the Redis GET (and the HTTP fallback on cache miss).++ Caveat: ``code_usage_billing_active`` rides the quota fetch, so a product+ without a credit bucket always reads as unbilled — removing or repointing+ posthog_code's bucket would silently turn off the org-billed cap bypass."""product_config = get_product_config(product)if product_config and product_config.credit_bucket is not None:@@ -210,6 +214,7 @@ async def enforce_throttles(plan_key=plan_info.plan_key,seat_created_at=plan_info.seat_created_at,seat_missing=plan_info.seat_missing,+ code_usage_billed=quota_status.code_usage_billing_active,billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,credits_exhausted=quota_status.limited,)diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 464335cbf44c..9d65d89cff58 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom enum import StrEnum-from typing import Final, Literal+from typing import Finalfrom fastapi import HTTPException@@ -16,10 +16,8 @@ class CreditBucket(StrEnum):Values match (or, once created, will match) the Django quota resource keys(ee/billing/quota_limiting.py QuotaResource), which is what the gateway'squota resolver checks against. Both buckets have gateway-side quota- enforcement; which users are blocked when a bucket is exhausted depends on- ``ProductConfig.credit_bucket_scope`` — AI_CREDITS blocks all users of the- product, POSTHOG_CODE_CREDITS blocks only usage-based-plan users (see- ``credit_bucket_scope`` below).+ enforcement: an exhausted bucket blocks every caller of the product, the+ same population the usage reporter counts into it."""AI_CREDITS = "ai_credits"@@ -36,18 +34,9 @@ class ProductConfig:# Which customer credit bucket this product bills into. None = not billed: emitted# $ai_generation events are tagged $ai_billable=false and the usage reporter# (posthog/tasks/usage_report.py) ignores them. A bucket value tags events billable- # so the reporter rolls them into that bucket's credit counter, and requests are- # blocked when the bucket's quota is exhausted — see credit_bucket_scope below for- # which users that block applies to.+ # so the reporter rolls them into that bucket's credit counter, and every caller+ # is blocked when the bucket's quota is exhausted.credit_bucket: CreditBucket | None = None- # Which users a bucket's exhausted-limit should block, once credit_bucket is set.- # "all_users" (default): every user of a billable product counts against the bucket- # limit — appropriate when all of the product's usage is billable (e.g. AI_CREDITS).- # "usage_based_plans": only users on a usage-based plan (see- # services.plan_resolver.is_usage_based_plan) count against the bucket limit —- # seat-covered (free/pro/alpha) users are excluded from the org's billed usage- # counter at the usage-report layer, so they must not be blocked by it either.- credit_bucket_scope: Literal["all_users", "usage_based_plans"] = "all_users"BEDROCK_MODELS = BEDROCK_MODEL_IDS@@ -111,10 +100,6 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {# Bills as posthog_code credits (pass-through model costs, no markup) — see# get_teams_with_posthog_code_credits_used_in_period in posthog/tasks/usage_report.py.credit_bucket=CreditBucket.POSTHOG_CODE_CREDITS,- # Only usage-based-plan users' generations are billed to the org's usage- # subscription (seat-covered usage is excluded at the usage-report layer), so- # only those users should be blocked when the org's usage limit is reached.- credit_bucket_scope="usage_based_plans",),# PostHog-initiated internal task runs (Task.internal=True without a more specific# origin route — e.g. the repo-selection agent). Deliberately unbilled: this isdiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py b/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.pyindex 99a705cfc275..aea1f147205b 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/billable_credits_throttle.py@@ -2,7 +2,6 @@ from __future__ import annotationsfrom llm_gateway.products.config import CreditBucket, get_product_configfrom llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult-from llm_gateway.services.plan_resolver import is_usage_based_plan_BUCKET_EXHAUSTED_DETAIL = {CreditBucket.AI_CREDITS: (@@ -30,29 +29,23 @@ _DEFAULT_EXHAUSTED_DETAIL = (_RETRY_AFTER_SECONDS = 60-def bucket_block_applies(product: str, plan_key: str | None, credits_exhausted: bool) -> bool:+def bucket_block_applies(context: ThrottleContext) -> bool:"""Whether the product's exhausted credit bucket blocks this caller.The single source of truth for the bucket-block decision, shared by therequest-path throttle and the usage endpoint so what's reported alwaysmatches what's enforced. Unbilled products (``credit_bucket=None``) are- never blocked. For a bucket scoped to usage-based plans (see- ``ProductConfig.credit_bucket_scope``), only a user on a usage-based plan- is blocked — seat-covered usage is excluded from the billed usage counter- at the usage-report layer, so the org's usage limit doesn't apply to those- users; blocking them would take the product away from free/pro seat holders- because of other users' usage-based spend. An unknown/missing plan_key- means NOT usage-based here too, i.e. not blocked — consistent with the- resolver's fail-open posture.+ never blocked. For billed products, exhaustion blocks every caller — the+ usage reporter counts every generation into the bucket regardless of who+ made it, so the blocked population must match or exempted callers burn+ past the limit they're filling. A free org's monthly allocation and a+ paying org's billing limit both surface here as exhaustion; ``limited``+ fails open on resolution errors, so a quota blip never spuriously blocks."""- config = get_product_config(product)+ config = get_product_config(context.product)if not (config and config.credit_bucket is not None):return False- if not credits_exhausted:- return False- if config.credit_bucket_scope == "usage_based_plans" and not is_usage_based_plan(plan_key):- return False- return True+ return context.credits_exhaustedclass BillableCreditThrottle(Throttle):@@ -70,7 +63,7 @@ class BillableCreditThrottle(Throttle):if config is None or config.credit_bucket is None:return ThrottleResult.allow()- if not bucket_block_applies(context.product, context.plan_key, context.credits_exhausted):+ if not bucket_block_applies(context):return ThrottleResult.allow()return ThrottleResult.deny(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 7c526c440d85..593dd6ce604c 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@@ -10,6 +10,7 @@ from redis.asyncio import Redisfrom llm_gateway.config import (DEFAULT_USER_COST_LIMIT,FREE_PLAN_COST_LIMIT,+ ORG_BILLED_USER_COST_LIMIT,get_settings,)@@ -45,6 +46,10 @@ def _is_free_plan_throttled(context: ThrottleContext) -> bool:)+def _is_org_billed_seatless(context: ThrottleContext) -> bool:+ return context.product == POSTHOG_CODE_PRODUCT and context.seat_missing and context.code_usage_billed++class CostThrottle(Throttle):scope: str@@ -245,6 +250,10 @@ class _UserCostThrottleBase(CostThrottle):return f"{base}:m{mult}"def _get_config(self, context: ThrottleContext) -> UserCostLimit:+ # Precedence matters: an org-billed seatless user is uncapped even though+ # seat_missing would otherwise select the free-plan cap below.+ if _is_org_billed_seatless(context):+ return ORG_BILLED_USER_COST_LIMITif _is_free_plan_throttled(context):return FREE_PLAN_COST_LIMITdiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.pyindex 78d145abc2e8..c53205b4b93e 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py@@ -48,6 +48,7 @@ class ThrottleContext:plan_key: str | None = Noneseat_created_at: str | None = Noneseat_missing: bool = False+ code_usage_billed: bool = Falsebilling_period_start: str | None = Nonecredits_exhausted: bool = Falsediff --git a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py b/services/llm-gateway/src/llm_gateway/services/plan_resolver.pyindex 9ee5585d3f38..f7cde5e69f91 100644--- a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py+++ b/services/llm-gateway/src/llm_gateway/services/plan_resolver.py@@ -57,20 +57,6 @@ def is_pro_plan(plan_key: str | None) -> bool:return any(plan_key.startswith(p) for p in PRO_PLAN_PREFIXES)-def is_usage_based_plan(plan_key: str | None) -> bool:- """Whether the plan bills usage-based (vs seat-based subscription).-- Prefix-matched like :func:`is_pro_plan`, but settings-driven so the prefix- can be corrected by env var when billing finalizes the plan key. Unknown or- missing plans are NOT usage-based, so a flaky plan resolution falls back to- the standard seat-based/free limits rather than the usage-based user cost- limit.- """- if not plan_key:- return False- return any(plan_key.startswith(p) for p in get_settings().usage_based_plan_prefixes)--def parse_iso_utc(value: str) -> datetime:parsed = datetime.fromisoformat(value)return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)diff --git a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py b/services/llm-gateway/src/llm_gateway/services/quota_resolver.pyindex d14e2254d279..ff7a9eb2c889 100644--- a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py+++ b/services/llm-gateway/src/llm_gateway/services/quota_resolver.py@@ -9,7 +9,10 @@ values in the product registry — e.g. ``ai_credits``, ``posthog_code_credits``Transient upstream failures (network errors, 5xx) are retried within therequest with exponential backoff. 4xx responses or exhausted retries fallopen and briefly cache ``limited=False`` so a struggling Django isn't hit on-every subsequent request.+every subsequent request. The Code usage billing bit in that fail-open entry+falls back to the team's last known value instead (see+``_LAST_KNOWN_BILLING_TTL_SECONDS``), so an upstream blip doesn't re-cap a+paying org's users."""from __future__ import annotations@@ -37,6 +40,12 @@ logger = structlog.get_logger(__name__)# upstream is consulted again within a minute._FAIL_OPEN_CACHE_TTL_SECONDS = 60+# Last known Code usage billing bit per team: written on every successful+# fetch, read only when a fetch fails. Bounds how stale the fail-time fallback+# may be — a billed org keeps paid-tier treatment through a day-long upstream+# outage, after which unknown teams fail closed again.+_LAST_KNOWN_BILLING_TTL_SECONDS = 24 * 60 * 60+# Exponential backoff between within-request retries on transient failures.# The first attempt fires immediately; each subsequent retry waits# ``MULTIPLIER * 2**n`` seconds, doubling the gap each step. Tune the@@ -53,16 +62,27 @@ _RETRY_DELAYS_SECONDS: tuple[float, ...] = (@dataclassclass QuotaResourceStatus:limited: bool+ code_usage_billing_active: bool = Falseclass _TransientUpstreamError(Exception):"""Retryable failure: a 5xx response or a network-level error."""+class _PermanentUpstreamError(Exception):+ """Non-retryable failure: a 4xx response — bad token, missing team, scope mismatch."""++def _redis_key(resource_key: str, team_id: int) -> str:return f"quota:{resource_key}:team:{team_id}"+def _billing_key(team_id: int) -> str:+ # Per team, not per resource: the billing bit is org-level and identical in+ # every quota_limits response for the team.+ return f"quota:code_usage_billing:team:{team_id}"++async def resolve_quota_status(request: Request, team_id: int | None, resource_key: str) -> QuotaResourceStatus:"""Resolve the team's quota state for one resource, falling open on errors."""if team_id is None:@@ -97,9 +117,25 @@ class QuotaResolver:try:status, ttl = await self._fetch_with_retry(resource_key, team_id, auth_header)+ await self._set_last_known_billing(team_id, status.code_usage_billing_active)+ except _PermanentUpstreamError:+ # 4xx is about this caller's credentials, not a team fact. Fail open+ # for the request but don't write the shared per-team cache — else a+ # caller who can 403 the quota endpoint pins limited=False team-wide.+ logger.warning("quota_fetch_denied", resource=resource_key, team_id=team_id)+ return QuotaResourceStatus(+ limited=False, code_usage_billing_active=await self._get_last_known_billing(team_id)+ )except Exception:+ # Billing serves last-known, not False, so a blip can't re-cap a paying org.logger.warning("quota_fetch_failed", resource=resource_key, team_id=team_id, exc_info=True)- status, ttl = QuotaResourceStatus(limited=False), _FAIL_OPEN_CACHE_TTL_SECONDS+ status, ttl = (+ QuotaResourceStatus(+ limited=False,+ code_usage_billing_active=await self._get_last_known_billing(team_id),+ ),+ _FAIL_OPEN_CACHE_TTL_SECONDS,+ )await self._set_cached(resource_key, team_id, status, ttl)return status@@ -110,9 +146,10 @@ class QuotaResolver:"""Try the upstream up to ``len(_RETRY_DELAYS_SECONDS)`` times.Network errors and 5xx responses are retried with growing waits between- attempts. 4xx and successful responses return immediately from- :meth:`_fetch`. If every attempt raises a transient error the last- exception is re-raised for the caller to fail open.+ attempts. Successful responses return immediately from :meth:`_fetch`;+ a 4xx raises :class:`_PermanentUpstreamError` straight through without+ burning the retry budget. If every attempt raises a transient error the+ last exception is re-raised for the caller to fail open."""last_exc: Exception | None = Nonefor delay in _RETRY_DELAYS_SECONDS:@@ -141,13 +178,16 @@ class QuotaResolver:raise _TransientUpstreamError(f"quota_limits returned {resp.status_code}")if resp.status_code >= 400:# 4xx is permanent for the lifetime of this request — bad token,- # missing team, scope mismatch. Fail open briefly so a hot loop- # with a broken token doesn't hammer Django.- return QuotaResourceStatus(limited=False), _FAIL_OPEN_CACHE_TTL_SECONDS+ # missing team, scope mismatch. The caller fails open briefly so a+ # hot loop with a broken token doesn't hammer Django.+ raise _PermanentUpstreamError(f"quota_limits returned {resp.status_code}")data = resp.json()resource = (data.get("limited") or {}).get(resource_key) or {}- return QuotaResourceStatus(limited=bool(resource.get("limited"))), self._cache_ttl+ return QuotaResourceStatus(+ limited=bool(resource.get("limited")),+ code_usage_billing_active=bool(data.get("code_usage_billing_active")),+ ), self._cache_ttlasync def _get_cached(self, resource_key: str, team_id: int) -> QuotaResourceStatus | None:if not self._redis:@@ -157,7 +197,12 @@ class QuotaResolver:if val is None:return Nonepayload = json.loads(val.decode())- return QuotaResourceStatus(limited=bool(payload.get("limited")))+ return QuotaResourceStatus(+ limited=bool(payload.get("limited")),+ # Entries written before this field existed read as False (capped)+ # until the TTL turns them over.+ code_usage_billing_active=bool(payload.get("code_usage_billing_active")),+ )except Exception:logger.debug("quota_cache_read_failed", resource=resource_key, team_id=team_id)return None@@ -166,7 +211,26 @@ class QuotaResolver:if not self._redis:returntry:- payload = json.dumps({"limited": status.limited})+ payload = json.dumps(+ {"limited": status.limited, "code_usage_billing_active": status.code_usage_billing_active}+ )await self._redis.set(_redis_key(resource_key, team_id), payload, ex=ttl)except Exception:logger.debug("quota_cache_write_failed", resource=resource_key, team_id=team_id)++ async def _get_last_known_billing(self, team_id: int) -> bool:+ if not self._redis:+ return False+ try:+ return await self._redis.get(_billing_key(team_id)) == b"1"+ except Exception:+ logger.debug("billing_fallback_read_failed", team_id=team_id)+ return False++ async def _set_last_known_billing(self, team_id: int, active: bool) -> None:+ if not self._redis:+ return+ try:+ await self._redis.set(_billing_key(team_id), b"1" if active else b"0", ex=_LAST_KNOWN_BILLING_TTL_SECONDS)+ except Exception:+ logger.debug("billing_fallback_write_failed", team_id=team_id)diff --git a/services/llm-gateway/tests/test_billable_credits_throttle.py b/services/llm-gateway/tests/test_billable_credits_throttle.pyindex 3f6704f31e6a..5d7da3bacd6b 100644--- a/services/llm-gateway/tests/test_billable_credits_throttle.py+++ b/services/llm-gateway/tests/test_billable_credits_throttle.py@@ -19,8 +19,22 @@ def _make_user() -> AuthenticatedUser:)-def _make_context(product: str, *, credits_exhausted: bool = False, plan_key: str | None = None) -> ThrottleContext:- return ThrottleContext(user=_make_user(), product=product, credits_exhausted=credits_exhausted, plan_key=plan_key)+def _make_context(+ product: str,+ *,+ credits_exhausted: bool = False,+ plan_key: str | None = None,+ seat_missing: bool = False,+ code_usage_billed: bool = False,+) -> ThrottleContext:+ return ThrottleContext(+ user=_make_user(),+ product=product,+ credits_exhausted=credits_exhausted,+ plan_key=plan_key,+ seat_missing=seat_missing,+ code_usage_billed=code_usage_billed,+ )class TestBillableCreditThrottle:@@ -36,15 +50,12 @@ class TestBillableCreditThrottle:@pytest.mark.asyncioasync def test_denies_posthog_code_when_its_bucket_is_exhausted(self) -> None:- # `posthog_code` bills into posthog_code_credits, scoped to usage-based-plan- # users; the dependency layer resolves exhaustion for that bucket, so the- # throttle blocks a usage-based-plan user on it — with the Code-specific- # message, not the PostHog AI one.+ # `posthog_code` bills into posthog_code_credits; the dependency layer+ # resolves exhaustion for that bucket, so the throttle blocks on it —+ # with the Code-specific message, not the PostHog AI one.throttle = BillableCreditThrottle()- result = await throttle.allow_request(- _make_context(product="posthog_code", credits_exhausted=True, plan_key="posthog-code-usage-20260709")- )+ result = await throttle.allow_request(_make_context(product="posthog_code", credits_exhausted=True))assert result.allowed is Falseassert result.status_code == 429@@ -52,21 +63,37 @@ class TestBillableCreditThrottle:@pytest.mark.asyncio@pytest.mark.parametrize(- "plan_key",- ["posthog-code-pro-200-20260301", "posthog-code-free-20260301", None],+ ("seat_missing", "code_usage_billed"),+ [+ # Seatless in a paying org: the org's billing limit is the only+ # ceiling (the per-user cap is lifted) - exhaustion must block, or+ # usage runs past the org's configured limit.+ (True, True),+ # Seatless in a non-paying org: the free plan's monthly allocation+ # surfaces the same way and must block the same way.+ (True, False),+ # Every generation is counted into the bucket regardless of seat+ # state, so a seat-based carve-out would let the exempted callers+ # burn past the limit their own spend is filling.+ (False, True),+ (False, False),+ ],)- async def test_allows_posthog_code_seat_covered_plans_even_when_exhausted(self, plan_key: str | None) -> None:- # `posthog_code`'s bucket is scoped to usage-based plans: seat-covered- # (pro/free/alpha) users' generations aren't billed to the org's usage- # subscription at the usage-report layer, so the org's usage limit must not- # block them either — including when the plan can't be resolved at all.+ async def test_bucket_blocks_regardless_of_seat_or_billing_state(+ self, seat_missing: bool, code_usage_billed: bool+ ) -> None:throttle = BillableCreditThrottle()result = await throttle.allow_request(- _make_context(product="posthog_code", credits_exhausted=True, plan_key=plan_key)+ _make_context(+ product="posthog_code",+ credits_exhausted=True,+ seat_missing=seat_missing,+ code_usage_billed=code_usage_billed,+ ))- assert result.allowed is True+ assert result.allowed is False@pytest.mark.asyncio@pytest.mark.parametrize("product", ["slack_app", "slack_app_routing", "posthog_code"])@@ -90,20 +117,6 @@ class TestBillableCreditThrottle:assert "PostHog AI credits" in result.detailassert result.retry_after == 60- @pytest.mark.asyncio- @pytest.mark.parametrize("plan_key", ["posthog-code-pro-200-20260301", "posthog-code-free-20260301", None])- async def test_denies_all_users_scope_product_regardless_of_plan_key(self, plan_key: str | None) -> None:- # `slack_app` bills AI_CREDITS with the default `credit_bucket_scope="all_users"`:- # unlike posthog_code, every user counts against the bucket limit, so exhaustion- # blocks the request no matter what plan (or lack of one) the caller is on.- throttle = BillableCreditThrottle()-- result = await throttle.allow_request(- _make_context(product="slack_app", credits_exhausted=True, plan_key=plan_key)- )-- assert result.allowed is False-@pytest.mark.asyncioasync def test_unmapped_bucket_falls_back_to_generic_detail(self) -> None:# A bucket added to the enum without a detail entry must still deny@@ -111,9 +124,7 @@ class TestBillableCreditThrottle:throttle = BillableCreditThrottle()with patch.dict("llm_gateway.rate_limiting.billable_credits_throttle._BUCKET_EXHAUSTED_DETAIL", clear=True):- result = await throttle.allow_request(- _make_context(product="posthog_code", credits_exhausted=True, plan_key="posthog-code-usage-20260709")- )+ result = await throttle.allow_request(_make_context(product="posthog_code", credits_exhausted=True))assert result.allowed is Falseassert result.status_code == 429diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.pyindex 8c5dc6d1a398..00c076b18002 100644--- a/services/llm-gateway/tests/test_cost_throttles.py+++ b/services/llm-gateway/tests/test_cost_throttles.py@@ -26,6 +26,7 @@ def make_context(plan_key: str | None = "posthog-code-200-20260301",seat_created_at: str | None = None,seat_missing: bool = False,+ code_usage_billed: bool = False,billing_period_start: str | None = None,) -> ThrottleContext:user = user or make_user()@@ -38,6 +39,7 @@ def make_context(plan_key=plan_key,seat_created_at=seat_created_at,seat_missing=seat_missing,+ code_usage_billed=code_usage_billed,billing_period_start=billing_period_start,)@@ -1407,6 +1409,55 @@ class TestPlanAwareThrottling:result = await throttle.allow_request(context)assert result.allowed is expected_allowed+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("seat_missing", "code_usage_billed", "expected_allowed"),+ [+ # Seatless + org-billed Code usage: bills to the org - no per-user cap.+ # $600 spent clears both the $75 free cap and the $500/day default.+ (True, True, True),+ # Seatless + not billed: the free cap holds (this pair pins that the+ # bypass never leaks to orgs that would get the usage for free).+ (True, False, False),+ # Seat still exists (pre-retirement): org billing doesn't lift the cap -+ # seat-covered usage stays bounded until the seat is deleted.+ (False, True, False),+ ],+ )+ async def test_code_usage_billing_gates_seatless_cap_bypass(+ self, seat_missing: bool, code_usage_billed: bool, expected_allowed: bool+ ) -> None:+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ context = make_context(+ product="posthog_code",+ plan_key=None if seat_missing else "posthog-code-free-20260301",+ seat_created_at=None if seat_missing else "2026-01-01T00:00:00+00:00",+ seat_missing=seat_missing,+ code_usage_billed=code_usage_billed,+ )++ await throttle.record_cost(context, 600.0)+ result = await throttle.allow_request(context)+ assert result.allowed is expected_allowed++ @pytest.mark.asyncio+ async def test_org_billed_seatless_status_reports_unlimited(self) -> None:+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ context = make_context(+ product="posthog_code", plan_key=None, seat_created_at=None, seat_missing=True, code_usage_billed=True+ )++ await throttle.record_cost(context, 600.0)+ status = await throttle.get_status(context)+ # The usage endpoint renders this - it must agree with enforcement (never+ # show a paying user as rate limited when nothing would block them).+ assert status.exceeded is False+ assert status.limit_usd == float("inf")+@pytest.mark.asyncioasync def test_non_code_product_ignores_plan(self) -> None:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlediff --git a/services/llm-gateway/tests/test_plan_resolver.py b/services/llm-gateway/tests/test_plan_resolver.pyindex ca7b8fc6a77f..1e0293e2c04d 100644--- a/services/llm-gateway/tests/test_plan_resolver.py+++ b/services/llm-gateway/tests/test_plan_resolver.py@@ -8,7 +8,6 @@ from llm_gateway.services.plan_resolver import (PlanResolver,get_billing_period_number,is_pro_plan,- is_usage_based_plan,resolve_plan_info,)@@ -32,23 +31,6 @@ class TestIsProPlan:assert is_pro_plan(plan_key) is expected-class TestIsUsageBasedPlan:- @pytest.mark.parametrize(- "plan_key,expected",- [- ("posthog-code-usage-20260709", True),- ("posthog-code-usage-20260901", True),- ("posthog-code-pro-200-20260301", False),- ("posthog-code-free-20260301", False),- ("some-other-plan", False),- (None, False),- ("", False),- ],- )- def test_is_usage_based_plan(self, plan_key: str | None, expected: bool) -> None:- assert is_usage_based_plan(plan_key) is expected--class TestGetBillingPeriodNumber:def test_none_returns_zero(self) -> None:assert get_billing_period_number(None) == 0@@ -302,7 +284,7 @@ class TestResolvePlanInfoCredentialForwarding:"""Credential forwarding must mirror extract_token: either headerauthenticates, so either header must reach plan resolution — otherwisex-api-key callers resolve no plan, silently disabling every- plan-conditioned control (usage-based cost caps, the plan-scoped+ plan-conditioned control (free vs pro cost caps, the seat-scopedcredit-bucket exemption)."""def _make_request(self, headers: dict[str, str]) -> MagicMock:@@ -312,7 +294,7 @@ class TestResolvePlanInfoCredentialForwarding:request.headers = Headers(headers)resolver = MagicMock()resolver.get_plan = AsyncMock(- return_value=PlanInfo(plan_key="posthog-code-usage-20260709", seat_created_at=None)+ return_value=PlanInfo(plan_key="posthog-code-pro-200-20260301", seat_created_at=None))request.app.state.plan_resolver = resolverreturn request@@ -321,14 +303,14 @@ class TestResolvePlanInfoCredentialForwarding:async def test_forwards_authorization_header(self) -> None:request = self._make_request({"Authorization": "Bearer phx_test"})result = await resolve_plan_info(request, user_id=1, product="posthog_code")- assert result.plan_key == "posthog-code-usage-20260709"+ assert result.plan_key == "posthog-code-pro-200-20260301"assert request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_test"@pytest.mark.asyncioasync def test_forwards_x_api_key_as_bearer(self) -> None:request = self._make_request({"x-api-key": " phx_test "})result = await resolve_plan_info(request, user_id=1, product="posthog_code")- assert result.plan_key == "posthog-code-usage-20260709"+ assert result.plan_key == "posthog-code-pro-200-20260301"assert request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_test"@pytest.mark.asynciodiff --git a/services/llm-gateway/tests/test_quota_resolver.py b/services/llm-gateway/tests/test_quota_resolver.pyindex 60eea6c65f4d..9409985bf273 100644--- a/services/llm-gateway/tests/test_quota_resolver.py+++ b/services/llm-gateway/tests/test_quota_resolver.py@@ -10,9 +10,11 @@ from starlette.datastructures import Headersfrom llm_gateway.services.quota_resolver import (_FAIL_OPEN_CACHE_TTL_SECONDS,+ _LAST_KNOWN_BILLING_TTL_SECONDS,_RETRY_DELAYS_SECONDS,QuotaResolver,QuotaResourceStatus,+ _billing_key,_redis_key,resolve_quota_status,)@@ -45,6 +47,22 @@ def _make_http_client_sequence(responses: list[httpx.Response | Exception]) -> Mreturn client+class _FakeRedis:+ """Dict-backed get/set so multi-key round-trips are honest instead of stubbed."""++ def __init__(self) -> None:+ self.store: dict[str, bytes] = {}+ self.ttls: dict[str, int] = {}++ async def get(self, key: str) -> bytes | None:+ return self.store.get(key)++ async def set(self, key: str, value: str | bytes, ex: int | None = None) -> None:+ self.store[key] = value if isinstance(value, bytes) else value.encode()+ if ex is not None:+ self.ttls[key] = ex++@pytest.fixture(autouse=True)def _no_retry_sleep() -> Iterator[None]:"""Don't actually sleep between retries — keeps tests fast and deterministic."""@@ -138,6 +156,79 @@ class TestQuotaResolver:http_client.get.assert_awaited_once()assert http_client.get.await_args.kwargs["headers"]["Authorization"] == "Bearer phx_test"+ @pytest.mark.asyncio+ async def test_parses_and_caches_code_usage_billing_flag(self) -> None:+ redis = AsyncMock()+ redis.get = AsyncMock(return_value=None)+ redis.set = AsyncMock()+ http_client = _make_http_client(+ _make_response(+ 200,+ {"team_id": 1, "limited": {"ai_credits": {"limited": False}}, "code_usage_billing_active": True},+ )+ )+ resolver = QuotaResolver(redis=redis, http_client=http_client)++ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")+ assert status.code_usage_billing_active is True++ # Round-trips through the cache - a one-sided cache would flip a paying+ # user's cap between hit and miss.+ cached_payload = redis.set.call_args.args[1]+ redis.get = AsyncMock(return_value=cached_payload.encode())+ cached = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")+ assert cached.code_usage_billing_active is True++ @pytest.mark.asyncio+ async def test_missing_billing_field_defaults_false(self) -> None:+ # Old Django responses (pre-flag) must read as not-billed, not error.+ http_client = _make_http_client(+ _make_response(200, {"team_id": 1, "limited": {"ai_credits": {"limited": False}}})+ )+ resolver = QuotaResolver(redis=None, http_client=http_client)++ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")+ assert status.code_usage_billing_active is False++ @pytest.mark.asyncio+ @pytest.mark.parametrize("failure_mode", ["4xx", "retries_exhausted"])+ async def test_billing_flag_falls_back_to_last_known_value_on_fetch_failure(self, failure_mode: str) -> None:+ # A Django blip - or one caller's under-scoped token 4xxing the shared+ # per-team fetch - must not flip a paying org's billing bit to False+ # and re-cap its users at the free limit for the fail-open window.+ failures: list[httpx.Response | Exception]+ if failure_mode == "4xx":+ failures = [_make_response(403, {"detail": "missing scope"})]+ else:+ failures = [httpx.ConnectError("boom")] * len(_RETRY_DELAYS_SECONDS)+ http_client = _make_http_client_sequence(+ [+ _make_response(200, {"limited": {"ai_credits": {"limited": False}}, "code_usage_billing_active": True}),+ *failures,+ ]+ )+ redis = _FakeRedis()+ resolver = QuotaResolver(redis=redis, http_client=http_client) # type: ignore[arg-type]++ first = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")+ assert first.code_usage_billing_active is True+ assert redis.ttls[_billing_key(42)] == _LAST_KNOWN_BILLING_TTL_SECONDS++ # The per-team quota entry expires; the refetch fails.+ del redis.store[_redis_key("ai_credits", 42)]+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")++ assert status == QuotaResourceStatus(limited=False, code_usage_billing_active=True)+ if failure_mode == "retries_exhausted":+ assert json.loads(redis.store[_redis_key("ai_credits", 42)]) == {+ "limited": False,+ "code_usage_billing_active": True,+ }+ assert redis.ttls[_redis_key("ai_credits", 42)] == _FAIL_OPEN_CACHE_TTL_SECONDS+ else:+ # 4xx is caller-specific and must not repopulate the shared entry.+ assert _redis_key("ai_credits", 42) not in redis.store+@pytest.mark.asyncioasync def test_fetches_and_parses_unlimited_response(self) -> None:http_client = _make_http_client(@@ -232,24 +323,27 @@ class TestQuotaResolver:await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")- redis.set.assert_awaited_once()- call = redis.set.await_args- assert call.args[0] == _redis_key("ai_credits", 42)- assert json.loads(call.args[1]) == {"limited": True}+ # One write per key: the team+resource quota entry and the per-team+ # last-known billing bit.+ quota_writes = [c for c in redis.set.await_args_list if c.args[0] == _redis_key("ai_credits", 42)]+ assert len(quota_writes) == 1+ call = quota_writes[0]+ assert json.loads(call.args[1]) == {"limited": True, "code_usage_billing_active": False}# Successful fetches use the gateway settings default of 5 minutes.assert call.kwargs.get("ex") == 300+ assert redis.set.await_count == 2@pytest.mark.asyncio- async def test_caches_fail_open_for_full_window_on_4xx(self) -> None:- # 4xx responses (e.g. expired token) cache for the fail-open window so- # a hot loop with a broken token doesn't hammer Django.+ async def test_does_not_cache_on_4xx(self) -> None:+ # Caching a 4xx team-wide would let a caller who can 403 the quota+ # endpoint pin limited=False for everyone on the team.redis = AsyncMock()redis.get = AsyncMock(return_value=None)redis.set = AsyncMock()http_client = _make_http_client(_make_response(401, {"detail": "no auth"}))resolver = QuotaResolver(redis=redis, http_client=http_client)- await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")- redis.set.assert_awaited_once()- assert redis.set.await_args.kwargs.get("ex") == _FAIL_OPEN_CACHE_TTL_SECONDS+ assert status == QuotaResourceStatus(limited=False)+ redis.set.assert_not_awaited()diff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.pyindex 47e8c44c29a3..2e91f8cbe9b2 100644--- a/services/llm-gateway/tests/test_usage.py+++ b/services/llm-gateway/tests/test_usage.py@@ -363,14 +363,13 @@ class TestUsageEndpoint:def test_credits_reflect_products_own_bucket(self, authenticated_usage_client: TestClient) -> None:# posthog_code's usage reports the posthog_code_credits bucket (under the# legacy `ai_credits` response field), resolved against its own resource key.- # A usage-based plan is the population the bucket actually blocks.from llm_gateway.services.quota_resolver import QuotaResourceStatusapp = authenticated_usage_client.appresolver_mock = AsyncMock(return_value=QuotaResourceStatus(limited=True))app.state.quota_resolver.get_resource_status = resolver_mockapp.state.plan_resolver.get_plan = AsyncMock(- return_value=PlanInfo(plan_key="posthog-code-usage-20260709", seat_created_at="2026-01-01T00:00:00+00:00")+ return_value=PlanInfo(plan_key=None, seat_created_at=None, seat_missing=True))response = authenticated_usage_client.get(@@ -384,12 +383,13 @@ class TestUsageEndpoint:assert resolver_mock.call_args.args[0] == "posthog_code_credits"@pytest.mark.parametrize("plan_key", ["posthog-code-200-20260301", "posthog-code-free-20260301", None])- def test_exhausted_bucket_not_reported_for_seat_covered_plans(+ def test_exhausted_bucket_reported_for_every_caller(self, authenticated_usage_client: TestClient, plan_key: str | None) -> None:- # Mirrors BillableCreditThrottle's credit_bucket_scope check: the gateway lets- # seat-covered users through an exhausted posthog_code bucket, so the usage- # endpoint must not report them rate-limited — clients gate on this response.+ # Mirrors BillableCreditThrottle: every posthog_code generation counts into+ # the org's bucket, so exhaustion blocks (and must be reported to) every+ # caller regardless of seat state — clients gate on this response, and a+ # carve-out here would let them keep sending requests enforcement denies.from llm_gateway.services.quota_resolver import QuotaResourceStatusapp = authenticated_usage_client.app@@ -404,8 +404,8 @@ class TestUsageEndpoint:)assert response.status_code == 200data = response.json()- assert data["ai_credits"] == {"exhausted": False}- assert data["is_rate_limited"] is False+ assert data["ai_credits"] == {"exhausted": True}+ assert data["is_rate_limited"] is Truedef test_ai_credits_reflects_resolver_for_billable_product(self, authenticated_usage_client: TestClient) -> None:from llm_gateway.services.quota_resolver import QuotaResourceStatusdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3c1d8939ac0a..8a02f8f8ba18 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -52441,13 +52441,15 @@ export namespace Schemas {}/**- * Per-resource limit state keyed by `QuotaResource` value. Currently only `ai_credits` is reported; additional resources may be added.+ * Per-resource limit state for every `QuotaResource` value, e.g. `ai_credits`, `posthog_code_credits`.*/export type QuotaLimitsResponseLimited = {[key: string]: QuotaResourceLimit};export interface QuotaLimitsResponse {- /** Per-resource limit state keyed by `QuotaResource` value. Currently only `ai_credits` is reported; additional resources may be added. */+ /** Per-resource limit state for every `QuotaResource` value, e.g. `ai_credits`, `posthog_code_credits`. */limited: QuotaLimitsResponseLimited;+ /** Whether the team's organization pays for PostHog Code usage: billing grants the `posthog_code_usage` product feature only on the Code usage product's paid plan, synced into the organization's available features. Consumers gate paid-tier Code behavior on this; an org unknown to billing reads as not paying. */+ code_usage_billing_active: boolean;}export interface RawUnmatchedSample {