Skip to main content

agentmux_srv_core/backend/transcript/
tail.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The last lines of an agent's transcript, for the readers that want only a few
5//! (`Agents transcript`, the previews in `Agents conversations`).
6//!
7//! Both used to read the block's whole `output` file (hundreds of MB for a long
8//! session) under the store's one connection, on a tokio worker, to return at
9//! most 500 lines. On a busy machine that parked workers and the connection long
10//! enough for every other call to queue behind them: a `GetControllerStatus`
11//! that does no work of its own took 38 s (narko, 2026-10-29, CPU ~96%). This
12//! reads a bounded tail instead, and [`off_worker`] keeps what is left off the
13//! async workers.
14
15use std::sync::Arc;
16
17use crate::backend::storage::filestore::FileStore;
18use crate::backend::storage::store::Store;
19use crate::backend::transcript::source::{Tail, TranscriptSource};
20
21/// The first tail read; grown fourfold while it holds too few lines.
22const FIRST_WINDOW: i64 = 256 * 1024;
23
24/// What a transcript read found.
25pub struct TailLines {
26    /// The last non-blank lines, oldest first.
27    pub lines: Vec<String>,
28    /// Whether the transcript holds earlier lines than these.
29    pub truncated: bool,
30}
31
32/// Run blocking work (store reads) off the async workers. A panic in `f` gives
33/// `T::default()`, as no result at all would for a best-effort reader.
34pub async fn off_worker<T: Default + Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
35    tokio::task::spawn_blocking(f).await.unwrap_or_default()
36}
37
38/// The last `requested` non-blank lines of `bytes`. `complete`: `bytes` starts at
39/// the start of the file; otherwise its first line may be cut and is dropped.
40/// `None` when a partial window holds no more than `requested` whole lines, so
41/// the caller must read more.
42fn last_lines(bytes: &[u8], requested: usize, complete: bool) -> Option<TailLines> {
43    let text = String::from_utf8_lossy(bytes);
44    let mut lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
45    if !complete && !lines.is_empty() {
46        lines.remove(0);
47    }
48    if !complete && lines.len() <= requested {
49        return None;
50    }
51    let truncated = lines.len() > requested;
52    let from = lines.len().saturating_sub(requested);
53    Some(TailLines { lines: lines[from..].iter().map(|l| l.to_string()).collect(), truncated })
54}
55
56/// [`last_lines`] over a live transcript, reading `FIRST_WINDOW` bytes from the end and
57/// more only while that holds too few lines. `None`: no live file (archived, or
58/// not written yet), or bytes not all stored yet.
59fn live_tail_lines(src: &TranscriptSource<'_>, requested: usize) -> Option<TailLines> {
60    tail_lines_with(|window| src.tail(window), requested)
61}
62
63/// [`live_tail_lines`] over any way of reading the last `window` bytes.
64fn tail_lines_with(mut read: impl FnMut(i64) -> Option<Tail>, requested: usize) -> Option<TailLines> {
65    let mut window = FIRST_WINDOW;
66    loop {
67        let tail = read(window)?;
68        if let Some(found) = last_lines(&tail.bytes, requested, tail.size <= window) {
69            return Some(found);
70        }
71        window = window.saturating_mul(4);
72    }
73}
74
75/// The last `requested` lines of `block_id`'s transcript: a bounded tail read of the
76/// live file, else (an archived session) the whole-session read. Blocking.
77pub fn tail_lines(
78    mstore: &Arc<Store>,
79    filestore: &Arc<FileStore>,
80    block_id: &str,
81    requested: usize,
82) -> Result<TailLines, String> {
83    let mut found = unvetted_tail_lines(mstore, filestore, block_id, requested)?;
84    let owner = crate::backend::transcript::origin_sig::owner_for_block(mstore, block_id);
85    crate::backend::transcript::attribution::vet_for_viewer(mstore, filestore, &owner, &mut found.lines);
86    Ok(found)
87}
88
89/// [`tail_lines`] for a reader that is not the agent itself (another agent, a device): a value srv holds secret is
90/// replaced by `withhold::MARK` in the lines it gets, whenever the line was stored.
91pub fn tail_lines_for_readers(
92    mstore: &Arc<Store>,
93    filestore: &Arc<FileStore>,
94    block_id: &str,
95    requested: usize,
96) -> Result<TailLines, String> {
97    let mut found = tail_lines(mstore, filestore, block_id, requested)?;
98    crate::backend::transcript::withhold::in_place(&mut found.lines);
99    Ok(found)
100}
101
102fn unvetted_tail_lines(
103    mstore: &Arc<Store>,
104    filestore: &Arc<FileStore>,
105    block_id: &str,
106    requested: usize,
107) -> Result<TailLines, String> {
108    if let Some(found) = live_tail_lines(&TranscriptSource::resolve(filestore, mstore, block_id), requested) {
109        return Ok(found);
110    }
111    let (raw, _) = crate::backend::session_archive::read_session_output(mstore, filestore, block_id)?;
112    Ok(last_lines(&raw, requested, true).unwrap_or(TailLines { lines: Vec::new(), truncated: false }))
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::backend::storage::filestore::{FileMeta, FileOpts};
119
120    const BLOCK: &str = "blk-tail";
121
122    fn store_with(lines: impl Iterator<Item = String>) -> (FileStore, Store) {
123        store_with_cache(lines, None)
124    }
125
126    /// `cache_cap`: the file store's cache size; a small one makes every read go to the database.
127    fn store_with_cache(lines: impl Iterator<Item = String>, cache_cap: Option<usize>) -> (FileStore, Store) {
128        let fs = match cache_cap {
129            Some(cap) => FileStore::open_in_memory_with_cap(cap).unwrap(),
130            None => FileStore::open_in_memory().unwrap(),
131        };
132        let mstore = Store::open_in_memory().unwrap();
133        fs.make_file(BLOCK, "output", FileMeta::default(), FileOpts::default()).unwrap();
134        let mut chunk = String::new();
135        for l in lines {
136            chunk.push_str(&l);
137            chunk.push('\n');
138            if chunk.len() > 1 << 20 {
139                fs.append_lines(BLOCK, "output", chunk.as_bytes()).unwrap();
140                chunk.clear();
141            }
142        }
143        if !chunk.is_empty() {
144            fs.append_lines(BLOCK, "output", chunk.as_bytes()).unwrap();
145        }
146        (fs, mstore)
147    }
148
149    /// What the route did before: every line of the whole file, then the last ones.
150    fn whole_file(fs: &FileStore, requested: usize) -> TailLines {
151        let raw = fs.read_file(BLOCK, "output").unwrap().unwrap_or_default();
152        last_lines(&raw, requested, true).unwrap()
153    }
154
155    fn tail(fs: &FileStore, mstore: &Store, requested: usize) -> TailLines {
156        live_tail_lines(&TranscriptSource::resolve_with(fs, None, mstore, BLOCK), requested).expect("a live file")
157    }
158
159    fn same(a: &TailLines, b: &TailLines) {
160        assert_eq!((&a.lines, a.truncated), (&b.lines, b.truncated));
161    }
162
163    #[test]
164    fn a_short_transcript_is_returned_whole() {
165        let (fs, m) = store_with(["{\"a\":1}", "", "{\"a\":2}"].into_iter().map(String::from));
166        let got = tail(&fs, &m, 100);
167        assert_eq!(got.lines, ["{\"a\":1}", "{\"a\":2}"]);
168        assert!(!got.truncated);
169        same(&got, &whole_file(&fs, 100));
170    }
171
172    #[test]
173    fn a_long_transcript_gives_the_same_last_lines_as_reading_all_of_it() {
174        // ~6 MB of 200-byte lines: far past the first window.
175        let (fs, m) = store_with((0..30_000).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "x".repeat(180))));
176        for requested in [1, 5, 100, 500] {
177            let (got, want) = (tail(&fs, &m, requested), whole_file(&fs, requested));
178            same(&got, &want);
179            assert_eq!(got.lines.len(), requested);
180            assert!(got.truncated);
181            assert!(got.lines.last().unwrap().starts_with("{\"n\":29999,"));
182        }
183    }
184
185    #[test]
186    fn lines_longer_than_the_first_window_widen_it() {
187        // 60 lines of 100 KB: the first 256 KiB holds two whole ones.
188        let (fs, m) = store_with((0..60).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "y".repeat(100_000))));
189        let got = tail(&fs, &m, 10);
190        same(&got, &whole_file(&fs, 10));
191        assert_eq!(got.lines.len(), 10);
192        assert!(got.lines[0].starts_with("{\"n\":50,") && got.truncated);
193    }
194
195    #[test]
196    fn exactly_the_requested_lines_in_a_file_bigger_than_the_window_are_not_truncated() {
197        let (fs, m) = store_with((0..50).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "z".repeat(20_000))));
198        let got = tail(&fs, &m, 50);
199        same(&got, &whole_file(&fs, 50));
200        assert_eq!((got.lines.len(), got.truncated), (50, false));
201    }
202
203    #[test]
204    fn a_large_transcript_is_read_through_one_bounded_window() {
205        // 6 MB, 100 lines asked for: one read of the first window, nothing more.
206        let (fs, m) = store_with((0..30_000).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "x".repeat(180))));
207        let src = TranscriptSource::resolve_with(&fs, None, &m, BLOCK);
208        let (mut windows, mut read) = (Vec::new(), 0usize);
209        let got = tail_lines_with(
210            |w| {
211                windows.push(w);
212                let t = src.tail(w);
213                read += t.as_ref().map_or(0, |t| t.bytes.len());
214                t
215            },
216            100,
217        )
218        .unwrap();
219        assert_eq!(windows, [FIRST_WINDOW], "no wider read than the first window");
220        assert!(read as i64 <= FIRST_WINDOW, "{read} bytes read of a ~6 MB file");
221        assert_eq!(got.lines.len(), 100);
222    }
223
224    #[tokio::test(flavor = "current_thread")]
225    async fn work_in_off_worker_does_not_stop_the_runtime() {
226        let t = std::time::Instant::now();
227        let work = tokio::spawn(off_worker(|| {
228            std::thread::sleep(std::time::Duration::from_millis(400));
229            7u32
230        }));
231        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
232        assert!(t.elapsed() < std::time::Duration::from_millis(250), "the runtime was held for {:?}", t.elapsed());
233        assert_eq!(work.await.unwrap(), 7);
234    }
235
236    #[test]
237    fn no_file_means_the_caller_falls_back() {
238        let (fs, m) = (FileStore::open_in_memory().unwrap(), Store::open_in_memory().unwrap());
239        assert!(live_tail_lines(&TranscriptSource::resolve_with(&fs, None, &m, BLOCK), 10).is_none());
240    }
241
242    /// Before and after, on a 96 MB transcript: the cost of one read, and how long a
243    /// 2-worker runtime stops answering while four of them run. Not run by default.
244    /// `cargo test -p agentmux-srv-core --lib transcript::tail::tests::bench -- --ignored --nocapture`
245    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
246    #[ignore = "a measurement, not a check"]
247    async fn bench_a_96_mb_transcript() {
248        use std::sync::Arc;
249        use std::time::{Duration, Instant};
250        // A 1 MB cache, so a read goes to the database as one of a long session's does.
251        let lines = (0..96_000).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "w".repeat(1000)));
252        let (fs, m) = store_with_cache(lines, Some(1 << 20));
253        let (fs, m) = (Arc::new(fs), Arc::new(m));
254        let old = |fs: &FileStore| whole_file(fs, 100);
255
256        let t = Instant::now();
257        for _ in 0..3 {
258            old(&fs);
259        }
260        println!("one read, before (whole file):   {:>7.1} ms (mean of 3)", t.elapsed().as_secs_f64() * 1e3 / 3.0);
261        let t = Instant::now();
262        let mut n = 0;
263        for _ in 0..3 {
264            n = tail(&fs, &m, 100).lines.len();
265        }
266        println!("one read, after  (bounded tail): {:>7.1} ms (mean of 3, {n} lines)", t.elapsed().as_secs_f64() * 1e3 / 3.0);
267
268        // A probe that wants to run every 10 ms; the worst gap is how long the runtime was deaf.
269        async fn probe_while(work: impl std::future::Future<Output = ()>) -> u128 {
270            let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
271            let flag = stop.clone();
272            let probe = tokio::spawn(async move {
273                let mut worst = 0u128;
274                while !flag.load(std::sync::atomic::Ordering::Relaxed) {
275                    let t = Instant::now();
276                    tokio::time::sleep(Duration::from_millis(10)).await;
277                    worst = worst.max(t.elapsed().as_millis() - 10);
278                }
279                worst
280            });
281            tokio::time::sleep(Duration::from_millis(50)).await;
282            work.await;
283            stop.store(true, std::sync::atomic::Ordering::Relaxed);
284            probe.await.unwrap()
285        }
286        let before = probe_while(async {
287            let tasks: Vec<_> = (0..4).map(|_| { let fs = fs.clone(); tokio::spawn(async move { old(&fs); }) }).collect();
288            for t in tasks { t.await.unwrap(); }
289        })
290        .await;
291        println!("runtime unresponsive, before (4 reads on the workers):  {before} ms");
292        let after = probe_while(async {
293            let tasks: Vec<_> = (0..4)
294                .map(|_| {
295                    let (fs, m) = (fs.clone(), m.clone());
296                    tokio::spawn(async move { off_worker(move || { tail_lines_live(&fs, &m); Some(()) }).await; })
297                })
298                .collect();
299            for t in tasks { t.await.unwrap(); }
300        })
301        .await;
302        println!("runtime unresponsive, after  (4 tail reads, off-worker): {after} ms");
303    }
304
305    fn tail_lines_live(fs: &FileStore, m: &Store) -> usize {
306        tail(fs, m, 100).lines.len()
307    }
308}