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(llma): normalize AI SDK v7 OTel spans (#64072)

Radu Raiceaf2082b2770ee
diff --git a/nodejs/src/ingestion/ai/costs/output-costs.ts b/nodejs/src/ingestion/ai/costs/output-costs.ts
index b992724ee124..b6d35b9e8551 100644
--- a/nodejs/src/ingestion/ai/costs/output-costs.ts
+++ b/nodejs/src/ingestion/ai/costs/output-costs.ts
@@ -8,7 +8,7 @@ import { ResolvedModelCost } from './providers/types'
const REASONING_COST_MODELS = [/^gemini-2\.5-/, /^gemini-3(\.\d+)?-/]
-const mustAddReasoningCost = (model: string): boolean => {
+export const mustAddReasoningCost = (model: string): boolean => {
return REASONING_COST_MODELS.some((candidate) => candidate.test(model.toLowerCase()))
}
diff --git a/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts b/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts
index 9f3a97d4d7b9..3d06a813694e 100644
--- a/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts
+++ b/nodejs/src/ingestion/ai/otel/attribute-mapping.test.ts
@@ -23,6 +23,8 @@ describe('mapOtelAttributes', () => {
['gen_ai.output.messages', '$ai_output_choices'],
['gen_ai.usage.input_tokens', '$ai_input_tokens'],
['gen_ai.usage.output_tokens', '$ai_output_tokens'],
+ ['gen_ai.usage.cache_read.input_tokens', '$ai_cache_read_input_tokens'],
+ ['gen_ai.usage.cache_creation.input_tokens', '$ai_cache_creation_input_tokens'],
['gen_ai.response.model', '$ai_model'],
['gen_ai.provider.name', '$ai_provider'],
['server.address', '$ai_base_url'],
diff --git a/nodejs/src/ingestion/ai/otel/attribute-mapping.ts b/nodejs/src/ingestion/ai/otel/attribute-mapping.ts
index 102afab03d82..1574dd8f385c 100644
--- a/nodejs/src/ingestion/ai/otel/attribute-mapping.ts
+++ b/nodejs/src/ingestion/ai/otel/attribute-mapping.ts
@@ -8,6 +8,8 @@ const ATTRIBUTE_MAP: Record<string, string> = {
'gen_ai.output.messages': '$ai_output_choices',
'gen_ai.usage.input_tokens': '$ai_input_tokens',
'gen_ai.usage.output_tokens': '$ai_output_tokens',
+ 'gen_ai.usage.cache_read.input_tokens': '$ai_cache_read_input_tokens',
+ 'gen_ai.usage.cache_creation.input_tokens': '$ai_cache_creation_input_tokens',
'gen_ai.response.model': '$ai_model',
'gen_ai.provider.name': '$ai_provider',
'server.address': '$ai_base_url',
diff --git a/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.test.ts b/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.test.ts
index f5d098cc68fe..e893bb96e69d 100644
--- a/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.test.ts
+++ b/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.test.ts
@@ -21,6 +21,14 @@ const mockedMapOtelAttributes = jest.mocked(mapOtelAttributes)
*/
function mockMapOtelAttributes(e: { event: string; properties?: Record<string, unknown> }): void {
const props = e.properties ?? {}
+ const mappings: Record<string, string> = {
+ 'gen_ai.usage.input_tokens': '$ai_input_tokens',
+ 'gen_ai.usage.output_tokens': '$ai_output_tokens',
+ 'gen_ai.usage.cache_read.input_tokens': '$ai_cache_read_input_tokens',
+ 'gen_ai.usage.cache_creation.input_tokens': '$ai_cache_creation_input_tokens',
+ 'gen_ai.response.model': '$ai_model',
+ 'gen_ai.provider.name': '$ai_provider',
+ }
if (props['gen_ai.input.messages'] !== undefined) {
const val = props['gen_ai.input.messages']
props['$ai_input'] = typeof val === 'string' ? parseJSON(val) : val
@@ -31,6 +39,12 @@ function mockMapOtelAttributes(e: { event: string; properties?: Record<string, u
props['$ai_output_choices'] = typeof val === 'string' ? parseJSON(val) : val
delete props['gen_ai.output.messages']
}
+ for (const [otelKey, phKey] of Object.entries(mappings)) {
+ if (props[otelKey] !== undefined) {
+ props[phKey] = props[otelKey]
+ delete props[otelKey]
+ }
+ }
if (e.event === '$ai_span' && !props['$ai_parent_id']) {
e.event = '$ai_trace'
}
@@ -119,6 +133,106 @@ describe('vercel-ai middleware', () => {
expect(event.properties!['$ai_stop_reason']).toBe('length')
})
+ it('normalizes AI SDK v7 detailed usage without relying on global cache semantics', () => {
+ const event = createEvent('$ai_generation', {
+ 'ai.operationId': 'ai.streamText.doStream',
+ 'gen_ai.provider.name': 'gateway',
+ 'gen_ai.response.model': 'gemini-2.5-pro',
+ 'gen_ai.usage.input_tokens': 100,
+ 'gen_ai.usage.output_tokens': 20,
+ 'gen_ai.usage.cache_read.input_tokens': 80,
+ 'gen_ai.usage.cache_creation.input_tokens': 10,
+ 'ai.usage.inputTokenDetails.noCacheTokens': 10,
+ 'ai.usage.outputTokenDetails.textTokens': 15,
+ 'ai.usage.outputTokenDetails.reasoningTokens': 5,
+ })
+ convertOtelEvent(event)
+
+ expect(event.properties!['$ai_provider']).toBe('gateway')
+ expect(event.properties!['$ai_model']).toBe('gemini-2.5-pro')
+ expect(event.properties!['$ai_input_tokens']).toBe(100)
+ expect(event.properties!['$ai_output_tokens']).toBe(20)
+ expect(event.properties!['$ai_cache_read_input_tokens']).toBe(80)
+ expect(event.properties!['$ai_cache_creation_input_tokens']).toBe(10)
+ expect(event.properties!['$ai_reasoning_tokens']).toBe(5)
+ expect(event.properties!['$ai_cache_reporting_exclusive']).toBe(false)
+ expect(event.properties!['$ai_framework']).toBe('vercel')
+ expect(event.properties!['$ai_text_output_tokens']).toBe(15)
+ expect(event.properties!['ai.usage.inputTokenDetails.noCacheTokens']).toBeUndefined()
+ expect(event.properties!['ai.usage.outputTokenDetails.textTokens']).toBeUndefined()
+ })
+
+ it('preserves explicit cache reporting semantics on AI SDK v7 spans', () => {
+ const event = createEvent('$ai_generation', {
+ 'ai.operationId': 'ai.generateText.doGenerate',
+ 'gen_ai.usage.cache_read.input_tokens': 80,
+ $ai_cache_reporting_exclusive: true,
+ })
+ convertOtelEvent(event)
+
+ expect(event.properties!['$ai_cache_reporting_exclusive']).toBe(true)
+ expect(event.properties!['$ai_framework']).toBe('vercel')
+ })
+
+ it('does not add AI SDK v7 cache semantics when detailed cache usage is absent', () => {
+ const event = createEvent('$ai_generation', {
+ 'ai.operationId': 'ai.generateText.doGenerate',
+ 'gen_ai.usage.input_tokens': 100,
+ 'gen_ai.usage.output_tokens': 20,
+ })
+ convertOtelEvent(event)
+
+ expect(event.properties!['$ai_input_tokens']).toBe(100)
+ expect(event.properties!['$ai_output_tokens']).toBe(20)
+ expect(event.properties!['$ai_cache_reporting_exclusive']).toBeUndefined()
+ expect(event.properties!['$ai_framework']).toBe('vercel')
+ })
+
+ it('preserves explicit text output tokens when AI SDK v7 reasoning details are present', () => {
+ const event = createEvent('$ai_generation', {
+ 'ai.operationId': 'ai.streamText.doStream',
+ 'gen_ai.response.model': 'gemini-2.5-pro',
+ 'gen_ai.usage.output_tokens': 20,
+ 'ai.usage.outputTokenDetails.reasoningTokens': 5,
+ $ai_text_output_tokens: 99,
+ })
+ convertOtelEvent(event)
+
+ expect(event.properties!['$ai_output_tokens']).toBe(20)
+ expect(event.properties!['$ai_reasoning_tokens']).toBe(5)
+ expect(event.properties!['$ai_text_output_tokens']).toBe(99)
+ })
+
+ it('does not split text output tokens for non-Gemini reasoning models', () => {
+ const event = createEvent('$ai_generation', {
+ 'ai.operationId': 'ai.streamText.doStream',
+ 'gen_ai.response.model': 'o1-mini',
+ 'gen_ai.usage.output_tokens': 20,
+ 'ai.usage.outputTokenDetails.textTokens': 15,
+ 'ai.usage.outputTokenDetails.reasoningTokens': 5,
+ })
+ convertOtelEvent(event)
+
+ expect(event.properties!['$ai_output_tokens']).toBe(20)
+ expect(event.properties!['$ai_reasoning_tokens']).toBe(5)
+ expect(event.properties!['$ai_text_output_tokens']).toBeUndefined()
+ expect(event.properties!['ai.usage.outputTokenDetails.textTokens']).toBeUndefined()
+ })
+
+ it('derives Gemini text output tokens when AI SDK v7 omits text token details', () => {
+ const event = createEvent('$ai_generation', {
+ 'ai.operationId': 'ai.streamText.doStream',
+ 'gen_ai.response.model': 'gemini-2.5-pro',
+ 'gen_ai.usage.output_tokens': 20,
+ 'ai.usage.outputTokenDetails.reasoningTokens': 5,
+ })
+ convertOtelEvent(event)
+
+ expect(event.properties!['$ai_output_tokens']).toBe(20)
+ expect(event.properties!['$ai_reasoning_tokens']).toBe(5)
+ expect(event.properties!['$ai_text_output_tokens']).toBe(15)
+ })
+
it('leaves $ai_stop_reason undefined when no finish reason is present', () => {
const event = createEvent('$ai_generation', {
'ai.operationId': 'ai.generateText.doGenerate',
@@ -353,6 +467,7 @@ describe('vercel-ai middleware', () => {
const event = createEvent(eventType, { 'ai.operationId': 'ai.generateText.doGenerate' })
convertOtelEvent(event)
expect(event.properties!['$ai_lib']).toBe('opentelemetry/vercel-ai')
+ expect(event.properties!['$ai_framework']).toBe('vercel')
})
})
})
diff --git a/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.ts b/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.ts
index 1ca77f7b4e7b..d71d1b5e8f4b 100644
--- a/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.ts
+++ b/nodejs/src/ingestion/ai/otel/middleware/vercel-ai.ts
@@ -1,6 +1,7 @@
import { PluginEvent } from '~/plugin-scaffold'
import { parseJSON } from '../../../../utils/json-parse'
+import { mustAddReasoningCost } from '../../costs/output-costs'
import { OtelLibraryMiddleware } from './types'
// Vercel AI SDK attributes to strip after processing. Includes both
@@ -18,6 +19,8 @@ const STRIP_KEYS = [
'ai.usage.promptTokens',
'ai.usage.completionTokens',
'ai.usage.tokens',
+ 'ai.usage.inputTokenDetails.noCacheTokens',
+ 'ai.usage.outputTokenDetails.textTokens',
'ai.response.id',
'ai.response.model',
'ai.response.timestamp',
@@ -57,6 +60,17 @@ function isPromptVersion(value: unknown): value is string | number {
return isNonEmptyString(value) || (typeof value === 'number' && Number.isInteger(value) && value > 0)
}
+function numericValue(value: unknown): number | null {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value
+ }
+ if (typeof value === 'string') {
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : null
+ }
+ return null
+}
+
function process(event: PluginEvent, next: () => void): void {
if (!event.properties) {
return next()
@@ -65,6 +79,17 @@ function process(event: PluginEvent, next: () => void): void {
// Capture opId before next() since STRIP_KEYS deletes it afterward
const opId = props['ai.operationId']
+ const hasAiSdkV7CacheUsage =
+ props['gen_ai.usage.cache_read.input_tokens'] !== undefined ||
+ props['gen_ai.usage.cache_creation.input_tokens'] !== undefined ||
+ props['ai.usage.inputTokenDetails.noCacheTokens'] !== undefined
+ const aiSdkV7TextOutputTokens = props['ai.usage.outputTokenDetails.textTokens']
+ const aiSdkV7ReasoningTokens = props['ai.usage.outputTokenDetails.reasoningTokens']
+ const hasAiSdkV7ReasoningDetails = aiSdkV7ReasoningTokens !== undefined
+
+ if (props['$ai_cache_reporting_exclusive'] === undefined && hasAiSdkV7CacheUsage) {
+ props['$ai_cache_reporting_exclusive'] = false
+ }
// Map ai.prompt.messages → gen_ai.input.messages before the standard mapping
// runs, so mapOtelAttributes() picks it up as $ai_input. Provider-level spans
@@ -212,6 +237,26 @@ function process(event: PluginEvent, next: () => void): void {
delete props['gen_ai.response.finish_reasons']
props['$ai_lib'] = 'opentelemetry/vercel-ai'
+ props['$ai_framework'] ??= 'vercel'
+
+ if (props['$ai_reasoning_tokens'] === undefined && aiSdkV7ReasoningTokens !== undefined) {
+ props['$ai_reasoning_tokens'] = aiSdkV7ReasoningTokens
+ }
+
+ const shouldSplitReasoningTokens =
+ typeof props['$ai_model'] === 'string' && mustAddReasoningCost(props['$ai_model'])
+ if (props['$ai_text_output_tokens'] === undefined && shouldSplitReasoningTokens) {
+ const textOutputTokens = numericValue(aiSdkV7TextOutputTokens)
+ if (textOutputTokens !== null) {
+ props['$ai_text_output_tokens'] = textOutputTokens
+ } else if (hasAiSdkV7ReasoningDetails) {
+ const outputTokens = numericValue(props['$ai_output_tokens'])
+ const reasoningTokens = numericValue(props['$ai_reasoning_tokens'])
+ if (outputTokens !== null && reasoningTokens !== null) {
+ props['$ai_text_output_tokens'] = Math.max(0, outputTokens - reasoningTokens)
+ }
+ }
+ }
for (const key of STRIP_KEYS) {
delete props[key]
diff --git a/nodejs/src/ingestion/ai/process-ai-event.test.ts b/nodejs/src/ingestion/ai/process-ai-event.test.ts
index 7e4629097ab5..b41fc40d1ed8 100644
--- a/nodejs/src/ingestion/ai/process-ai-event.test.ts
+++ b/nodejs/src/ingestion/ai/process-ai-event.test.ts
@@ -300,6 +300,46 @@ describe('processAiEvent()', () => {
expect(result.properties!.$ai_tools_called).toBe('get_weather,search_docs')
expect(result.properties!.$ai_tool_call_count).toBe(2)
})
+
+ it('uses total output tokens for non-Gemini AI SDK v7 reasoning models', () => {
+ event.properties = {
+ $ai_ingestion_source: 'otel',
+ 'ai.operationId': 'ai.streamText.doStream',
+ 'gen_ai.provider.name': 'openai',
+ 'gen_ai.response.model': 'o1-mini',
+ 'gen_ai.usage.input_tokens': 0,
+ 'gen_ai.usage.output_tokens': 250,
+ 'ai.usage.outputTokenDetails.textTokens': 50,
+ 'ai.usage.outputTokenDetails.reasoningTokens': 200,
+ }
+
+ const result = processAiEvent(event)
+
+ expect(result.properties!.$ai_reasoning_tokens).toBe(200)
+ expect(result.properties!.$ai_text_output_tokens).toBeUndefined()
+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0011, 6)
+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0011, 6)
+ })
+
+ it('splits Gemini AI SDK v7 text and reasoning tokens before cost calculation', () => {
+ event.properties = {
+ $ai_ingestion_source: 'otel',
+ 'ai.operationId': 'ai.streamText.doStream',
+ 'gen_ai.provider.name': 'google',
+ 'gen_ai.response.model': 'gemini-2.5-flash',
+ 'gen_ai.usage.input_tokens': 0,
+ 'gen_ai.usage.output_tokens': 250,
+ 'ai.usage.outputTokenDetails.textTokens': 50,
+ 'ai.usage.outputTokenDetails.reasoningTokens': 200,
+ }
+
+ const result = processAiEvent(event)
+
+ expect(result.properties!.$ai_text_output_tokens).toBe(50)
+ expect(result.properties!.$ai_reasoning_tokens).toBe(200)
+ expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.000625, 6)
+ expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000625, 6)
+ })
})
describe('model matching', () => {
diff --git a/rust/capture/src/otel/error_status.rs b/rust/capture/src/otel/error_status.rs
new file mode 100644
index 000000000000..88cb80ed8b88
--- /dev/null
+++ b/rust/capture/src/otel/error_status.rs
@@ -0,0 +1,372 @@
+use opentelemetry_proto::tonic::trace::v1::{span, status::StatusCode, Span};
+use serde_json::{Map, Value};
+
+use super::fan_out::attributes_to_map;
+
+const HTTP_STATUS_KEYS: &[&str] = &[
+ "$ai_http_status",
+ "http.response.status_code",
+ "http.status_code",
+ "http.status",
+ "status_code",
+ "error.status_code",
+ "exception.status_code",
+];
+
+fn http_status_from_value(value: &Value) -> Option<i64> {
+ match value {
+ Value::Number(n) => n.as_i64().filter(|status| (100..=599).contains(status)),
+ Value::String(s) => s
+ .parse::<i64>()
+ .ok()
+ .filter(|status| (100..=599).contains(status)),
+ _ => None,
+ }
+}
+
+fn http_status_from_attrs(attrs: &Map<String, Value>) -> Option<i64> {
+ HTTP_STATUS_KEYS
+ .iter()
+ .find_map(|key| attrs.get(*key).and_then(http_status_from_value))
+}
+
+fn is_word_byte(byte: u8) -> bool {
+ byte.is_ascii_alphanumeric() || byte == b'_'
+}
+
+fn has_marker_boundaries(text: &str, index: usize, marker: &str) -> bool {
+ let bytes = text.as_bytes();
+ let before = index == 0 || !is_word_byte(bytes[index - 1]);
+ let after_index = index + marker.len();
+ let after = after_index >= bytes.len() || !is_word_byte(bytes[after_index]);
+ before && after
+}
+
+fn strip_word_prefix<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
+ let trimmed = text.trim_start();
+ let lower = trimmed.to_ascii_lowercase();
+ if lower.starts_with(prefix) && has_marker_boundaries(&lower, 0, prefix) {
+ return Some(&trimmed[prefix.len()..]);
+ }
+ None
+}
+
+fn http_status_at_start(text: &str) -> Option<i64> {
+ let trimmed = text.trim_start();
+ let bytes = trimmed.as_bytes();
+ if bytes.len() < 3 || !bytes[..3].iter().all(u8::is_ascii_digit) {
+ return None;
+ }
+ if let Some(next) = bytes.get(3) {
+ if is_word_byte(*next) {
+ return None;
+ }
+ }
+
+ trimmed[..3]
+ .parse::<i64>()
+ .ok()
+ .filter(|status| (100..=599).contains(status))
+}
+
+fn http_status_after_separator(text: &str, allow_bare_number: bool) -> Option<i64> {
+ let trimmed = text.trim_start();
+ if trimmed.starts_with("://") {
+ return None;
+ }
+
+ if let Some(separator) = trimmed.chars().next().filter(|ch| matches!(ch, ':' | '=')) {
+ return http_status_at_start(&trimmed[separator.len_utf8()..]);
+ }
+
+ allow_bare_number.then(|| http_status_at_start(trimmed))?
+}
+
+fn http_status_after_status_marker(text: &str) -> Option<i64> {
+ if let Some(after_code) = strip_word_prefix(text, "code") {
+ return http_status_after_separator(after_code, true);
+ }
+ http_status_after_separator(text, false)
+}
+
+fn http_status_after_http_marker(text: &str) -> Option<i64> {
+ if let Some(after_status) = strip_word_prefix(text, "status") {
+ return http_status_after_status_marker(after_status);
+ }
+ http_status_after_separator(text, true)
+}
+
+fn find_status_after_marker(
+ text: &str,
+ lower: &str,
+ marker: &str,
+ parser: fn(&str) -> Option<i64>,
+) -> Option<i64> {
+ let mut offset = 0;
+ while let Some(index) = lower[offset..].find(marker) {
+ let absolute_index = offset + index;
+ let marker_end = absolute_index + marker.len();
+ if has_marker_boundaries(lower, absolute_index, marker) {
+ if let Some(status) = parser(&text[marker_end..]) {
+ return Some(status);
+ }
+ }
+ offset = marker_end;
+ }
+ None
+}
+
+fn http_status_from_text(text: &str) -> Option<i64> {
+ let lower = text.to_ascii_lowercase();
+
+ find_status_after_marker(text, &lower, "status_code", |text| {
+ http_status_after_separator(text, true)
+ })
+ .or_else(|| {
+ find_status_after_marker(text, &lower, "status code", |text| {
+ http_status_after_separator(text, true)
+ })
+ })
+ .or_else(|| find_status_after_marker(text, &lower, "status", http_status_after_status_marker))
+ .or_else(|| find_status_after_marker(text, &lower, "http", http_status_after_http_marker))
+}
+
+fn http_status_from_error_attrs(attrs: &Map<String, Value>) -> Option<i64> {
+ ["exception.message", "error.message"]
+ .iter()
+ .find_map(|key| {
+ attrs
+ .get(*key)
+ .and_then(Value::as_str)
+ .and_then(http_status_from_text)
+ })
+}
+
+fn latest_exception_event(span: &Span) -> Option<&span::Event> {
+ span.events.iter().rev().find(|event| {
+ event.name == "exception"
+ || event
+ .attributes
+ .iter()
+ .any(|kv| kv.key == "exception.message" || kv.key == "exception.type")
+ })
+}
+
+fn error_message_from_exception(event: &span::Event) -> Option<String> {
+ let attrs = attributes_to_map(&event.attributes);
+ let message = attrs.get("exception.message").and_then(Value::as_str);
+ let error_type = attrs.get("exception.type").and_then(Value::as_str);
+
+ match (error_type, message) {
+ (Some(error_type), Some(message)) if !error_type.is_empty() && !message.is_empty() => {
+ Some(format!("{error_type}: {message}"))
+ }
+ (_, Some(message)) if !message.is_empty() => Some(message.to_string()),
+ (Some(error_type), _) if !error_type.is_empty() => Some(error_type.to_string()),
+ _ => None,
+ }
+}
+
+pub fn apply_error_status_properties(span: &Span, properties: &mut Map<String, Value>) {
+ let Some(status) = span.status.as_ref() else {
+ return;
+ };
+
+ if StatusCode::try_from(status.code) != Ok(StatusCode::Error) {
+ return;
+ }
+
+ properties.insert("$ai_is_error".to_string(), Value::Bool(true));
+
+ if !properties.contains_key("$ai_error") {
+ let error = latest_exception_event(span)
+ .and_then(error_message_from_exception)
+ .or_else(|| (!status.message.is_empty()).then(|| status.message.clone()))
+ .unwrap_or_else(|| "OpenTelemetry span status error".to_string());
+ properties.insert("$ai_error".to_string(), Value::String(error));
+ }
+
+ if !properties.contains_key("$ai_http_status") {
+ let event_status = latest_exception_event(span)
+ .map(|event| attributes_to_map(&event.attributes))
+ .and_then(|attrs| {
+ http_status_from_attrs(&attrs).or_else(|| http_status_from_error_attrs(&attrs))
+ });
+ let http_status = event_status
+ .or_else(|| http_status_from_attrs(properties))
+ .or_else(|| http_status_from_text(&status.message))
+ .unwrap_or(500);
+ properties.insert(
+ "$ai_http_status".to_string(),
+ Value::Number(http_status.into()),
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use opentelemetry_proto::tonic::common::v1::{any_value, AnyValue, KeyValue};
+ use opentelemetry_proto::tonic::trace::v1::Status;
+
+ fn make_kv(key: &str, value: any_value::Value) -> KeyValue {
+ KeyValue {
+ key: key.to_string(),
+ value: Some(AnyValue { value: Some(value) }),
+ }
+ }
+
+ fn make_span(attributes: Vec<KeyValue>) -> Span {
+ Span {
+ attributes,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn test_error_status_maps_exception_event() {
+ let mut span = make_span(vec![make_kv(
+ "http.response.status_code",
+ any_value::Value::IntValue(429),
+ )]);
+ span.status = Some(Status {
+ code: StatusCode::Error as i32,
+ message: "rate limited".to_string(),
+ });
+ span.events = vec![span::Event {
+ name: "exception".to_string(),
+ attributes: vec![
+ make_kv(
+ "exception.type",
+ any_value::Value::StringValue("RateLimitError".to_string()),
+ ),
+ make_kv(
+ "exception.message",
+ any_value::Value::StringValue("Too many requests".to_string()),
+ ),
+ ],
+ ..Default::default()
+ }];
+ let mut properties = attributes_to_map(&span.attributes);
+
+ apply_error_status_properties(&span, &mut properties);
+
+ assert_eq!(properties["$ai_is_error"], Value::Bool(true));
+ assert_eq!(
+ properties["$ai_error"],
+ Value::String("RateLimitError: Too many requests".to_string())
+ );
+ assert_eq!(properties["$ai_http_status"], Value::Number(429.into()));
+ }
+
+ #[test]
+ fn test_error_status_falls_back_to_status_message_and_500() {
+ let mut span = make_span(vec![]);
+ span.status = Some(Status {
+ code: StatusCode::Error as i32,
+ message: "provider failed".to_string(),
+ });
+ let mut properties = Map::new();
+
+ apply_error_status_properties(&span, &mut properties);
+
+ assert_eq!(properties["$ai_is_error"], Value::Bool(true));
+ assert_eq!(
+ properties["$ai_error"],
+ Value::String("provider failed".to_string())
+ );
+ assert_eq!(properties["$ai_http_status"], Value::Number(500.into()));
+ }
+
+ #[test]
+ fn test_error_status_recovers_http_status_from_error_message() {
+ let mut span = make_span(vec![]);
+ span.status = Some(Status {
+ code: StatusCode::Error as i32,
+ message: "Status code: 429".to_string(),
+ });
+ span.events = vec![span::Event {
+ name: "exception".to_string(),
+ attributes: vec![make_kv(
+ "exception.message",
+ any_value::Value::StringValue("Provider failed with HTTP 429".to_string()),
+ )],
+ ..Default::default()
+ }];
+ let mut properties = Map::new();
+
+ apply_error_status_properties(&span, &mut properties);
+
+ assert_eq!(properties["$ai_is_error"], Value::Bool(true));
+ assert_eq!(properties["$ai_http_status"], Value::Number(429.into()));
+ }
+
+ #[test]
+ fn test_error_status_ignores_ambiguous_numbers_in_error_message() {
+ let mut span = make_span(vec![]);
+ span.status = Some(Status {
+ code: StatusCode::Error as i32,
+ message: "status of 200 records is unknown".to_string(),
+ });
+ span.events = vec![span::Event {
+ name: "exception".to_string(),
+ attributes: vec![make_kv(
+ "exception.message",
+ any_value::Value::StringValue(
+ "request to https://example.com/items/404 failed".to_string(),
+ ),
+ )],
+ ..Default::default()
+ }];
+ let mut properties = Map::new();
+
+ apply_error_status_properties(&span, &mut properties);
+
+ assert_eq!(properties["$ai_is_error"], Value::Bool(true));
+ assert_eq!(properties["$ai_http_status"], Value::Number(500.into()));
+ }
+
+ #[test]
+ fn test_ok_status_does_not_mark_error() {
+ let mut span = make_span(vec![]);
+ span.status = Some(Status {
+ code: StatusCode::Ok as i32,
+ message: String::new(),
+ });
+ span.events = vec![span::Event {
+ name: "exception".to_string(),
+ attributes: vec![make_kv(
+ "exception.message",
+ any_value::Value::StringValue("not a span failure".to_string()),
+ )],
+ ..Default::default()
+ }];
+ let mut properties = Map::new();
+
+ apply_error_status_properties(&span, &mut properties);
+
+ assert!(!properties.contains_key("$ai_is_error"));
+ assert!(!properties.contains_key("$ai_error"));
+ assert!(!properties.contains_key("$ai_http_status"));
+ }
+
+ #[test]
+ fn test_error_status_preserves_explicit_error_attributes() {
+ let mut span = make_span(vec![]);
+ span.status = Some(Status {
+ code: StatusCode::Error as i32,
+ message: "provider failed".to_string(),
+ });
+ let mut properties = Map::from_iter([
+ ("$ai_error".to_string(), Value::String("custom".to_string())),
+ ("$ai_is_error".to_string(), Value::Bool(false)),
+ ("$ai_http_status".to_string(), Value::Number(418.into())),
+ ]);
+
+ apply_error_status_properties(&span, &mut properties);
+
+ assert_eq!(properties["$ai_is_error"], Value::Bool(true));
+ assert_eq!(properties["$ai_error"], Value::String("custom".to_string()));
+ assert_eq!(properties["$ai_http_status"], Value::Number(418.into()));
+ }
+}
diff --git a/rust/capture/src/otel/fan_out.rs b/rust/capture/src/otel/fan_out.rs
index a43622a7d7be..dadc7e1f51c4 100644
--- a/rust/capture/src/otel/fan_out.rs
+++ b/rust/capture/src/otel/fan_out.rs
@@ -2,8 +2,9 @@ use chrono::{DateTime, TimeZone, Utc};
use common_types::HasEventName;
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use opentelemetry_proto::tonic::common::v1::{any_value, KeyValue};
-use serde_json::Value;
+use serde_json::{Map, Value};
+use super::error_status::apply_error_status_properties;
use super::identity::extract_distinct_id_for_span;
use super::providers;
@@ -59,7 +60,7 @@ fn any_value_to_json(value: &any_value::Value) -> Value {
}
}
-fn attributes_to_map(attrs: &[KeyValue]) -> serde_json::Map<String, Value> {
+pub(super) fn attributes_to_map(attrs: &[KeyValue]) -> Map<String, Value> {
attrs
.iter()
.filter_map(|kv| {
@@ -76,7 +77,7 @@ fn attributes_to_map(attrs: &[KeyValue]) -> serde_json::Map<String, Value> {
/// pass through since they don't match these prefixes.
const NOISY_RESOURCE_PREFIXES: &[&str] = &["host.", "process.", "os.", "telemetry."];
-fn filter_resource_attributes(attrs: &[KeyValue]) -> serde_json::Map<String, Value> {
+fn filter_resource_attributes(attrs: &[KeyValue]) -> Map<String, Value> {
attrs
.iter()
.filter_map(|kv| {
@@ -94,7 +95,7 @@ fn filter_resource_attributes(attrs: &[KeyValue]) -> serde_json::Map<String, Val
.collect()
}
-fn apply_geoip_default(properties: &mut serde_json::Map<String, Value>) {
+fn apply_geoip_default(properties: &mut Map<String, Value>) {
let alias = properties.remove("posthog.geoip_disable");
if properties.contains_key("$geoip_disable") {
return;
@@ -189,6 +190,7 @@ pub fn expand_into_events(
"$otel_end_time_unix_nano".to_string(),
Value::String(span.end_time_unix_nano.to_string()),
);
+ apply_error_status_properties(span, &mut properties);
let timestamp = nanos_to_datetime(span.start_time_unix_nano);
diff --git a/rust/capture/src/otel/mod.rs b/rust/capture/src/otel/mod.rs
index 227dfdf136d8..e347bfd83588 100644
--- a/rust/capture/src/otel/mod.rs
+++ b/rust/capture/src/otel/mod.rs
@@ -1,3 +1,4 @@
+mod error_status;
mod fan_out;
mod filtering;
mod identity;