: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(posthog-code): enforce posthog_code_credits quota at the gateway (#69324)
Adam Bowker9a664dab7ed6
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 6c09d3a68d39..cdb8e46be9e9 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -446,6 +446,7 @@ class BillingManager:llm_events=usage_summary.get("llm_events", {}),ai_credits=usage_summary.get("ai_credits", {}),signals_credits=usage_summary.get("signals_credits", {}),+ posthog_code_credits=usage_summary.get("posthog_code_credits", {}),workflow_emails=usage_summary.get("workflow_emails", {}),workflow_destinations_dispatched=usage_summary.get("workflow_destinations_dispatched", {}),logs_mb_ingested=usage_summary.get("logs_mb_ingested", {}),diff --git a/ee/billing/quota_limiting.py b/ee/billing/quota_limiting.pyindex 9342572dd6db..cd4dcced3d6c 100644--- a/ee/billing/quota_limiting.py+++ b/ee/billing/quota_limiting.py@@ -34,6 +34,7 @@ from posthog.tasks.usage_report import (get_teams_with_exceptions_captured_in_period,get_teams_with_feature_flag_requests_count_in_period,get_teams_with_logs_bytes_in_period,+ get_teams_with_posthog_code_credits_used_in_period,get_teams_with_recording_count_in_period,get_teams_with_replay_vision_credits_used_in_period,get_teams_with_rows_exported_in_period,@@ -85,6 +86,7 @@ class QuotaResource(Enum):ROWS_EXPORTED = "rows_exported"AI_CREDITS = "ai_credits"SIGNALS_CREDITS = "signals_credits"+ POSTHOG_CODE_CREDITS = "posthog_code_credits"WORKFLOW_EMAILS = "workflow_emails"WORKFLOW_DESTINATIONS = "workflow_destinations_dispatched"LOGS_MB_INGESTED = "logs_mb_ingested"@@ -109,6 +111,7 @@ OVERAGE_BUFFER = {QuotaResource.ROWS_EXPORTED: 0,QuotaResource.AI_CREDITS: 0,QuotaResource.SIGNALS_CREDITS: 0,+ QuotaResource.POSTHOG_CODE_CREDITS: 0,QuotaResource.WORKFLOW_EMAILS: 0,QuotaResource.WORKFLOW_DESTINATIONS: 0,QuotaResource.LOGS_MB_INGESTED: 0,@@ -120,6 +123,7 @@ GRACE_PERIOD_EXEMPT_RESOURCES: set[QuotaResource] = {QuotaResource.AI_CREDITS,QuotaResource.SIGNALS_CREDITS,QuotaResource.REPLAY_VISION_CREDITS,+ QuotaResource.POSTHOG_CODE_CREDITS,}@@ -137,6 +141,7 @@ class UsageCounters(TypedDict):rows_exported: intai_credits: intsignals_credits: int+ posthog_code_credits: intworkflow_emails: intworkflow_destinations_dispatched: intlogs_mb_ingested: int@@ -913,6 +918,11 @@ def update_all_orgs_billing_quotas("teams_with_signals_credits_used_in_period": convert_team_usage_rows_to_dict(_timed_query("signals_credits", get_teams_with_signals_credits_used_in_period, period_start, period_end)),+ "teams_with_posthog_code_credits_used_in_period": convert_team_usage_rows_to_dict(+ _timed_query(+ "posthog_code_credits", get_teams_with_posthog_code_credits_used_in_period, period_start, period_end+ )+ ),"teams_with_workflow_emails_sent_in_period": convert_team_usage_rows_to_dict(_timed_query("workflow_emails", get_teams_with_workflow_emails_sent_in_period, period_start, period_end)),@@ -984,6 +994,7 @@ def update_all_orgs_billing_quotas(llm_events=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),ai_credits=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),signals_credits=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),+ posthog_code_credits=all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),cdp_trigger_events=all_data["teams_with_cdp_trigger_events_metrics"].get(team.id, 0),rows_exported=all_data["teams_with_rows_exported_in_period"].get(team.id, 0),workflow_emails=all_data["teams_with_workflow_emails_sent_in_period"].get(team.id, 0),diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.pyindex acdf376fb8b6..f0c6b78e124a 100644--- a/ee/billing/test/test_billing_manager.py+++ b/ee/billing/test/test_billing_manager.py@@ -247,6 +247,7 @@ class TestBillingManager(BaseTest):"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},"signals_credits": {},"replay_vision_credits": {},+ "posthog_code_credits": {},"workflow_emails": {"usage": 100, "limit": 10000, "todays_usage": 10},"workflow_destinations_dispatched": {"usage": 50, "limit": 10000, "todays_usage": 5},"logs_mb_ingested": {"usage": 5500, "limit": 50000, "todays_usage": 500},diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.pyindex 9a1fbb81eed0..afd43f48a7f1 100644--- a/ee/billing/test/test_quota_limiting.py+++ b/ee/billing/test/test_quota_limiting.py@@ -2307,6 +2307,7 @@ def _full_usage_counters(**overrides: int) -> UsageCounters:llm_events=0,ai_credits=0,signals_credits=0,+ posthog_code_credits=0,cdp_trigger_events=0,rows_exported=0,workflow_emails=0,diff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex d7705b3f153a..00eef0a88273 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -55,6 +55,7 @@ class OrganizationUsageInfo(TypedDict):llm_events: OrganizationUsageResource | Noneai_credits: OrganizationUsageResource | Nonesignals_credits: OrganizationUsageResource | None+ posthog_code_credits: OrganizationUsageResource | Noneworkflow_emails: OrganizationUsageResource | Noneworkflow_destinations_dispatched: OrganizationUsageResource | Nonelogs_mb_ingested: OrganizationUsageResource | Nonediff --git a/services/llm-gateway/src/llm_gateway/api/usage.py b/services/llm-gateway/src/llm_gateway/api/usage.pyindex e94976b571c3..3797552fa6a6 100644--- a/services/llm-gateway/src/llm_gateway/api/usage.py+++ b/services/llm-gateway/src/llm_gateway/api/usage.py@@ -9,6 +9,7 @@ from pydantic import BaseModelfrom llm_gateway.auth.models import AuthenticatedUserfrom llm_gateway.dependencies import get_authenticated_user, resolve_plan_and_quota+from llm_gateway.rate_limiting.billable_credits_throttle import bucket_block_appliesfrom llm_gateway.rate_limiting.cost_throttles import CostStatus, UserCostBurstThrottle, UserCostSustainedThrottlefrom llm_gateway.rate_limiting.runner import ThrottleRunnerfrom llm_gateway.rate_limiting.throttles import ThrottleContext@@ -77,7 +78,13 @@ async def get_usage(product=product,)now = datetime.now(tz=UTC)- ai_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 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,@@ -86,7 +93,7 @@ async def get_usage(plan_key=plan_info.plan_key,seat_created_at=plan_info.seat_created_at,billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,- ai_credits_exhausted=ai_credits_exhausted,+ credits_exhausted=quota_status.limited,)burst_status: CostLimitStatus | None = None@@ -130,8 +137,8 @@ async def get_usage(user_id=user.user_id,burst=burst_status,sustained=sustained_status,- ai_credits=AiCreditsStatus(exhausted=ai_credits_exhausted),- is_rate_limited=burst_status.exceeded or sustained_status.exceeded or ai_credits_exhausted,+ ai_credits=AiCreditsStatus(exhausted=credits_exhausted),+ is_rate_limited=burst_status.exceeded or sustained_status.exceeded or credits_exhausted,is_pro=is_pro_plan(plan_info.plan_key),billing_period_end=billing_period_end,)diff --git a/services/llm-gateway/src/llm_gateway/auth/service.py b/services/llm-gateway/src/llm_gateway/auth/service.pyindex 4c6c62e33782..9c2441245618 100644--- a/services/llm-gateway/src/llm_gateway/auth/service.py+++ b/services/llm-gateway/src/llm_gateway/auth/service.py@@ -25,6 +25,25 @@ def extract_token(request: Request) -> str | None:return match.group(1).strip() if match else None+def upstream_auth_header(request: Request) -> str:+ """Build the Authorization header to forward to PostHog for the request's token.++ Mirrors :func:`extract_token`'s precedence (x-api-key wins over+ Authorization). Auth accepts either header, so any upstream check that+ forwarded only Authorization could be bypassed by sending the same token+ via x-api-key — e.g. plan resolution returning no plan (and with it any+ plan-conditioned enforcement), or quota resolution failing open.+ Returns "" when the request carries no token.+ """+ api_key = request.headers.get("x-api-key")+ if api_key:+ # Not a route handler: this builds an outbound header value from the+ # caller's own credential; nothing is rendered to a response body.+ # nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-string+ return f"Bearer {api_key.strip()}"+ return request.headers.get("authorization", "")++class AuthService:"""Coordinates authentication with caching and metrics."""diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex c87ef56798be..f26933a67279 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -177,6 +177,12 @@ 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 87a592a3aa96..b672737e1a59 100644--- a/services/llm-gateway/src/llm_gateway/dependencies.py+++ b/services/llm-gateway/src/llm_gateway/dependencies.py@@ -13,7 +13,6 @@ from llm_gateway.auth.service import AuthService, get_auth_servicefrom llm_gateway.circuit_breaker import AnthropicCircuitBreakerfrom llm_gateway.products.config import (ALLOWED_PRODUCTS,- CreditBucket,check_product_access,get_product_config,resolve_product_alias,@@ -164,20 +163,18 @@ async def resolve_plan_and_quota(team_id: int | None,product: str,) -> tuple[PlanInfo, QuotaResourceStatus]:- """Fetch plan info and (for ai_credits-billed products) AI credits quota in parallel.+ """Fetch plan info and (for bucket-billed products) the bucket's quota in parallel.Both calls are independent Django roundtrips on cache miss, so for products- billing into the ai_credits bucket we overlap them. Everything else — unbilled- products, and products billing into a bucket without gateway-side quota- enforcement (e.g. posthog_code_credits) — short-circuits the throttle stack- regardless of quota state, so we skip the resolver entirely rather than paying- for the Redis GET (and the HTTP fallback on cache miss).+ billing into a credit bucket we overlap them. Unbilled products short-circuit+ the throttle stack regardless of quota state, so we skip the resolver entirely+ rather than paying for the Redis GET (and the HTTP fallback on cache miss)."""product_config = get_product_config(product)- if product_config and product_config.credit_bucket is CreditBucket.AI_CREDITS:+ if product_config and product_config.credit_bucket is not None:plan_info, quota_status = await asyncio.gather(resolve_plan_info(request, user_id, product),- resolve_quota_status(request, team_id),+ resolve_quota_status(request, team_id, product_config.credit_bucket.value),)return plan_info, quota_statusplan_info = await resolve_plan_info(request, user_id, product)@@ -213,7 +210,7 @@ async def enforce_throttles(plan_key=plan_info.plan_key,seat_created_at=plan_info.seat_created_at,billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,- ai_credits_exhausted=quota_status.limited,+ credits_exhausted=quota_status.limited,)request.state.throttle_context = contextset_throttle_context(runner, context)diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex ee062c1a3b56..464335cbf44c 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+from typing import Final, Literalfrom fastapi import HTTPException@@ -15,9 +15,11 @@ 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's- quota resolver checks against. Only AI_CREDITS has a QuotaResource and- gateway-side quota enforcement today; POSTHOG_CODE_CREDITS bills without- blocking until its resource lands.+ quota 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)."""AI_CREDITS = "ai_credits"@@ -35,9 +37,17 @@ class ProductConfig:# $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 — currently only AI_CREDITS has- # gateway-side quota enforcement; other buckets bill without blocking.+ # blocked when the bucket's quota is exhausted — see credit_bucket_scope below for+ # which users that block applies to.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@@ -101,6 +111,10 @@ 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 33d4615da815..99a705cfc275 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,6 +2,25 @@ 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: (+ "Your team has used its monthly PostHog AI credits. "+ "Top up at https://app.posthog.com/organization/billing to continue."+ ),+ CreditBucket.POSTHOG_CODE_CREDITS: (+ "Your team has reached its PostHog Code usage limit for this billing period. "+ "See https://app.posthog.com/organization/billing for your usage and limits."+ ),+}++# Fallback for a bucket added to the enum without a matching entry above —+# a missing message should never turn an exhausted team's 429 into a 500.+_DEFAULT_EXHAUSTED_DETAIL = (+ "Your team has reached its usage limit for this billing period. "+ "See https://app.posthog.com/organization/billing for your usage and limits."+)# Hint the client to back off for a minute. A precise expiry timestamp is# available upstream in Redis, but with Django's 30s in-process cache and the@@ -11,30 +30,51 @@ from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, Throt_RETRY_AFTER_SECONDS = 60+def bucket_block_applies(product: str, plan_key: str | None, credits_exhausted: bool) -> bool:+ """Whether the product's exhausted credit bucket blocks this caller.++ The single source of truth for the bucket-block decision, shared by the+ request-path throttle and the usage endpoint so what's reported always+ matches 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.+ """+ config = get_product_config(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++class BillableCreditThrottle(Throttle):- """Gate ai_credits-billed LLM calls on the team's AI credits balance.+ """Gate bucket-billed LLM calls on the team's balance for that bucket.- Reads ``ai_credits_exhausted`` from :class:`ThrottleContext`, pre-resolved- by the dependency layer (see ``resolve_quota_status``). Products billing- into other credit buckets (e.g. posthog_code) are never blocked here —- only the ai_credits bucket has gateway-side quota enforcement today.+ Reads ``credits_exhausted`` from :class:`ThrottleContext`, pre-resolved by+ the dependency layer for the product's own credit bucket (see+ ``resolve_quota_status``), and applies :func:`bucket_block_applies`."""scope = "billable_credits"async def allow_request(self, context: ThrottleContext) -> ThrottleResult:config = get_product_config(context.product)- if not (config and config.credit_bucket is CreditBucket.AI_CREDITS):+ if config is None or config.credit_bucket is None:return ThrottleResult.allow()- if not context.ai_credits_exhausted:+ if not bucket_block_applies(context.product, context.plan_key, context.credits_exhausted):return ThrottleResult.allow()return ThrottleResult.deny(- detail=(- "Your team has used its monthly PostHog AI credits. "- "Top up at https://us.posthog.com/organization/billing to continue."- ),+ detail=_BUCKET_EXHAUSTED_DETAIL.get(config.credit_bucket, _DEFAULT_EXHAUSTED_DETAIL),scope=self.scope,retry_after=_RETRY_AFTER_SECONDS,)diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.pyindex 6620d455bcf7..2f0a123d594e 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py@@ -48,7 +48,7 @@ class ThrottleContext:plan_key: str | None = Noneseat_created_at: str | None = Nonebilling_period_start: str | None = None- ai_credits_exhausted: bool = False+ credits_exhausted: bool = False@dataclassdiff --git a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py b/services/llm-gateway/src/llm_gateway/services/plan_resolver.pyindex 73fce616fa40..0fb4f487f630 100644--- a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py+++ b/services/llm-gateway/src/llm_gateway/services/plan_resolver.py@@ -16,6 +16,7 @@ from typing import TYPE_CHECKINGimport structlog+from llm_gateway.auth.service import upstream_auth_headerfrom llm_gateway.config import get_settingsif TYPE_CHECKING:@@ -55,6 +56,20 @@ 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)@@ -99,7 +114,11 @@ async def resolve_plan_info(return PlanInfo(plan_key=None, seat_created_at=None)plan_resolver: PlanResolver = request.app.state.plan_resolver- auth_header = request.headers.get("Authorization", "")+ # upstream_auth_header mirrors extract_token's precedence (x-api-key wins).+ # Forwarding only Authorization would resolve no plan for x-api-key callers,+ # silently disabling every plan-conditioned control (usage-based cost caps,+ # the plan-scoped credit-bucket exemption) for a token placement auth accepts.+ auth_header = upstream_auth_header(request)try:return await plan_resolver.get_plan(user_id=user_id,diff --git a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py b/services/llm-gateway/src/llm_gateway/services/quota_resolver.pyindex 0004f09a8953..d14e2254d279 100644--- a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py+++ b/services/llm-gateway/src/llm_gateway/services/quota_resolver.py@@ -1,8 +1,10 @@"""Resolves a team's quota state via the PostHog API quota_limits endpoint.Mirrors :mod:`llm_gateway.services.plan_resolver` — forwards the caller's-``Authorization`` header to ``GET /api/projects/{team_id}/quota_limits/`` and-caches the result per team-and-resource in the gateway's own Redis.+credentials to ``GET /api/projects/{team_id}/quota_limits/`` and+caches the result per team-and-resource in the gateway's own Redis. The+resource key is a Django ``QuotaResource`` value (matches ``CreditBucket``+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 fall@@ -20,6 +22,7 @@ from typing import TYPE_CHECKINGimport httpximport structlog+from llm_gateway.auth.service import upstream_auth_headerfrom llm_gateway.config import get_settingsif TYPE_CHECKING:@@ -28,8 +31,6 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)-_AI_CREDITS_RESOURCE = "ai_credits"-# Cache window for the fail-open path (4xx from Django, or transient failure# after retries are exhausted). Long enough to keep a misconfigured client off# Django's neck during an auth-failure storm; short enough that a recovered@@ -62,19 +63,22 @@ def _redis_key(resource_key: str, team_id: int) -> str:return f"quota:{resource_key}:team:{team_id}"-async def resolve_quota_status(request: Request, team_id: int | None) -> QuotaResourceStatus:- """Resolve the team's AI credits quota state, falling open on errors."""+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:return QuotaResourceStatus(limited=False)- auth_header = request.headers.get("Authorization", "")+ # x-api-key wins over Authorization (see upstream_auth_header): forwarding+ # only Authorization would let an over-quota caller bypass the check by+ # sending their token via x-api-key.+ auth_header = upstream_auth_header(request)if not auth_header:return QuotaResourceStatus(limited=False)quota_resolver: QuotaResolver = request.app.state.quota_resolvertry:- return await quota_resolver.get_ai_credits_status(team_id=team_id, auth_header=auth_header)+ return await quota_resolver.get_resource_status(resource_key, team_id=team_id, auth_header=auth_header)except Exception:- logger.warning("quota_resolve_failed", team_id=team_id)+ logger.warning("quota_resolve_failed", resource=resource_key, team_id=team_id)return QuotaResourceStatus(limited=False)@@ -86,10 +90,7 @@ class QuotaResolver:self._http = http_clientself._cache_ttl = get_settings().quota_cache_ttl- async def get_ai_credits_status(self, team_id: int, auth_header: str) -> QuotaResourceStatus:- return await self._get_resource_status(_AI_CREDITS_RESOURCE, team_id, auth_header)-- async def _get_resource_status(self, resource_key: str, team_id: int, auth_header: str) -> QuotaResourceStatus:+ async def get_resource_status(self, resource_key: str, team_id: int, auth_header: str) -> QuotaResourceStatus:cached = await self._get_cached(resource_key, team_id)if cached is not None:return cacheddiff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.pyindex 6c4538b75055..85c01bb4c1b3 100644--- a/services/llm-gateway/tests/conftest.py+++ b/services/llm-gateway/tests/conftest.py@@ -23,7 +23,7 @@ from llm_gateway.services.quota_resolver import QuotaResourceStatusdef _make_fake_quota_resolver() -> AsyncMock:resolver = AsyncMock()- resolver.get_ai_credits_status = AsyncMock(return_value=QuotaResourceStatus(limited=False))+ resolver.get_resource_status = AsyncMock(return_value=QuotaResourceStatus(limited=False))return resolverdiff --git a/services/llm-gateway/tests/test_billable_credits_throttle.py b/services/llm-gateway/tests/test_billable_credits_throttle.pyindex 164c855ded15..3f6704f31e6a 100644--- a/services/llm-gateway/tests/test_billable_credits_throttle.py+++ b/services/llm-gateway/tests/test_billable_credits_throttle.py@@ -1,5 +1,7 @@from __future__ import annotations+from unittest.mock import patch+import pytestfrom llm_gateway.auth.models import AuthenticatedUser@@ -17,8 +19,8 @@ def _make_user() -> AuthenticatedUser:)-def _make_context(product: str, *, ai_credits_exhausted: bool = False) -> ThrottleContext:- return ThrottleContext(user=_make_user(), product=product, ai_credits_exhausted=ai_credits_exhausted)+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)class TestBillableCreditThrottle:@@ -28,26 +30,50 @@ class TestBillableCreditThrottle:# irrelevant — the throttle short-circuits before checking the flag.throttle = BillableCreditThrottle()- result = await throttle.allow_request(_make_context(product="sherlockhog", ai_credits_exhausted=True))+ result = await throttle.allow_request(_make_context(product="sherlockhog", credits_exhausted=True))assert result.allowed is True@pytest.mark.asyncio- async def test_allows_product_billing_outside_ai_credits_even_when_exhausted(self) -> None:- # `posthog_code` bills into the posthog_code_credits bucket, not the- # PostHog AI one, so the ai_credits quota must never block it.+ async 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.+ throttle = BillableCreditThrottle()++ result = await throttle.allow_request(+ _make_context(product="posthog_code", credits_exhausted=True, plan_key="posthog-code-usage-20260709")+ )++ assert result.allowed is False+ assert result.status_code == 429+ assert "PostHog Code usage limit" in result.detail++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "plan_key",+ ["posthog-code-pro-200-20260301", "posthog-code-free-20260301", None],+ )+ 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.throttle = BillableCreditThrottle()- result = await throttle.allow_request(_make_context(product="posthog_code", ai_credits_exhausted=True))+ result = await throttle.allow_request(+ _make_context(product="posthog_code", credits_exhausted=True, plan_key=plan_key)+ )assert result.allowed is True@pytest.mark.asyncio- @pytest.mark.parametrize("product", ["slack_app", "slack_app_routing"])+ @pytest.mark.parametrize("product", ["slack_app", "slack_app_routing", "posthog_code"])async def test_allows_billable_product_when_not_exhausted(self, product: str) -> None:throttle = BillableCreditThrottle()- result = await throttle.allow_request(_make_context(product=product, ai_credits_exhausted=False))+ result = await throttle.allow_request(_make_context(product=product, credits_exhausted=False))assert result.allowed is True@@ -56,10 +82,39 @@ class TestBillableCreditThrottle:async def test_denies_billable_product_when_exhausted(self, product: str) -> None:throttle = BillableCreditThrottle()- result = await throttle.allow_request(_make_context(product=product, ai_credits_exhausted=True))+ result = await throttle.allow_request(_make_context(product=product, credits_exhausted=True))assert result.allowed is Falseassert result.status_code == 429assert result.scope == "billable_credits"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.asyncio+ async def test_unmapped_bucket_falls_back_to_generic_detail(self) -> None:+ # A bucket added to the enum without a detail entry must still deny+ # with a 429, not blow up with a KeyError.+ 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")+ )++ assert result.allowed is False+ assert result.status_code == 429+ assert "reached its usage limit" in result.detaildiff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.pyindex fca1240e697b..a5eaee20b8ea 100644--- a/services/llm-gateway/tests/test_dependencies.py+++ b/services/llm-gateway/tests/test_dependencies.py@@ -205,9 +205,8 @@ class TestEnforceThrottles:class TestResolvePlanAndQuota:- """The ai_credits quota resolver roundtrip is skipped for products that don't- bill into the ai_credits bucket — unbilled ones, and products billing into a- bucket without gateway-side quota enforcement (e.g. posthog_code)."""+ """The quota resolver roundtrip runs for bucket-billed products (against the+ product's own bucket) and is skipped entirely for unbilled ones."""async def _run(self, product: str) -> tuple:plan_info = PlanInfo(plan_key="pro", seat_created_at=None)@@ -221,18 +220,21 @@ class TestResolvePlanAndQuota:return result, quota_mock@pytest.mark.asyncio- async def test_ai_credits_billed_product_resolves_quota(self) -> None:- (_, quota_status), quota_mock = await self._run("slack_app")+ @pytest.mark.parametrize(+ ("product", "expected_resource"),+ [("slack_app", "ai_credits"), ("posthog_code", "posthog_code_credits")],+ )+ async def test_bucket_billed_product_resolves_its_own_bucket(self, product: str, expected_resource: str) -> None:+ (_, quota_status), quota_mock = await self._run(product)quota_mock.assert_awaited_once()+ assert quota_mock.call_args.args[2] == expected_resourceassert quota_status.limited is True@pytest.mark.asyncio- @pytest.mark.parametrize("product", ["posthog_code", "wizard"])- async def test_ungated_products_skip_quota_resolver(self, product: str) -> None:- # posthog_code bills into its own bucket (no gateway quota enforcement);- # wizard is unbilled. Neither should pay for the quota resolver roundtrip.- (_, quota_status), quota_mock = await self._run(product)+ async def test_unbilled_product_skips_quota_resolver(self) -> None:+ # wizard is unbilled — it shouldn't pay for the quota resolver roundtrip.+ (_, quota_status), quota_mock = await self._run("wizard")quota_mock.assert_not_awaited()assert quota_status.limited is Falsediff --git a/services/llm-gateway/tests/test_plan_resolver.py b/services/llm-gateway/tests/test_plan_resolver.pyindex c5cd9567d260..7c275c6c0a11 100644--- a/services/llm-gateway/tests/test_plan_resolver.py+++ b/services/llm-gateway/tests/test_plan_resolver.py@@ -4,9 +4,12 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom llm_gateway.services.plan_resolver import (+ PlanInfo,PlanResolver,get_billing_period_number,is_pro_plan,+ is_usage_based_plan,+ resolve_plan_info,)@@ -29,6 +32,23 @@ 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@@ -252,3 +272,45 @@ class TestPlanResolver:assert result.plan_key is Noneassert resolver_with_redis._redis is not Noneresolver_with_redis._redis.set.assert_not_called() # type: ignore[attr-defined]+++class TestResolvePlanInfoCredentialForwarding:+ """Credential forwarding must mirror extract_token: either header+ authenticates, so either header must reach plan resolution — otherwise+ x-api-key callers resolve no plan, silently disabling every+ plan-conditioned control (usage-based cost caps, the plan-scoped+ credit-bucket exemption)."""++ def _make_request(self, headers: dict[str, str]) -> MagicMock:+ from starlette.datastructures import Headers++ request = MagicMock()+ request.headers = Headers(headers)+ resolver = MagicMock()+ resolver.get_plan = AsyncMock(+ return_value=PlanInfo(plan_key="posthog-code-usage-20260709", seat_created_at=None)+ )+ request.app.state.plan_resolver = resolver+ return request++ @pytest.mark.asyncio+ 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 request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_test"++ @pytest.mark.asyncio+ async 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 request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_test"++ @pytest.mark.asyncio+ async def test_x_api_key_takes_precedence_over_authorization(self) -> None:+ # Matches extract_token — the token that authenticated the request is+ # the one whose plan gets resolved.+ request = self._make_request({"x-api-key": "phx_from_api_key", "Authorization": "Bearer phx_from_auth"})+ await resolve_plan_info(request, user_id=1, product="posthog_code")+ assert request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_from_api_key"diff --git a/services/llm-gateway/tests/test_quota_resolver.py b/services/llm-gateway/tests/test_quota_resolver.pyindex 28254e6c11e5..60eea6c65f4d 100644--- a/services/llm-gateway/tests/test_quota_resolver.py+++ b/services/llm-gateway/tests/test_quota_resolver.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytest+from starlette.datastructures import Headersfrom llm_gateway.services.quota_resolver import (_FAIL_OPEN_CACHE_TTL_SECONDS,@@ -13,6 +14,7 @@ from llm_gateway.services.quota_resolver import (QuotaResolver,QuotaResourceStatus,_redis_key,+ resolve_quota_status,)@@ -50,6 +52,78 @@ def _no_retry_sleep() -> Iterator[None]:yield+def _make_request(headers: dict[str, str], resolver: AsyncMock | None = None) -> MagicMock:+ request = MagicMock()+ request.headers = Headers(headers)+ request.app.state.quota_resolver = resolver+ return request+++class TestResolveQuotaStatus:+ """Credential forwarding must mirror extract_token: either header authenticates,+ so either header must reach the quota check — otherwise x-api-key callers+ bypass enforcement."""++ def _make_resolver(self) -> AsyncMock:+ resolver = MagicMock()+ resolver.get_resource_status = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ return resolver++ @pytest.mark.asyncio+ async def test_forwards_authorization_header(self) -> None:+ resolver = self._make_resolver()+ request = _make_request({"Authorization": "Bearer phx_test"}, resolver)++ status = await resolve_quota_status(request, team_id=42, resource_key="ai_credits")++ assert status == QuotaResourceStatus(limited=True)+ assert resolver.get_resource_status.await_args.kwargs["auth_header"] == "Bearer phx_test"++ @pytest.mark.asyncio+ async def test_forwards_x_api_key_as_bearer(self) -> None:+ resolver = self._make_resolver()+ request = _make_request({"x-api-key": " phx_test "}, resolver)++ status = await resolve_quota_status(request, team_id=42, resource_key="ai_credits")++ assert status == QuotaResourceStatus(limited=True)+ assert resolver.get_resource_status.await_args.kwargs["auth_header"] == "Bearer phx_test"++ @pytest.mark.asyncio+ async def test_x_api_key_takes_precedence_over_authorization(self) -> None:+ # Matches extract_token — the token that authenticated the request is+ # the one whose quota gets checked.+ resolver = self._make_resolver()+ request = _make_request(+ {"x-api-key": "phx_from_api_key", "Authorization": "Bearer phx_from_auth"},+ resolver,+ )++ await resolve_quota_status(request, team_id=42, resource_key="ai_credits")++ assert resolver.get_resource_status.await_args.kwargs["auth_header"] == "Bearer phx_from_api_key"++ @pytest.mark.asyncio+ async def test_no_credentials_fails_open_without_resolver_call(self) -> None:+ resolver = self._make_resolver()+ request = _make_request({}, resolver)++ status = await resolve_quota_status(request, team_id=42, resource_key="ai_credits")++ assert status == QuotaResourceStatus(limited=False)+ resolver.get_resource_status.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_no_team_id_fails_open(self) -> None:+ resolver = self._make_resolver()+ request = _make_request({"Authorization": "Bearer phx_test"}, resolver)++ status = await resolve_quota_status(request, team_id=None, resource_key="ai_credits")++ assert status == QuotaResourceStatus(limited=False)+ resolver.get_resource_status.assert_not_awaited()++class TestQuotaResolver:@pytest.mark.asyncioasync def test_fetches_and_parses_limited_response(self) -> None:@@ -58,7 +132,7 @@ class TestQuotaResolver:)resolver = QuotaResolver(redis=None, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=True)http_client.get.assert_awaited_once()@@ -71,7 +145,7 @@ class TestQuotaResolver:)resolver = QuotaResolver(redis=None, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=False)@@ -82,7 +156,7 @@ class TestQuotaResolver:http_client = _make_http_client(_make_response(401, {"detail": "no auth"}))resolver = QuotaResolver(redis=None, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=False)http_client.get.assert_awaited_once()@@ -98,7 +172,7 @@ class TestQuotaResolver:)resolver = QuotaResolver(redis=None, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=True)assert http_client.get.await_count == 2@@ -113,7 +187,7 @@ class TestQuotaResolver:)resolver = QuotaResolver(redis=None, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=False)assert http_client.get.await_count == 2@@ -128,7 +202,7 @@ class TestQuotaResolver:redis.set = AsyncMock()resolver = QuotaResolver(redis=redis, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=False)assert http_client.get.await_count == len(_RETRY_DELAYS_SECONDS)@@ -142,7 +216,7 @@ class TestQuotaResolver:http_client = _make_http_client(_make_response(200))resolver = QuotaResolver(redis=redis, http_client=http_client)- status = await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ status = await resolver.get_resource_status("ai_credits", team_id=42, auth_header="Bearer phx_test")assert status == QuotaResourceStatus(limited=True)redis.get.assert_awaited_once_with(_redis_key("ai_credits", 42))@@ -156,7 +230,7 @@ class TestQuotaResolver:http_client = _make_http_client(_make_response(200, {"limited": {"ai_credits": {"limited": True}}}))resolver = QuotaResolver(redis=redis, http_client=http_client)- await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ 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@@ -175,7 +249,7 @@ class TestQuotaResolver:http_client = _make_http_client(_make_response(401, {"detail": "no auth"}))resolver = QuotaResolver(redis=redis, http_client=http_client)- await resolver.get_ai_credits_status(team_id=42, auth_header="Bearer phx_test")+ 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_SECONDSdiff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.pyindex 417ee4e5ac0a..47e8c44c29a3 100644--- a/services/llm-gateway/tests/test_usage.py+++ b/services/llm-gateway/tests/test_usage.py@@ -1,3 +1,4 @@+from collections.abc import Generatorfrom datetime import UTC, datetime, timedeltafrom unittest.mock import AsyncMock, MagicMock@@ -57,7 +58,7 @@ class TestToCostLimitStatus:class TestUsageEndpoint:@pytest.fixture- def authenticated_usage_client(self, mock_db_pool: MagicMock) -> TestClient:+ def authenticated_usage_client(self, mock_db_pool: MagicMock) -> Generator[TestClient]:app = create_test_app(mock_db_pool)conn = AsyncMock()@@ -359,14 +360,43 @@ class TestUsageEndpoint:assert response.status_code == 200assert response.json()["user_id"] == 42- def test_ai_credits_reported_unlimited_for_ungated_product(self, authenticated_usage_client: TestClient) -> None:- # posthog_code bills into its own credit bucket, not ai_credits; ai_credits- # should be unlimited and not contribute to is_rate_limited even if the- # resolver thinks the team is over.+ 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.app- app.state.quota_resolver.get_ai_credits_status = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ resolver_mock = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ app.state.quota_resolver.get_resource_status = resolver_mock+ app.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")+ )++ response = authenticated_usage_client.get(+ "/v1/usage/posthog_code",+ headers={"Authorization": "Bearer phx_test"},+ )+ assert response.status_code == 200+ data = response.json()+ assert data["ai_credits"] == {"exhausted": True}+ assert data["is_rate_limited"] is True+ 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(+ 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.+ from llm_gateway.services.quota_resolver import QuotaResourceStatus++ app = authenticated_usage_client.app+ app.state.quota_resolver.get_resource_status = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ app.state.plan_resolver.get_plan = AsyncMock(+ return_value=PlanInfo(plan_key=plan_key, seat_created_at="2026-01-01T00:00:00+00:00")+ )response = authenticated_usage_client.get("/v1/usage/posthog_code",@@ -381,7 +411,8 @@ class TestUsageEndpoint:from llm_gateway.services.quota_resolver import QuotaResourceStatusapp = authenticated_usage_client.app- app.state.quota_resolver.get_ai_credits_status = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ resolver_mock = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ app.state.quota_resolver.get_resource_status = resolver_mockresponse = authenticated_usage_client.get("/v1/usage/slack_app",@@ -391,6 +422,7 @@ class TestUsageEndpoint:data = response.json()assert data["ai_credits"] == {"exhausted": True}assert data["is_rate_limited"] is True+ assert resolver_mock.call_args.args[0] == "ai_credits"def test_invalidate_plan_cache_calls_resolver(self, authenticated_usage_client: TestClient) -> None:app = authenticated_usage_client.app