Skip to main content

nitpicker_agent/
telemetry.rs

1//! Span contract shared by every instrumented seam in this crate.
2//!
3//! Spans are plain `tracing` spans, so any subscriber can consume them; the field names follow
4//! the OpenTelemetry GenAI semantic conventions (`gen_ai.*`) plus `nitpicker.*` for
5//! harness-specific attributes, and `otel.name` / `otel.kind` / `otel.status_code` are the
6//! `tracing-opentelemetry` conventions for span name, kind, and status. Only identifiers,
7//! counts, and timings are recorded — never prompts, tool arguments, tool output, or provider
8//! error text — so exporting every span is safe by construction.
9
10use crate::llm::FinishReason;
11use crate::tools::floor_char_boundary;
12
13/// Upper bound on any exported string attribute (model ids, agent names, tool names).
14const MAX_ATTR_CHARS: usize = 128;
15
16/// Truncate an identifier to `MAX_ATTR_CHARS` bytes on a char boundary. Every string that
17/// becomes a span attribute passes through here so a pathological config value stays bounded.
18pub fn bounded(s: &str) -> &str {
19    &s[..floor_char_boundary(s, MAX_ATTR_CHARS)]
20}
21
22/// Constant vocabulary for `gen_ai.response.finish_reasons`; `Other` carries the provider's
23/// own (bounded) label.
24pub(crate) fn finish_reason_label(reason: &FinishReason) -> &str {
25    match reason {
26        FinishReason::None => "none",
27        FinishReason::Stop => "stop",
28        FinishReason::MaxTokens => "length",
29        FinishReason::ToolUse => "tool_calls",
30        FinishReason::Other(label) => bounded(label),
31    }
32}
33
34#[cfg(test)]
35pub(crate) mod capture {
36    //! A test layer that records every span's name, parent, and fields so tests can assert
37    //! the exported tree without a real exporter.
38    //!
39    //! One global subscriber is installed once per test binary and forwards to whichever
40    //! `SpanCapture` the current thread has activated. Scoped per-test dispatchers are not an
41    //! option: `tracing-core` recomputes its global callsite-interest and max-level caches
42    //! whenever a scoped dispatcher registers or unregisters, and a span created on another
43    //! thread during that window is silently disabled.
44    use std::cell::RefCell;
45    use std::collections::BTreeMap;
46    use std::fmt::Debug;
47    use std::sync::{Arc, Mutex, Once};
48
49    use tracing::Subscriber;
50    use tracing::field::{Field, Visit};
51    use tracing::span::{Attributes, Id, Record};
52    use tracing_subscriber::layer::{Context, Layer, SubscriberExt};
53    use tracing_subscriber::registry::LookupSpan;
54
55    #[derive(Clone, Debug)]
56    pub struct CapturedSpan {
57        pub id: u64,
58        pub parent: Option<u64>,
59        pub name: &'static str,
60        pub fields: BTreeMap<String, String>,
61    }
62
63    impl CapturedSpan {
64        pub fn field(&self, name: &str) -> Option<&str> {
65            self.fields.get(name).map(String::as_str)
66        }
67    }
68
69    #[derive(Clone, Default)]
70    pub struct SpanCapture {
71        spans: Arc<Mutex<Vec<CapturedSpan>>>,
72    }
73
74    thread_local! {
75        static ACTIVE: RefCell<Option<SpanCapture>> = const { RefCell::new(None) };
76    }
77
78    /// Routes this thread's spans into `capture` until dropped.
79    pub struct ActiveCapture(());
80
81    impl Drop for ActiveCapture {
82        fn drop(&mut self) {
83            ACTIVE.with(|active| *active.borrow_mut() = None);
84        }
85    }
86
87    impl SpanCapture {
88        pub fn activate(&self) -> ActiveCapture {
89            static INSTALL: Once = Once::new();
90            INSTALL.call_once(|| {
91                let _ = tracing::subscriber::set_global_default(
92                    tracing_subscriber::registry().with(Forwarder),
93                );
94            });
95            ACTIVE.with(|active| *active.borrow_mut() = Some(self.clone()));
96            ActiveCapture(())
97        }
98
99        pub fn spans(&self) -> Vec<CapturedSpan> {
100            self.spans.lock().unwrap_or_else(|e| e.into_inner()).clone()
101        }
102
103        /// Fail if `secret` appears in any captured span name or field value.
104        pub fn assert_no_secret(&self, secret: &str) {
105            for span in self.spans() {
106                assert!(
107                    !span.name.contains(secret),
108                    "span name leaks: {}",
109                    span.name
110                );
111                for (key, value) in &span.fields {
112                    assert!(
113                        !value.contains(secret),
114                        "{}.{key} leaks: {value}",
115                        span.name
116                    );
117                }
118            }
119        }
120
121        pub fn named(&self, name: &str) -> Vec<CapturedSpan> {
122            self.spans()
123                .into_iter()
124                .filter(|s| s.name == name)
125                .collect()
126        }
127
128        fn push(&self, span: CapturedSpan) {
129            self.spans
130                .lock()
131                .unwrap_or_else(|e| e.into_inner())
132                .push(span);
133        }
134
135        fn record(&self, id: u64, values: &Record<'_>) {
136            let mut spans = self.spans.lock().unwrap_or_else(|e| e.into_inner());
137            if let Some(span) = spans.iter_mut().find(|s| s.id == id) {
138                values.record(&mut FieldVisitor(&mut span.fields));
139            }
140        }
141    }
142
143    struct FieldVisitor<'a>(&'a mut BTreeMap<String, String>);
144
145    impl Visit for FieldVisitor<'_> {
146        fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
147            self.0
148                .insert(field.name().to_string(), format!("{value:?}"));
149        }
150        fn record_str(&mut self, field: &Field, value: &str) {
151            self.0.insert(field.name().to_string(), value.to_string());
152        }
153        fn record_u64(&mut self, field: &Field, value: u64) {
154            self.0.insert(field.name().to_string(), value.to_string());
155        }
156        fn record_i64(&mut self, field: &Field, value: i64) {
157            self.0.insert(field.name().to_string(), value.to_string());
158        }
159        fn record_bool(&mut self, field: &Field, value: bool) {
160            self.0.insert(field.name().to_string(), value.to_string());
161        }
162    }
163
164    struct Forwarder;
165
166    impl<S: Subscriber + for<'a> LookupSpan<'a>> Layer<S> for Forwarder {
167        fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
168            let Some(capture) = ACTIVE.with(|active| active.borrow().clone()) else {
169                return;
170            };
171            let parent = ctx
172                .span(id)
173                .and_then(|span| span.parent().map(|p| p.id().into_u64()));
174            let mut fields = BTreeMap::new();
175            attrs.record(&mut FieldVisitor(&mut fields));
176            capture.push(CapturedSpan {
177                id: id.into_u64(),
178                parent,
179                name: attrs.metadata().name(),
180                fields,
181            });
182        }
183
184        fn on_record(&self, id: &Id, values: &Record<'_>, _ctx: Context<'_, S>) {
185            if let Some(capture) = ACTIVE.with(|active| active.borrow().clone()) {
186                capture.record(id.into_u64(), values);
187            }
188        }
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn bounded_cuts_on_a_char_boundary() {
198        let short = "gpt-5";
199        assert_eq!(bounded(short), short);
200        let long = "é".repeat(MAX_ATTR_CHARS);
201        let cut = bounded(&long);
202        assert!(cut.len() <= MAX_ATTR_CHARS);
203        assert_eq!(cut, "é".repeat(MAX_ATTR_CHARS / 2));
204    }
205
206    #[test]
207    fn finish_reason_labels_are_constant_except_other() {
208        assert_eq!(finish_reason_label(&FinishReason::Stop), "stop");
209        assert_eq!(finish_reason_label(&FinishReason::MaxTokens), "length");
210        assert_eq!(finish_reason_label(&FinishReason::ToolUse), "tool_calls");
211        assert_eq!(finish_reason_label(&FinishReason::None), "none");
212        assert_eq!(
213            finish_reason_label(&FinishReason::Other("content_filter".to_string())),
214            "content_filter"
215        );
216    }
217}