Skip to content

: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.

fix(aio): correct cost and session mapping for otel genai spans (#113956)

Carlos Marchal46da12fa13e6
diff --git a/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx b/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx
index 7a29b4516c64..8b6bf148b31d 100644
--- a/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx
+++ b/docs/onboarding/ai-observability/_snippets/otel-session-id.tsx
@@ -125,6 +125,10 @@ export const getOtelSessionIdStep = (ctx: OnboardingComponentsContext, config: O
to. Add a span processor that sets the \`$ai_session_id\` attribute as each span starts.
PostHog forwards span attributes it does not recognize onto the event, so the value arrives
as the \`$ai_session_id\` property.
+
+ If your instrumentation already sets the \`gen_ai.conversation.id\` attribute, PostHog uses
+ it as the session ID and you can skip this step. An explicit \`$ai_session_id\` takes
+ priority.
`}
</Markdown>
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts
index 0ef26bf789e4..62ee6fcd5106 100644
--- a/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/otel/attribute-mapping.test.ts
@@ -734,6 +734,32 @@ describe('mapOtelAttributes', () => {
})
})
+ describe('gen_ai.conversation.id as the session id fallback', () => {
+ it.each([
+ ['uses the conversation id', { 'gen_ai.conversation.id': 'conversation-1' }, 'conversation-1'],
+ [
+ 'keeps an explicit session id',
+ { 'gen_ai.conversation.id': 'conversation-1', $ai_session_id: 'explicit' },
+ 'explicit',
+ ],
+ [
+ 'keeps a session id a middleware resolves from its own attributes',
+ {
+ 'ai.operationId': 'ai.generateText.doGenerate',
+ 'ai.telemetry.metadata.$ai_session_id': 'from-metadata',
+ 'gen_ai.conversation.id': 'conversation-1',
+ },
+ 'from-metadata',
+ ],
+ ['ignores an empty conversation id', { 'gen_ai.conversation.id': '' }, undefined],
+ ])('%s', (_label, properties, expected) => {
+ const event = createEvent('$ai_generation', properties)
+ convertOtelEvent(event)
+ expect(event.properties!.$ai_session_id).toBe(expected)
+ expect(event.properties!['gen_ai.conversation.id']).toBe(properties['gen_ai.conversation.id'])
+ })
+ })
+
describe('$groups normalization', () => {
it('parses a JSON-string $groups into an object', () => {
const event = createEvent('$ai_generation', {
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts
index 7ea557003ed8..b42ee5bf51b4 100644
--- a/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/otel/index.test.ts
@@ -97,7 +97,7 @@ describe('convertOtelEvent', () => {
})
// vercel-ai matches the whole ai.* namespace, so it only stays off
- // traceloop spans because it is last in the registry.
+ // traceloop spans because it comes after traceloop in the registry.
it('traceloop markers take priority over an ai.* attribute', () => {
const event = createEvent('$ai_span', {
'traceloop.span.kind': 'workflow',
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/index.ts b/nodejs/src/ingestion/pipelines/ai/otel/index.ts
index e6d4d5211fc5..781577d6620b 100644
--- a/nodejs/src/ingestion/pipelines/ai/otel/index.ts
+++ b/nodejs/src/ingestion/pipelines/ai/otel/index.ts
@@ -2,13 +2,25 @@ import { aiOtelEventTypeCounter, aiOtelMiddlewareCounter } from '~/ingestion/pip
import { PluginEvent } from '~/plugin-scaffold'
import { mapOtelAttributes } from './attribute-mapping'
+import { anthropic } from './middleware/anthropic'
import { pydanticAi } from './middleware/pydantic-ai'
import { traceloop } from './middleware/traceloop'
import { OtelLibraryMiddleware } from './middleware/types'
import { vercelAi } from './middleware/vercel-ai'
// Middleware registry — checked in order, first match wins.
-const MIDDLEWARES: OtelLibraryMiddleware[] = [pydanticAi, traceloop, vercelAi]
+const MIDDLEWARES: OtelLibraryMiddleware[] = [pydanticAi, traceloop, vercelAi, anthropic]
+
+// Runs after the middlewares, because each of them can resolve a session id the producer set on
+// purpose. The conversation id stays on the event: where a producer has a wider session grouping,
+// it still separates the threads.
+function setSessionIdFromConversationId(event: PluginEvent): void {
+ const props = event.properties
+ const conversationId = props?.['gen_ai.conversation.id']
+ if (props && props['$ai_session_id'] === undefined && typeof conversationId === 'string' && conversationId !== '') {
+ props['$ai_session_id'] = conversationId
+ }
+}
export function convertOtelEvent(event: PluginEvent): void {
const middleware = MIDDLEWARES.find((mw) => mw.matches(event))
@@ -20,6 +32,8 @@ export function convertOtelEvent(event: PluginEvent): void {
mapOtelAttributes(event)
}
+ setSessionIdFromConversationId(event)
+
aiOtelMiddlewareCounter.labels({ library }).inc()
aiOtelEventTypeCounter.labels({ event_type: event.event, library }).inc()
}
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/anthropic.test.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/anthropic.test.ts
new file mode 100644
index 000000000000..b97957e40770
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/anthropic.test.ts
@@ -0,0 +1,294 @@
+import { convertOtelEvent } from '~/ingestion/pipelines/ai/otel/index'
+import { createEvent } from '~/ingestion/pipelines/ai/otel/test-helpers'
+
+import { anthropic } from './anthropic'
+
+const convert = (eventName: string, properties: Record<string, unknown>): Record<string, unknown> => {
+ const event = createEvent(eventName, properties)
+ convertOtelEvent(event)
+ return event.properties!
+}
+
+describe('anthropic middleware', () => {
+ it.each([
+ ['a request span', { 'anthropic.request.id': 'req_example' }],
+ ['a session span', { 'anthropic.session.id': 'sesn_example' }],
+ ['a tool span', { 'anthropic.tool_result.content': '[]' }],
+ ])('matches %s', (_label, properties) => {
+ expect(anthropic.matches(createEvent('$ai_span', properties))).toBe(true)
+ })
+
+ it.each([
+ ['no vendor attribute', { 'gen_ai.provider.name': 'anthropic', 'gen_ai.request.model': 'claude-example' }],
+ ['no properties at all', {}],
+ ])('does not match a span with %s', (_label, properties) => {
+ expect(anthropic.matches(createEvent('$ai_generation', properties))).toBe(false)
+ })
+
+ it('leaves a traceloop span to the traceloop middleware', () => {
+ const props = convert('$ai_span', { 'llm.request.type': 'chat', 'anthropic.request.id': 'req_example' })
+ expect(props['$ai_lib']).toBe('opentelemetry/traceloop')
+ })
+
+ it('marks input tokens as cache-inclusive and maps the cache write breakdown', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.input_tokens': 1000,
+ 'gen_ai.usage.cache_read.input_tokens': 600,
+ 'gen_ai.usage.cache_write.input_tokens': 300,
+ 'anthropic.usage.cache_creation.ephemeral_5m_input_tokens': 200,
+ 'anthropic.usage.cache_creation.ephemeral_1h_input_tokens': 100,
+ })
+ expect(props).toMatchObject({
+ $ai_lib: 'opentelemetry/anthropic',
+ $ai_input_tokens: 1000,
+ $ai_cache_read_input_tokens: 600,
+ $ai_cache_creation_input_tokens: 300,
+ $ai_cache_creation_5m_input_tokens: 200,
+ $ai_cache_creation_1h_input_tokens: 100,
+ $ai_cache_reporting_exclusive: false,
+ })
+ expect(props['anthropic.usage.cache_creation.ephemeral_5m_input_tokens']).toBeUndefined()
+ expect(props['anthropic.usage.cache_creation.ephemeral_1h_input_tokens']).toBeUndefined()
+ })
+
+ it.each([
+ ['a numeric total', 300],
+ ['a total sent as a numeric string', '300'],
+ ])('does not use a cache write breakdown that does not add up to %s', (_label, total) => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.input_tokens': 1000,
+ 'gen_ai.usage.cache_write.input_tokens': total,
+ 'anthropic.usage.cache_creation.ephemeral_5m_input_tokens': 200,
+ 'anthropic.usage.cache_creation.ephemeral_1h_input_tokens': 0,
+ })
+ expect(props['$ai_cache_creation_input_tokens']).toBe(total)
+ expect(props['$ai_cache_creation_5m_input_tokens']).toBeUndefined()
+ expect(props['$ai_cache_creation_1h_input_tokens']).toBeUndefined()
+ expect(props['anthropic.usage.cache_creation.ephemeral_5m_input_tokens']).toBe(200)
+ })
+
+ it('keeps an explicit cache write breakdown', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.input_tokens': 1000,
+ $ai_cache_creation_5m_input_tokens: 50,
+ $ai_cache_creation_1h_input_tokens: 0,
+ 'anthropic.usage.cache_creation.ephemeral_5m_input_tokens': 200,
+ 'anthropic.usage.cache_creation.ephemeral_1h_input_tokens': 0,
+ })
+ expect(props).toMatchObject({ $ai_cache_creation_5m_input_tokens: 50, $ai_cache_creation_1h_input_tokens: 0 })
+ expect(props['$ai_cache_creation_input_tokens']).toBeUndefined()
+ })
+
+ it('counts a missing TTL as zero when a span reports one cache write TTL without a total', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.input_tokens': 1000,
+ 'anthropic.usage.cache_creation.ephemeral_1h_input_tokens': 250,
+ })
+ expect(props).toMatchObject({
+ $ai_cache_creation_input_tokens: 250,
+ $ai_cache_creation_5m_input_tokens: 0,
+ $ai_cache_creation_1h_input_tokens: 250,
+ })
+ })
+
+ it.each([
+ ['gen_ai.usage.reasoning.output_tokens', '$ai_reasoning_tokens', 120],
+ ['gen_ai.request.max_tokens', '$ai_max_tokens', 4096],
+ ['gen_ai.request.stream', '$ai_stream', true],
+ ])('renames %s to %s for these spans only', (otelKey, phKey, value) => {
+ const matched = convert('$ai_generation', { 'anthropic.request.id': 'req_example', [otelKey]: value })
+ expect(matched[phKey]).toBe(value)
+ expect(matched[otelKey]).toBeUndefined()
+
+ const otherProducer = convert('$ai_generation', { 'gen_ai.provider.name': 'example', [otelKey]: value })
+ expect(otherProducer[phKey]).toBeUndefined()
+ expect(otherProducer[otelKey]).toBe(value)
+ })
+
+ it('keeps the cache write total from the older attribute name when a span reports both names', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.cache_creation.input_tokens': 300,
+ 'gen_ai.usage.cache_write.input_tokens': 999,
+ })
+ expect(props['$ai_cache_creation_input_tokens']).toBe(300)
+ expect(props['gen_ai.usage.cache_write.input_tokens']).toBeUndefined()
+ })
+
+ it('adds compaction tokens to the generation, which reports them outside its own usage', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.input_tokens': 600,
+ 'gen_ai.usage.output_tokens': 200,
+ 'anthropic.usage.compaction.input_tokens': 5000,
+ 'anthropic.usage.compaction.output_tokens': 700,
+ })
+ expect(props).toMatchObject({
+ $ai_input_tokens: 5600,
+ $ai_output_tokens: 900,
+ 'anthropic.usage.compaction.input_tokens': 5000,
+ 'anthropic.usage.compaction.output_tokens': 700,
+ })
+ })
+
+ it('does not set the cache reporting mode on a span without token usage', () => {
+ const props = convert('$ai_span', { 'anthropic.request.id': 'req_example' })
+ expect(props['$ai_cache_reporting_exclusive']).toBeUndefined()
+ })
+
+ it('keeps an explicit cache reporting mode', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.usage.input_tokens': 10,
+ $ai_cache_reporting_exclusive: true,
+ })
+ expect(props['$ai_cache_reporting_exclusive']).toBe(true)
+ })
+
+ it.each([['anthropic.message.stop_reason'], ['anthropic.session.turn.stop_reason']])(
+ 'maps %s to $ai_stop_reason',
+ (key) => {
+ const props = convert('$ai_generation', { [key]: 'end_turn' })
+ expect(props['$ai_stop_reason']).toBe('end_turn')
+ expect(props[key]).toBeUndefined()
+ }
+ )
+
+ it.each([
+ [
+ 'the session id over the conversation id',
+ { 'anthropic.session.id': 'sesn_example', 'gen_ai.conversation.id': 'thread_example' },
+ 'sesn_example',
+ ],
+ [
+ 'the conversation id when there is no session id',
+ { 'gen_ai.conversation.id': 'thread_example' },
+ 'thread_example',
+ ],
+ [
+ 'an explicit $ai_session_id over both',
+ {
+ $ai_session_id: 'explicit',
+ 'anthropic.session.id': 'sesn_example',
+ 'gen_ai.conversation.id': 'thread_example',
+ },
+ 'explicit',
+ ],
+ ])('uses %s as $ai_session_id', (_label, properties, expected) => {
+ const props = convert('$ai_span', { 'anthropic.request.id': 'req_example', ...properties })
+ expect(props['$ai_session_id']).toBe(expected)
+ })
+
+ it('turns a tool execution span into a named span with input and output state', () => {
+ const props = convert('$ai_span', {
+ $ai_parent_id: 'parent-span',
+ $otel_span_name: 'anthropic.tool_use lookup_part',
+ 'gen_ai.operation.name': 'execute_tool',
+ 'gen_ai.tool.name': 'lookup_part',
+ 'gen_ai.tool.call.id': 'call_example',
+ 'gen_ai.tool.call.arguments': '{"part_number":"P-100"}',
+ 'anthropic.tool_result.content': '[{"type":"text","text":"7 in stock"}]',
+ })
+ expect(props).toMatchObject({
+ $ai_span_name: 'lookup_part',
+ $ai_input_state: { part_number: 'P-100' },
+ $ai_output_state: [{ type: 'text', text: '7 in stock' }],
+ 'gen_ai.tool.call.id': 'call_example',
+ })
+ expect(props['gen_ai.tool.call.arguments']).toBeUndefined()
+ expect(props['anthropic.tool_result.content']).toBeUndefined()
+ })
+
+ it('keeps input and output state the integration already set on a tool span', () => {
+ const props = convert('$ai_span', {
+ $ai_parent_id: 'parent-span',
+ 'gen_ai.operation.name': 'execute_tool',
+ 'gen_ai.tool.name': 'lookup_part',
+ 'gen_ai.tool.call.arguments': '{"part_number":"P-100"}',
+ 'anthropic.tool_result.content': '[{"type":"text","text":"7 in stock"}]',
+ $ai_input_state: 'explicit input',
+ $ai_output_state: 'explicit output',
+ })
+ expect(props).toMatchObject({ $ai_input_state: 'explicit input', $ai_output_state: 'explicit output' })
+ })
+
+ it('keeps a tool result that is not JSON as a string', () => {
+ const props = convert('$ai_span', {
+ $ai_parent_id: 'parent-span',
+ 'gen_ai.operation.name': 'execute_tool',
+ 'gen_ai.tool.name': 'lookup_part',
+ 'anthropic.tool_result.content': 'plain text result',
+ })
+ expect(props['$ai_output_state']).toBe('plain text result')
+ })
+
+ const searchResults = [{ type: 'web_search_result', title: 'Example', url: 'https://example.com' }]
+ const refusedSearch = { type: 'web_search_tool_result_error', error_code: 'max_uses_exceeded' }
+
+ it.each([
+ [
+ 'counts server-side web searches that returned results and ignores other tool calls',
+ [
+ { type: 'tool_call', id: 'srvtoolu_example1', name: 'web_search', arguments: { query: 'a' } },
+ { type: 'tool_call_response', id: 'srvtoolu_example1', response: searchResults },
+ { type: 'server_tool_call', id: 'srvtoolu_example2', name: 'web_search', arguments: { query: 'b' } },
+ { type: 'server_tool_call_response', id: 'srvtoolu_example2', response: searchResults },
+ { type: 'tool_call', id: 'srvtoolu_example3', name: 'code_execution', arguments: {} },
+ { type: 'tool_call_response', id: 'srvtoolu_example3', response: [{ type: 'text', text: 'ok' }] },
+ { type: 'text', content: 'done' },
+ ],
+ 2,
+ ],
+ [
+ 'does not count searches the provider refused',
+ [
+ { type: 'tool_call', id: 'srvtoolu_example1', name: 'web_search', arguments: { query: 'a' } },
+ { type: 'tool_call', id: 'srvtoolu_example2', name: 'web_search', arguments: { query: 'b' } },
+ { type: 'tool_call_response', id: 'srvtoolu_example1', response: searchResults },
+ { type: 'tool_call_response', id: 'srvtoolu_example2', response: refusedSearch },
+ ],
+ 1,
+ ],
+ [
+ 'does not count a search that has no result in the same response',
+ [{ type: 'tool_call', id: 'srvtoolu_example1', name: 'web_search', arguments: { query: 'a' } }],
+ undefined,
+ ],
+ [
+ 'ignores a client tool that is also named web_search',
+ [
+ { type: 'tool_call', id: 'toolu_example', name: 'web_search', arguments: { query: 'a' } },
+ { type: 'tool_call_response', id: 'toolu_example', response: searchResults },
+ ],
+ undefined,
+ ],
+ ['sets no count when there were no searches', [{ type: 'text', content: 'done' }], undefined],
+ ])('%s', (_label, parts, expected) => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ 'gen_ai.output.messages': JSON.stringify([{ role: 'assistant', parts }]),
+ })
+ expect(props['$ai_web_search_count']).toBe(expected)
+ })
+
+ it('keeps an explicit web search count', () => {
+ const props = convert('$ai_generation', {
+ 'anthropic.request.id': 'req_example',
+ $ai_web_search_count: 5,
+ 'gen_ai.output.messages': JSON.stringify([
+ {
+ role: 'assistant',
+ parts: [
+ { type: 'tool_call', id: 'srvtoolu_example', name: 'web_search' },
+ { type: 'tool_call_response', id: 'srvtoolu_example', response: searchResults },
+ ],
+ },
+ ]),
+ })
+ expect(props['$ai_web_search_count']).toBe(5)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/ai/otel/middleware/anthropic.ts b/nodejs/src/ingestion/pipelines/ai/otel/middleware/anthropic.ts
new file mode 100644
index 000000000000..b801ddeace69
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/ai/otel/middleware/anthropic.ts
@@ -0,0 +1,222 @@
+import { parseJSON } from '~/common/utils/json-parse'
+import { finiteNumberOrUndefined } from '~/ingestion/pipelines/ai/costs/cost-utils'
+import { PluginEvent } from '~/plugin-scaffold'
+
+import { usableStopReason } from './stop-reason'
+import { OtelLibraryMiddleware } from './types'
+
+const ATTRIBUTE_PREFIX = 'anthropic.'
+
+const SESSION_ID_KEY = 'anthropic.session.id'
+const STOP_REASON_KEYS = ['anthropic.message.stop_reason', 'anthropic.session.turn.stop_reason']
+const TOOL_RESULT_KEY = 'anthropic.tool_result.content'
+
+// Kept out of the generic mapping on purpose. Other producers of these attributes can count
+// tokens differently, and the cost calculation would then bill them twice.
+const RENAMED_ATTRIBUTES: Record<string, string> = {
+ 'gen_ai.usage.cache_write.input_tokens': '$ai_cache_creation_input_tokens',
+ 'gen_ai.usage.reasoning.output_tokens': '$ai_reasoning_tokens',
+ 'gen_ai.request.max_tokens': '$ai_max_tokens',
+ 'gen_ai.request.stream': '$ai_stream',
+}
+
+// Compaction runs before the model, and the span's own usage attributes leave its tokens out.
+const COMPACTION_TOKENS: Record<string, string> = {
+ 'anthropic.usage.compaction.input_tokens': '$ai_input_tokens',
+ 'anthropic.usage.compaction.output_tokens': '$ai_output_tokens',
+}
+
+const CACHE_WRITE_5M_KEY = 'anthropic.usage.cache_creation.ephemeral_5m_input_tokens'
+const CACHE_WRITE_1H_KEY = 'anthropic.usage.cache_creation.ephemeral_1h_input_tokens'
+
+const WEB_SEARCH_TOOL_NAME = 'web_search'
+// A client tool can also be named web_search. Only calls the provider ran itself carry this id
+// prefix, and only those have a per-search fee.
+const SERVER_TOOL_CALL_ID_PREFIX = 'srvtoolu_'
+const TOOL_CALL_PART_TYPES = new Set(['tool_call', 'server_tool_call'])
+const TOOL_RESPONSE_PART_TYPES = new Set(['tool_call_response', 'server_tool_call_response'])
+
+function renameAttributes(props: Record<string, unknown>): void {
+ for (const [otelKey, phKey] of Object.entries(RENAMED_ATTRIBUTES)) {
+ if (props[otelKey] !== undefined && props[phKey] === undefined) {
+ props[phKey] = props[otelKey]
+ }
+ delete props[otelKey]
+ }
+}
+
+// The cost calculation bills the breakdown instead of the total when both are present. A request
+// that ran several model iterations can report a breakdown that covers only some of them, so the
+// breakdown is used only when it adds up to the total. A missing TTL counts as zero.
+function mapCacheWriteBreakdown(props: Record<string, unknown>): void {
+ if (
+ props['$ai_cache_creation_5m_input_tokens'] !== undefined ||
+ props['$ai_cache_creation_1h_input_tokens'] !== undefined
+ ) {
+ return
+ }
+ const write5m = finiteNumberOrUndefined(props[CACHE_WRITE_5M_KEY])
+ const write1h = finiteNumberOrUndefined(props[CACHE_WRITE_1H_KEY])
+ if (write5m === undefined && write1h === undefined) {
+ return
+ }
+
+ const breakdownTotal = (write5m ?? 0) + (write1h ?? 0)
+ const total = finiteNumberOrUndefined(props['$ai_cache_creation_input_tokens'])
+ if (total !== undefined && total !== breakdownTotal) {
+ return
+ }
+ props['$ai_cache_creation_input_tokens'] = breakdownTotal
+ props['$ai_cache_creation_5m_input_tokens'] = write5m ?? 0
+ props['$ai_cache_creation_1h_input_tokens'] = write1h ?? 0
+ delete props[CACHE_WRITE_5M_KEY]
+ delete props[CACHE_WRITE_1H_KEY]
+}
+
+function addCompactionTokens(props: Record<string, unknown>): void {
+ for (const [compactionKey, phKey] of Object.entries(COMPACTION_TOKENS)) {
+ const compactionTokens = finiteNumberOrUndefined(props[compactionKey])
+ const reportedTokens = finiteNumberOrUndefined(props[phKey])
+ if (compactionTokens !== undefined && compactionTokens > 0 && reportedTokens !== undefined) {
+ props[phKey] = reportedTokens + compactionTokens
+ }
+ }
+}
+
+function parseIfJson(value: unknown): unknown {
+ if (typeof value !== 'string') {
+ return value
+ }
+ try {
+ return parseJSON(value)
+ } catch {
+ return value
+ }
+}
+
+function serverWebSearchCallId(part: object): string | undefined {
+ if (!('type' in part) || !('name' in part) || !('id' in part)) {
+ return undefined
+ }
+ if (typeof part.type !== 'string' || typeof part.id !== 'string') {
+ return undefined
+ }
+ const isServerWebSearch =
+ TOOL_CALL_PART_TYPES.has(part.type) &&
+ part.name === WEB_SEARCH_TOOL_NAME &&
+ part.id.startsWith(SERVER_TOOL_CALL_ID_PREFIX)
+ return isServerWebSearch ? part.id : undefined
+}
+
+// A search that returned results reports them as a list. A refused search, for example one past
+// the request's search limit, reports an error object and has no fee.
+function successfulToolResponseId(part: object): string | undefined {
+ if (!('type' in part) || !('id' in part) || !('response' in part)) {
+ return undefined
+ }
+ if (typeof part.type !== 'string' || typeof part.id !== 'string') {
+ return undefined
+ }
+ return TOOL_RESPONSE_PART_TYPES.has(part.type) && Array.isArray(part.response) ? part.id : undefined
+}
+
+function countServerWebSearches(outputChoices: unknown): number {
+ if (!Array.isArray(outputChoices)) {
+ return 0
+ }
+ const searchIds = new Set<string>()
+ const succeededIds = new Set<string>()
+ for (const message of outputChoices) {
+ if (typeof message !== 'object' || message === null || !('parts' in message) || !Array.isArray(message.parts)) {
+ continue
+ }
+ for (const part of message.parts) {
+ if (typeof part !== 'object' || part === null) {
+ continue
+ }
+ const searchId = serverWebSearchCallId(part)
+ if (searchId !== undefined) {
+ searchIds.add(searchId)
+ }
+ const succeededId = successfulToolResponseId(part)
+ if (succeededId !== undefined) {
+ succeededIds.add(succeededId)
+ }
+ }
+ }
+ return [...searchIds].filter((id) => succeededIds.has(id)).length
+}
+
+function mapToolExecution(props: Record<string, unknown>): void {
+ if (props['gen_ai.tool.name'] !== undefined) {
+ props['$ai_span_name'] = props['gen_ai.tool.name']
+ }
+ if (props['gen_ai.tool.call.arguments'] !== undefined && props['$ai_input_state'] === undefined) {
+ props['$ai_input_state'] = parseIfJson(props['gen_ai.tool.call.arguments'])
+ }
+ if (props[TOOL_RESULT_KEY] !== undefined && props['$ai_output_state'] === undefined) {
+ props['$ai_output_state'] = parseIfJson(props[TOOL_RESULT_KEY])
+ }
+ delete props['gen_ai.tool.name']
+ delete props['gen_ai.tool.call.arguments']
+ delete props[TOOL_RESULT_KEY]
+}
+
+function process(event: PluginEvent, next: () => void): void {
+ if (!event.properties) {
+ return next()
+ }
+ const props = event.properties
+
+ // The generic mapping strips the operation name, so it must be read first.
+ const isToolExecution = props['gen_ai.operation.name'] === 'execute_tool'
+
+ next()
+
+ renameAttributes(props)
+
+ // These spans report input tokens that already include the tokens read from and written to
+ // the prompt cache. The cost calculation otherwise assumes the opposite for this provider.
+ if (props['$ai_input_tokens'] !== undefined && props['$ai_cache_reporting_exclusive'] === undefined) {
+ props['$ai_cache_reporting_exclusive'] = false
+ }
+ mapCacheWriteBreakdown(props)
+ addCompactionTokens(props)
+
+ if (props['$ai_stop_reason'] === undefined) {
+ const stopReason = STOP_REASON_KEYS.map((key) => usableStopReason(props[key])).find((r) => r !== undefined)
+ if (stopReason !== undefined) {
+ props['$ai_stop_reason'] = stopReason
+ }
+ }
+ for (const key of STOP_REASON_KEYS) {
+ delete props[key]
+ }
+
+ // A session can hold several conversation threads, so it is the wider grouping and takes the
+ // session id before the conversation id fallback runs.
+ const sessionId = props[SESSION_ID_KEY]
+ if (props['$ai_session_id'] === undefined && typeof sessionId === 'string' && sessionId !== '') {
+ props['$ai_session_id'] = sessionId
+ }
+ delete props[SESSION_ID_KEY]
+
+ if (isToolExecution) {
+ mapToolExecution(props)
+ }
+
+ if (event.event === '$ai_generation' && props['$ai_web_search_count'] === undefined) {
+ const webSearches = countServerWebSearches(props['$ai_output_choices'])
+ if (webSearches > 0) {
+ props['$ai_web_search_count'] = webSearches
+ }
+ }
+
+ props['$ai_lib'] = 'opentelemetry/anthropic'
+}
+
+export const anthropic: OtelLibraryMiddleware = {
+ name: 'anthropic',
+ matches: (event) => Object.keys(event.properties ?? {}).some((key) => key.startsWith(ATTRIBUTE_PREFIX)),
+ process,
+}
diff --git a/rust/capture/src/otel/fan_out.rs b/rust/capture/src/otel/fan_out.rs
index dadc7e1f51c4..4aec17322f86 100644
--- a/rust/capture/src/otel/fan_out.rs
+++ b/rust/capture/src/otel/fan_out.rs
@@ -5,7 +5,7 @@ use opentelemetry_proto::tonic::common::v1::{any_value, KeyValue};
use serde_json::{Map, Value};
use super::error_status::apply_error_status_properties;
-use super::identity::extract_distinct_id_for_span;
+use super::identity::{extract_distinct_id_for_span, span_fallback_distinct_id};
use super::providers;
pub struct SpanEvent {
@@ -117,8 +117,9 @@ fn nanos_to_datetime(nanos: u64) -> Option<DateTime<Utc>> {
/// Convert OTLP spans into [`SpanEvent`]s. `request_fallback_distinct_id` is
/// used only when neither the span nor its enclosing resource carries a
-/// distinct_id attribute — see [`extract_distinct_id_for_span`] for the full
-/// precedence list.
+/// distinct_id attribute and the span has no session id or valid trace id to
+/// derive one from. See [`extract_distinct_id_for_span`] and
+/// [`span_fallback_distinct_id`] for the full precedence list.
pub fn expand_into_events(
request: &ExportTraceServiceRequest,
request_fallback_distinct_id: &str,
@@ -144,11 +145,17 @@ pub fn expand_into_events(
continue;
};
- let distinct_id = extract_distinct_id_for_span(
+ let fallback_distinct_id = span_fallback_distinct_id(
&span.attributes,
rs.resource.as_ref(),
+ &span.trace_id,
request_fallback_distinct_id,
);
+ let distinct_id = extract_distinct_id_for_span(
+ &span.attributes,
+ rs.resource.as_ref(),
+ &fallback_distinct_id,
+ );
let span_attrs = attributes_to_map(&span.attributes);
let event_name = (provider.classify)(&span_attrs);
@@ -332,7 +339,6 @@ mod tests {
let event = &events[0];
assert_eq!(event.event_name, "$ai_generation");
- assert_eq!(event.distinct_id, "user-1");
let props = event.properties.as_object().unwrap();
assert_eq!(props["$ai_trace_id"], "0102030405060708090a0b0c0d0e0f10");
@@ -659,6 +665,36 @@ mod tests {
assert_eq!(events[0].distinct_id, "fallback-id");
}
+ #[test]
+ fn test_spans_of_one_trace_share_a_distinct_id_across_requests() {
+ let request = ExportTraceServiceRequest {
+ resource_spans: vec![ResourceSpans {
+ resource: None,
+ scope_spans: vec![ScopeSpans {
+ scope: None,
+ spans: vec![make_span(
+ vec![7; 16],
+ vec![1; 8],
+ vec![],
+ 0,
+ 0,
+ "",
+ vec![make_kv(
+ "gen_ai.request.model",
+ any_value::Value::StringValue("gpt-4".to_string()),
+ )],
+ )],
+ schema_url: String::new(),
+ }],
+ schema_url: String::new(),
+ }],
+ };
+ let first = expand_into_events(&request, "first-request");
+ let second = expand_into_events(&request, "second-request");
+ assert_eq!(first[0].distinct_id, second[0].distinct_id);
+ assert_ne!(first[0].distinct_id, "first-request");
+ }
+
fn make_minimal_request(
extra_resource_attrs: Vec<KeyValue>,
extra_span_attrs: Vec<KeyValue>,
diff --git a/rust/capture/src/otel/identity.rs b/rust/capture/src/otel/identity.rs
index fb9973503647..a65d585ca8f8 100644
--- a/rust/capture/src/otel/identity.rs
+++ b/rust/capture/src/otel/identity.rs
@@ -15,6 +15,21 @@ const SPAN_DISTINCT_ID_KEYS: &[&str] = &[
/// override is set.
const RESOURCE_DISTINCT_ID_KEYS: &[&str] = &["posthog.distinct_id", "user.id"];
+/// A session can span several traces, so its id takes priority over the trace id. The keys and
+/// their order mirror what the AI ingestion pipeline in nodejs/src/ingestion/pipelines/ai/otel
+/// resolves `$ai_session_id` from. Keep the two in step.
+const SESSION_ID_KEYS: &[&str] = &[
+ "$ai_session_id",
+ "ai.telemetry.metadata.$ai_session_id",
+ "ai.settings.context.$ai_session_id",
+ "eve.session.id",
+ "anthropic.session.id",
+ "gen_ai.conversation.id",
+];
+
+/// Changing this value gives every session and trace without an explicit distinct_id a new one.
+const DERIVED_DISTINCT_ID_NAMESPACE: Uuid = Uuid::from_u128(0x392e81d53d134a6fb541bdbf6c865e56);
+
fn get_string_attr<'a>(attrs: &'a [KeyValue], key: &str) -> Option<&'a str> {
attrs
.iter()
@@ -59,6 +74,33 @@ pub fn request_fallback_distinct_id() -> String {
Uuid::new_v4().to_string()
}
+/// Distinct id for a span that names no user. The spans of one trace can arrive in separate
+/// requests, and a session produces several traces, so the id is derived from the session id or
+/// the trace id to keep them on one anonymous person. `request_fallback` covers a span that has
+/// neither a session id nor a valid trace id.
+pub fn span_fallback_distinct_id(
+ span_attrs: &[KeyValue],
+ resource: Option<&Resource>,
+ trace_id: &[u8],
+ request_fallback: &str,
+) -> String {
+ for key in SESSION_ID_KEYS {
+ let session_id = get_string_attr(span_attrs, key)
+ .or_else(|| resource.and_then(|r| get_string_attr(&r.attributes, key)));
+ if let Some(session_id) = session_id {
+ return derived_distinct_id(&format!("session:{session_id}"));
+ }
+ }
+ if trace_id.iter().any(|byte| *byte != 0) {
+ return derived_distinct_id(&format!("trace:{}", hex::encode(trace_id)));
+ }
+ request_fallback.to_string()
+}
+
+fn derived_distinct_id(name: &str) -> String {
+ Uuid::new_v5(&DERIVED_DISTINCT_ID_NAMESPACE, name.as_bytes()).to_string()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -170,6 +212,82 @@ mod tests {
);
}
+ #[test]
+ fn test_span_fallback_is_stable_per_trace_and_differs_across_traces() {
+ let first = span_fallback_distinct_id(&[], None, &[1; 16], "request");
+ assert_eq!(
+ first,
+ span_fallback_distinct_id(&[], None, &[1; 16], "other-request")
+ );
+ assert_ne!(
+ first,
+ span_fallback_distinct_id(&[], None, &[2; 16], "request")
+ );
+ assert_ne!(first, "request");
+ }
+
+ #[test]
+ fn test_span_fallback_groups_the_traces_of_one_session() {
+ for key in SESSION_ID_KEYS {
+ let attrs = vec![string_kv(key, "session-1")];
+ let first = span_fallback_distinct_id(&attrs, None, &[1; 16], "request");
+ assert_eq!(
+ first,
+ span_fallback_distinct_id(&attrs, None, &[2; 16], "request")
+ );
+ assert_ne!(
+ first,
+ span_fallback_distinct_id(&[], None, &[1; 16], "request")
+ );
+ }
+ }
+
+ #[test]
+ fn test_span_fallback_prefers_the_widest_session_grouping() {
+ let all = vec![
+ string_kv("gen_ai.conversation.id", "thread-1"),
+ string_kv("anthropic.session.id", "session-1"),
+ string_kv("$ai_session_id", "explicit-1"),
+ ];
+ let explicit_only = vec![string_kv("$ai_session_id", "explicit-1")];
+ assert_eq!(
+ span_fallback_distinct_id(&all, None, &[1; 16], "request"),
+ span_fallback_distinct_id(&explicit_only, None, &[1; 16], "request")
+ );
+
+ let session_and_thread = vec![
+ string_kv("gen_ai.conversation.id", "thread-1"),
+ string_kv("anthropic.session.id", "session-1"),
+ ];
+ let session_only = vec![string_kv("anthropic.session.id", "session-1")];
+ assert_eq!(
+ span_fallback_distinct_id(&session_and_thread, None, &[1; 16], "request"),
+ span_fallback_distinct_id(&session_only, None, &[1; 16], "request")
+ );
+ }
+
+ #[test]
+ fn test_span_fallback_reads_the_session_from_the_resource() {
+ let resource = resource_with(vec![string_kv("$ai_session_id", "session-1")]);
+ let on_span = vec![string_kv("$ai_session_id", "session-1")];
+ assert_eq!(
+ span_fallback_distinct_id(&[], Some(&resource), &[1; 16], "request"),
+ span_fallback_distinct_id(&on_span, None, &[2; 16], "request")
+ );
+ }
+
+ #[test]
+ fn test_span_fallback_uses_the_request_id_without_a_valid_trace_id() {
+ assert_eq!(
+ span_fallback_distinct_id(&[], None, &[0; 16], "request"),
+ "request"
+ );
+ assert_eq!(
+ span_fallback_distinct_id(&[], None, &[], "request"),
+ "request"
+ );
+ }
+
#[test]
fn test_empty_span_value_falls_through_to_resource() {
let span_attrs = vec![string_kv("posthog.distinct_id", "")];