: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(llma): coerce non-numeric custom token prices in AI cost ingestion (#67185)
posthog[bot]75ff37d4029a
diff --git a/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.test.tsindex ef3c2484c867..245e8d5b3ee2 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.test.ts@@ -1,6 +1,6 @@import { PluginEvent } from '~/plugin-scaffold'-import { numericProperty } from './cost-utils'+import { finiteNumberOrUndefined, numericProperty } from './cost-utils'import { createAIEvent } from './test-helpers'describe('numericProperty()', () => {@@ -14,6 +14,8 @@ describe('numericProperty()', () => {{ description: 'parses decimal numeric strings', value: '12.5', expected: 12.5 },{ description: 'returns 0 for non-numeric strings', value: 'not-a-number', expected: 0 },{ description: 'returns 0 for empty strings', value: '', expected: 0 },+ { description: 'returns 0 for whitespace-only strings', value: ' ', expected: 0 },+ { description: 'returns 0 for hexadecimal literals', value: '0x10', expected: 0 },{ description: 'returns 0 for null', value: null, expected: 0 },{ description: 'returns 0 for undefined', value: undefined, expected: 0 },{ description: 'returns 0 for objects', value: { foo: 'bar' }, expected: 0 },@@ -33,3 +35,34 @@ describe('numericProperty()', () => {expect(numericProperty(event, '$ai_audio_input_tokens')).toBe(0)})})++describe('finiteNumberOrUndefined()', () => {+ it.each<{ description: string; value: unknown; expected: number | undefined }>([+ { description: 'keeps a legitimate 0 distinct from absent', value: 0, expected: 0 },+ { description: 'keeps a legitimate "0" string distinct from absent', value: '0', expected: 0 },+ { description: 'returns the value when it is a finite number', value: 0.001, expected: 0.001 },+ { description: 'parses numeric strings', value: '0.001', expected: 0.001 },+ { description: 'parses exponent notation', value: '1E-7', expected: 1e-7 },+ { description: 'parses a leading decimal point', value: '.5', expected: 0.5 },+ { description: 'trims surrounding whitespace', value: ' 0.001 ', expected: 0.001 },+ { description: 'rejects whitespace-only strings', value: ' ', expected: undefined },+ { description: 'rejects empty strings', value: '', expected: undefined },+ { description: 'rejects currency-formatted strings', value: '$0.001', expected: undefined },+ // js-big-decimal reads these character by character, so adopting Number()'s+ // reading of them would invent a rate rather than parse one.+ { description: 'rejects hexadecimal literals', value: '0x10', expected: undefined },+ { description: 'rejects binary literals', value: '0b101', expected: undefined },+ { description: 'rejects octal literals', value: '0o17', expected: undefined },+ { description: 'rejects numeric separators', value: '1_000', expected: undefined },+ { description: 'rejects thousands separators', value: '1,000', expected: undefined },+ { description: 'rejects the string "Infinity"', value: 'Infinity', expected: undefined },+ { description: 'rejects NaN', value: Number.NaN, expected: undefined },+ { description: 'rejects Infinity', value: Number.POSITIVE_INFINITY, expected: undefined },+ { description: 'rejects null', value: null, expected: undefined },+ { description: 'rejects undefined', value: undefined, expected: undefined },+ { description: 'rejects objects', value: { value: 0.001 }, expected: undefined },+ { description: 'rejects booleans', value: true, expected: undefined },+ ])('$description', ({ value, expected }) => {+ expect(finiteNumberOrUndefined(value)).toBe(expected)+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.ts b/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.tsindex 4f3e088cee13..5b13f03b5d96 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/cost-utils.ts@@ -1,20 +1,39 @@import { PluginEvent } from '~/plugin-scaffold'/**- * Read a numeric property from the event's properties bag, returning zero for- * any value that is missing, non-finite, or not numeric. Accepts numeric- * strings (e.g. `"100"`) as well as numbers — third-party SDKs and OTel- * collectors occasionally serialise token counts as strings, and the cost- * pipeline must bill those tokens correctly rather than silently zeroing them.+ * Read a numeric property from the event's properties bag, defaulting to zero.+ * Numeric strings count as numbers — third-party SDKs and OTel collectors+ * occasionally serialize token counts as strings, and the cost pipeline must+ * bill those tokens rather than silently zeroing them.*/export const numericProperty = (event: PluginEvent, key: string): number => {- const value = event.properties?.[key]+ return finiteNumberOrUndefined(event.properties?.[key]) ?? 0+}++// Deliberately narrower than `Number()`, which reads `'0x10'` as 16, `''` as 0 and+// `' '` as 0. Billing can't invent a rate out of a radix prefix or a blank string,+// and `js-big-decimal` reads both into `NaN` digits anyway.+const DECIMAL_NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/++/**+ * Coerce a raw property value to a finite number, or `undefined` when it isn't+ * one. Unlike {@link numericProperty} this keeps "absent or unusable" distinct+ * from a legitimate `0`, so callers can fall back to another pricing source+ * instead of billing at a rate of zero.+ *+ * Everything reaching `js-big-decimal` must pass through here first, and must use+ * the number this returns rather than the original value: the library parses its+ * operands character by character, so a string it disagrees with becomes a+ * `'NaN10'`-style result that either throws downstream or lands in ClickHouse as+ * the cost.+ */+export const finiteNumberOrUndefined = (value: unknown): number | undefined => {if (typeof value === 'number') {- return Number.isFinite(value) ? value : 0+ return Number.isFinite(value) ? value : undefined}- if (typeof value === 'string' && value.length > 0) {+ if (typeof value === 'string' && DECIMAL_NUMBER.test(value.trim())) {const parsed = Number(value)- return Number.isFinite(parsed) ? parsed : 0+ return Number.isFinite(parsed) ? parsed : undefined}- return 0+ return undefined}diff --git a/nodejs/src/ingestion/pipelines/ai/costs/index.ts b/nodejs/src/ingestion/pipelines/ai/costs/index.tsindex 4641f64db11e..364ec6f8f0d6 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/index.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/index.ts@@ -10,6 +10,7 @@ import {getNewModelName,requireSpecialCost,} from './cost-model-matching'+import { finiteNumberOrUndefined } from './cost-utils'import { calculateInputCost } from './input-costs'import { extractModalityTokens } from './modality-tokens'import { calculateOutputCost } from './output-costs'@@ -21,9 +22,37 @@ export interface EventWithProperties extends PluginEvent {properties: Properties}+const PRECALCULATED_COST_PROPERTIES = [+ '$ai_input_cost_usd',+ '$ai_output_cost_usd',+ '$ai_request_cost_usd',+ '$ai_web_search_cost_usd',+ '$ai_total_cost_usd',+] as const++/**+ * Replace each cost the client sent with its parsed number, dropping the ones+ * `bigDecimal` can't use so they get recalculated instead of trusted. Checking a+ * value in place isn't enough — the check and the arithmetic have to agree on the+ * same value, or a string like `"0x10"` passes the check and still reaches+ * `bigDecimal`.+ */+const parsePrecalculatedCosts = (properties: Properties): void => {+ for (const key of PRECALCULATED_COST_PROPERTIES) {+ if (properties[key] === undefined) {+ continue+ }+ const parsed = finiteNumberOrUndefined(properties[key])+ if (parsed === undefined) {+ delete properties[key]+ } else {+ properties[key] = parsed+ }+ }+}+const setPropertyIfValidOrMissing = (properties: Properties, key: string, value: number): void => {- const existingValue = properties[key]- if (existingValue !== null && existingValue !== undefined && isBigDecimalInput(existingValue)) {+ if (typeof properties[key] === 'number') {return}if (!Number.isNaN(value)) {@@ -31,10 +60,6 @@ const setPropertyIfValidOrMissing = (properties: Properties, key: string, value:}}-const isBigDecimalInput = (value: unknown): value is string | number => {- return typeof value === 'string' || typeof value === 'number'-}-const trackCostOutcome = (totalCost: number): void => {if (Number.isNaN(totalCost)) {aiCostTotalOutcomeCounter.labels({ outcome: 'error' }).inc()@@ -58,8 +83,7 @@ const setCostsOnEvent = (event: EventWithProperties, cost: ResolvedModelCost): vsetPropertyIfValidOrMissing(event.properties, '$ai_request_cost_usd', parseFloat(requestCost))setPropertyIfValidOrMissing(event.properties, '$ai_web_search_cost_usd', parseFloat(webSearchCost))- const existingTotal = event.properties['$ai_total_cost_usd']- if (existingTotal !== null && existingTotal !== undefined && isBigDecimalInput(existingTotal)) {+ if (typeof event.properties['$ai_total_cost_usd'] === 'number') {return}@@ -91,23 +115,25 @@ export const processCost = (event: EventWithProperties): EventWithProperties =>// First, extract modality tokens from raw usage if presentextractModalityTokens(event)+ parsePrecalculatedCosts(event.properties)+const inputCost = event.properties['$ai_input_cost_usd']const outputCost = event.properties['$ai_output_cost_usd']// If we already have valid input and output costs, we can skip the rest of the logic- if (inputCost && outputCost && isBigDecimalInput(inputCost) && isBigDecimalInput(outputCost)) {+ if (inputCost && outputCost) {if (!event.properties['$ai_total_cost_usd']) {let total = bigDecimal.add(inputCost, outputCost)// Add pre-calculated request cost if presentconst requestCost = event.properties['$ai_request_cost_usd']- if (requestCost && isBigDecimalInput(requestCost)) {+ if (requestCost) {total = bigDecimal.add(total, requestCost)}// Add pre-calculated web search cost if presentconst webSearchCost = event.properties['$ai_web_search_cost_usd']- if (webSearchCost && isBigDecimalInput(webSearchCost)) {+ if (webSearchCost) {total = bigDecimal.add(total, webSearchCost)}@@ -120,23 +146,23 @@ export const processCost = (event: EventWithProperties): EventWithProperties =>return event}- // If custom token pricing is provided, use it to calculate costs- const hasCustomPricing =- event.properties['$ai_input_token_price'] !== undefined &&- event.properties['$ai_output_token_price'] !== undefined+ // A non-numeric price throws inside js-big-decimal, so treat one as absent and+ // fall back to model pricing rather than billing at a rate of zero.+ const inputTokenPrice = finiteNumberOrUndefined(event.properties['$ai_input_token_price'])+ const outputTokenPrice = finiteNumberOrUndefined(event.properties['$ai_output_token_price'])- if (hasCustomPricing) {+ if (inputTokenPrice !== undefined && outputTokenPrice !== undefined) {const customCost: ResolvedModelCost = {model: 'custom',provider: 'custom',cost: {- prompt_token: event.properties['$ai_input_token_price'],- completion_token: event.properties['$ai_output_token_price'],- cache_read_token: event.properties['$ai_cache_read_token_price'],- cache_write_token: event.properties['$ai_cache_write_token_price'],- cache_write_1h_token: event.properties['$ai_cache_write_1h_token_price'],- request: event.properties['$ai_request_price'],- web_search: event.properties['$ai_web_search_price'],+ prompt_token: inputTokenPrice,+ completion_token: outputTokenPrice,+ cache_read_token: finiteNumberOrUndefined(event.properties['$ai_cache_read_token_price']),+ cache_write_token: finiteNumberOrUndefined(event.properties['$ai_cache_write_token_price']),+ cache_write_1h_token: finiteNumberOrUndefined(event.properties['$ai_cache_write_1h_token_price']),+ request: finiteNumberOrUndefined(event.properties['$ai_request_price']),+ web_search: finiteNumberOrUndefined(event.properties['$ai_web_search_price']),},}diff --git a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.tsindex 44acf73eb381..6cbe8d63649a 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.test.ts@@ -104,16 +104,36 @@ describe('calculateOutputCost()', () => {expectCost(result, expectedCost)})- it.each([+ // 100 output tokens at 0.00001 is 0.001; a reasoning count that survives+ // coercion is billed at the same rate on top.+ it.each<{ reasoningTokens: unknown; expectedCost: number; description: string }>([{reasoningTokens: undefined,+ expectedCost: 0.001,description: 'handles undefined reasoning tokens',},{reasoningTokens: 0,+ expectedCost: 0.001,description: 'handles zero reasoning tokens',},- ])('$description for gemini-2.5', ({ reasoningTokens }) => {+ {+ reasoningTokens: 'abc',+ expectedCost: 0.001,+ description: 'ignores non-numeric reasoning tokens',+ },+ {+ // Number() reads this as 16, but bigDecimal reads it as "NaN10".+ reasoningTokens: '0x10',+ expectedCost: 0.001,+ description: 'ignores hexadecimal reasoning tokens',+ },+ {+ reasoningTokens: ' 200 ',+ expectedCost: 0.003,+ description: 'bills reasoning tokens sent as a numeric string',+ },+ ])('$description for gemini-2.5', ({ reasoningTokens, expectedCost }) => {const event = createAIEvent({$ai_provider: 'google',$ai_model: 'gemini-2.5-pro',@@ -123,7 +143,7 @@ describe('calculateOutputCost()', () => {const result = calculateOutputCost(event, gemini25ProModel)- expectCost(result, 0.001) // 100 * 0.00001 = 0.001+ expectCost(result, expectedCost)})it.each([diff --git a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.tsindex af81e534b43c..26a24e469e6c 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/output-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/output-costs.ts@@ -91,7 +91,7 @@ export const calculateOutputCost = (event: PluginEvent, cost: ResolvedModelCost)textOutputTokens = audioOutputTokens > 0 || imageOutputTokens > 0 ? Math.max(0, derived) : derived}- const reasoningTokens = event.properties['$ai_reasoning_tokens']+ const reasoningTokens = numericProperty(event, '$ai_reasoning_tokens')if (reasoningTokens && event.properties['$ai_model'] && mustAddReasoningCost(event.properties['$ai_model'])) {textOutputTokens = bigDecimal.add(textOutputTokens, reasoningTokens)}diff --git a/nodejs/src/ingestion/pipelines/ai/costs/request-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/request-costs.tsindex e6843559dfa0..4f82f6c6ba77 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/request-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/request-costs.ts@@ -2,6 +2,7 @@ import bigDecimal from 'js-big-decimal'import { EventWithProperties } from '~/ingestion/pipelines/ai/process-ai-event'+import { finiteNumberOrUndefined } from './cost-utils'import { ResolvedModelCost } from './providers/types'export const calculateRequestCost = (event: EventWithProperties, cost: ResolvedModelCost): string => {@@ -10,11 +11,9 @@ export const calculateRequestCost = (event: EventWithProperties, cost: ResolvedMreturn '0'}- // Get the request count, defaulting to 1 only if the model has request pricing- const requestCount =- event.properties['$ai_request_count'] !== undefined && event.properties['$ai_request_count'] !== null- ? event.properties['$ai_request_count']- : 1+ // An unusable count is treated like an absent one — the model bills per+ // request, so still charge for the single request we know happened.+ const requestCount = finiteNumberOrUndefined(event.properties['$ai_request_count']) ?? 1return bigDecimal.multiply(cost.cost.request, requestCount)}diff --git a/nodejs/src/ingestion/pipelines/ai/costs/web-search-costs.ts b/nodejs/src/ingestion/pipelines/ai/costs/web-search-costs.tsindex 0355abeffd61..40d3361bf51b 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/web-search-costs.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/web-search-costs.ts@@ -2,6 +2,7 @@ import bigDecimal from 'js-big-decimal'import { EventWithProperties } from '~/ingestion/pipelines/ai/process-ai-event'+import { finiteNumberOrUndefined } from './cost-utils'import { ResolvedModelCost } from './providers/types'export const calculateWebSearchCost = (event: EventWithProperties, cost: ResolvedModelCost): string => {@@ -11,9 +12,9 @@ export const calculateWebSearchCost = (event: EventWithProperties, cost: Resolve}// Only calculate if web search count is explicitly provided (no default)- const webSearchCount = event.properties['$ai_web_search_count']+ const webSearchCount = finiteNumberOrUndefined(event.properties['$ai_web_search_count'])- if (webSearchCount === undefined || webSearchCount === null) {+ if (webSearchCount === undefined) {return '0'}diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.tsindex 7bd33a5c6575..69d3e441d6ce 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts@@ -766,6 +766,58 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_request_cost_usd).toBe(0.02)})++ // A pre-calculated cost is only worth preserving if bigDecimal can add it up,+ // so an unusable one has to be recomputed instead of trusted. "0x10" earns its+ // place next to "abc": Number() reads it as 16, so a check that doesn't also+ // replace the value lets the original string reach bigDecimal.+ it.each([+ '$ai_input_cost_usd',+ '$ai_output_cost_usd',+ '$ai_request_cost_usd',+ '$ai_web_search_cost_usd',+ '$ai_total_cost_usd',+ ])('recomputes costs when the pre-calculated %s is unusable', (property) => {+ for (const value of ['abc', '0x10', '1_000', 'Infinity']) {+ const candidate = { ...event, properties: { ...event.properties, [property]: value } }+ candidate.properties.$ai_model = 'gpt-4'+ candidate.properties.$ai_provider = 'openai'+ candidate.properties.$ai_input_tokens = 100+ candidate.properties.$ai_output_tokens = 50++ const result = processAiEvent(candidate)++ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(20, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(10, 6)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(30, 6)+ }+ })++ // Valid input and output costs short-circuit to a passthrough, where the total+ // is only recomputed when falsy, so an unusable one would otherwise be kept.+ it.each(['abc', '0x10'])('recomputes a passthrough total of %p', (total) => {+ event.properties!.$ai_input_cost_usd = 3+ event.properties!.$ai_output_cost_usd = 2+ event.properties!.$ai_total_cost_usd = total++ const result = processAiEvent(event)++ expect(result.properties!.$ai_total_cost_usd).toBe(5)+ expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)+ })++ // A usable cost has to come out as the parsed number, not the original string,+ // since these properties are read as floats downstream.+ it('parses pre-calculated costs supplied as numeric strings', () => {+ event.properties!.$ai_input_cost_usd = '3'+ event.properties!.$ai_output_cost_usd = ' 2.5 '++ const result = processAiEvent(event)++ expect(result.properties!.$ai_input_cost_usd).toBe(3)+ expect(result.properties!.$ai_output_cost_usd).toBe(2.5)+ expect(result.properties!.$ai_total_cost_usd).toBe(5.5)+ })})describe('custom token pricing', () => {@@ -1002,6 +1054,127 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_cost_model_provider).toBe('openai')})+ // A price js-big-decimal can't parse has to count as unset, so the event bills+ // at model rates rather than throwing or silently billing at a rate of zero.+ it.each<{ description: string; inputPrice: unknown; outputPrice: unknown }>([+ { description: 'non-numeric string input price', inputPrice: '$0.001', outputPrice: 0.002 },+ { description: 'whitespace-only input price', inputPrice: ' ', outputPrice: 0.002 },+ { description: 'null input price', inputPrice: null, outputPrice: 0.002 },+ { description: 'object input price', inputPrice: { value: 0.001 }, outputPrice: 0.002 },+ { description: 'boolean input price', inputPrice: true, outputPrice: 0.002 },+ { description: 'non-numeric string output price', inputPrice: 0.001, outputPrice: '$0.002' },+ { description: 'NaN output price', inputPrice: 0.001, outputPrice: Number.NaN },+ ])('falls back to model pricing for $description', ({ inputPrice, outputPrice }) => {+ event.properties!.$ai_input_token_price = inputPrice+ event.properties!.$ai_output_token_price = outputPrice+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_output_tokens = 50++ const result = processAiEvent(event)++ expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4')+ expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)+ expect(result.properties!.$ai_cost_model_provider).toBe('openai')+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(20, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(10, 6)+ })++ // Every optional price OpenAI events consume is garbage at once, so dropping+ // the coercion on any single one puts it back in front of js-big-decimal. The+ // cache-write rates only apply to Anthropic events, covered separately below.+ it('ignores unusable optional prices and keeps custom pricing', () => {+ event.properties!.$ai_provider = 'openai'+ event.properties!.$ai_input_token_price = 0.001+ event.properties!.$ai_output_token_price = 0.002+ event.properties!.$ai_cache_read_token_price = '$0.10'+ event.properties!.$ai_request_price = Number.NaN+ event.properties!.$ai_web_search_price = ' '+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_cache_read_input_tokens = 40+ event.properties!.$ai_output_tokens = 50+ event.properties!.$ai_request_count = 3+ event.properties!.$ai_web_search_count = 2++ const result = processAiEvent(event)++ expect(result.properties!.$ai_model_cost_used).toBe('custom')+ // Cache reads fall back to the 0.5 multiplier: 60 * 0.001 + 40 * 0.001 * 0.5.+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.08, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)+ expect(result.properties!.$ai_request_cost_usd).toBe(0)+ expect(result.properties!.$ai_web_search_cost_usd).toBe(0)+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.18, 6)+ })++ // Only the Anthropic path consumes the cache-write rates, and only when the+ // 5m/1h breakdown is present does it consume both of them.+ it('ignores unusable cache write prices on an Anthropic event', () => {+ event.properties!.$ai_model = 'claude-sonnet-4'+ event.properties!.$ai_provider = 'anthropic'+ event.properties!.$ai_input_token_price = 0.001+ event.properties!.$ai_output_token_price = 0.002+ event.properties!.$ai_cache_write_token_price = 'abc'+ event.properties!.$ai_cache_write_1h_token_price = { value: 0.1 }+ event.properties!.$ai_input_tokens = 1000+ event.properties!.$ai_cache_creation_5m_input_tokens = 100+ event.properties!.$ai_cache_creation_1h_input_tokens = 200+ event.properties!.$ai_output_tokens = 50++ const result = processAiEvent(event)++ expect(result.properties!.$ai_model_cost_used).toBe('custom')+ // Both writes fall back to prompt-rate multipliers, 1.25 for 5m and 2 for 1h:+ // 1000 * 0.001 + 100 * 0.00125 + 200 * 0.002.+ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(1.525, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)+ })++ it('treats a null cache read price as unset rather than free', () => {+ event.properties!.$ai_provider = 'openai'+ event.properties!.$ai_input_token_price = 0.001+ event.properties!.$ai_output_token_price = 0.002+ event.properties!.$ai_cache_read_token_price = null+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_cache_read_input_tokens = 40+ event.properties!.$ai_output_tokens = 50++ const result = processAiEvent(event)++ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.08, 6)+ })++ // A request count defaults to 1 when absent, a web search count to nothing, so+ // an unusable value has to land on each default rather than on bigDecimal.+ it.each<{ property: string; costProperty: string; expected: number }>([+ { property: '$ai_request_count', costProperty: '$ai_request_cost_usd', expected: 0.01 },+ { property: '$ai_web_search_count', costProperty: '$ai_web_search_cost_usd', expected: 0 },+ ])('prices the event when $property is not a number', ({ property, costProperty, expected }) => {+ event.properties!.$ai_input_token_price = 0.001+ event.properties!.$ai_output_token_price = 0.002+ event.properties!.$ai_request_price = 0.01+ event.properties!.$ai_web_search_price = 0.02+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_output_tokens = 50+ event.properties![property] = 'lots'++ const result = processAiEvent(event)++ expect(result.properties![costProperty]).toBeCloseTo(expected, 6)+ })++ it('accepts numeric-string custom prices', () => {+ event.properties!.$ai_input_token_price = '0.001'+ event.properties!.$ai_output_token_price = '0.002'+ event.properties!.$ai_input_tokens = 100+ event.properties!.$ai_output_tokens = 50++ const result = processAiEvent(event)++ expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)+ expect(result.properties!.$ai_model_cost_used).toBe('custom')+ })+it('works without provider when using custom pricing', () => {delete event.properties!.$ai_providerevent.properties!.$ai_input_token_price = 0.001