1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! Binary OTLP (`.pb` / `.otlp`) parser — reads protobuf-encoded
//! OpenTelemetry trace exports.
//!
//! Gated behind the `otel-proto` Cargo feature because `prost` and its
//! transitive deps add meaningful binary size. Users who only consume JSON
//! traces don't pay that cost; users who do need protobuf rebuild with
//! `--features otel-proto`.
//!
//! When the feature is off, `load` returns a helpful error rather than a
//! confusing UTF-8 decode failure, so the failure mode is "agx tells you
//! how to fix it" not "panic".
//!
//! The protobuf-decoding path reuses `otel_json::append_span` for the
//! actual span → Step conversion. Only the wire decode is different.
// Imports used only by the stub path below. The feature-on path lives in
// `real` and has its own imports — keeping top-level imports minimal avoids
// unused-import warnings when `otel-proto` is enabled.
#[cfg(not(feature = "otel-proto"))]
use {crate::timeline::Step, anyhow::Result, std::path::Path};
/// Entry point for loading a binary OTLP file. When the `otel-proto` feature
/// is disabled, returns a helpful error pointing the user at the rebuild
/// instructions.
#[cfg(not(feature = "otel-proto"))]
pub fn load(_path: &Path) -> Result<Vec<Step>> {
anyhow::bail!(
"binary OTLP (.pb / .otlp) support requires rebuilding agx with --features otel-proto.\n\
\tInstall: cargo install agx --features otel-proto\n\
\tBuild: cargo build --release --features otel-proto"
)
}
#[cfg(feature = "otel-proto")]
pub use real::load;
#[cfg(feature = "otel-proto")]
mod real {
use crate::otel_json::append_span;
use crate::timeline::{Step, compute_durations};
use anyhow::{Context, Result};
use prost::Message;
use std::collections::HashMap;
use std::path::Path;
// Minimal subset of the OTLP trace protobuf schema — only fields agx
// actually reads. Unknown fields decode without error and are ignored,
// so we're resilient to schema growth. Tags match the canonical OTLP
// proto file (trace.proto v1).
// prost's `Message` derive emits a `Default` impl (protobuf-3 zero
// defaults), so deriving both `Default` and `Message` conflicts. We
// rely on the prost-generated Default below for every struct.
#[derive(Clone, PartialEq, Message)]
struct TracesData {
#[prost(message, repeated, tag = "1")]
resource_spans: Vec<ResourceSpans>,
}
#[derive(Clone, PartialEq, Message)]
struct ResourceSpans {
#[prost(message, repeated, tag = "2")]
scope_spans: Vec<ScopeSpans>,
}
#[derive(Clone, PartialEq, Message)]
struct ScopeSpans {
#[prost(message, repeated, tag = "2")]
spans: Vec<Span>,
}
#[derive(Clone, PartialEq, Message)]
struct Span {
#[prost(fixed64, tag = "7")]
start_time_unix_nano: u64,
#[prost(message, repeated, tag = "9")]
attributes: Vec<KeyValue>,
}
#[derive(Clone, PartialEq, Message)]
struct KeyValue {
#[prost(string, tag = "1")]
key: String,
#[prost(message, optional, tag = "2")]
value: Option<AnyValue>,
}
#[derive(Clone, PartialEq, Message)]
struct AnyValue {
#[prost(oneof = "any_value::Value", tags = "1, 2, 3, 4")]
value: Option<any_value::Value>,
}
pub mod any_value {
// Variant names mirror the OTLP `AnyValue` protobuf oneof field
// names (string_value / bool_value / int_value / double_value) —
// renaming would diverge from the spec and make cross-referencing
// harder. Suppress clippy::enum_variant_names accordingly.
#[derive(Clone, PartialEq, ::prost::Oneof)]
#[allow(clippy::enum_variant_names)]
pub enum Value {
#[prost(string, tag = "1")]
StringValue(String),
#[prost(bool, tag = "2")]
BoolValue(bool),
#[prost(int64, tag = "3")]
IntValue(i64),
#[prost(double, tag = "4")]
DoubleValue(f64),
}
}
pub fn load(path: &Path) -> Result<Vec<Step>> {
let bytes = std::fs::read(path)
.with_context(|| format!("reading binary OTLP file: {}", path.display()))?;
let data = TracesData::decode(bytes.as_slice())
.with_context(|| format!("decoding OTLP protobuf: {}", path.display()))?;
// Flatten every span into a single chronologically-ordered list.
// Same convention as otel_json::load so multi-resource / multi-scope
// files produce one coherent timeline.
let mut all_spans: Vec<(&Span, u64)> = Vec::new();
for rs in &data.resource_spans {
for ss in &rs.scope_spans {
for span in &ss.spans {
all_spans.push((span, span.start_time_unix_nano));
}
}
}
all_spans.sort_by_key(|(_, ts)| *ts);
let mut steps: Vec<Step> = Vec::new();
for (span, ts_ns) in all_spans {
// Convert prost attrs → owned HashMap<String, Value>, then
// re-borrow as HashMap<&str, Value> to match the signature
// append_span already uses for the JSON path.
let attrs_owned = index_attributes(&span.attributes);
let attrs_borrowed: HashMap<&str, serde_json::Value> = attrs_owned
.iter()
.map(|(k, v)| (k.as_str(), v.clone()))
.collect();
append_span(&attrs_borrowed, ts_ns, &mut steps);
}
compute_durations(&mut steps);
Ok(steps)
}
fn index_attributes(attrs: &[KeyValue]) -> HashMap<String, serde_json::Value> {
let mut out = HashMap::new();
for kv in attrs {
let Some(v) = kv.value.as_ref() else {
continue;
};
let Some(jv) = any_value_to_json(v) else {
continue;
};
out.insert(kv.key.clone(), jv);
}
out
}
fn any_value_to_json(v: &AnyValue) -> Option<serde_json::Value> {
let inner = v.value.as_ref()?;
match inner {
any_value::Value::StringValue(s) => Some(serde_json::Value::String(s.clone())),
any_value::Value::BoolValue(b) => Some(serde_json::Value::Bool(*b)),
// OTel usage counters are non-negative; drop negative ints
// rather than silently mapping to a wrong u64.
any_value::Value::IntValue(i) if *i >= 0 =>
{
#[allow(clippy::cast_sign_loss)]
Some(serde_json::Value::Number((*i as u64).into()))
}
any_value::Value::IntValue(_) => None,
any_value::Value::DoubleValue(d) => {
serde_json::Number::from_f64(*d).map(serde_json::Value::Number)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::timeline::StepKind;
use std::io::Write;
use tempfile::NamedTempFile;
fn write_bytes(bytes: &[u8]) -> NamedTempFile {
let mut f = NamedTempFile::new().unwrap();
f.write_all(bytes).unwrap();
f
}
fn kv_str(k: &str, v: &str) -> KeyValue {
KeyValue {
key: k.into(),
value: Some(AnyValue {
value: Some(any_value::Value::StringValue(v.into())),
}),
}
}
fn kv_int(k: &str, v: i64) -> KeyValue {
KeyValue {
key: k.into(),
value: Some(AnyValue {
value: Some(any_value::Value::IntValue(v)),
}),
}
}
fn encode(data: &TracesData) -> Vec<u8> {
data.encode_to_vec()
}
fn minimal_chat_bytes() -> Vec<u8> {
encode(&TracesData {
resource_spans: vec![ResourceSpans {
scope_spans: vec![ScopeSpans {
spans: vec![Span {
start_time_unix_nano: 1_000_000_000,
attributes: vec![
kv_str("gen_ai.operation.name", "chat"),
kv_str("gen_ai.request.model", "gpt-5"),
kv_int("gen_ai.usage.input_tokens", 100),
kv_int("gen_ai.usage.output_tokens", 50),
kv_str("gen_ai.prompt.0.role", "user"),
kv_str("gen_ai.prompt.0.content", "hello"),
kv_str("gen_ai.completion.0.role", "assistant"),
kv_str("gen_ai.completion.0.content", "hi"),
],
}],
}],
}],
})
}
#[test]
fn decodes_minimal_chat_span_into_two_steps() {
let f = write_bytes(&minimal_chat_bytes());
let steps = load(f.path()).unwrap();
assert_eq!(steps.len(), 2);
assert_eq!(steps[0].kind, StepKind::UserText);
assert_eq!(steps[1].kind, StepKind::AssistantText);
assert!(steps[0].detail.contains("hello"));
assert!(steps[1].detail.contains("hi"));
}
#[test]
fn usage_and_model_attach_to_first_step() {
let f = write_bytes(&minimal_chat_bytes());
let steps = load(f.path()).unwrap();
assert_eq!(steps[0].model.as_deref(), Some("gpt-5"));
assert_eq!(steps[0].tokens_in, Some(100));
assert_eq!(steps[0].tokens_out, Some(50));
assert_eq!(steps[1].model, None);
}
#[test]
fn execute_tool_span_produces_paired_use_and_result() {
let data = TracesData {
resource_spans: vec![ResourceSpans {
scope_spans: vec![ScopeSpans {
spans: vec![Span {
start_time_unix_nano: 2_000_000_000,
attributes: vec![
kv_str("gen_ai.operation.name", "execute_tool"),
kv_str("gen_ai.tool.name", "list_dir"),
kv_str("gen_ai.tool.call.id", "call_x"),
kv_str("gen_ai.tool.call.arguments", r#"{"p":"."}"#),
kv_str("gen_ai.tool.call.result", "a\nb\n"),
],
}],
}],
}],
};
let f = write_bytes(&encode(&data));
let steps = load(f.path()).unwrap();
assert_eq!(steps.len(), 2);
assert_eq!(steps[0].kind, StepKind::ToolUse);
assert!(steps[0].label.contains("list_dir"));
assert_eq!(steps[1].kind, StepKind::ToolResult);
assert!(steps[1].detail.contains("a\nb"));
}
#[test]
fn spans_sorted_by_start_time_across_resource_boundaries() {
let data = TracesData {
resource_spans: vec![
ResourceSpans {
scope_spans: vec![ScopeSpans {
spans: vec![Span {
start_time_unix_nano: 3_000_000_000,
attributes: vec![
kv_str("gen_ai.operation.name", "chat"),
kv_str("gen_ai.prompt.0.role", "user"),
kv_str("gen_ai.prompt.0.content", "third"),
],
}],
}],
},
ResourceSpans {
scope_spans: vec![ScopeSpans {
spans: vec![Span {
start_time_unix_nano: 1_000_000_000,
attributes: vec![
kv_str("gen_ai.operation.name", "chat"),
kv_str("gen_ai.prompt.0.role", "user"),
kv_str("gen_ai.prompt.0.content", "first"),
],
}],
}],
},
],
};
let f = write_bytes(&encode(&data));
let steps = load(f.path()).unwrap();
assert_eq!(steps.len(), 2);
assert!(steps[0].detail.contains("first"));
assert!(steps[1].detail.contains("third"));
}
#[test]
fn spans_without_genai_marker_are_ignored() {
let data = TracesData {
resource_spans: vec![ResourceSpans {
scope_spans: vec![ScopeSpans {
spans: vec![
// Non-GenAI span — no gen_ai.operation.name.
Span {
start_time_unix_nano: 1_000_000_000,
attributes: vec![kv_str("http.method", "GET")],
},
// GenAI chat span.
Span {
start_time_unix_nano: 2_000_000_000,
attributes: vec![
kv_str("gen_ai.operation.name", "chat"),
kv_str("gen_ai.prompt.0.role", "user"),
kv_str("gen_ai.prompt.0.content", "hi"),
],
},
],
}],
}],
};
let f = write_bytes(&encode(&data));
let steps = load(f.path()).unwrap();
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].kind, StepKind::UserText);
}
#[test]
fn invalid_protobuf_returns_error() {
// Not valid protobuf — decode should fail with a contextual error.
let f = write_bytes(&[0xff, 0xfe, 0xfd, 0xfc]);
let err = load(f.path()).unwrap_err();
let msg = format!("{err:#}");
assert!(
msg.contains("decoding OTLP protobuf"),
"expected decode error context, got: {msg}"
);
}
}
}
// Stub-path tests — these run when the feature is OFF (the default CI
// build). Verify the helpful error message shows up.
#[cfg(not(feature = "otel-proto"))]
#[cfg(test)]
mod stub_tests {
use super::*;
use std::path::PathBuf;
#[test]
fn load_returns_helpful_error_when_feature_disabled() {
let err = load(&PathBuf::from("/dev/null")).unwrap_err();
let msg = format!("{err:#}");
assert!(msg.contains("--features otel-proto"));
assert!(msg.contains("cargo install agx"));
}
}