Skip to main content

gadk_engine/telemetry/
mod.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 engine's ADK telemetry as `tracing` spans and events: the spans (`invoke_workflow`,
17//! `invoke_node`, `generate_content`, `execute_tool`, `compact_events`; agents' own `invoke_agent`
18//! spans come from gadk-agent) and the OTel log records.
19//! No OpenTelemetry: the static span name is the operation and `otel.name` the full span name;
20//! every other field is an OTel attribute (structured values per `converters`). All spans are
21//! `INFO`. A `tracing` span records only the fields it declares, so each constructor declares every
22//! attribute that may be set on it later as `Empty`, plus `otel.status_code` and `error.message`
23//! (the span status and its description).
24//!
25//! The module is public for [`set_env_provider`], [`LOG_TARGET`] and [`d6`] (the shared decoder of
26//! this layout); everything else stays crate-private. Submodules: `env` (the process-wide
27//! environment provider and its rules), the span attributes (`attrs`, `converters`, `inference`,
28//! `instrumentation`, `semconv`, `genai_messages`), the OTel log records of the legacy schema
29//! (`logger`), and the test digests (`span_digest`, `log_digest`).
30
31pub(crate) mod attrs;
32pub(crate) mod converters;
33pub mod d6;
34pub(crate) mod env;
35pub(crate) mod genai_messages;
36pub(crate) mod inference;
37pub(crate) mod instrumentation;
38#[cfg(any(test, feature = "testutil"))]
39pub(crate) mod log_digest;
40pub(crate) mod logger;
41pub(crate) mod semconv;
42#[cfg(any(test, feature = "testutil"))]
43pub(crate) mod span_digest;
44
45pub use env::set_env_provider;
46
47use chrono::{DateTime, Utc};
48use gadk_genai::GenerateContentResponseUsageMetadata;
49use gadk_model::Backend;
50use gadk_session::{Event, zero_time};
51use serde_json::Value;
52
53use attrs::SpanError;
54
55/// The `tracing` target of the OTel log records; a `tracing` layer that collects them
56/// (gadk-server's debug store) filters on it.
57pub const LOG_TARGET: &str = "gadk_engine::telemetry::log";
58
59/// The [`SpanIds`](d6::SpanIds) of the nearest enclosing span (the current span first, then its
60/// ancestors) that carries them in its `tracing` registry extensions — the IDs gadk-telemetry's
61/// bridge leaves on every ADK span it exports. The analytics plugin reads them where it needs the
62/// current trace and span IDs. `None` outside any span, when no enclosing span carries IDs (no
63/// bridge installed), or under a subscriber that is not a `tracing_subscriber::Registry` stack (as
64/// `gadk_agent::agent::telemetry::in_workflow_scope`).
65pub fn current_span_ids() -> Option<d6::SpanIds> {
66    let id = tracing::Span::current().id()?;
67    tracing::dispatcher::get_default(|d| {
68        use tracing_subscriber::registry::LookupSpan;
69        let registry = d.downcast_ref::<tracing_subscriber::Registry>()?;
70        registry
71            .span(&id)?
72            .scope()
73            .find_map(|s| s.extensions().get::<d6::SpanIds>().copied())
74    })
75}
76
77/// The `invoke_agent` span. Engine-internal: agents' own spans come from `CustomAgent::run`
78/// (gadk-agent), and engine code never wraps `Agent::run` in another one, so only the span unit
79/// tests use it.
80#[cfg(test)]
81pub(crate) fn agent_span(agent_name: &str) -> tracing::Span {
82    tracing::info_span!(
83        "invoke_agent",
84        otel.name = %format!("invoke_agent {agent_name}"),
85        gen_ai.operation.name = "invoke_agent",
86        gen_ai.agent.name = agent_name
87    )
88}
89
90/// Installs, once per process, gadk-engine's resolver of the type name that spans record as
91/// `error.type` for engine errors gadk-agent cannot see ([`crate::error::go_error_type`], which
92/// names dynamic child run failures). Called where such an error is built, so it is in place before
93/// one can reach a span.
94pub(crate) fn install_go_error_type_resolver() {
95    static INSTALL: std::sync::Once = std::sync::Once::new();
96    INSTALL.call_once(|| {
97        gadk_agent::agent::telemetry::set_go_error_type_resolver(crate::error::go_error_type);
98    });
99}
100
101/// Whether the current span is inside an `invoke_workflow` span (shared with gadk-agent's agent
102/// spans).
103pub(crate) use gadk_agent::agent::telemetry::in_workflow_scope;
104
105/// The `invoke_workflow` span: `gen_ai.workflow.nested` marks a span started inside another
106/// `invoke_workflow` span (default schema only).
107pub(crate) fn workflow_span(name: &str, conversation_id: &str) -> tracing::Span {
108    use tracing::field::Empty;
109    let nested = in_workflow_scope() && !env::use_legacy_schema();
110    let span = tracing::info_span!(
111        "invoke_workflow",
112        otel.name = %format!("invoke_workflow {name}"),
113        gen_ai.operation.name = "invoke_workflow",
114        gen_ai.workflow.name = name,
115        gen_ai.conversation.id = conversation_id,
116        gen_ai.workflow.nested = Empty,
117        error.type = Empty,
118        otel.status_code = Empty,
119        error.message = Empty
120    );
121    if nested {
122        span.record("gen_ai.workflow.nested", true);
123    }
124    span
125}
126
127/// The `invoke_node` span.
128pub(crate) fn node_span(node_name: &str, conversation_id: &str) -> tracing::Span {
129    use tracing::field::Empty;
130    tracing::info_span!(
131        "invoke_node",
132        otel.name = %format!("invoke_node {node_name}"),
133        gen_ai.operation.name = "invoke_node",
134        gen_ai.node.name = node_name,
135        gen_ai.conversation.id = conversation_id,
136        error.type = Empty,
137        otel.status_code = Empty,
138        error.message = Empty
139    )
140}
141
142/// The `generate_content` span, with its start attributes other than the provider (see
143/// [`attrs::start_generate_content_span`]).
144pub(crate) fn generate_content_span(model: &str, invocation_id: &str) -> tracing::Span {
145    use tracing::field::Empty;
146    tracing::info_span!(
147        "generate_content",
148        otel.name = %format!("generate_content {model}"),
149        gcp.vertex.agent.invocation_id = invocation_id,
150        gen_ai.operation.name = "generate_content",
151        gen_ai.request.model = model,
152        gen_ai.provider.name = Empty,
153        gen_ai.system_instructions = Empty,
154        gen_ai.input.messages = Empty,
155        gen_ai.response.finish_reasons = Empty,
156        gcp.vertex.agent.event_id = Empty,
157        gen_ai.usage.input_tokens = Empty,
158        gen_ai.usage.output_tokens = Empty,
159        gen_ai.usage.cache_read.input_tokens = Empty,
160        gen_ai.usage.reasoning.output_tokens = Empty,
161        gen_ai.output.messages = Empty,
162        error.type = Empty,
163        otel.status_code = Empty,
164        error.message = Empty
165    )
166}
167
168/// The `execute_tool` span, with its name attributes (see [`attrs::start_execute_tool_span`]).
169pub(crate) fn execute_tool_span(tool_name: &str) -> tracing::Span {
170    use tracing::field::Empty;
171    tracing::info_span!(
172        "execute_tool",
173        otel.name = %format!("execute_tool {tool_name}"),
174        gen_ai.operation.name = "execute_tool",
175        gen_ai.tool.name = tool_name,
176        gcp.vertex.agent.tool_call_args = Empty,
177        gen_ai.tool.call.arguments = Empty,
178        gen_ai.tool.description = Empty,
179        gcp.vertex.agent.event_id = Empty,
180        gen_ai.tool.call.id = Empty,
181        gen_ai.tool.call.result = Empty,
182        gcp.vertex.agent.tool_response = Empty,
183        error.type = Empty,
184        otel.status_code = Empty,
185        error.message = Empty
186    )
187}
188
189/// The `execute_tool (merged)` span: over parallel tool calls, without attributes until
190/// [`attrs::trace_merged_tool_calls_result`].
191pub(crate) fn merged_tool_calls_span() -> tracing::Span {
192    use tracing::field::Empty;
193    tracing::info_span!(
194        "execute_tool",
195        otel.name = "execute_tool (merged)",
196        gen_ai.operation.name = Empty,
197        gen_ai.tool.name = Empty,
198        gen_ai.tool.description = Empty,
199        gcp.vertex.agent.tool_call_args = Empty,
200        gcp.vertex.agent.tool_response = Empty,
201        gcp.vertex.agent.event_id = Empty,
202        error.type = Empty,
203        otel.status_code = Empty,
204        error.message = Empty
205    )
206}
207
208/// Emits one OTel log record as a `tracing` event under `parent`: target [`LOG_TARGET`], fields
209/// `event.name`, `otel.log.body` (the JSON text of the body; `null` when it has none) and, when
210/// there are any, `otel.log.attributes` (a JSON object). A `DEBUG` record is emitted at the `DEBUG`
211/// level, anything else at `INFO`.
212pub(crate) fn emit_log_record(
213    parent: &tracing::Span,
214    level: tracing::Level,
215    event_name: &str,
216    body: &Value,
217    attributes: &[(String, Value)],
218) {
219    let body = body.to_string();
220    let attributes = (!attributes.is_empty()).then(|| {
221        Value::Object(
222            attributes
223                .iter()
224                .cloned()
225                .collect::<serde_json::Map<_, _>>(),
226        )
227        .to_string()
228    });
229    if level == tracing::Level::DEBUG {
230        tracing::event!(
231            target: LOG_TARGET,
232            parent: parent,
233            tracing::Level::DEBUG,
234            event.name = event_name,
235            otel.log.body = body.as_str(),
236            otel.log.attributes = attributes.as_deref()
237        );
238    } else {
239        tracing::event!(
240            target: LOG_TARGET,
241            parent: parent,
242            tracing::Level::INFO,
243            event.name = event_name,
244            otel.log.body = body.as_str(),
245            otel.log.attributes = attributes.as_deref()
246        );
247    }
248}
249
250/// The name of the compaction span.
251const COMPACT_EVENTS: &str = "compact_events";
252
253/// The trigger of a sliding-window compaction.
254pub(crate) const COMPACTION_TRIGGER_SLIDING_WINDOW: &str = "sliding_window";
255/// The trigger of a token-threshold compaction.
256pub(crate) const COMPACTION_TRIGGER_TOKEN_THRESHOLD: &str = "token_threshold";
257
258/// The parameters of a `compact_events` span. Zero thresholds mean "strategy disabled" and their
259/// attributes are omitted.
260#[derive(Debug, Clone, Default)]
261pub(crate) struct CompactEventsSpanParams {
262    pub(crate) trigger: &'static str,
263    pub(crate) session_id: String,
264    pub(crate) invocation_id: String,
265    pub(crate) summarizer_type: String,
266    pub(crate) backend: Option<Backend>,
267    pub(crate) event_count: usize,
268    pub(crate) compaction_interval: i32,
269    pub(crate) overlap_size: i32,
270    pub(crate) token_threshold: i32,
271    pub(crate) event_retention_size: i32,
272}
273
274/// The `gen_ai.system` value: `gcp.vertex_ai` / `gcp.gemini` (semconv v1.36), `None` for a backend
275/// that cannot be named.
276pub(crate) fn gen_ai_system(backend: Option<Backend>) -> Option<&'static str> {
277    match backend {
278        Some(Backend::VertexAi) => Some("gcp.vertex_ai"),
279        Some(Backend::GeminiApi) => Some("gcp.gemini"),
280        None => None,
281    }
282}
283
284/// Seconds since the Unix epoch as a float: nanoseconds since the epoch divided by 1e9.
285pub(crate) fn epoch_seconds(t: DateTime<Utc>) -> f64 {
286    match t.timestamp_nanos_opt() {
287        Some(n) => n as f64 / 1e9,
288        // Outside the range of nanoseconds since the epoch: whole seconds plus the sub-second part.
289        // Never reached for a recorded bound, which is omitted when zero.
290        None => t.timestamp() as f64 + f64::from(t.timestamp_subsec_nanos()) / 1e9,
291    }
292}
293
294/// Starts a span named `compact_events` (`otel.name` `compact_events <trigger>`), a child of the
295/// caller's current span.
296pub(crate) fn compact_events_span(p: &CompactEventsSpanParams) -> tracing::Span {
297    use tracing::field::Empty;
298    let span = tracing::info_span!(
299        "compact_events",
300        otel.name = %format!("{COMPACT_EVENTS} {}", p.trigger),
301        gen_ai.operation.name = COMPACT_EVENTS,
302        gen_ai.conversation.id = p.session_id.as_str(),
303        gen_ai.compaction.trigger = p.trigger,
304        gen_ai.compaction.summarizer_type = p.summarizer_type.as_str(),
305        gen_ai.compaction.event_count = u64::try_from(p.event_count).unwrap_or(u64::MAX),
306        gcp.vertex.agent.invocation_id = Empty,
307        gen_ai.system = Empty,
308        gen_ai.compaction.compaction_interval = Empty,
309        gen_ai.compaction.overlap_size = Empty,
310        gen_ai.compaction.token_threshold = Empty,
311        gen_ai.compaction.event_retention_size = Empty,
312        gen_ai.compaction.declined = Empty,
313        gen_ai.compaction.result_event_id = Empty,
314        gen_ai.compaction.start_timestamp = Empty,
315        gen_ai.compaction.end_timestamp = Empty,
316        gen_ai.usage.input_tokens = Empty,
317        gen_ai.usage.output_tokens = Empty,
318        error.type = Empty,
319        otel.status_code = Empty,
320        error.message = Empty
321    );
322    if !p.invocation_id.is_empty() {
323        span.record("gcp.vertex.agent.invocation_id", p.invocation_id.as_str());
324    }
325    if let Some(sys) = gen_ai_system(p.backend) {
326        span.record("gen_ai.system", sys);
327    }
328    if p.compaction_interval > 0 {
329        span.record(
330            "gen_ai.compaction.compaction_interval",
331            i64::from(p.compaction_interval),
332        );
333        span.record("gen_ai.compaction.overlap_size", i64::from(p.overlap_size));
334    }
335    if p.token_threshold > 0 {
336        span.record(
337            "gen_ai.compaction.token_threshold",
338            i64::from(p.token_threshold),
339        );
340        span.record(
341            "gen_ai.compaction.event_retention_size",
342            i64::from(p.event_retention_size),
343        );
344    }
345    span
346}
347
348/// The outcome of a compaction, recorded by [`trace_compaction_result`].
349pub(crate) struct CompactionResultParams<'a> {
350    pub(crate) result_event: Option<&'a Event>,
351    pub(crate) error: Option<&'a (dyn std::error::Error + 'static)>,
352    pub(crate) discard_reason: &'a str,
353    pub(crate) declined: bool,
354    pub(crate) usage: Option<&'a GenerateContentResponseUsageMetadata>,
355}
356
357/// Records an error known only by its text on `span`.
358pub(crate) fn record_span_error(span: &tracing::Span, err: &dyn std::fmt::Display) {
359    attrs::record_error(span, Some(&SpanError::text(err.to_string())));
360}
361
362/// Records a compaction's outcome on its span: any error, the decline reason, the usage and the
363/// result event's range.
364pub(crate) fn trace_compaction_result(span: &tracing::Span, p: CompactionResultParams<'_>) {
365    if let Some(e) = p.error {
366        attrs::record_error(span, Some(&SpanError::new(e)));
367    }
368    if p.declined && p.discard_reason.is_empty() {
369        span.record(
370            "gen_ai.compaction.declined",
371            "the summarizer returned no content",
372        );
373    }
374    if !p.discard_reason.is_empty() {
375        span.record("gen_ai.compaction.declined", p.discard_reason);
376    }
377    // Usage before anything conditional: the spend is not conditional on success.
378    if let Some(u) = p.usage {
379        record_compaction_usage(span, u);
380    }
381    if p.error.is_some() {
382        return;
383    }
384    let Some(ev) = p.result_event else { return };
385    let Some(rng) = &ev.actions.compaction else {
386        return;
387    };
388    if let Some(u) = &ev.response.usage_metadata {
389        record_compaction_usage(span, u);
390    }
391    span.record("gen_ai.compaction.result_event_id", ev.id.as_str());
392    // A zero time means "no bound recorded": omit the key rather than report the year 1754.
393    if rng.start_timestamp != zero_time() {
394        span.record(
395            "gen_ai.compaction.start_timestamp",
396            epoch_seconds(rng.start_timestamp),
397        );
398    }
399    if rng.end_timestamp != zero_time() {
400        span.record(
401            "gen_ai.compaction.end_timestamp",
402            epoch_seconds(rng.end_timestamp),
403        );
404    }
405}
406
407/// A closed span with the same attributes plus the reason.
408pub(crate) fn trace_compaction_declined(p: &CompactEventsSpanParams, reason: &str) {
409    let span = compact_events_span(p);
410    span.record("gen_ai.compaction.declined", reason);
411}
412
413/// Records the compaction's token usage: output tokens include thoughts, per semconv.
414fn record_compaction_usage(span: &tracing::Span, u: &GenerateContentResponseUsageMetadata) {
415    if u.prompt_token_count > 0 {
416        span.record("gen_ai.usage.input_tokens", i64::from(u.prompt_token_count));
417    }
418    let out = i64::from(u.candidates_token_count) + i64::from(u.thoughts_token_count);
419    if out > 0 {
420        span.record("gen_ai.usage.output_tokens", out);
421    }
422}
423
424#[cfg(test)]
425#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
426mod tests {
427    use super::*;
428    use parking_lot::Mutex;
429    use std::collections::BTreeMap;
430    use std::sync::Arc;
431    use tracing::field::{Field, Visit};
432    use tracing::span::{Attributes, Id};
433    use tracing_subscriber::layer::{Context as LayerContext, Layer, SubscriberExt};
434
435    type Captured = Arc<Mutex<Vec<(String, BTreeMap<String, String>)>>>;
436
437    struct Capture(Captured);
438    struct Fields(BTreeMap<String, String>);
439    impl Visit for Fields {
440        fn record_str(&mut self, f: &Field, v: &str) {
441            self.0.insert(f.name().to_string(), v.to_string());
442        }
443        fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
444            self.0.insert(f.name().to_string(), format!("{v:?}"));
445        }
446    }
447    impl<S: tracing::Subscriber> Layer<S> for Capture {
448        fn on_new_span(&self, attrs: &Attributes<'_>, _id: &Id, _ctx: LayerContext<'_, S>) {
449            let mut f = Fields(BTreeMap::new());
450            attrs.record(&mut f);
451            self.0
452                .lock()
453                .push((attrs.metadata().name().to_string(), f.0));
454        }
455    }
456
457    fn capture(f: impl FnOnce()) -> Vec<(String, BTreeMap<String, String>)> {
458        crate::llm::flow::span_capture::pin_tracing_interest();
459        let captured: Captured = Arc::default();
460        let sub = tracing_subscriber::registry().with(Capture(captured.clone()));
461        tracing::subscriber::with_default(sub, f);
462        captured.lock().clone()
463    }
464
465    #[test]
466    fn spans_helper_agent() {
467        let spans = capture(|| {
468            let _s = agent_span("weather");
469        });
470        assert_eq!(spans.len(), 1);
471        assert_eq!(spans[0].0, "invoke_agent");
472        assert_eq!(spans[0].1["otel.name"], "invoke_agent weather");
473        assert_eq!(spans[0].1["gen_ai.operation.name"], "invoke_agent");
474        assert_eq!(spans[0].1["gen_ai.agent.name"], "weather");
475    }
476
477    #[test]
478    fn spans_helper_workflow_node_model_tool() {
479        let spans = capture(|| {
480            let _a = workflow_span("wf", "sess");
481            let _b = node_span("step", "sess");
482            let _c = generate_content_span("gemini-2.5-flash", "inv");
483            let _d = execute_tool_span("get_weather");
484            let _e = merged_tool_calls_span();
485        });
486        let names: Vec<_> = spans.iter().map(|s| s.0.as_str()).collect();
487        assert_eq!(
488            names,
489            [
490                "invoke_workflow",
491                "invoke_node",
492                "generate_content",
493                "execute_tool",
494                "execute_tool"
495            ]
496        );
497        assert_eq!(spans[0].1["otel.name"], "invoke_workflow wf");
498        assert_eq!(spans[0].1["gen_ai.workflow.name"], "wf");
499        assert_eq!(spans[0].1["gen_ai.conversation.id"], "sess");
500        assert_eq!(spans[1].1["otel.name"], "invoke_node step");
501        assert_eq!(spans[1].1["gen_ai.node.name"], "step");
502        assert_eq!(spans[1].1["gen_ai.conversation.id"], "sess");
503        assert_eq!(spans[2].1["otel.name"], "generate_content gemini-2.5-flash");
504        assert_eq!(spans[2].1["gen_ai.request.model"], "gemini-2.5-flash");
505        assert_eq!(spans[2].1["gcp.vertex.agent.invocation_id"], "inv");
506        assert_eq!(spans[3].1["otel.name"], "execute_tool get_weather");
507        assert_eq!(spans[3].1["gen_ai.tool.name"], "get_weather");
508        assert_eq!(spans[4].1["otel.name"], "execute_tool (merged)");
509        assert_eq!(spans[4].1.len(), 1, "{:?}", spans[4].1);
510        // Empty fields are declared but not visited at creation.
511        assert!(!spans[1].1.contains_key("otel.status_code"));
512        assert!(!spans[0].1.contains_key("gen_ai.workflow.nested"));
513    }
514
515    #[test]
516    fn spans_helpers_declare_status_fields() {
517        let mut declared = Vec::new();
518        let _ = capture(|| {
519            for s in [
520                workflow_span("w", "s"),
521                node_span("n", "s"),
522                generate_content_span("m", ""),
523                execute_tool_span("t"),
524                merged_tool_calls_span(),
525            ] {
526                let m = s
527                    .metadata()
528                    .expect("span enabled under the capture subscriber");
529                declared.push((
530                    m.name(),
531                    m.fields().field("otel.status_code").is_some(),
532                    m.fields().field("error.message").is_some(),
533                    m.fields().field("error.type").is_some(),
534                ));
535            }
536        });
537        assert_eq!(
538            declared,
539            [
540                ("invoke_workflow", true, true, true),
541                ("invoke_node", true, true, true),
542                ("generate_content", true, true, true),
543                ("execute_tool", true, true, true),
544                ("execute_tool", true, true, true)
545            ]
546        );
547    }
548
549    #[tokio::test]
550    async fn compact_events_span_records_go_attributes() {
551        use crate::llm::flow::span_capture::capture_spans;
552        let ((), spans) = capture_spans(async {
553            let parent = tracing::info_span!("invoke_workflow");
554            let _g = parent.enter();
555            let span = compact_events_span(&CompactEventsSpanParams {
556                trigger: COMPACTION_TRIGGER_SLIDING_WINDOW,
557                session_id: "sess".into(),
558                invocation_id: "inv2".into(),
559                summarizer_type: "fakeSummarizer".into(),
560                backend: Some(gadk_model::Backend::VertexAi),
561                event_count: 4,
562                compaction_interval: 2,
563                overlap_size: 1,
564                ..Default::default()
565            });
566            trace_compaction_declined(
567                &CompactEventsSpanParams {
568                    trigger: COMPACTION_TRIGGER_TOKEN_THRESHOLD,
569                    token_threshold: 10,
570                    event_retention_size: 50,
571                    ..Default::default()
572                },
573                "no compactable window past the retained tail",
574            );
575            drop(span);
576        })
577        .await;
578        let c: Vec<_> = spans
579            .iter()
580            .filter(|s| s.name == "compact_events")
581            .collect();
582        assert_eq!(c.len(), 2);
583        assert_eq!(c[0].otel_name, "compact_events sliding_window");
584        assert_eq!(c[0].parent.as_deref(), Some("invoke_workflow"));
585        for (k, v) in [
586            ("gen_ai.operation.name", "compact_events"),
587            ("gen_ai.conversation.id", "sess"),
588            ("gen_ai.compaction.trigger", "sliding_window"),
589            ("gen_ai.compaction.summarizer_type", "fakeSummarizer"),
590            ("gen_ai.compaction.event_count", "4"),
591            ("gcp.vertex.agent.invocation_id", "inv2"),
592            ("gen_ai.system", "gcp.vertex_ai"),
593            ("gen_ai.compaction.compaction_interval", "2"),
594            ("gen_ai.compaction.overlap_size", "1"),
595        ] {
596            assert_eq!(c[0].field(k).as_deref(), Some(v), "{k}");
597        }
598        assert!(c[0].field("gen_ai.compaction.token_threshold").is_none());
599        assert!(c[0].closed);
600        assert_eq!(c[1].otel_name, "compact_events token_threshold");
601        assert_eq!(
602            c[1].field("gen_ai.compaction.token_threshold").as_deref(),
603            Some("10")
604        );
605        assert_eq!(
606            c[1].field("gen_ai.compaction.event_retention_size")
607                .as_deref(),
608            Some("50")
609        );
610        assert_eq!(
611            c[1].field("gen_ai.compaction.event_count").as_deref(),
612            Some("0")
613        );
614        assert!(c[1].field("gcp.vertex.agent.invocation_id").is_none());
615        assert!(c[1].field("gen_ai.system").is_none());
616        assert_eq!(
617            c[1].field("gen_ai.compaction.declined").as_deref(),
618            Some("no compactable window past the retained tail")
619        );
620        assert!(c[1].closed);
621    }
622
623    #[test]
624    fn epoch_seconds_matches_go_and_gen_ai_system_matches_semconv() {
625        let t = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:01.5Z")
626            .unwrap()
627            .with_timezone(&chrono::Utc);
628        assert_eq!(epoch_seconds(t), 1_767_225_601.5);
629        assert_eq!(
630            gen_ai_system(Some(gadk_model::Backend::GeminiApi)),
631            Some("gcp.gemini")
632        );
633        assert_eq!(
634            gen_ai_system(Some(gadk_model::Backend::VertexAi)),
635            Some("gcp.vertex_ai")
636        );
637        assert_eq!(gen_ai_system(None), None);
638    }
639
640    #[tokio::test]
641    async fn trace_compaction_result_records_error_usage_and_result() {
642        use crate::llm::flow::span_capture::capture_spans;
643        use gadk_genai::GenerateContentResponseUsageMetadata as Usage;
644        let ((), spans) = capture_spans(async {
645            let p = CompactEventsSpanParams {
646                trigger: COMPACTION_TRIGGER_SLIDING_WINDOW,
647                ..Default::default()
648            };
649            let failed = compact_events_span(&p);
650            let err = std::io::Error::other("boom");
651            let usage = Usage {
652                prompt_token_count: 4000,
653                candidates_token_count: 8,
654                ..Default::default()
655            };
656            trace_compaction_result(
657                &failed,
658                CompactionResultParams {
659                    result_event: None,
660                    error: Some(&err),
661                    discard_reason: "",
662                    declined: false,
663                    usage: Some(&usage),
664                },
665            );
666            drop(failed);
667            let ok = compact_events_span(&p);
668            let mut ev = gadk_session::Event {
669                id: "sum-1".into(),
670                ..Default::default()
671            };
672            ev.actions.compaction = Some(gadk_session::EventCompaction {
673                start_timestamp: gadk_session::zero_time(),
674                end_timestamp: chrono::DateTime::from_timestamp(1_767_225_604, 0).unwrap(),
675                compacted_content: None,
676                excluded_events: vec![],
677            });
678            trace_compaction_result(
679                &ok,
680                CompactionResultParams {
681                    result_event: Some(&ev),
682                    error: None,
683                    discard_reason: "",
684                    declined: false,
685                    usage: None,
686                },
687            );
688        })
689        .await;
690        let c: Vec<_> = spans
691            .iter()
692            .filter(|s| s.name == "compact_events")
693            .collect();
694        assert_eq!(c[0].field("otel.status_code").as_deref(), Some("ERROR"));
695        assert_eq!(c[0].field("error.message").as_deref(), Some("boom"));
696        assert_eq!(
697            c[0].field("otel.status_description").as_deref(),
698            Some("boom")
699        );
700        assert_eq!(
701            c[0].field("gen_ai.usage.input_tokens").as_deref(),
702            Some("4000")
703        );
704        assert_eq!(
705            c[0].field("gen_ai.usage.output_tokens").as_deref(),
706            Some("8")
707        );
708        assert!(c[0].field("gen_ai.compaction.result_event_id").is_none());
709        assert_eq!(
710            c[1].field("gen_ai.compaction.result_event_id").as_deref(),
711            Some("sum-1")
712        );
713        assert!(c[1].field("gen_ai.compaction.start_timestamp").is_none());
714        assert_eq!(
715            c[1].field("gen_ai.compaction.end_timestamp")
716                .unwrap()
717                .parse::<f64>()
718                .unwrap(),
719            1_767_225_604.0
720        );
721        assert!(c[1].field("otel.status_code").is_none());
722    }
723
724    /// The model and tool spans of one LLM turn, digested: Go's attribute set on each (the
725    /// wire-probe's `debug_trace` view of a successful turn and a failed call), and the
726    /// inference-details record under the model span.
727    #[tokio::test]
728    async fn engine_spans_carry_go_attributes() {
729        use crate::telemetry::span_digest::{build_digest, capture};
730        use gadk_agent::InvocationContext;
731        use gadk_genai::{Content, FinishReason, Part};
732        use gadk_model::{LlmRequest, LlmResponse, ModelError};
733        use serde_json::json;
734
735        let _env = env::test_env(&[]);
736        let ok = LlmResponse {
737            content: Some(Content {
738                role: "model".into(),
739                parts: vec![Part {
740                    text: "hi".into(),
741                    ..Default::default()
742                }],
743            }),
744            usage_metadata: Some(GenerateContentResponseUsageMetadata {
745                prompt_token_count: 10,
746                candidates_token_count: 5,
747                ..Default::default()
748            }),
749            finish_reason: Some(FinishReason::Stop),
750            ..Default::default()
751        };
752        let model =
753            crate::testutil::MockModel::new(vec![Ok(ok), Err(ModelError::Other("boom".into()))]);
754        let ctx = InvocationContext::builder()
755            .invocation_id("inv")
756            .build_invocation();
757        let (ids, spans, logs) = capture(async {
758            let root = workflow_span("root", "sess");
759            let _g = root.enter();
760            let mut ids = Vec::new();
761            for _ in 0..2 {
762                let mut s = crate::llm::flow::generate_content(
763                    &ctx,
764                    model.clone(),
765                    LlmRequest::default(),
766                    false,
767                );
768                while let Some((_, id)) = futures::StreamExt::next(&mut s).await {
769                    ids.push(id);
770                }
771            }
772            ids
773        })
774        .await;
775        assert_eq!(ids.len(), 2);
776        // The success span's event ID is the one reserved for its response.
777        let event_id = spans[1]
778            .attributes
779            .iter()
780            .find(|(k, _)| k == "gcp.vertex.agent.event_id")
781            .map(|(_, v)| v.clone());
782        assert_eq!(event_id, Some(json!(ids[0])));
783        let d = build_digest(&spans, &logs).unwrap();
784        let ok_attrs = json!({
785            "gcp.vertex.agent.event_id": "PRESENT",
786            "gcp.vertex.agent.invocation_id": "PRESENT",
787            "gen_ai.operation.name": "generate_content",
788            "gen_ai.request.model": "mock",
789            "gen_ai.response.finish_reasons": ["stop"],
790            "gen_ai.usage.cache_read.input_tokens": 0,
791            "gen_ai.usage.input_tokens": 10,
792            "gen_ai.usage.output_tokens": 5,
793            "gen_ai.usage.reasoning.output_tokens": 0
794        });
795        let failed_attrs = json!({
796            "error.type": "*errors.errorString",
797            "gcp.vertex.agent.invocation_id": "PRESENT",
798            "gen_ai.operation.name": "generate_content",
799            "gen_ai.request.model": "mock",
800            "gen_ai.response.finish_reasons": ["error"]
801        });
802        assert_eq!(
803            serde_json::to_value(&d).unwrap(),
804            json!({"root_span": {
805                "name": "invoke_workflow root",
806                "attributes": {
807                    "gen_ai.conversation.id": "PRESENT",
808                    "gen_ai.operation.name": "invoke_workflow",
809                    "gen_ai.workflow.name": "root"
810                },
811                "status": "UNSET",
812                "children": [
813                    {
814                        "name": "generate_content mock",
815                        "attributes": ok_attrs.clone(),
816                        "status": "UNSET",
817                        "children": [],
818                        "logs": [{
819                            "event_name": "gen_ai.client.inference.operation.details",
820                            "body": null,
821                            "attributes": ok_attrs
822                        }]
823                    },
824                    {
825                        "name": "generate_content mock",
826                        "attributes": failed_attrs.clone(),
827                        "status": "ERROR",
828                        "children": [],
829                        "logs": [{
830                            "event_name": "gen_ai.client.inference.operation.details",
831                            "body": null,
832                            "attributes": failed_attrs
833                        }]
834                    }
835                ],
836                "logs": []
837            }})
838        );
839    }
840}
841
842#[cfg(test)]
843#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
844mod span_ids_tests {
845    use tracing::span::{Attributes, Id};
846    use tracing_subscriber::layer::{Context, Layer, SubscriberExt};
847    use tracing_subscriber::registry::LookupSpan;
848
849    use super::current_span_ids;
850    use super::d6::SpanIds;
851
852    /// Leaves [`SpanIds`] on every span named `with_ids`, the way gadk-telemetry's bridge does
853    /// on the spans it exports; the span ID's last byte counts the spans it tagged.
854    #[derive(Default)]
855    struct Tagger(std::sync::atomic::AtomicU8);
856
857    impl<S> Layer<S> for Tagger
858    where
859        S: tracing::Subscriber + for<'a> LookupSpan<'a>,
860    {
861        fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
862            if attrs.metadata().name() != "with_ids" {
863                return;
864            }
865            let n = self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
866            if let Some(span) = ctx.span(id) {
867                span.extensions_mut().insert(ids(n));
868            }
869        }
870    }
871
872    fn ids(n: u8) -> SpanIds {
873        SpanIds {
874            trace_id: [7; 16],
875            span_id: [0, 0, 0, 0, 0, 0, 0, n],
876        }
877    }
878
879    fn with_tagger(f: impl FnOnce()) {
880        let sub = tracing_subscriber::registry().with(Tagger::default());
881        tracing::subscriber::with_default(sub, f);
882    }
883
884    #[test]
885    fn none_outside_any_span_and_without_ids() {
886        with_tagger(|| {
887            assert_eq!(current_span_ids(), None);
888            let _plain = tracing::info_span!("plain").entered();
889            assert_eq!(current_span_ids(), None);
890        });
891    }
892
893    #[test]
894    fn the_nearest_enclosing_span_with_ids_wins() {
895        with_tagger(|| {
896            let outer = tracing::info_span!("with_ids").entered();
897            assert_eq!(current_span_ids(), Some(ids(1)));
898            let plain = tracing::info_span!("plain").entered();
899            assert_eq!(
900                current_span_ids(),
901                Some(ids(1)),
902                "an untagged child inherits"
903            );
904            let inner = tracing::info_span!("with_ids").entered();
905            assert_eq!(current_span_ids(), Some(ids(2)));
906            drop(inner);
907            assert_eq!(current_span_ids(), Some(ids(1)));
908            drop(plain);
909            drop(outer);
910            assert_eq!(current_span_ids(), None);
911        });
912    }
913
914    #[test]
915    fn none_under_a_subscriber_without_a_registry() {
916        let sub = tracing::subscriber::NoSubscriber::default();
917        tracing::subscriber::with_default(sub, || {
918            let _span = tracing::info_span!("with_ids").entered();
919            assert_eq!(current_span_ids(), None);
920        });
921    }
922}