Skip to main content

gadk_engine/telemetry/
d6.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The one decoder of gadk's ADK telemetry as `tracing` carries it, shared by every consumer:
17//! gadk-server's debug store, the engine's test digests and gadk-telemetry's OpenTelemetry bridge.
18//! No OpenTelemetry dependency; consumers render the decoded values.
19//!
20//! - An ADK span is a span whose metadata declares [`OTEL_NAME`] ([`is_adk_span`]); any other
21//!   span is foreign and transparent to ADK parenting.
22//! - [`D6Fields`] reads an ADK span's fields: [`OTEL_NAME`] is the span name,
23//!   [`OTEL_STATUS_CODE`] and [`ERROR_MESSAGE`] the span status and its description, any other
24//!   `otel.*` field is ignored, and every remaining field is an OTel attribute ([`D6Value`]).
25//! - [`decode_log`] reads an OTel log record: an event on [`LOG_TARGET`] with fields
26//!   [`EVENT_NAME`], [`LOG_BODY`] (JSON text) and [`LOG_ATTRIBUTES`] (JSON object text).
27//! - [`SpanIds`] is a span extension carrying the span's OTel trace and span IDs, written by the
28//!   layer that owns them (the bridge) and read by the others (the debug store).
29
30use serde_json::{Map, Value};
31use tracing::field::{Field, Visit};
32
33use super::LOG_TARGET;
34
35/// The span field carrying the full span name; declaring it makes a span an ADK span.
36pub const OTEL_NAME: &str = "otel.name";
37/// The span field carrying the span status code (`OK` or `ERROR`).
38pub const OTEL_STATUS_CODE: &str = "otel.status_code";
39/// The span field carrying the span status description.
40pub const ERROR_MESSAGE: &str = "error.message";
41/// The log event field carrying the record's event name.
42pub const EVENT_NAME: &str = "event.name";
43/// The log event field carrying the record's body as JSON text.
44pub const LOG_BODY: &str = "otel.log.body";
45/// The log event field carrying the record's attributes as JSON object text.
46pub const LOG_ATTRIBUTES: &str = "otel.log.attributes";
47
48/// Whether a span is an ADK span (one an OTel SDK would see): its metadata declares [`OTEL_NAME`].
49pub fn is_adk_span(meta: &tracing::Metadata<'_>) -> bool {
50    meta.fields().field(OTEL_NAME).is_some()
51}
52
53/// One decoded span attribute value, by the `tracing` field kind that recorded it.
54#[derive(Debug, Clone, PartialEq)]
55pub enum D6Value {
56    /// A `str` field, or a `Debug`/`Display` field's text; also an `i128`/`u128` field's decimal
57    /// text.
58    Str(String),
59    /// An `i64` field, or a `u64` field that fits in `i64`.
60    I64(i64),
61    /// A `u64` field above `i64::MAX` (OTel has no unsigned integer type).
62    U64(u64),
63    /// An `f64` field (possibly NaN or infinite).
64    F64(f64),
65    /// A `bool` field.
66    Bool(bool),
67    /// A bytes field whose JSON text is an array of strings only.
68    StrSlice(Vec<String>),
69    /// A bytes field whose JSON text is any other JSON value (a structured attribute).
70    Json(Value),
71    /// A bytes field that is not JSON text.
72    Bytes(Vec<u8>),
73}
74
75impl D6Value {
76    /// The value as JSON: a string, a number (a non-finite float is `null`), a bool, an array of
77    /// strings, the structured value itself, or `null` for bytes that are not JSON.
78    pub fn to_json(&self) -> Value {
79        match self {
80            Self::Str(s) => Value::String(s.clone()),
81            Self::I64(i) => Value::from(*i),
82            Self::U64(u) => Value::from(*u),
83            Self::F64(f) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
84            Self::Bool(b) => Value::Bool(*b),
85            Self::StrSlice(items) => {
86                Value::Array(items.iter().cloned().map(Value::String).collect())
87            }
88            Self::Json(v) => v.clone(),
89            Self::Bytes(_) => Value::Null,
90        }
91    }
92
93    /// Decodes a bytes field: the JSON text of a structured value.
94    fn from_bytes(v: &[u8]) -> Self {
95        match serde_json::from_slice::<Value>(v) {
96            Ok(Value::Array(items)) if items.iter().all(Value::is_string) => Self::StrSlice(
97                items
98                    .into_iter()
99                    .filter_map(|item| match item {
100                        Value::String(s) => Some(s),
101                        _ => None,
102                    })
103                    .collect(),
104            ),
105            Ok(value) => Self::Json(value),
106            Err(_) => Self::Bytes(v.to_vec()),
107        }
108    }
109}
110
111/// The span status code as recorded on [`OTEL_STATUS_CODE`].
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
113pub enum D6StatusCode {
114    /// No status, or a recorded value other than `OK`/`ERROR`.
115    #[default]
116    Unset,
117    /// Success (recorded as `OK`).
118    Ok,
119    /// Failure (recorded as `ERROR`).
120    Error,
121}
122
123impl D6StatusCode {
124    /// The upper-case name: `UNSET`, `OK` or `ERROR`.
125    pub fn as_str(self) -> &'static str {
126        match self {
127            Self::Unset => "UNSET",
128            Self::Ok => "OK",
129            Self::Error => "ERROR",
130        }
131    }
132}
133
134/// The ADK fields of one `tracing` visit (a span's `Attributes` or one `Record`), as a
135/// [`Visit`] implementation. Each member is what this visit recorded; a consumer merges it into
136/// the span's state (a later value of a name or attribute replaces the earlier one).
137#[derive(Debug, Clone, Default, PartialEq)]
138pub struct D6Fields {
139    /// The span name: the [`OTEL_NAME`] field when recorded as a string (`str` or `Debug`/`Display`
140    /// text).
141    pub name: Option<String>,
142    /// The OTel attributes, in record order (a field recorded twice in one visit keeps its first
143    /// position and its last value).
144    pub attributes: Vec<(String, D6Value)>,
145    /// The status code, when [`OTEL_STATUS_CODE`] was recorded: `ERROR` and `OK` (as strings)
146    /// are [`D6StatusCode::Error`] and [`D6StatusCode::Ok`], any other value is unset.
147    pub status_code: Option<D6StatusCode>,
148    /// The status description: the [`ERROR_MESSAGE`] field when recorded as a string.
149    pub status_description: Option<String>,
150}
151
152impl D6Fields {
153    fn set(&mut self, f: &Field, v: D6Value) {
154        match f.name() {
155            OTEL_NAME => {
156                if let D6Value::Str(s) = v {
157                    self.name = Some(s);
158                }
159            }
160            OTEL_STATUS_CODE => {
161                self.status_code = Some(match &v {
162                    D6Value::Str(s) if s == "ERROR" => D6StatusCode::Error,
163                    D6Value::Str(s) if s == "OK" => D6StatusCode::Ok,
164                    _ => D6StatusCode::Unset,
165                });
166            }
167            ERROR_MESSAGE => {
168                if let D6Value::Str(s) = v {
169                    self.status_description = Some(s);
170                }
171            }
172            n if n.starts_with("otel.") => {}
173            n => match self.attributes.iter_mut().find(|(k, _)| k == n) {
174                Some(slot) => slot.1 = v,
175                None => self.attributes.push((n.to_owned(), v)),
176            },
177        }
178    }
179}
180
181impl Visit for D6Fields {
182    fn record_str(&mut self, f: &Field, v: &str) {
183        self.set(f, D6Value::Str(v.to_owned()));
184    }
185    fn record_bool(&mut self, f: &Field, v: bool) {
186        self.set(f, D6Value::Bool(v));
187    }
188    fn record_i64(&mut self, f: &Field, v: i64) {
189        self.set(f, D6Value::I64(v));
190    }
191    fn record_u64(&mut self, f: &Field, v: u64) {
192        self.set(f, i64::try_from(v).map_or(D6Value::U64(v), D6Value::I64));
193    }
194    fn record_i128(&mut self, f: &Field, v: i128) {
195        self.set(f, D6Value::Str(v.to_string()));
196    }
197    fn record_u128(&mut self, f: &Field, v: u128) {
198        self.set(f, D6Value::Str(v.to_string()));
199    }
200    fn record_f64(&mut self, f: &Field, v: f64) {
201        self.set(f, D6Value::F64(v));
202    }
203    fn record_bytes(&mut self, f: &Field, v: &[u8]) {
204        self.set(f, D6Value::from_bytes(v));
205    }
206    fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
207        self.set(f, D6Value::Str(format!("{v:?}")));
208    }
209}
210
211/// One decoded OTel log record.
212#[derive(Debug, Clone, PartialEq)]
213pub struct D6Log {
214    /// The [`EVENT_NAME`] field (empty when absent).
215    pub event_name: String,
216    /// The event's level (`INFO` or `DEBUG` as gadk emits them).
217    pub level: tracing::Level,
218    /// The [`LOG_BODY`] JSON text, parsed: `Ok(null)` when absent, `Err(())` when not JSON (the
219    /// body could not be serialized).
220    pub body: Result<Value, ()>,
221    /// The [`LOG_ATTRIBUTES`] JSON object, parsed; `None` when absent, not JSON or not an object.
222    pub attributes: Option<Map<String, Value>>,
223}
224
225/// Decodes an OTel log record: `None` for an event whose target is not [`LOG_TARGET`].
226pub fn decode_log(event: &tracing::Event<'_>) -> Option<D6Log> {
227    let meta = event.metadata();
228    if meta.target() != LOG_TARGET {
229        return None;
230    }
231    let mut fields = LogFields::default();
232    event.record(&mut fields);
233    Some(D6Log {
234        event_name: fields.event_name,
235        level: *meta.level(),
236        body: fields.body.unwrap_or(Ok(Value::Null)),
237        attributes: match fields.attributes {
238            Some(Ok(Value::Object(m))) => Some(m),
239            _ => None,
240        },
241    })
242}
243
244/// The visitor behind [`decode_log`].
245#[derive(Default)]
246struct LogFields {
247    event_name: String,
248    body: Option<Result<Value, ()>>,
249    attributes: Option<Result<Value, ()>>,
250}
251
252impl Visit for LogFields {
253    fn record_str(&mut self, f: &Field, v: &str) {
254        match f.name() {
255            EVENT_NAME => self.event_name = v.to_owned(),
256            LOG_BODY => self.body = Some(serde_json::from_str(v).map_err(|_| ())),
257            LOG_ATTRIBUTES => self.attributes = Some(serde_json::from_str(v).map_err(|_| ())),
258            _ => {}
259        }
260    }
261    fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
262        self.record_str(f, &format!("{v:?}"));
263    }
264}
265
266/// An ADK span's OTel IDs, kept in the span's `tracing` registry extensions by the layer that
267/// owns them (gadk-telemetry's bridge, from the SDK span it started) and reused by the other
268/// layers (gadk-server's debug store), so every consumer reports the same IDs.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
270pub struct SpanIds {
271    /// The trace ID (OTel `TraceId` bytes, big-endian).
272    pub trace_id: [u8; 16],
273    /// The span ID (OTel `SpanId` bytes, big-endian).
274    pub span_id: [u8; 8],
275}
276
277impl SpanIds {
278    /// Whether both IDs are non-zero; a shut-down provider hands out all-zero IDs, which consumers
279    /// replace with their own.
280    pub fn is_valid(&self) -> bool {
281        self.trace_id.iter().any(|b| *b != 0) && self.span_id.iter().any(|b| *b != 0)
282    }
283}
284
285#[cfg(test)]
286#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
287mod tests {
288    use std::sync::Arc;
289
290    use parking_lot::Mutex;
291    use tracing::span::{Attributes, Id, Record};
292    use tracing_subscriber::layer::{Context, Layer, SubscriberExt};
293    use tracing_subscriber::registry::LookupSpan;
294
295    use super::*;
296
297    /// One probed span: whether it is an ADK span, and the [`D6Fields`] of each visit.
298    type ProbedSpan = (bool, Vec<D6Fields>);
299
300    /// Records, per span, whether it is an ADK span and the [`D6Fields`] of its visits; and every
301    /// decoded log record.
302    #[derive(Clone, Default)]
303    struct Probe {
304        spans: Arc<Mutex<Vec<ProbedSpan>>>,
305        logs: Arc<Mutex<Vec<D6Log>>>,
306    }
307
308    struct Idx(usize);
309
310    impl<S> Layer<S> for Probe
311    where
312        S: tracing::Subscriber + for<'a> LookupSpan<'a>,
313    {
314        fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
315            let mut fields = D6Fields::default();
316            attrs.record(&mut fields);
317            let mut spans = self.spans.lock();
318            spans.push((is_adk_span(attrs.metadata()), vec![fields]));
319            let i = spans.len() - 1;
320            drop(spans);
321            if let Some(span) = ctx.span(id) {
322                span.extensions_mut().insert(Idx(i));
323            }
324        }
325
326        fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
327            let Some(i) = ctx
328                .span(id)
329                .and_then(|s| s.extensions().get::<Idx>().map(|i| i.0))
330            else {
331                return;
332            };
333            let mut fields = D6Fields::default();
334            values.record(&mut fields);
335            if let Some(span) = self.spans.lock().get_mut(i) {
336                span.1.push(fields);
337            }
338        }
339
340        fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
341            if let Some(log) = decode_log(event) {
342                self.logs.lock().push(log);
343            }
344        }
345    }
346
347    fn probe(f: impl FnOnce()) -> Probe {
348        let p = Probe::default();
349        let sub = tracing_subscriber::registry().with(p.clone());
350        tracing::subscriber::with_default(sub, f);
351        p
352    }
353
354    /// Every field kind decodes to its value; `otel.*` and `error.message` are not attributes.
355    #[test]
356    fn span_fields_decode_each_value_kind() {
357        let p = probe(|| {
358            let _span = tracing::info_span!(
359                "generate_content",
360                otel.name = %"generate_content m",
361                s = "<a>",
362                d = ?"dbg",
363                b = true,
364                i = -3_i64,
365                u = 7_u64,
366                u_big = u64::MAX,
367                i128v = -5_i128,
368                u128v = 6_u128,
369                f = 0.5_f64,
370                f_nan = f64::NAN,
371                strs = br#"["a","<b>"]"#.as_slice(),
372                empty = br#"[]"#.as_slice(),
373                mixed = br#"[1,"x"]"#.as_slice(),
374                map = br#"{"k":"v"}"#.as_slice(),
375                scalar = br#"1.5"#.as_slice(),
376                raw = b"\xff".as_slice(),
377                otel.kind = "client",
378            );
379        });
380        let spans = p.spans.lock();
381        assert_eq!(spans.len(), 1);
382        let (adk, visits) = &spans[0];
383        assert!(*adk);
384        let f = &visits[0];
385        assert_eq!(f.name.as_deref(), Some("generate_content m"));
386        assert_eq!(f.status_code, None);
387        assert_eq!(f.status_description, None);
388        let attrs: Vec<(&str, &D6Value)> =
389            f.attributes.iter().map(|(k, v)| (k.as_str(), v)).collect();
390        assert_eq!(attrs.len(), 16);
391        let want = [
392            ("s", D6Value::Str("<a>".into())),
393            ("d", D6Value::Str("\"dbg\"".into())),
394            ("b", D6Value::Bool(true)),
395            ("i", D6Value::I64(-3)),
396            ("u", D6Value::I64(7)),
397            ("u_big", D6Value::U64(u64::MAX)),
398            ("i128v", D6Value::Str("-5".into())),
399            ("u128v", D6Value::Str("6".into())),
400            ("f", D6Value::F64(0.5)),
401        ];
402        for (i, (k, v)) in want.iter().enumerate() {
403            assert_eq!(attrs[i], (*k, v), "attribute {i}");
404        }
405        assert_eq!(attrs[9].0, "f_nan");
406        assert!(matches!(attrs[9].1, D6Value::F64(x) if x.is_nan()));
407        let rest = [
408            ("strs", D6Value::StrSlice(vec!["a".into(), "<b>".into()])),
409            ("empty", D6Value::StrSlice(Vec::new())),
410            ("mixed", D6Value::Json(serde_json::json!([1, "x"]))),
411            ("map", D6Value::Json(serde_json::json!({"k": "v"}))),
412            ("scalar", D6Value::Json(serde_json::json!(1.5))),
413            ("raw", D6Value::Bytes(vec![0xff])),
414        ];
415        for (i, (k, v)) in rest.iter().enumerate() {
416            assert_eq!(attrs[10 + i], (*k, v), "attribute {}", 10 + i);
417        }
418    }
419
420    /// `to_json` is the digest's view of each value kind.
421    #[test]
422    fn values_as_json() {
423        use serde_json::json;
424        assert_eq!(D6Value::Str("x".into()).to_json(), json!("x"));
425        assert_eq!(D6Value::I64(-1).to_json(), json!(-1));
426        assert_eq!(D6Value::U64(u64::MAX).to_json(), json!(u64::MAX));
427        assert_eq!(D6Value::F64(0.5).to_json(), json!(0.5));
428        assert_eq!(D6Value::F64(f64::INFINITY).to_json(), Value::Null);
429        assert_eq!(D6Value::Bool(false).to_json(), json!(false));
430        assert_eq!(D6Value::StrSlice(vec!["a".into()]).to_json(), json!(["a"]));
431        assert_eq!(D6Value::Json(json!({"k": 1})).to_json(), json!({"k": 1}));
432        assert_eq!(D6Value::Bytes(vec![0xff]).to_json(), Value::Null);
433    }
434
435    /// The status code and description come from `otel.status_code` and `error.message`, also
436    /// when recorded later; a value other than `OK`/`ERROR` is unset.
437    #[test]
438    fn status_fields_decode() {
439        let p = probe(|| {
440            let span = tracing::info_span!(
441                "execute_tool",
442                otel.name = "execute_tool f",
443                otel.status_code = tracing::field::Empty,
444                error.message = tracing::field::Empty,
445            );
446            span.record("otel.status_code", "ERROR");
447            span.record("error.message", "boom");
448            span.record("otel.status_code", "OK");
449            span.record("otel.status_code", "nope");
450            span.record("otel.status_code", 1_i64);
451        });
452        let spans = p.spans.lock();
453        let visits = &spans[0].1;
454        assert_eq!(visits.len(), 6);
455        assert_eq!(visits[0].status_code, None);
456        assert_eq!(visits[1].status_code, Some(D6StatusCode::Error));
457        assert_eq!(visits[2].status_description.as_deref(), Some("boom"));
458        assert_eq!(visits[3].status_code, Some(D6StatusCode::Ok));
459        assert_eq!(visits[4].status_code, Some(D6StatusCode::Unset));
460        assert_eq!(visits[5].status_code, Some(D6StatusCode::Unset));
461        assert!(visits.iter().all(|v| v.attributes.is_empty()));
462        assert_eq!(D6StatusCode::Error.as_str(), "ERROR");
463        assert_eq!(D6StatusCode::Ok.as_str(), "OK");
464        assert_eq!(D6StatusCode::default().as_str(), "UNSET");
465    }
466
467    /// A span without `otel.name` is not an ADK span; a non-string `otel.name` is no name.
468    #[test]
469    fn non_adk_spans_are_classified() {
470        let p = probe(|| {
471            let _a = tracing::debug_span!("Connection", gen_ai.conversation.id = "s");
472            let _b = tracing::info_span!("n", otel.name = 5_i64);
473        });
474        let spans = p.spans.lock();
475        assert!(!spans[0].0);
476        assert_eq!(spans[0].1[0].name, None);
477        assert_eq!(
478            spans[0].1[0].attributes,
479            vec![(
480                "gen_ai.conversation.id".to_owned(),
481                D6Value::Str("s".into())
482            )]
483        );
484        assert!(spans[1].0);
485        assert_eq!(spans[1].1[0].name, None);
486        assert!(spans[1].1[0].attributes.is_empty());
487    }
488
489    /// Log events on `LOG_TARGET` decode; other events do not.
490    #[test]
491    fn log_events_decode() {
492        let p = probe(|| {
493            tracing::event!(
494                target: "gadk_engine::telemetry::log",
495                tracing::Level::DEBUG,
496                event.name = "e",
497                otel.log.body = r#"{"content":"hi"}"#,
498                otel.log.attributes = r#"{"a":[1]}"#
499            );
500            tracing::event!(
501                target: "gadk_engine::telemetry::log",
502                tracing::Level::INFO,
503                event.name = "bad",
504                otel.log.body = "not json",
505                otel.log.attributes = "[1]"
506            );
507            tracing::event!(
508                target: "gadk_engine::telemetry::log",
509                tracing::Level::INFO,
510                event.name = "absent"
511            );
512            tracing::info!(event.name = "other", "not a log record");
513        });
514        let logs = p.logs.lock();
515        assert_eq!(logs.len(), 3);
516        assert_eq!(
517            logs[0],
518            D6Log {
519                event_name: "e".into(),
520                level: tracing::Level::DEBUG,
521                body: Ok(serde_json::json!({"content": "hi"})),
522                attributes: serde_json::from_str(r#"{"a":[1]}"#).unwrap(),
523            }
524        );
525        assert_eq!(logs[1].event_name, "bad");
526        assert_eq!(logs[1].level, tracing::Level::INFO);
527        assert_eq!(logs[1].body, Err(()));
528        assert_eq!(logs[1].attributes, None);
529        assert_eq!(logs[2].body, Ok(Value::Null));
530        assert_eq!(logs[2].attributes, None);
531    }
532
533    /// IDs are valid only when both are non-zero.
534    #[test]
535    fn span_ids_validity() {
536        assert!(!SpanIds::default().is_valid());
537        let ids = |t: u8, s: u8| SpanIds {
538            trace_id: [t; 16],
539            span_id: [s; 8],
540        };
541        assert!(ids(1, 2).is_valid());
542        assert!(!ids(0, 2).is_valid());
543        assert!(!ids(1, 0).is_valid());
544    }
545}