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
437
438
439
440
441
use crate::record;
use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};

const MEMORY_CAPACITY_DEFAULT: usize = 100_000;
const MEMORY_BYTES_DEFAULT: usize = 64 * 1024 * 1024;
const MARKER_BYTES_MAX: u64 = 80;
const HEADER_LINE_BYTES_MAX: u64 = 64 * 1024;
const MAX_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
const FLUSH_EVERY_DEFAULT: u32 = 64;
const PATH_NAME_BYTES_MAX: usize = 64;

/// A destination for finished trace record lines.
/// Input: one JSON line per call, without a trailing newline.
/// A sink never returns an error and never panics through the caller.
pub trait TraceSink: Send + Sync {
    /// Takes one record line. Errors are counted by the sink, not returned.
    fn write(&self, line: &str);

    /// Pushes buffered lines to their destination. The default does nothing.
    /// Trace points made during a flush are suppressed, as during a write.
    fn flush(&self) {}
}

fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Settings for `JsonlSink`. Defaults: refuse an existing file, stop at
/// 256 MiB with one `truncated` record inside the limit, flush every 64
/// records.
/// Input: `with_*` setters. Output: passed to `JsonlSink::with_options`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct JsonlOptions {
    append: bool,
    max_bytes: u64,
    flush_every: u32,
}

impl Default for JsonlOptions {
    fn default() -> JsonlOptions {
        JsonlOptions {
            append: false,
            max_bytes: MAX_BYTES_DEFAULT,
            flush_every: FLUSH_EVERY_DEFAULT,
        }
    }
}

impl JsonlOptions {
    /// Appends to an existing file instead of refusing it. The file must be
    /// empty or start with a trace header line, and must not be a symlink;
    /// it is made private (mode 0600 on Unix) before the first write.
    /// A file already at or over the byte limit opens stopped: nothing more
    /// is written to it.
    /// Input: the flag. Output: the options.
    pub fn with_append(mut self, append: bool) -> JsonlOptions {
        self.append = append;
        self
    }

    /// Sets the byte limit of the file, the `truncated` record included.
    /// A limit too small for that record ends the file without it.
    /// Input: bytes. Output: the options.
    pub fn with_max_bytes(mut self, max_bytes: u64) -> JsonlOptions {
        self.max_bytes = max_bytes;
        self
    }

    /// Flushes after this many records, at least 1. Input: the count.
    /// Output: the options.
    pub fn with_flush_every(mut self, flush_every: u32) -> JsonlOptions {
        self.flush_every = flush_every.max(1);
        self
    }
}

struct JsonlState {
    out: BufWriter<File>,
    written: u64,
    pending: u32,
    stopped: bool,
}

/// Writes record lines to a private JSON lines file.
/// The file is created with mode 0600 and missing folders with 0700 on
/// Unix. I/O errors are counted, never returned to the traced run; a
/// failed record write stops the sink, since its bytes on disk are unknown.
pub struct JsonlSink {
    state: Mutex<JsonlState>,
    options: JsonlOptions,
    errors: AtomicU64,
    path: PathBuf,
}

impl JsonlSink {
    /// Creates `path` with the default options; an existing file is refused.
    /// Input: the file path. Output: the sink or the I/O error.
    pub fn create(path: impl AsRef<Path>) -> io::Result<JsonlSink> {
        JsonlSink::with_options(path, JsonlOptions::default())
    }

    /// Creates or, with `with_append(true)`, opens `path` for appending.
    /// Input: the file path and options. Output: the sink or the I/O error.
    pub fn with_options(path: impl AsRef<Path>, options: JsonlOptions) -> io::Result<JsonlSink> {
        let path = path.as_ref().to_path_buf();
        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
            create_private_dirs(parent)?;
        }
        let mut file = open_private(&path, options.append)?;
        let written = prepare_existing(&mut file)?;
        let state = JsonlState {
            out: BufWriter::new(file),
            written,
            pending: 0,
            stopped: written >= options.max_bytes,
        };
        Ok(JsonlSink {
            state: Mutex::new(state),
            options,
            errors: AtomicU64::new(0),
            path,
        })
    }

    /// Returns the file path. Input: none. Output: the path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Returns the number of I/O errors so far. Input: none. Output: the count.
    pub fn errors(&self) -> u64 {
        self.errors.load(Ordering::Relaxed)
    }

    /// Returns the bytes in the file, buffered lines included.
    /// Input: none. Output: the count.
    pub fn bytes_written(&self) -> u64 {
        locked(&self.state).written
    }

    fn count(&self, result: io::Result<()>) {
        if result.is_err() {
            self.errors.fetch_add(1, Ordering::Relaxed);
        }
    }
}

