: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): bill LLM costs as pass-through credits (no markup) (#69062)
Adam Bowker47dae52916b4
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.pyindex 2d3a295113f9..75a267b59f0e 100644--- a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py@@ -17,6 +17,7 @@ from posthog.tasks.usage_report import (AI_COST_MARKUP_PERCENT,CLOUD_REGION_TO_TEAM_ID,CLOUD_REGION_TO_URL,+ POSTHOG_AI_PRODUCTS,build_ai_billing_region_filter,)from posthog.utils import get_instance_region@@ -253,6 +254,9 @@ def get_ai_credits(AND timestamp >= %(begin)sAND timestamp < %(end)sAND event = '$ai_generation'+ -- Only products that bill into the PostHog AI credit bucket; other billable+ -- products (e.g. posthog_code) have their own credit counters.+ AND JSONExtractString(properties, 'ai_product') IN %(ai_products)s{session_filter_prewhere})WHERE@@ -269,13 +273,14 @@ def get_ai_credits(WHERE t.is_billable = 1 OR t.trace_id IS NULL"""- params: dict[str, int | datetime | float | list[str] | str] = {+ params: dict[str, int | datetime | float | list[str] | tuple[str, ...] | str] = {"team_id": team_id,"team_to_query": team_to_query,"begin": begin,"end": end,"markup_multiplier": 1 + AI_COST_MARKUP_PERCENT,"excluded_tools": AI_BILLING_EXCLUDED_TOOLS,+ "ai_products": tuple(POSTHOG_AI_PRODUCTS),**region_filter_params,}diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.pyindex 2596749b1f62..5e7e393b0972 100644--- a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py@@ -22,6 +22,7 @@ from ee.hogai.chat_agent.slash_commands.commands.usage.queries import (CLOUD_REGION_TO_URL,DEFAULT_FREE_TIER_CREDITS,DEFAULT_GA_LAUNCH_DATE,+ POSTHOG_AI_PRODUCTS,AiUsagePeriod,format_usage_message,get_ai_credits,@@ -129,6 +130,9 @@ class TestUsage(BaseTest):query, params = mock_sync_execute.call_args[0][:2]self.assertEqual(params["team_to_query"], expected_team_to_query)self.assertEqual(params["session_id"], str(conversation_id))+ # Only PostHog AI bucket products count — posthog_code bills separately.+ self.assertIn("AND JSONExtractString(properties, 'ai_product') IN %(ai_products)s", query)+ self.assertEqual(params["ai_products"], tuple(POSTHOG_AI_PRODUCTS))if expected_region_url is None:self.assertNotIn("region_url", params)self.assertNotIn("%(region_url)s", query)diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 1d1d90af0b43..6534596ddd1a 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -4522,12 +4522,13 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouseposthog_code_result = get_teams_with_posthog_code_credits_used_in_period(period_start, period_end)- # posthog_code: 2.0 USD * 100 * 1.2 = 240 — only the posthog_code event, not the signals one.- self.assertEqual(posthog_code_result, [(self.org_1_team_1.id, 240)])+ # posthog_code bills at cost (no markup): 2.0 USD * 100 * 1.0 = 200 — only the+ # posthog_code event, not the signals one.+ self.assertEqual(posthog_code_result, [(self.org_1_team_1.id, 200)])@parameterized.expand([- ("billable", True, 480),+ ("billable", True, 400),("non_billable", False, None),])@@ -4559,7 +4560,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouseproperties={"team_id": self.org_1_team_1.id,"$ai_trace_id": "trace_posthog_code",- "$ai_total_cost_usd": 4.0, # 4.0 USD * 100 * 1.2 = 480 credits+ "$ai_total_cost_usd": 4.0, # 4.0 USD * 100 * 1.0 (no markup) = 400 credits"$ai_billable": billable,"ai_product": "posthog_code","$group_1": "https://us.posthog.com",diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex d2b717b63629..e74e98023d59 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -1265,6 +1265,8 @@ def get_teams_with_ai_event_count_in_period(# AI billing markup: 20% markup on top of costAI_COST_MARKUP_PERCENT = 0.2+# PostHog Code bills model costs as pure pass-through: no markup+POSTHOG_CODE_COST_MARKUP_PERCENT = 0.0# Tools excluded from AI billing (traces with only these tools are not billed)AI_BILLING_EXCLUDED_TOOLS = ["summarize_sessions", "search"]AI_BILLING_INSTANCE_GROUP_TYPE = "instance"@@ -1318,6 +1320,7 @@ def _get_teams_with_ai_credits_for_products(ai_products: list[str],usage_report_tag: str,product_tag: Product = Product.MAX_AI,+ markup_percent: float = AI_COST_MARKUP_PERCENT,) -> list[tuple[int, int]]:"""Shared implementation for AI billing credit aggregation, whitelisting on the@@ -1477,7 +1480,7 @@ def _get_teams_with_ai_credits_for_products("team_to_query": team_to_query,"begin": begin,"end": end,- "markup_multiplier": 1 + AI_COST_MARKUP_PERCENT,+ "markup_multiplier": 1 + markup_percent,"excluded_tools": AI_BILLING_EXCLUDED_TOOLS,"ai_products": tuple(ai_products),**region_filter_params,@@ -1523,13 +1526,17 @@ def get_teams_with_posthog_code_credits_used_in_period(begin: datetime,end: datetime,) -> list[tuple[int, int]]:- """PostHog Code billing credits — only events tagged with ai_product='posthog_code'."""+ """PostHog Code billing credits — only events tagged with ai_product='posthog_code'.++ Billed as pure pass-through of model costs (no markup), unlike PostHog AI's 20%.+ """return _get_teams_with_ai_credits_for_products(begin,end,ai_products=POSTHOG_CODE_AI_PRODUCTS,usage_report_tag="posthog_code_credits",product_tag=Product.POSTHOG_CODE,+ markup_percent=POSTHOG_CODE_COST_MARKUP_PERCENT,)diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsxindex 8c8b4296c808..8f0f27cc5ea8 100644--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx@@ -671,7 +671,7 @@ function CostChip({<hr className="my-0.5 border-border" /><div>Billed: {formatLLMCost(billedTotalUsd!)}</div>{typeof markupUsd === 'number' && markupUsd > 0 && (- <div>Markup (20%): {formatLLMCost(markupUsd)}</div>+ <div>Markup: {formatLLMCost(markupUsd)}</div>)}{typeof billedCredits === 'number' && <div>Credits: {billedCredits}</div>}</>diff --git a/products/ai_observability/frontend/usePosthogAIBillingCalculations.test.ts b/products/ai_observability/frontend/usePosthogAIBillingCalculations.test.tsnew file mode 100644index 000000000000..1972d353c61c--- /dev/null+++ b/products/ai_observability/frontend/usePosthogAIBillingCalculations.test.ts@@ -0,0 +1,48 @@+import { EnrichedTraceTreeNode } from './aiObservabilityTraceDataLogic'+import { computeBillingTotals } from './usePosthogAIBillingCalculations'++function makeNode(properties: Record<string, any>, children?: EnrichedTraceTreeNode[]): EnrichedTraceTreeNode {+ return {+ event: {+ id: `event-${Math.random()}`,+ event: '$ai_generation',+ properties,+ createdAt: '2026-01-01T00:00:00Z',+ },+ children,+ displayTotalCost: 0,+ displayLatency: 0,+ displayUsage: null,+ }+}++describe('computeBillingTotals', () => {+ it('applies markup per event, skipping pass-through products', () => {+ const tree = [+ makeNode({ $ai_billable: true, $ai_total_cost_usd: 10, ai_product: 'posthog_ai' }, [+ // Nested pass-through generation must still be summed, without markup+ makeNode({ $ai_billable: true, $ai_total_cost_usd: 5, ai_product: 'posthog_code' }),+ ]),+ ]++ expect(computeBillingTotals(tree)).toEqual({ totalCostUsd: 15, markupUsd: 2 })+ })++ it('excludes billable generations outside the billing whitelist', () => {+ // The usage reporter whitelists on ai_product — events with a missing or unknown+ // product never bill, even when tagged $ai_billable, so they must not display as billed.+ const tree = [+ makeNode({ $ai_billable: true, $ai_total_cost_usd: 10, ai_product: 'posthog_ai' }),+ makeNode({ $ai_billable: true, $ai_total_cost_usd: 5 }), // untagged+ makeNode({ $ai_billable: true, $ai_total_cost_usd: 5, ai_product: 'sherlockhog' }), // unbilled product+ ]++ expect(computeBillingTotals(tree)).toEqual({ totalCostUsd: 10, markupUsd: 2 })+ })++ it('ignores non-billable generations', () => {+ const tree = [makeNode({ $ai_billable: false, $ai_total_cost_usd: 10, ai_product: 'posthog_ai' })]++ expect(computeBillingTotals(tree)).toEqual({ totalCostUsd: 0, markupUsd: 0 })+ })+})diff --git a/products/ai_observability/frontend/usePosthogAIBillingCalculations.ts b/products/ai_observability/frontend/usePosthogAIBillingCalculations.tsindex 635c82f8d535..0e4371ed0726 100644--- a/products/ai_observability/frontend/usePosthogAIBillingCalculations.ts+++ b/products/ai_observability/frontend/usePosthogAIBillingCalculations.ts@@ -7,9 +7,54 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { EnrichedTraceTreeNode } from './aiObservabilityTraceDataLogic'import { isLLMEvent } from './utils'-// AI billing markup: 20% markup on top of cost+// AI billing markup: 20% on top of cost, except posthog_code which bills model costs+// at cost (pass-through).const AI_COST_MARKUP_PERCENT = 0.2+// ai_product → markup fraction applied on top of cost. Mirrors the billing whitelists+// in posthog/tasks/usage_report.py (POSTHOG_AI_PRODUCTS at 20%, POSTHOG_CODE_AI_PRODUCTS+// at cost) — keep in sync. Billable generations whose ai_product is missing or not listed+// here are NOT billed by the usage reporter, so they're excluded from the totals entirely.+const AI_PRODUCT_MARKUP: Record<string, number> = {+ posthog_ai: AI_COST_MARKUP_PERCENT,+ slack_app: AI_COST_MARKUP_PERCENT,+ subscriptions: AI_COST_MARKUP_PERCENT,+ alert_investigation_agent: AI_COST_MARKUP_PERCENT,+ product_analytics: AI_COST_MARKUP_PERCENT,+ surveys: AI_COST_MARKUP_PERCENT,+ posthog_code: 0,+}++export function computeBillingTotals(enrichedTree: EnrichedTraceTreeNode[]): {+ totalCostUsd: number+ markupUsd: number+} {+ let totalCostUsd = 0+ let markupUsd = 0+ const sumBilled = (node: EnrichedTraceTreeNode): void => {+ const ev = node.event+ if (isLLMEvent(ev) && ev.event === '$ai_generation' && !!ev.properties?.$ai_billable) {+ const markupPercent = AI_PRODUCT_MARKUP[ev.properties.ai_product as string]+ const cost = Number(ev.properties.$ai_total_cost_usd ?? 0)+ // Unknown/untagged products bill nothing regardless of $ai_billable — mirror that.+ if (markupPercent !== undefined && !isNaN(cost)) {+ totalCostUsd += cost+ markupUsd += cost * markupPercent+ }+ }+ if (node.children) {+ for (const child of node.children) {+ sumBilled(child)+ }+ }+ }++ for (const node of enrichedTree) {+ sumBilled(node)+ }+ return { totalCostUsd, markupUsd }+}+// Banker's roundingfunction roundBankers(value: number): number {const rounded = Math.round(value)@@ -38,33 +83,16 @@ export function usePosthogAIBillingCalculations(enrichedTree: EnrichedTraceTreeNconst showBillingInfo = !!featureFlags[FEATURE_FLAGS.POSTHOG_AI_BILLING_DISPLAY]- // Compute total billed USD across billed generations in the tree- const totalCostUsd = useMemo(() => {+ // Compute total billed USD and per-product markup across billed generations in the tree+ const { totalCostUsd, markupUsd } = useMemo(() => {if (!showBillingInfo || !enrichedTree) {- return 0+ return { totalCostUsd: 0, markupUsd: 0 }}-- const sumBilled = (node: EnrichedTraceTreeNode): number => {- const ev = node.event- let total = 0- if (isLLMEvent(ev) && ev.event === '$ai_generation' && !!ev.properties?.$ai_billable) {- const cost = Number(ev.properties.$ai_total_cost_usd ?? 0)- total += isNaN(cost) ? 0 : cost- }- if (node.children) {- for (const child of node.children) {- total += sumBilled(child)- }- }- return total- }-- return enrichedTree.reduce((acc, n) => acc + sumBilled(n), 0)+ return computeBillingTotals(enrichedTree)}, [enrichedTree, showBillingInfo])- const markupUsd = showBillingInfo ? totalCostUsd * AI_COST_MARKUP_PERCENT : 0- const billedTotalUsd = showBillingInfo ? totalCostUsd + markupUsd : 0 // Total cost + markup- const billedCredits = showBillingInfo ? roundBankers(billedTotalUsd * 100) : 0+ const billedTotalUsd = totalCostUsd + markupUsd // Total cost + markup+ const billedCredits = roundBankers(billedTotalUsd * 100)return {showBillingInfo,diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.pyindex e7f16877ab5c..ed5c46eca2cd 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py@@ -64,11 +64,12 @@ _TRUNCATABLE_FIELDS = ("$ai_output_choices", "$ai_input")def _is_product_billable(product: str) -> bool:- """Look up the product's billable flag in the central registry. False for- unknown products so we never accidentally bill calls we can't attribute.+ """A product is billable if it bills into a credit bucket in the central+ registry. False for unknown products so we never accidentally bill calls we+ can't attribute."""config = get_product_config(product)- return bool(config and config.billable)+ return config is not None and config.credit_bucket is not Nonedef _apply_owned_event_properties(properties: dict[str, Any], product: str, team_id: int | None) -> None:diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.pyindex 752357f92903..87a592a3aa96 100644--- a/services/llm-gateway/src/llm_gateway/dependencies.py+++ b/services/llm-gateway/src/llm_gateway/dependencies.py@@ -13,6 +13,7 @@ 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,@@ -163,15 +164,17 @@ async def resolve_plan_and_quota(team_id: int | None,product: str,) -> tuple[PlanInfo, QuotaResourceStatus]:- """Fetch plan info and (for billable products) AI credits quota in parallel.-- Both calls are independent Django roundtrips on cache miss, so for billable- products we overlap them. For non-billable products the throttle stack- short-circuits regardless of quota state, so we skip the resolver entirely- rather than paying for the Redis GET (and the HTTP fallback on cache miss).+ """Fetch plan info and (for ai_credits-billed products) AI credits 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)."""product_config = get_product_config(product)- if product_config and product_config.billable:+ if product_config and product_config.credit_bucket is CreditBucket.AI_CREDITS:plan_info, quota_status = await asyncio.gather(resolve_plan_info(request, user_id, product),resolve_quota_status(request, team_id),diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 88f147ccc236..ec33ff98c985 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom dataclasses import dataclass+from enum import StrEnumfrom typing import Finalfrom fastapi import HTTPException@@ -9,6 +10,20 @@ from llm_gateway.bedrock import BEDROCK_MODEL_IDS, get_bedrock_model_access_candfrom llm_gateway.config import get_settings+class CreditBucket(StrEnum):+ """Customer credit bucket a product's generations bill into.++ 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.+ """++ AI_CREDITS = "ai_credits"+ POSTHOG_CODE_CREDITS = "posthog_code_credits"++@dataclass(frozen=True)class ProductConfig:# Empty set (the default) or None means no OAuth application is authorized for this product.@@ -16,10 +31,13 @@ class ProductConfig:allowed_application_ids: frozenset[str] | None = frozenset()allowed_models: frozenset[str] | None = None # None = all allowedallow_api_keys: bool = True- # Tag emitted $ai_generation events with $ai_billable=true so the usage reporter- # (posthog/tasks/usage_report.py) rolls them into the customer team's credit bucket- # for this product's ai_product (e.g. PostHog AI credits, or signals credits).- billable: bool = False+ # 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 — currently only AI_CREDITS has+ # gateway-side quota enforcement; other buckets bill without blocking.+ credit_bucket: CreditBucket | None = NoneBEDROCK_MODELS = BEDROCK_MODEL_IDS@@ -77,7 +95,15 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),allowed_models=_POSTHOG_CODE_AGENT_MODELS | BEDROCK_MODELS,allow_api_keys=False,+ # 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,),+ # PostHog-initiated internal task runs (Task.internal=True without a more specific+ # origin route — e.g. the repo-selection agent). Deliberately unbilled: this is+ # "work completed by PostHog" per the pricing RFC, which gets its own (marked-up)+ # pricing later rather than posthog_code's pass-through bucket. Interim spend+ # control is the product/user cost limits in llm_gateway/config.py."background_agents": ProductConfig(allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),allowed_models=frozenset(@@ -98,12 +124,13 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {| BEDROCK_MODELS),allow_api_keys=False,+ credit_bucket=None,),"slack_app": ProductConfig(allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),allowed_models=_POSTHOG_CODE_AGENT_MODELS | BEDROCK_MODELS,allow_api_keys=False,- billable=True,+ credit_bucket=CreditBucket.AI_CREDITS,),# SherlockHog (https://github.com/PostHog/SherlockHog) — the internal SRE# bot. Authenticates with a personal API key (not OAuth), so no application@@ -114,7 +141,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=None,allowed_models=None,allow_api_keys=True,- billable=False,+ credit_bucket=None,),"wizard": ProductConfig(allowed_application_ids=frozenset({WIZARD_US_APP_ID, WIZARD_EU_APP_ID}),@@ -135,7 +162,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=None,allowed_models=frozenset({"claude-haiku-4-5"}),allow_api_keys=True,- billable=True,+ credit_bucket=CreditBucket.AI_CREDITS,),"growth": ProductConfig(allowed_application_ids=None,@@ -171,7 +198,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),allowed_models=None, # any model — the signals pipeline picks models per stage (haiku, sonnet, ...)allow_api_keys=True,- billable=False,+ credit_bucket=None,),"subscriptions": ProductConfig(allowed_application_ids=None,@@ -184,13 +211,16 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),allowed_models=frozenset({"claude-haiku-4-5", "claude-sonnet-4-6", "claude-sonnet-5"}),allow_api_keys=True,- billable=False,+ # Deliberately unbilled: autonomous support-reply drafting is "work completed by+ # PostHog" per the pricing RFC — it gets its own pricing later, not posthog_code's+ # pass-through bucket.+ credit_bucket=None,),"warehouse_semantic_enrichment": ProductConfig(allowed_application_ids=None,allowed_models=frozenset({"claude-haiku-4-5"}),allow_api_keys=True,- billable=False,+ credit_bucket=None,),# Drafts a Custom REST source manifest from API docs. Low volume, high stakes, long context —# pinned to Opus rather than the cheap per-row model the enrichment context layer uses.@@ -198,13 +228,13 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=None,allowed_models=frozenset({"claude-opus-4-8"}),allow_api_keys=True,- billable=False,+ credit_bucket=None,),"posthog_ai": ProductConfig(allowed_application_ids=frozenset({POSTHOG_AI_US_APP_ID, POSTHOG_AI_EU_APP_ID, POSTHOG_AI_DEV_APP_ID}),allowed_models=None, # any modelallow_api_keys=True,- billable=True,+ credit_bucket=CreditBucket.AI_CREDITS,),}diff --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 4be99145f703..33d4615da815 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@@ -1,6 +1,6 @@from __future__ import annotations-from llm_gateway.products.config import get_product_config+from llm_gateway.products.config import CreditBucket, get_product_configfrom llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult# Hint the client to back off for a minute. A precise expiry timestamp is@@ -12,17 +12,19 @@ _RETRY_AFTER_SECONDS = 60class BillableCreditThrottle(Throttle):- """Gate billable-product LLM calls on the team's AI credits balance.+ """Gate ai_credits-billed LLM calls on the team's AI credits balance.Reads ``ai_credits_exhausted`` from :class:`ThrottleContext`, pre-resolved- by the dependency layer (see ``resolve_quota_status``).+ 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."""scope = "billable_credits"async def allow_request(self, context: ThrottleContext) -> ThrottleResult:config = get_product_config(context.product)- if not (config and config.billable):+ if not (config and config.credit_bucket is CreditBucket.AI_CREDITS):return ThrottleResult.allow()if not context.ai_credits_exhausted:diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.pyindex ebe8e611cb29..ecc4a3cc906d 100644--- a/services/llm-gateway/tests/callbacks/test_posthog.py+++ b/services/llm-gateway/tests/callbacks/test_posthog.py@@ -249,7 +249,7 @@ class TestPostHogCallback:patch("llm_gateway.callbacks.posthog.get_product", return_value="posthog_code"),patch("llm_gateway.callbacks.posthog.get_posthog_properties",- return_value={"ai_product": "spoofed", "$ai_billable": True},+ return_value={"ai_product": "spoofed", "$ai_billable": False},),):await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)@@ -257,8 +257,9 @@ class TestPostHogCallback:props = mock_client.capture.call_args.kwargs["properties"]# route-derived product wins over the header valueassert props["ai_product"] == "posthog_code"- # config-derived billable flag wins (posthog_code is non-billable)- assert props["$ai_billable"] is False+ # config-derived billable flag wins (posthog_code is billable) — a caller+ # can't opt out of billing by spoofing the header+ assert props["$ai_billable"] is True@pytest.mark.asyncioasync def test_on_success_uses_uuid_when_no_auth_user(@@ -645,8 +646,8 @@ class TestPostHogCallback:assert props["ai_product"] == product@pytest.mark.asyncio- @pytest.mark.parametrize("product", ["slack_app", "slack_app_routing"])- async def test_on_success_marks_slack_products_billable(+ @pytest.mark.parametrize("product", ["slack_app", "slack_app_routing", "posthog_code"])+ async def test_on_success_marks_billable_products_billable(self,callback: PostHogCallback,auth_user: AuthenticatedUser,@@ -667,7 +668,7 @@ class TestPostHogCallback:assert props["$ai_billable"] is True@pytest.mark.asyncio- @pytest.mark.parametrize("product", ["posthog_code", "background_agents", "wizard", "llm_gateway"])+ @pytest.mark.parametrize("product", ["background_agents", "wizard", "llm_gateway"])async def test_on_success_does_not_mark_other_products_billable(self,callback: PostHogCallback,@@ -689,8 +690,8 @@ class TestPostHogCallback:assert props["$ai_billable"] is False@pytest.mark.asyncio- @pytest.mark.parametrize("product", ["slack_app", "slack_app_routing"])- async def test_on_failure_marks_slack_products_billable(+ @pytest.mark.parametrize("product", ["slack_app", "slack_app_routing", "posthog_code"])+ async def test_on_failure_marks_billable_products_billable(self,callback: PostHogCallback,auth_user: AuthenticatedUser,diff --git a/services/llm-gateway/tests/test_billable_credits_throttle.py b/services/llm-gateway/tests/test_billable_credits_throttle.pyindex 50a276af80e7..164c855ded15 100644--- a/services/llm-gateway/tests/test_billable_credits_throttle.py+++ b/services/llm-gateway/tests/test_billable_credits_throttle.py@@ -24,10 +24,20 @@ def _make_context(product: str, *, ai_credits_exhausted: bool = False) -> Throttclass TestBillableCreditThrottle:@pytest.mark.asyncioasync def test_allows_non_billable_product_even_when_exhausted(self) -> None:- # `posthog_code` is non-billable; exhaustion at the context level is+ # `sherlockhog` is non-billable; exhaustion at the context level is# irrelevant — the throttle short-circuits before checking the flag.throttle = BillableCreditThrottle()+ result = await throttle.allow_request(_make_context(product="sherlockhog", ai_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.+ throttle = BillableCreditThrottle()+result = await throttle.allow_request(_make_context(product="posthog_code", ai_credits_exhausted=True))assert result.allowed is Truediff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.pyindex 9530ce37359e..fca1240e697b 100644--- a/services/llm-gateway/tests/test_dependencies.py+++ b/services/llm-gateway/tests/test_dependencies.py@@ -1,13 +1,20 @@import json-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import HTTPException, Requestfrom starlette.datastructures import Headersfrom llm_gateway.auth.models import AuthenticatedUser-from llm_gateway.dependencies import _extract_end_user_id_from_body, enforce_throttles, get_provider_from_request+from llm_gateway.dependencies import (+ _extract_end_user_id_from_body,+ enforce_throttles,+ get_provider_from_request,+ resolve_plan_and_quota,+)from llm_gateway.rate_limiting.throttles import ThrottleContext, ThrottleResult+from llm_gateway.services.plan_resolver import PlanInfo+from llm_gateway.services.quota_resolver import QuotaResourceStatusdef _make_request(body: dict | None = None, headers: dict[str, str] | None = None) -> Request:@@ -195,3 +202,37 @@ class TestEnforceThrottles:auth_method="personal_api_key",)assert context.end_user_id is None+++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)."""++ async def _run(self, product: str) -> tuple:+ plan_info = PlanInfo(plan_key="pro", seat_created_at=None)+ plan_mock = AsyncMock(return_value=plan_info)+ quota_mock = AsyncMock(return_value=QuotaResourceStatus(limited=True))+ with (+ patch("llm_gateway.dependencies.resolve_plan_info", plan_mock),+ patch("llm_gateway.dependencies.resolve_quota_status", quota_mock),+ ):+ result = await resolve_plan_and_quota(_make_request(), user_id=1, team_id=42, product=product)+ 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")++ quota_mock.assert_awaited_once()+ assert 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)++ quota_mock.assert_not_awaited()+ assert quota_status.limited is Falsediff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.pyindex 9f534125067d..417ee4e5ac0a 100644--- a/services/llm-gateway/tests/test_usage.py+++ b/services/llm-gateway/tests/test_usage.py@@ -359,11 +359,10 @@ class TestUsageEndpoint:assert response.status_code == 200assert response.json()["user_id"] == 42- def test_ai_credits_reported_unlimited_for_non_billable_product(- self, authenticated_usage_client: TestClient- ) -> None:- # posthog_code is not billable; ai_credits should be unlimited and not contribute- # to is_rate_limited even if the resolver thinks the team is over.+ 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.from llm_gateway.services.quota_resolver import QuotaResourceStatusapp = authenticated_usage_client.app