troupekit-trace 0.4.0

Zero-dependency trace spans, sinks and viewers for the Troupekit LLM agent framework.
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use super::parse::Json;
use crate::category::Trace;
use crate::value::cut_to;
use std::collections::HashMap;

const KEY_BYTES_MAX: usize = 64;
const NAME_BYTES_MAX: usize = 128;
const TEXT_BYTES_MAX: usize = 16 * 1024;
const FIELDS_PER_RECORD_MAX: usize = 32;
const NODE_BYTES: u64 = 192;
const FIELD_BYTES: u64 = 48;

/// A field value read back from a trace file.
/// `Withheld` is content written only as its byte count; `Other` stands
/// for an array or object, which the writer never produces.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum FieldValue {
    Str(String),
    Int(i64),
    UInt(u64),
    Float(f64),
    Bool(bool),
    Null,
    Withheld(u64),
    Other,
}

/// Whether a node is a span with a duration or a point event.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeKind {
    Span,
    Event,
}

/// One span or event of a `SpanTree`, with its children in start order.
/// Input: built by `read_jsonl`. Output: getters only.
#[derive(Clone, Debug)]
pub struct Node {
    kind: NodeKind,
    category: Trace,
    name: String,
    span: u64,
    parent: u64,
    start_us: u64,
    end_us: Option<u64>,
    dur_us: Option<u64>,
    ok: Option<bool>,
    err: Option<String>,
    fields: Vec<(String, FieldValue)>,
    children: Vec<usize>,
}

impl Node {
    /// Returns span or event. Input: none.
    pub fn kind(&self) -> NodeKind {
        self.kind
    }

    /// Returns the category. Input: none.
    pub fn category(&self) -> Trace {
        self.category
    }

    /// Returns the span or event name. Input: none.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the span id, 0 for an event. Input: none.
    pub fn span_id(&self) -> u64 {
        self.span
    }

    /// Returns the parent span id, 0 at the root. Input: none.
    pub fn parent_id(&self) -> u64 {
        self.parent
    }

    /// Returns the start time in microseconds since the Unix epoch.
    pub fn start_us(&self) -> u64 {
        self.start_us
    }

    /// Returns the end time, `None` for an event or an open span.
    pub fn end_us(&self) -> Option<u64> {
        self.end_us
    }

    /// Returns the duration in microseconds when the span ended.
    pub fn dur_us(&self) -> Option<u64> {
        self.dur_us
    }

    /// Returns whether the span ended without error; `None` while open.
    pub fn ok(&self) -> Option<bool> {
        self.ok
    }

    /// Returns the error text of a failed span. Input: none.
    pub fn err(&self) -> Option<&str> {
        self.err.as_deref()
    }

    /// Returns the start fields followed by the end fields. Input: none.
    pub fn fields(&self) -> &[(String, FieldValue)] {
        &self.fields
    }

    /// Returns the last value written under `key`. Input: the key.
    pub fn field(&self, key: &str) -> Option<&FieldValue> {
        self.fields
            .iter()
            .rev()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v)
    }

    /// Returns the indexes of the children, in start order. Input: none.
    pub fn children(&self) -> &[usize] {
        &self.children
    }

    /// Returns whether this is a span whose end record never came.
    pub fn is_open(&self) -> bool {
        self.kind == NodeKind::Span && self.end_us.is_none()
    }
}

/// Every span and event of a trace file as a tree, plus counters for
/// every line or limit the reader refused. Input: built by `read_jsonl`.
/// Output: roots, nodes by index, per-category counts and the time range.
#[derive(Clone, Debug, Default)]
pub struct SpanTree {
    name: Option<String>,
    trace_id: Option<String>,
    nodes: Vec<Node>,
    roots: Vec<usize>,
    counts: [u64; Trace::ALL.len()],
    range_us: Option<(u64, u64)>,
    pub(super) bad_lines: u64,
    pub(super) oversized_lines: u64,
    pub(super) deep_lines: u64,
    pub(super) record_limit_hit: bool,
    pub(super) bytes_limit_hit: bool,
    pub(super) kept_bytes: u64,
    dropped_fields: u64,
    cut_values: u64,
    sessions: u64,
    unmatched_ends: u64,
    truncated: bool,
    footer: Option<(u64, u64)>,
    index: HashMap<(String, u64), usize>,
}

impl SpanTree {
    /// Returns the trace name from the header. Input: none.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns the trace id from the header, 16 hex characters.
    pub fn trace_id(&self) -> Option<&str> {
        self.trace_id.as_deref()
    }