impl TraceSink for JsonlSink {
    fn write(&self, line: &str) {
        let mut state = locked(&self.state);
        if state.stopped {
            return;
        }
        let size = line.len() as u64 + 1;
        let reserved = state.written.saturating_add(MARKER_BYTES_MAX + 1);
        if reserved.saturating_add(size) > self.options.max_bytes {
            state.stopped = true;
            let marker = record::truncated_from(line);
            let marker_size = marker.len() as u64 + 1;
            assert!(marker_size <= MARKER_BYTES_MAX + 1);
            if state.written + marker_size <= self.options.max_bytes {
                let result = writeln!(state.out, "{marker}").and_then(|()| state.out.flush());
                if result.is_ok() {
                    state.written += marker_size;
                }
                self.count(result);
            }
            assert!(state.written <= self.options.max_bytes);
            return;
        }
        let result = writeln!(state.out, "{line}");
        if result.is_err() {
            state.stopped = true;
            self.count(result);
            return;
        }
        state.written += size;
        state.pending += 1;
        if state.pending >= self.options.flush_every {
            state.pending = 0;
            let result = state.out.flush();
            self.count(result);
        }
        assert!(state.written <= self.options.max_bytes);
    }

    fn flush(&self) {
        let mut state = locked(&self.state);
        state.pending = 0;
        let result = state.out.flush();
        self.count(result);
    }
}

impl Drop for JsonlSink {
    fn drop(&mut self) {
        TraceSink::flush(self);
    }
}

#[cfg(unix)]
fn create_private_dirs(dir: &Path) -> io::Result<()> {
    use std::os::unix::fs::DirBuilderExt;
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(dir)
}

#[cfg(not(unix))]
fn create_private_dirs(dir: &Path) -> io::Result<()> {
    std::fs::create_dir_all(dir)
}

fn open_private(path: &Path, append: bool) -> io::Result<File> {
    let mut options = OpenOptions::new();
    if append {
        let is_link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink());
        if is_link {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "trace file is a symlink",
            ));
        }
        options.read(true).append(true).create(true);
    } else {
        options.write(true).create_new(true);
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    options.open(path)
}

/// Checks a file opened for appending before the first write: an existing
/// file must start with a trace header line and is made private, and a
/// last line without its newline gets one, so no new record joins it.
/// Input: the open file. Output: its length after the fix, or the reason.
fn prepare_existing(file: &mut File) -> io::Result<u64> {
    let len = file.metadata()?.len();
    if len == 0 {
        return Ok(0);
    }
    let mut first = String::new();
    BufReader::new(Read::by_ref(file).take(HEADER_LINE_BYTES_MAX)).read_line(&mut first)?;
    if !(first.starts_with("{\"v\":") && first.contains(",\"t\":\"header\",")) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "existing file is not a trace",
        ));
    }
    make_private(file)?;
    file.seek(SeekFrom::Start(len - 1))?;
    let mut last = [0u8; 1];
    file.read_exact(&mut last)?;
    if last[0] == b'\n' {
        return Ok(len);
    }
    file.write_all(b"\n")?;
    Ok(len + 1)
}

#[cfg(unix)]
fn make_private(file: &File) -> io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mode = file.metadata()?.permissions().mode();
    if mode & 0o077 == 0 {
        return Ok(());
    }
    file.set_permissions(std::fs::Permissions::from_mode(mode & 0o700))
}

#[cfg(not(unix))]
fn make_private(_file: &File) -> io::Result<()> {
    Ok(())
}

/// Keeps the newest record lines in memory, dropping the oldest past its
/// capacity (default 100 000 lines) or its byte limit (default 64 MiB),
/// and counting what it dropped. Input: lines. Output: `lines()` copies
/// and `dropped()`.
pub struct MemorySink {
    lines: Mutex<MemoryLines>,
    capacity: usize,
    max_bytes: usize,
    dropped: AtomicU64,
}

struct MemoryLines {
    lines: VecDeque<String>,
    bytes: usize,
}

impl Default for MemorySink {
    fn default() -> MemorySink {
        MemorySink::new(MEMORY_CAPACITY_DEFAULT)
    }
}

