:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): stop negative AI costs when cache reads exceed input tokens (#74183)
Christiaan Hendriksen3c015d607ae8
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.tsindex 6d9709fe793e..8455ae306b23 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.test.ts@@ -1,3 +1,4 @@+import { aiCacheExclusiveFallbackCounter } from '~/ingestion/pipelines/ai/metrics'import { PluginEvent } from '~/plugin-scaffold'import { calculateInputCost, resolveCacheReportingExclusive } from './input-costs'@@ -159,6 +160,37 @@ describe('resolveCacheReportingExclusive()', () => {properties: { $ai_provider: 'openai' },expected: false,},+ {+ name: 'falls back to exclusive for a non-Anthropic provider when cache reads exceed input tokens',+ properties: {+ $ai_provider: 'openai',+ $ai_model: 'xiaomi/mimo-v2.5',+ $ai_input_tokens: 149,+ $ai_cache_read_input_tokens: 23104,+ },+ expected: true,+ },+ {+ name: 'stays inclusive for a non-Anthropic provider when cache reads fit within input tokens',+ properties: {+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 500,+ },+ expected: false,+ },+ {+ name: 'explicit false wins over the provably-not-inclusive fallback',+ properties: {+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o',+ $ai_cache_reporting_exclusive: false,+ $ai_input_tokens: 100,+ $ai_cache_read_input_tokens: 200,+ },+ expected: false,+ },{name: 'returns false when event has no properties',properties: undefined,@@ -178,6 +210,71 @@ describe('resolveCacheReportingExclusive()', () => {} as PluginEventexpect(resolveCacheReportingExclusive(event)).toBe(expected)})++ describe('fallback counter', () => {+ async function fallbackCount(prior: 'inclusive' | 'anthropic_inclusive'): Promise<number> {+ const data = await aiCacheExclusiveFallbackCounter.get()+ return data.values.find((v) => v.labels.prior === prior)?.value ?? 0+ }++ beforeEach(() => {+ aiCacheExclusiveFallbackCounter.reset()+ })++ it.each<{+ name: string+ properties: Record<string, any>+ expected: { inclusive: number; anthropic_inclusive: number }+ }>([+ {+ name: 'counts a non-Anthropic fallback flip under prior=inclusive',+ properties: {+ $ai_provider: 'openai',+ $ai_model: 'xiaomi/mimo-v2.5',+ $ai_input_tokens: 149,+ $ai_cache_read_input_tokens: 23104,+ },+ expected: { inclusive: 1, anthropic_inclusive: 0 },+ },+ {+ name: 'counts an Anthropic-via-Vercel fallback flip under prior=anthropic_inclusive',+ properties: {+ $ai_provider: 'gateway',+ $ai_framework: 'vercel',+ $ai_model: 'anthropic/claude-opus-4.6',+ $ai_input_tokens: 247,+ $ai_cache_read_input_tokens: 6287,+ },+ expected: { inclusive: 0, anthropic_inclusive: 1 },+ },+ {+ name: 'does not count an inclusive event whose cache tokens fit within input tokens',+ properties: {+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o',+ $ai_input_tokens: 1000,+ $ai_cache_read_input_tokens: 500,+ },+ expected: { inclusive: 0, anthropic_inclusive: 0 },+ },+ {+ name: 'does not count an explicitly declared event even when tokens are provably not inclusive',+ properties: {+ $ai_provider: 'openai',+ $ai_model: 'gpt-4o',+ $ai_cache_reporting_exclusive: true,+ $ai_input_tokens: 100,+ $ai_cache_read_input_tokens: 200,+ },+ expected: { inclusive: 0, anthropic_inclusive: 0 },+ },+ ])('$name', async ({ properties, expected }) => {+ resolveCacheReportingExclusive(createAIEvent(properties))++ expect(await fallbackCount('inclusive')).toBe(expected.inclusive)+ expect(await fallbackCount('anthropic_inclusive')).toBe(expected.anthropic_inclusive)+ })+ })})describe('calculateInputCost()', () => {@@ -595,15 +692,15 @@ describe('calculateInputCost()', () => {expect(result).toBe('0')})- it('handles cache read tokens exceeding input tokens', () => {+ it('resolves to exclusive accounting when cache read tokens exceed input tokens', () => {const event = createOpenAITestEvent(100, 200, { $ai_model: 'gpt-4' })const result = calculateInputCost(event, testModel)- // Regular: (100 - 200) = -100, negative regular tokens// Read: 200 * 0.000001 * 0.5 = 0.0001- // Regular: -100 * 0.000001 = -0.0001- // Total: 0.0001 + (-0.0001) = 0- expectCostToBeCloseTo(result, 0)+ // Regular: 100 * 0.000001 = 0.0001+ // Total: 0.0001 + 0.0001 = 0.0002+ expectCostToBeCloseTo(result, 0.0002)+ expect(event.properties!['$ai_cache_reporting_exclusive']).toBe(true)})it('handles very large token counts', () => {diff --git a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.tsindex 6863d9648a88..2526a9bd427a 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/input-costs.ts@@ -1,6 +1,7 @@import bigDecimal from 'js-big-decimal'import { logger } from '~/common/utils/logger'+import { aiCacheExclusiveFallbackCounter } from '~/ingestion/pipelines/ai/metrics'import { PluginEvent } from '~/plugin-scaffold'import { numericProperty } from './cost-utils'@@ -57,18 +58,21 @@ export const resolveCacheReportingExclusive = (event: PluginEvent): boolean => {return explicit}- if (!matchProvider(event, 'anthropic')) {- return false- }-- if (!usesInclusiveAnthropicInputTokens(event)) {+ const anthropicStyle = matchProvider(event, 'anthropic')+ if (anthropicStyle && !usesInclusiveAnthropicInputTokens(event)) {return true}const inputTokens = numericProperty(event, '$ai_input_tokens')const cacheReadTokens = numericProperty(event, '$ai_cache_read_input_tokens')const cacheWriteTokens = numericProperty(event, '$ai_cache_creation_input_tokens')- return inputTokens < cacheReadTokens + cacheWriteTokens+ const provablyExclusive = inputTokens < cacheReadTokens + cacheWriteTokens++ if (provablyExclusive) {+ aiCacheExclusiveFallbackCounter.labels({ prior: anthropicStyle ? 'anthropic_inclusive' : 'inclusive' }).inc()+ }++ return provablyExclusive}/**diff --git a/nodejs/src/ingestion/pipelines/ai/metrics.ts b/nodejs/src/ingestion/pipelines/ai/metrics.tsindex ff2ccba379df..dd1e92dfc716 100644--- a/nodejs/src/ingestion/pipelines/ai/metrics.ts+++ b/nodejs/src/ingestion/pipelines/ai/metrics.ts@@ -63,6 +63,12 @@ export const aiOtelGroupsCounter = new Counter({// The team was renamed from LLMA to AIO: metrics above keep their historical// `llma_` prefix (dashboards depend on it); new metrics use `aio_` from now on.+export const aiCacheExclusiveFallbackCounter = new Counter({+ name: 'aio_ai_cost_cache_exclusive_fallback_total',+ help: 'Undeclared events resolved to exclusive cache reporting because cache tokens exceed input tokens',+ labelNames: ['prior'], // prior: inclusive | anthropic_inclusive+})+export const aiBlobOffloadS3Duration = new Histogram({name: 'aio_blob_offload_s3_request_duration_seconds',help: 'Latency of S3 requests made by the AI blob offload store',