    /// Returns the indexes of the root nodes, in start order.
    pub fn roots(&self) -> &[usize] {
        &self.roots
    }

    /// Returns the node at `index`, from `roots` or `Node::children`.
    /// Input: an index this tree gave out. Panics on any other index.
    pub fn node(&self, index: usize) -> &Node {
        &self.nodes[index]
    }

    /// Returns every node in file order. Input: none.
    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    /// Returns how many spans and events have category `t`.
    pub fn count(&self, t: Trace) -> u64 {
        self.counts[t.index()]
    }

    /// Returns the first and last timestamp in microseconds, if any node.
    pub fn time_range_us(&self) -> Option<(u64, u64)> {
        self.range_us
    }

    /// Returns how many lines were not valid records. Input: none.
    pub fn bad_lines(&self) -> u64 {
        self.bad_lines
    }

    /// Returns how many lines were longer than the line limit.
    pub fn oversized_lines(&self) -> u64 {
        self.oversized_lines
    }

    /// Returns how many lines nested deeper than the depth limit.
    pub fn deep_lines(&self) -> u64 {
        self.deep_lines
    }

    /// Returns whether reading stopped at the record limit.
    pub fn record_limit_hit(&self) -> bool {
        self.record_limit_hit
    }

    /// Returns whether reading stopped at the memory budget
    /// (`ViewLimits::with_bytes_max`). Input: none.
    pub fn bytes_limit_hit(&self) -> bool {
        self.bytes_limit_hit
    }

    /// Returns how many fields past 32 per record were dropped, and how
    /// many names, error texts and string values were cut to the writer's
    /// limits (64 bytes for keys, 16 KiB for text). Input: none.
    pub fn dropped_and_cut(&self) -> (u64, u64) {
        (self.dropped_fields, self.cut_values)
    }

    /// Returns how many trace sessions the file holds: a header with a
    /// new trace id starts one, so appended runs count separately.
    pub fn sessions(&self) -> u64 {
        self.sessions
    }

    /// Returns how many end records matched no start. Input: none.
    pub fn unmatched_ends(&self) -> u64 {
        self.unmatched_ends
    }

    /// Returns how many spans never ended. Input: none.
    pub fn open_spans(&self) -> u64 {
        self.nodes.iter().filter(|n| n.is_open()).count() as u64
    }

    /// Returns whether the writer stopped at its byte limit.
    pub fn truncated(&self) -> bool {
        self.truncated
    }

    /// Returns the dropped-field and cut-string counts summed over every
    /// footer, so sessions appended to one file add up; `None` without one.
    pub fn footer_counts(&self) -> Option<(u64, u64)> {
        self.footer
    }

    pub(super) fn apply(&mut self, record: Json) -> Result<(), ()> {
        let Json::Obj(fields) = record else {
            return Err(());
        };
        let rec = Record(&fields);
        match rec.str("t")? {
            "header" => {
                let name = rec.str("name")?;
                let trace = rec.str("trace")?;
                if self.trace_id.as_deref() != Some(cut_to(trace, NAME_BYTES_MAX)) {
                    self.sessions += 1;
                }
                self.name = Some(self.cut(name, NAME_BYTES_MAX));
                self.trace_id = Some(self.cut(trace, NAME_BYTES_MAX));
            }
            "start" => self.add(&rec, NodeKind::Span)?,
            "event" => self.add(&rec, NodeKind::Event)?,
            "end" => self.end(&rec)?,
            "truncated" => self.truncated = true,
            "footer" => {
                let (dropped, cut) = self.footer.unwrap_or((0, 0));
                let more = (rec.num("dropped")?, rec.num("truncated")?);
                self.footer = Some((dropped.saturating_add(more.0), cut.saturating_add(more.1)));
            }
            _ => return Err(()),
        }
        Ok(())
    }

    fn add(&mut self, rec: &Record<'_>, kind: NodeKind) -> Result<(), ()> {
        let trace = rec.str("trace")?;
        let span = rec.num("span")?;
        let parent = rec.num("parent")?;
        let category: Trace = rec.str("cat")?.parse().map_err(|_| ())?;
        let start_us = rec.num("ts_us")?;
        if kind == NodeKind::Span
            && (span == 0 || self.index.contains_key(&(trace.to_owned(), span)))
        {
            return Err(());
        }
        let name = rec.str("name")?;
        let index = self.nodes.len();
        let name = self.cut(name, TEXT_BYTES_MAX);
        let fields = self.fields(rec);
        self.kept_bytes = self.kept_bytes.saturating_add(NODE_BYTES);
        self.nodes.push(Node {
            kind,
            category,
            name,
            span,
            parent,
            start_us,
            end_us: None,
            dur_us: None,
            ok: None,
            err: None,
            fields,
            children: Vec::new(),
        });
        match self
            .index
            .get(&(trace.to_owned(), parent))
            .filter(|_| parent != 0)
        {
            Some(&up) => self.nodes[up].children.push(index),
            None => self.roots.push(index),
        }
        if kind == NodeKind::Span {
            self.index.insert((trace.to_owned(), span), index);
        }
        self.counts[category.index()] += 1;
        self.widen(start_us);
        Ok(())
    }

