Skip to main content

a2a_protocol_server/tool_loop/
trace.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The tool trace a run keeps: one line per call, each of them bounded, and
5//! where the lines go when the run fails.
6
7use std::sync::{Mutex, PoisonError};
8
9/// The most bytes of one trace line: name, arguments and result together.
10///
11/// The result goes whole to the model, which a context window bounds; the
12/// trace is a record for the caller, and with no bound a large result made
13/// every `GetTask` body as large and, past the 16 MiB event limit, failed a run
14/// that had finished (hostile campaign, wave 2, W2-LIVE-4). A longer line is
15/// cut on a character boundary and says how much it lost.
16pub const TRACE_LINE_LIMIT: usize = 16 * 1024;
17
18/// `name(arguments) -> content`, cut to [`TRACE_LINE_LIMIT`] bytes.
19pub(super) fn line(name: &str, arguments: &str, content: &str) -> String {
20    let full = format!("{name}({arguments}) -> {content}");
21    if full.len() <= TRACE_LINE_LIMIT {
22        return full;
23    }
24    let mut end = TRACE_LINE_LIMIT;
25    while !full.is_char_boundary(end) {
26        end -= 1;
27    }
28    format!("{}… [{} more bytes]", &full[..end], full.len() - end)
29}
30
31/// Where a run puts its trace lines as they are made. An `Err` carries no
32/// [`Answer`](super::Answer) and so no trace, though the tools it ran have run:
33/// the executor reads this when a run fails and sends the trace before the
34/// failure, so the caller can see what was done (and does not repeat it).
35#[derive(Default)]
36pub(super) struct Sink(Mutex<Vec<String>>);
37
38impl Sink {
39    pub(super) fn push(&self, line: String) {
40        self.0
41            .lock()
42            .unwrap_or_else(PoisonError::into_inner)
43            .push(line);
44    }
45
46    pub(super) fn take(&self) -> Vec<String> {
47        std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner))
48    }
49}
50
51/// Keeps `line` in the run's trace and, when the executor is watching, in its
52/// sink too.
53pub(super) fn record(trace: &mut Vec<String>, sink: Option<&Sink>, line: String) {
54    if let Some(sink) = sink {
55        sink.push(line.clone());
56    }
57    trace.push(line);
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    /// The documented limit is 16 KiB, and a line well inside it, longer than
65    /// a thousand bytes, is kept whole (the mutation run found nothing that
66    /// pinned the value).
67    #[test]
68    fn the_limit_is_sixteen_kibibytes_and_a_line_inside_it_is_whole() {
69        assert_eq!(TRACE_LINE_LIMIT, 16_384);
70        let body = "r".repeat(5_000);
71        assert_eq!(line("t", "{}", &body), format!("t({{}}) -> {body}"));
72    }
73
74    /// A line within the limit is as it always was.
75    #[test]
76    fn a_short_line_is_name_arguments_and_result() {
77        assert_eq!(line("t", "{}", "ok"), "t({}) -> ok");
78        // Exactly at the limit: kept whole.
79        let fits = "x".repeat(TRACE_LINE_LIMIT - "t({}) -> ".len());
80        let whole = line("t", "{}", &fits);
81        assert_eq!(whole.len(), TRACE_LINE_LIMIT);
82        assert!(!whole.contains("more bytes"));
83    }
84
85    /// One byte over: cut, and the marker counts what was lost.
86    #[test]
87    fn a_line_over_the_limit_is_cut_and_says_how_much() {
88        let over = "x".repeat(TRACE_LINE_LIMIT - "t({}) -> ".len() + 1);
89        let cut = line("t", "{}", &over);
90        let kept = format!("t({{}}) -> {}", &over[..over.len() - 1]);
91        assert_eq!(cut, format!("{kept}… [1 more bytes]"));
92        let huge = line("t", "{}", &"y".repeat(8 * 1024 * 1024));
93        assert!(huge.len() < TRACE_LINE_LIMIT + 32, "{}", huge.len());
94        assert!(huge.ends_with("more bytes]"));
95    }
96
97    /// The cut falls on a character boundary: a three-byte character that
98    /// straddles the limit is left out whole, and counted as lost.
99    #[test]
100    fn the_cut_never_splits_a_character() {
101        let prefix = "t({}) -> ";
102        // Fill to one byte short of the limit, then a three-byte character.
103        let content = format!("{}€€", "x".repeat(TRACE_LINE_LIMIT - prefix.len() - 1));
104        let cut = line("t", "{}", &content);
105        assert!(cut.is_char_boundary(cut.len()));
106        assert_eq!(
107            cut,
108            format!(
109                "{prefix}{}… [6 more bytes]",
110                "x".repeat(TRACE_LINE_LIMIT - prefix.len() - 1)
111            )
112        );
113    }
114
115    /// The sink hands back what was recorded, once.
116    #[test]
117    fn the_sink_keeps_lines_in_order_and_gives_them_up_once() {
118        let sink = Sink::default();
119        let mut trace = Vec::new();
120        record(&mut trace, Some(&sink), "a".to_owned());
121        record(&mut trace, Some(&sink), "b".to_owned());
122        record(&mut trace, None, "c".to_owned());
123        assert_eq!(trace, ["a", "b", "c"]);
124        assert_eq!(sink.take(), ["a", "b"]);
125        assert_eq!(sink.take(), Vec::<String>::new());
126    }
127}