impl MemorySink {
    /// Returns an empty sink holding at most `capacity` lines, at least 1.
    /// Input: the capacity. Output: the sink.
    pub fn new(capacity: usize) -> MemorySink {
        let capacity = capacity.max(1);
        MemorySink {
            lines: Mutex::new(MemoryLines {
                lines: VecDeque::new(),
                bytes: 0,
            }),
            capacity,
            max_bytes: MEMORY_BYTES_DEFAULT,
            dropped: AtomicU64::new(0),
        }
    }

    /// Sets the byte limit of the kept lines, at least 1. A line longer
    /// than the limit is dropped and counted. Input: bytes. Output: the sink.
    pub fn with_max_bytes(mut self, max_bytes: usize) -> MemorySink {
        self.max_bytes = max_bytes.max(1);
        self
    }

    /// Returns a copy of the kept lines, oldest first. Input: none.
    pub fn lines(&self) -> Vec<String> {
        locked(&self.lines).lines.iter().cloned().collect()
    }

    /// Returns how many lines were dropped. Input: none. Output: the count.
    pub fn dropped(&self) -> u64 {
        self.dropped.load(Ordering::Relaxed)
    }

    /// Returns the line capacity. Input: none. Output: the capacity.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns the byte limit. Input: none. Output: the limit.
    pub fn max_bytes(&self) -> usize {
        self.max_bytes
    }
}

impl TraceSink for MemorySink {
    fn write(&self, line: &str) {
        if line.len() > self.max_bytes {
            self.dropped.fetch_add(1, Ordering::Relaxed);
            return;
        }
        let mut kept = locked(&self.lines);
        while kept.lines.len() == self.capacity || kept.bytes + line.len() > self.max_bytes {
            let old = kept.lines.pop_front().expect("a line over the limit was refused");
            kept.bytes -= old.len();
            self.dropped.fetch_add(1, Ordering::Relaxed);
        }
        kept.bytes += line.len();
        kept.lines.push_back(line.to_owned());
        assert!(kept.lines.len() <= self.capacity);
        assert!(kept.bytes <= self.max_bytes);
    }
}

type Callback = Box<dyn Fn(&str) + Send + Sync>;

/// Hands every record line to a callback. A panic in the callback is
/// caught, counted and disables the sink, so it never fails the run.
/// Input: lines. Output: calls to the callback.
pub struct CallbackSink {
    callback: Callback,
    disabled: AtomicBool,
    panics: AtomicU64,
}

impl CallbackSink {
    /// Returns a sink that calls `callback` with each line.
    /// Input: the callback. Output: the sink.
    pub fn new(callback: impl Fn(&str) + Send + Sync + 'static) -> CallbackSink {
        CallbackSink {
            callback: Box::new(callback),
            disabled: AtomicBool::new(false),
            panics: AtomicU64::new(0),
        }
    }

    /// Returns how many times the callback panicked. Input: none.
    pub fn panics(&self) -> u64 {
        self.panics.load(Ordering::Relaxed)
    }

    /// Returns whether a panic disabled the sink. Input: none.
    pub fn is_disabled(&self) -> bool {
        self.disabled.load(Ordering::Relaxed)
    }
}

impl TraceSink for CallbackSink {
    fn write(&self, line: &str) {
        if self.is_disabled() {
            return;
        }
        if catch_unwind(AssertUnwindSafe(|| (self.callback)(line))).is_err() {
            self.disabled.store(true, Ordering::Relaxed);
            self.panics.fetch_add(1, Ordering::Relaxed);
        }
    }
}

/// Returns the default trace file path: `$TROUPEKIT_TRACE_DIR` or
/// `./traces`, file `<name>-<trace id>.jsonl`. Bytes of `name` outside
/// `[a-z0-9_-]` become `_`; the name is cut to 64 bytes, empty is `trace`.
pub fn default_trace_path(name: &str, trace_id: u64) -> PathBuf {
    let dir = std::env::var_os("TROUPEKIT_TRACE_DIR")
        .map_or_else(|| PathBuf::from("traces"), PathBuf::from);
    dir.join(format!("{}-{trace_id:016x}.jsonl", file_stem(name)))
}

fn file_stem(name: &str) -> String {
    if name.is_empty() {
        return "trace".to_owned();
    }
    let stem: String = name
        .bytes()
        .take(PATH_NAME_BYTES_MAX)
        .map(|b| match b {
            b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' => char::from(b),
            _ => '_',
        })
        .collect();
    assert!(stem.len() <= PATH_NAME_BYTES_MAX);
    assert!(!stem.contains(['/', '\\', '.']));
    stem
}