: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): don't record zero cost when a generation has no token counts (#90211)
Bernat Torresf35164bb5073
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 68a54377e841..de63cf19d27d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5943,7 +5943,7 @@ snapshots:scenes-app-ai-observability-trace--full--dark:hash: v1.k794b7964.3ea0677df8e51f08cfd46ad1957c78cb0e0c14dff003b15959f9dc9434a239ca.GUZTGarCld-XKdmLqsfKRE1ZIWdWvfojoa2vHPGVVOAscenes-app-ai-observability-trace--full--light:- hash: v1.k794b7964.ccfd240291b68c038036220ca359b4987c4ac7323a1e000037cc4ca5b82d8ec9.i9mrpnbsbZ1684VkG-73iX07RcINQT0AeFz9Dpcb9dA+ hash: v1.k794b7964.57c11ed1fabef66c724244d8f8c10a48048451bfb8c20725e5a7db7e6f3e97fa.ECgSmPCIFu7JDolQEatnDs2tvmkmel9NzTvekgyGgpAscenes-app-ai-observability-trace--full-specific-event--dark:hash: v1.k794b7964.e3496790d775f03b10ed1bc55489b53bd68a8f1d5bf4c36e92e7c58cba73c3cf.LADKqNV4wMSksDi7YyzIWu2l9bwlxk97FCwHADpTgKcscenes-app-ai-observability-trace--full-specific-event--light:diff --git a/nodejs/src/ingestion/pipelines/ai/costs/index.ts b/nodejs/src/ingestion/pipelines/ai/costs/index.tsindex 364ec6f8f0d6..806114d6f6c3 100644--- a/nodejs/src/ingestion/pipelines/ai/costs/index.ts+++ b/nodejs/src/ingestion/pipelines/ai/costs/index.ts@@ -22,14 +22,15 @@ export interface EventWithProperties extends PluginEvent {properties: Properties}-const PRECALCULATED_COST_PROPERTIES = [+const COST_COMPONENT_PROPERTIES = ['$ai_input_cost_usd','$ai_output_cost_usd','$ai_request_cost_usd','$ai_web_search_cost_usd',- '$ai_total_cost_usd',] as const+const PRECALCULATED_COST_PROPERTIES = [...COST_COMPONENT_PROPERTIES, '$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@@ -72,14 +73,83 @@ const trackCostOutcome = (totalCost: number): void => {}}+// Every token count each cost calculator reads, split by the side it prices.+// Presence is what matters, not value: `0` is a usage report that says the+// model consumed nothing, while an absent property means the provider never+// reported usage at all. The sides gate independently, because an interrupted+// stream often reports one side only — Anthropic sends input tokens on+// message_start and the output count in the final delta.+//+// Hand-maintained, so a calculator that starts reading a new token property has+// to add it to its side's list too. Leave it out and an event carrying only+// that property prices as unknown. Properties that modality extraction writes+// but no calculator reads, such as `$ai_text_input_tokens`, do not belong here.+//+// The validation step (steps/validate-ai-event-tokens.ts) sanitizes only a+// core subset of these. That is safe: every calculator read goes through+// finiteNumberOrUndefined, which treats an unusable value as absent.+const INPUT_TOKEN_COUNT_PROPERTIES = [+ '$ai_input_tokens',+ '$ai_cache_read_input_tokens',+ '$ai_cache_creation_input_tokens',+ '$ai_cache_creation_5m_input_tokens',+ '$ai_cache_creation_1h_input_tokens',+ '$ai_audio_input_tokens',+ '$ai_image_input_tokens',+ '$ai_cache_read_audio_tokens',+] as const++const OUTPUT_TOKEN_COUNT_PROPERTIES = [+ '$ai_output_tokens',+ '$ai_text_output_tokens',+ '$ai_reasoning_tokens',+ '$ai_audio_output_tokens',+ '$ai_image_output_tokens',+] as const++const hasAnyTokenCount = (properties: Properties, keys: readonly string[]): boolean => {+ return keys.some((key) => finiteNumberOrUndefined(properties[key]) !== undefined)+}+const setCostsOnEvent = (event: EventWithProperties, cost: ResolvedModelCost): void => {- const inputCost = calculateInputCost(event, cost)- const outputCost = calculateOutputCost(event, cost)+ // Neither of these reads a token count. A per-request charge bills for the+ // call itself, and a web search charge bills a count the provider reported,+ // so both stay known when the token counts are not.const requestCost = calculateRequestCost(event, cost)const webSearchCost = calculateWebSearchCost(event, cost)+ const hasNonTokenCost = parseFloat(requestCost) > 0 || parseFloat(webSearchCost) > 0++ // Costs the client computed themselves are costs we know. They survive+ // parsePrecalculatedCosts only as numbers, so presence is the test. One-sided+ // costs never reach the passthrough early return, which needs both input and+ // output, so they have to be caught here.+ const hasClientCost = PRECALCULATED_COST_PROPERTIES.some((key) => typeof event.properties[key] === 'number')++ const hasInputTokenCount = hasAnyTokenCount(event.properties, INPUT_TOKEN_COUNT_PROPERTIES)+ const hasOutputTokenCount = hasAnyTokenCount(event.properties, OUTPUT_TOKEN_COUNT_PROPERTIES)++ // A token rate multiplied by no usage is 0, which reads as "this call was+ // free" rather than "we never learned what this call used". The two are+ // different facts, and only one of them is true for an aborted stream: it is+ // billed for the tokens it consumed, we just never received the count. Leave+ // the costs unset so downstream can say it does not know — but only when+ // nothing at all priced this call.+ if (!hasInputTokenCount && !hasOutputTokenCount && !hasNonTokenCost && !hasClientCost) {+ aiCostTotalOutcomeCounter.labels({ outcome: 'unknown' }).inc()+ return+ }- setPropertyIfValidOrMissing(event.properties, '$ai_input_cost_usd', parseFloat(inputCost))- setPropertyIfValidOrMissing(event.properties, '$ai_output_cost_usd', parseFloat(outputCost))+ // Each side's cost is a token rate times that side's counts, so a side+ // without counts is unknown, not zero. One reported side must not fabricate+ // a $0 for the other. The other two components stay known either way.+ if (hasInputTokenCount) {+ const inputCost = calculateInputCost(event, cost)+ setPropertyIfValidOrMissing(event.properties, '$ai_input_cost_usd', parseFloat(inputCost))+ }+ if (hasOutputTokenCount) {+ const outputCost = calculateOutputCost(event, cost)+ setPropertyIfValidOrMissing(event.properties, '$ai_output_cost_usd', parseFloat(outputCost))+ }setPropertyIfValidOrMissing(event.properties, '$ai_request_cost_usd', parseFloat(requestCost))setPropertyIfValidOrMissing(event.properties, '$ai_web_search_cost_usd', parseFloat(webSearchCost))@@ -87,18 +157,16 @@ const setCostsOnEvent = (event: EventWithProperties, cost: ResolvedModelCost): vreturn}- const totalCost = parseFloat(- bigDecimal.add(- bigDecimal.add(- String(event.properties['$ai_input_cost_usd']),- String(event.properties['$ai_output_cost_usd'])- ),- bigDecimal.add(- String(event.properties['$ai_request_cost_usd']),- String(event.properties['$ai_web_search_cost_usd'])- )- )- )+ // A sum over the known components is still a known total; the unset ones+ // stay unset rather than contributing a zero they never asserted.+ let total = '0'+ for (const key of COST_COMPONENT_PROPERTIES) {+ const value = event.properties[key]+ if (typeof value === 'number') {+ total = bigDecimal.add(total, String(value))+ }+ }+ const totalCost = parseFloat(total)event.properties['$ai_total_cost_usd'] = totalCosttrackCostOutcome(totalCost)}diff --git a/nodejs/src/ingestion/pipelines/ai/metrics.ts b/nodejs/src/ingestion/pipelines/ai/metrics.tsindex 3116a2f312e6..492b14e2cb54 100644--- a/nodejs/src/ingestion/pipelines/ai/metrics.ts+++ b/nodejs/src/ingestion/pipelines/ai/metrics.ts@@ -20,7 +20,12 @@ export const aiCostModalityExtractionCounter = new Counter({export const aiCostTotalOutcomeCounter = new Counter({name: 'llma_ai_cost_outcome_total',- help: 'Outcome of total cost calculation (positive, zero, negative)',+ // "unknown" means nothing priced the event — no token counts, no request or+ // web search charge, and no cost the client sent — so no cost was recorded.+ // "zero" is a usage report of nothing, which is a different fact. "error"+ // means the computed total came out NaN, which takes an Infinity-sized cost+ // component surviving the write guards; it should never fire.+ help: 'Outcome of total cost calculation (positive, zero, negative, unknown, error)',labelNames: ['outcome'],})diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.tsindex 69d3e441d6ce..543c3523e60a 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.test.ts@@ -470,22 +470,121 @@ describe('processAiEvent()', () => {expect(result.properties!.$ai_total_cost_usd).toBeGreaterThan(0)})- it('handles missing token counts', () => {+ // Absent and zero token counts describe different calls, so they must not+ // price the same. Zero is a usage report of nothing; absent is no report.+ it.each([+ { counts: 'absent', tokens: {}, expected: undefined },+ { counts: 'zero', tokens: { $ai_input_tokens: 0, $ai_output_tokens: 0 }, expected: 0 },+ ])('records $expected cost when token counts are $counts', ({ tokens, expected }) => {delete event.properties!.$ai_input_tokensdelete event.properties!.$ai_output_tokens+ Object.assign(event.properties!, tokens)+const result = processAiEvent(event)- expect(result.properties!.$ai_total_cost_usd).toBe(0)- expect(result.properties!.$ai_input_cost_usd).toBe(0)- expect(result.properties!.$ai_output_cost_usd).toBe(0)++ expect(result.properties!.$ai_total_cost_usd).toBe(expected)+ expect(result.properties!.$ai_input_cost_usd).toBe(expected)+ expect(result.properties!.$ai_output_cost_usd).toBe(expected)+ })++ // The properties are named here rather than read from the token count+ // lists, so narrowing either list to the plain input/output counts fails+ // these. Iterating the lists themselves would only drop the case. Neither+ // catches the opposite drift: a calculator that starts reading a token+ // property nobody added to its list.+ it.each(['$ai_cache_read_input_tokens', '$ai_audio_input_tokens', '$ai_reasoning_tokens'])(+ 'treats %s on its own as a usage report',+ (property) => {+ delete event.properties!.$ai_input_tokens+ delete event.properties!.$ai_output_tokens+ event.properties![property] = 100++ const result = processAiEvent(event)++ expect(result.properties!.$ai_total_cost_usd).toBeDefined()+ }+ )++ // Each side is a rate times its own counts, so one reported side must+ // not fabricate a $0 for the other. Interrupted streams commonly report+ // input only: Anthropic sends input tokens on message_start and the+ // output count in the final delta.+ it.each([+ {+ reported: 'input',+ tokens: { $ai_input_tokens: 100 },+ pricedProperty: '$ai_input_cost_usd',+ absentProperty: '$ai_output_cost_usd',+ },+ {+ reported: 'output',+ tokens: { $ai_output_tokens: 50 },+ pricedProperty: '$ai_output_cost_usd',+ absentProperty: '$ai_input_cost_usd',+ },+ ])(+ 'prices only the $reported side when only it reported usage',+ ({ tokens, pricedProperty, absentProperty }) => {+ delete event.properties!.$ai_input_tokens+ delete event.properties!.$ai_output_tokens+ Object.assign(event.properties!, tokens)++ const result = processAiEvent(event)++ expect(result.properties![pricedProperty]).toBeGreaterThan(0)+ expect(result.properties![absentProperty]).toBeUndefined()+ expect(result.properties!.$ai_total_cost_usd).toBe(result.properties![pricedProperty])+ }+ )++ // Request and web search charges are computed without reading a token+ // count, so absent token counts must not discard a cost we do know.+ it.each([+ {+ charge: 'per-request',+ model: 'model-with-request-only',+ provider: 'custom',+ extra: {},+ costProperty: '$ai_request_cost_usd',+ },+ {+ charge: 'web search',+ model: 'perplexity/sonar-pro',+ provider: 'perplexity',+ extra: { $ai_web_search_count: 3 },+ costProperty: '$ai_web_search_cost_usd',+ },+ ])('prices a $charge charge when token counts are absent', ({ model, provider, extra, costProperty }) => {+ delete event.properties!.$ai_input_tokens+ delete event.properties!.$ai_output_tokens+ Object.assign(event.properties!, { $ai_model: model, $ai_provider: provider }, extra)++ const result = processAiEvent(event)++ expect(result.properties![costProperty]).toBeGreaterThan(0)+ expect(result.properties!.$ai_total_cost_usd).toBeGreaterThan(0)+ // Input and output are token costs, so without token counts they are+ // unknown. Writing them as 0 would show "Input $0.00" in the cost+ // breakdown for the same class of event this distinction exists for.+ expect(result.properties!.$ai_input_cost_usd).toBeUndefined()+ expect(result.properties!.$ai_output_cost_usd).toBeUndefined()})- it('handles zero token counts', () => {- event.properties!.$ai_input_tokens = 0- event.properties!.$ai_output_tokens = 0+ // A cost the client computed themselves is a cost we know, so absent+ // token counts must not discard it. One-sided costs never reach the+ // passthrough early return, which needs both input and output present.+ it.each([+ { component: 'input', property: '$ai_input_cost_usd', value: 0.5 },+ { component: 'per-request', property: '$ai_request_cost_usd', value: 0.25 },+ ])('keeps a client-supplied $component cost when token counts are absent', ({ property, value }) => {+ delete event.properties!.$ai_input_tokens+ delete event.properties!.$ai_output_tokens+ event.properties![property] = value+const result = processAiEvent(event)- expect(result.properties!.$ai_total_cost_usd).toBe(0)- expect(result.properties!.$ai_input_cost_usd).toBe(0)- expect(result.properties!.$ai_output_cost_usd).toBe(0)++ expect(result.properties![property]).toBe(value)+ expect(result.properties!.$ai_total_cost_usd).toBe(value)})})diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsxindex 8ef6a7a1756a..9ed092123efb 100644--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx@@ -1216,7 +1216,7 @@ function TraceSidebar({topLevelTrace={trace}node={{event: trace,- displayTotalCost: trace.totalCost || 0,+ displayTotalCost: trace.totalCost ?? null,displayLatency: trace.totalLatency || 0,displayUsage: formatLLMUsage(trace),}}@@ -1275,7 +1275,7 @@ const TreeNode = React.memo(function TraceNode({topLevelTrace: LLMTracenode:| EnrichedTraceTreeNode- | { event: LLMTrace; displayTotalCost: number; displayLatency: number; displayUsage: string | null }+ | { event: LLMTrace; displayTotalCost: number | null; displayLatency: number; displayUsage: string | null }isSelected: booleansearchQuery?: stringshowBillingInfo?: boolean@@ -1634,7 +1634,7 @@ const EventContent = React.memo(<div className="flex flex-col gap-1">{aggregation && (<div className="flex flex-row flex-wrap items-center gap-2">- {aggregation.totalCost > 0 && (+ {aggregation.totalCost !== null && aggregation.totalCost > 0 && (<LemonTag type="muted" size="small">Total Cost: {formatLLMCost(aggregation.totalCost)}</LemonTag>diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.tsindex e89670b899d6..2956570ac40f 100644--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts@@ -5,6 +5,7 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import {TraceTreeNode,buildFeedbackAttachmentMap,+ extractTotalCost,getEffectiveEventId,getHighlightedEventId,getInitialFocusEventId,@@ -47,6 +48,56 @@ describe('aiObservabilityTraceDataLogic: restoreTree', () => {])})+ // A span sums what its children reported. A sum over nothing known is not+ // zero, so a span whose generations all went unpriced has no cost to show.+ it('leaves a span cost unknown when no child reported one', () => {+ const events: LLMTraceEvent[] = [+ {+ id: 'span',+ event: '$ai_span',+ properties: { $ai_parent_id: 'trace' },+ createdAt: '2024-01-01T00:00:00Z',+ },+ {+ id: 'generation',+ event: '$ai_generation',+ properties: { $ai_parent_id: 'span' },+ createdAt: '2024-01-01T00:00:00Z',+ },+ ]++ const tree = restoreTree(events, 'trace')++ expect(tree[0].aggregation?.totalCost).toBeNull()+ })++ it('sums only the children that reported a cost', () => {+ const events: LLMTraceEvent[] = [+ {+ id: 'span',+ event: '$ai_span',+ properties: { $ai_parent_id: 'trace' },+ createdAt: '2024-01-01T00:00:00Z',+ },+ {+ id: 'priced',+ event: '$ai_generation',+ properties: { $ai_parent_id: 'span', $ai_total_cost_usd: 0.25 },+ createdAt: '2024-01-01T00:00:00Z',+ },+ {+ id: 'unpriced',+ event: '$ai_generation',+ properties: { $ai_parent_id: 'span' },+ createdAt: '2024-01-01T00:00:00Z',+ },+ ]++ const tree = restoreTree(events, 'trace')++ expect(tree[0].aggregation?.totalCost).toBe(0.25)+ })+it('should build a nested tree', () => {const events: LLMTraceEvent[] = [{@@ -80,7 +131,7 @@ describe('aiObservabilityTraceDataLogic: restoreTree', () => {{event: events[0],aggregation: expect.objectContaining({- totalCost: 0,+ totalCost: null,totalLatency: 0,inputTokens: 0,outputTokens: 0,@@ -89,7 +140,7 @@ describe('aiObservabilityTraceDataLogic: restoreTree', () => {{event: events[1],aggregation: expect.objectContaining({- totalCost: 0,+ totalCost: null,totalLatency: 0,inputTokens: 0,outputTokens: 0,@@ -202,7 +253,7 @@ describe('aiObservabilityTraceDataLogic: restoreTree', () => {{event: events[0],aggregation: expect.objectContaining({- totalCost: 0,+ totalCost: null,}),children: [{@@ -366,6 +417,26 @@ describe('getHighlightedEventId', () => {})})+describe('extractTotalCost', () => {+ // Absent and zero are different facts: zero is a priced call that cost+ // nothing, absent is a call whose usage was never reported. Coercing absent+ // to 0 renders $0.00 in the trace tree, which reads as a free call.+ it.each([+ { call: 'a priced call', properties: { $ai_total_cost_usd: 0.0042 }, expected: 0.0042 },+ { call: 'a call that cost nothing', properties: { $ai_total_cost_usd: 0 }, expected: 0 },+ { call: 'a call with no reported cost', properties: {}, expected: null },+ ])('returns $expected for $call', ({ properties, expected }) => {+ const event: LLMTraceEvent = {+ id: '1',+ event: '$ai_generation',+ properties,+ createdAt: '2024-01-01T00:00:00Z',+ }++ expect(extractTotalCost(event)).toBe(expected)+ })+})+describe('getSingleTraceLoadTiming', () => {it('computes trace age from earliest event timestamp in UTC with query runner duration', () => {const trace: LLMTrace = {diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.tsindex 89cb5218a668..9cdd05f66f4a 100644--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts@@ -834,22 +834,27 @@ export interface TraceTreeNode {export interface EnrichedTraceTreeNode extends TraceTreeNode {children?: EnrichedTraceTreeNode[]- displayTotalCost: number+ displayTotalCost: number | nulldisplayLatency: numberdisplayUsage: string | nullattachedFeedback: LLMTraceEvent[]}export interface SpanAggregation {- totalCost: number+ // Null when no descendant reported a cost. A sum over nothing known is not+ // zero, the same distinction extractTotalCost draws for a single event.+ totalCost: number | nulltotalLatency: numberinputTokens: numberoutputTokens: numberhasGenerationChildren: boolean}-function extractTotalCost(event: LLMTraceEvent): number {- return event.properties.$ai_total_cost_usd || 0+// Null, not 0, when the event carries no cost. A generation whose provider never+// reported usage has no cost to show, and $0.00 would read as a free call.+export function extractTotalCost(event: LLMTraceEvent): number | null {+ const totalCost = event.properties.$ai_total_cost_usd+ return typeof totalCost === 'number' ? totalCost : null}function extractLatency(event: LLMTraceEvent): number {@@ -871,14 +876,17 @@ function aggregateSpanMetrics(node: TraceTreeNode): SpanAggregation {const event = node.eventlet hasGenerationChildren = false- // Use direct values if available, otherwise start with 0 for aggregation- let totalCost = event.properties.$ai_total_cost_usd ?? 0+ // Cost starts from the event's own known cost, or null when it has none, so+ // a span whose children all went unpriced stays unknown instead of summing+ // to zero. The first known cost promotes it. extractTotalCost is the single+ // arbiter of "known" here, as it is for the tree rows.+ let totalCost: number | null = extractTotalCost(event)let totalLatency = event.properties.$ai_latency ?? 0let inputTokens = event.properties.$ai_input_tokens ?? 0let outputTokens = event.properties.$ai_output_tokens ?? 0// Only aggregate from children if parent doesn't have direct values- const shouldAggregateCost = event.properties.$ai_total_cost_usd === undefined+ const shouldAggregateCost = totalCost === nullconst shouldAggregateLatency = event.properties.$ai_latency === undefinedconst shouldAggregateInputTokens = event.properties.$ai_input_tokens === undefinedconst shouldAggregateOutputTokens = event.properties.$ai_output_tokens === undefined@@ -892,8 +900,8 @@ function aggregateSpanMetrics(node: TraceTreeNode): SpanAggregation {// Use aggregated metrics if child has children, otherwise use direct metricsif (child.children && child.children.length > 0) {const childAgg = aggregateSpanMetrics(child)- if (shouldAggregateCost) {- totalCost += childAgg.totalCost+ if (shouldAggregateCost && childAgg.totalCost !== null) {+ totalCost = (totalCost ?? 0) + childAgg.totalCost}if (shouldAggregateLatency) {totalLatency += childAgg.totalLatency@@ -909,8 +917,9 @@ function aggregateSpanMetrics(node: TraceTreeNode): SpanAggregation {}} else {// Child has no children, use its direct metrics- if (shouldAggregateCost) {- totalCost += child.event.properties.$ai_total_cost_usd || 0+ const childCost = extractTotalCost(child.event)+ if (shouldAggregateCost && childCost !== null) {+ totalCost = (totalCost ?? 0) + childCost}if (shouldAggregateLatency) {totalLatency += child.event.properties.$ai_latency || 0