    fn end(&mut self, rec: &Record<'_>) -> Result<(), ()> {
        let key = (rec.str("trace")?.to_owned(), rec.num("span")?);
        let end_us = rec.num("ts_us")?;
        let dur_us = rec.num("dur_us")?;
        let ok = rec.bool("ok")?;
        let Some(&index) = self.index.get(&key) else {
            self.unmatched_ends += 1;
            return Ok(());
        };
        if self.nodes[index].end_us.is_some() {
            return Err(());
        }
        let err = rec.str("err").ok().map(|text| self.cut(text, TEXT_BYTES_MAX));
        let fields = self.fields(rec);
        let node = &mut self.nodes[index];
        node.end_us = Some(end_us);
        node.dur_us = Some(dur_us);
        node.ok = Some(ok);
        node.err = err;
        node.fields.extend(fields);
        self.widen(end_us);
        Ok(())
    }

    /// Copies `text` cut to `bytes_max` at a char boundary, counting the
    /// cut and the bytes kept. Input: the text and the limit. Output: the copy.
    fn cut(&mut self, text: &str, bytes_max: usize) -> String {
        let kept = cut_to(text, bytes_max);
        if kept.len() < text.len() {
            self.cut_values += 1;
        }
        self.kept_bytes = self.kept_bytes.saturating_add(kept.len() as u64);
        kept.to_owned()
    }

    /// Returns at most 32 fields of `rec`, keys and string values cut to the
    /// writer's limits, counting what was dropped or cut.
    /// Input: the record. Output: the fields to keep.
    fn fields(&mut self, rec: &Record<'_>) -> Vec<(String, FieldValue)> {
        let Some(Json::Obj(raw)) = rec.get("fields") else {
            return Vec::new();
        };
        let kept_count = raw.len().min(FIELDS_PER_RECORD_MAX);
        self.dropped_fields += (raw.len() - kept_count) as u64;
        let mut fields = Vec::with_capacity(kept_count);
        for (key, value) in &raw[..kept_count] {
            let key = self.cut(key, KEY_BYTES_MAX);
            let value = match value {
                Json::Str(text) => FieldValue::Str(self.cut(text, TEXT_BYTES_MAX)),
                other => field_value(other),
            };
            self.kept_bytes = self.kept_bytes.saturating_add(FIELD_BYTES);
            fields.push((key, value));
        }
        assert!(fields.len() <= FIELDS_PER_RECORD_MAX);
        fields
    }

    fn widen(&mut self, ts_us: u64) {
        let (first, last) = self.range_us.unwrap_or((ts_us, ts_us));
        self.range_us = Some((first.min(ts_us), last.max(ts_us)));
    }
}

struct Record<'a>(&'a [(String, Json)]);

impl Record<'_> {
    fn get(&self, key: &str) -> Option<&Json> {
        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
    }

    fn str(&self, key: &str) -> Result<&str, ()> {
        match self.get(key) {
            Some(Json::Str(text)) => Ok(text),
            _ => Err(()),
        }
    }

    fn num(&self, key: &str) -> Result<u64, ()> {
        match self.get(key) {
            Some(Json::UInt(n)) => Ok(*n),
            _ => Err(()),
        }
    }

    fn bool(&self, key: &str) -> Result<bool, ()> {
        match self.get(key) {
            Some(Json::Bool(b)) => Ok(*b),
            _ => Err(()),
        }
    }

}

fn field_value(value: &Json) -> FieldValue {
    match value {
        Json::Str(text) => FieldValue::Str(text.clone()),
        Json::Int(n) => FieldValue::Int(*n),
        Json::UInt(n) => FieldValue::UInt(*n),
        Json::Float(n) => FieldValue::Float(*n),
        Json::Bool(b) => FieldValue::Bool(*b),
        Json::Null => FieldValue::Null,
        Json::Obj(inner) => match inner.as_slice() {
            [(key, Json::UInt(bytes))] if key == "bytes" => FieldValue::Withheld(*bytes),
            _ => FieldValue::Other,
        },
        Json::Arr(_) => FieldValue::Other,
    }
}