Skip to main content

agentmux_srv_core/backend/transcript/
source.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where an agent block's transcript is read from.
5//!
6//! An agent's output is stored in the agent's own zone in the global transcript
7//! store (`agent:<definitionId>:current`) and, until it stops being written
8//! (SPEC_AGENT_TRANSCRIPT_SINGLE_COPY_2026_10_19), also in the block's own store.
9//! A reader that wants "the block's recent output" asks here which copy to use:
10//! the agent's zone when it has content (the copy the pane reads, see
11//! `global_output_source`), the block's own otherwise.
12//!
13//! The reads go through the WAL reader pool (`read_snapshot`), so they never
14//! queue behind the store's single writer.
15
16use crate::backend::agent_session::{agent_zone_for_block_meta, global_transcript_store, OUTPUT_FILE};
17use crate::backend::obj::Block;
18use crate::backend::storage::error::StoreError;
19use crate::backend::storage::filestore::FileStore;
20use crate::backend::transcript::damage;
21use crate::backend::storage::store::Store;
22
23/// How much newer (ms) the block's own copy must be than the agent's zone to be read instead of it. Both are
24/// written for every line, one after the other, so their times differ by milliseconds in a healthy session;
25/// a copy that is seconds ahead is the one still being written.
26pub const OWN_NEWER_SLACK_MS: i64 = 5_000;
27
28/// Whether the block's own copy of the transcript is the live one and the agent's zone is behind it: the own copy
29/// has content and was modified more than `slack_ms` after the zone. A container agent's turns that never
30/// reached the zone left every reader quoting the zone's last line, hours old. Each is `(size, modts)`.
31pub fn own_is_newer(own: Option<(i64, i64)>, zone: Option<(i64, i64)>, slack_ms: i64) -> bool {
32    match (own, zone) {
33        (Some((own_size, own_at)), Some((_, zone_at))) => own_size > 0 && own_at > zone_at.saturating_add(slack_ms),
34        _ => false,
35    }
36}
37
38/// The store and zone a block's transcript is read from.
39pub struct TranscriptSource<'a> {
40    pub fs: &'a FileStore,
41    pub zone: String,
42    /// The agent's zone in the global store, rather than the block's own.
43    pub global: bool,
44    /// For a global source: the block's own copy, which a read uses when the
45    /// zone turns out to be corrupt ([`damage`]).
46    pub own: Option<(&'a FileStore, String)>,
47}
48
49/// What a tail read found.
50pub struct Tail {
51    pub bytes: Vec<u8>,
52    /// The file's size and last-modified time at that snapshot.
53    pub size: i64,
54    pub modts: i64,
55}
56
57impl<'a> TranscriptSource<'a> {
58    /// The agent's zone when the block is a defined agent's block (not a
59    /// quick-launch pane, whose zone is shared by every pane of its provider)
60    /// that is not archived and the zone has content; the block's own store otherwise (no
61    /// `agentId`, no global store, an archived session, an empty zone, or a zone
62    /// found corrupt).
63    pub fn resolve(block_fs: &'a FileStore, mstore: &Store, block_id: &str) -> Self {
64        Self::resolve_with(block_fs, global_transcript_store().map(|g| g.as_ref()), mstore, block_id)
65    }
66
67    /// The block's own copy, whatever the global store holds.
68    pub fn own(block_fs: &'a FileStore, block_id: &str) -> Self {
69        TranscriptSource { fs: block_fs, zone: block_id.to_string(), global: false, own: None }
70    }
71
72    /// [`Self::resolve`] with the global store given (tests install none).
73    pub fn resolve_with(block_fs: &'a FileStore, global: Option<&'a FileStore>, mstore: &Store, block_id: &str) -> Self {
74        Self::resolve_with_slack(block_fs, global, mstore, block_id, OWN_NEWER_SLACK_MS)
75    }
76
77    /// [`Self::resolve_with`] with how much newer the block's own copy must be to win (tests pass 0).
78    fn resolve_with_slack(block_fs: &'a FileStore, global: Option<&'a FileStore>, mstore: &Store, block_id: &str, slack_ms: i64) -> Self {
79        let own = || Self::own(block_fs, block_id);
80        let Some(gfs) = global else { return own() };
81        let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return own() };
82        let archived = block
83            .meta
84            .get(crate::backend::session_archive::META_SESSION_ARCHIVED_AT)
85            .and_then(|v| v.as_i64())
86            .map(|v| v > 0)
87            .unwrap_or(false);
88        if archived {
89            return own();
90        }
91        let Some(zone) = agent_zone_for_block_meta(&block.meta) else { return own() };
92        // A quick-launch pane carries a provider key (`claude`, `codex`, ...) as
93        // its `agentId`, and every pane of that provider shares the zone: its
94        // tail would be built from the interleaved output of all of them. Only
95        // an agent definition's own zone is one conversation.
96        let agent_id = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
97        if crate::backend::providers::get_provider(&agent_id).is_some() {
98            return own();
99        }
100        if damage::is_damaged(&zone) {
101            return own();
102        }
103        let zone_file = match gfs.read_snapshot(|r| Ok(r.file(&zone, OUTPUT_FILE)?.map(|f| (f.size, f.modts)))) {
104            Ok(file) => file,
105            Err(e) => {
106                damage::note_corrupt(&zone, "tail read", &e);
107                None
108            }
109        };
110        let own_file = block_fs.read_snapshot(|r| Ok(r.file(block_id, OUTPUT_FILE)?.map(|f| (f.size, f.modts)))).ok().flatten();
111        if zone_file.is_some_and(|z| z.0 > 0) && !own_is_newer(own_file, zone_file, slack_ms) {
112            TranscriptSource { fs: gfs, zone, global: true, own: Some((block_fs, block_id.to_string())) }
113        } else {
114            own()
115        }
116    }
117
118    /// Runs `read` on this source. A global zone that answers with a corrupt
119    /// database is marked damaged and the read runs again on the block's own copy.
120    fn read<T>(&self, read: impl Fn(&FileStore, &str) -> Result<Option<T>, StoreError>) -> Option<T> {
121        match read(self.fs, &self.zone) {
122            Ok(v) => v,
123            Err(e) => match &self.own {
124                Some((own_fs, own_zone)) if self.global && damage::note_corrupt(&self.zone, "tail read", &e) => {
125                    read(own_fs, own_zone).ok().flatten()
126                }
127                _ => None,
128            },
129        }
130    }
131
132    /// The file's size and last-modified time, or `None` if it does not exist.
133    pub fn stat(&self) -> Option<(i64, i64)> {
134        self.read(|fs, zone| fs.read_snapshot(|r| Ok(r.file(zone, OUTPUT_FILE)?.map(|f| (f.size, f.modts)))))
135    }
136
137    /// The last `max_bytes` of the file (all of it if smaller) from one snapshot.
138    /// `None` for no file, an empty one, or bytes that are not all stored yet.
139    pub fn tail(&self, max_bytes: i64) -> Option<Tail> {
140        self.read(|fs, zone| {
141            fs.read_snapshot(|r| {
142                let Some(file) = r.file(zone, OUTPUT_FILE)? else { return Ok(None) };
143                if file.size <= 0 {
144                    return Ok(None);
145                }
146                let start = (file.size - max_bytes).max(0);
147                Ok(r.bytes(zone, OUTPUT_FILE, start, file.size - start)?.map(|bytes| Tail {
148                    bytes,
149                    size: file.size,
150                    modts: file.modts,
151                }))
152            })
153        })
154    }
155
156    /// `[offset, offset + len)` of the file, from one snapshot; `None` if any of
157    /// it is not stored (a writer mid-append).
158    pub fn read_range(&self, offset: i64, len: i64) -> Option<Vec<u8>> {
159        self.read(|fs, zone| fs.read_snapshot(|r| r.bytes(zone, OUTPUT_FILE, offset, len)))
160    }
161
162    /// The whole file.
163    pub fn read_all(&self) -> Option<Vec<u8>> {
164        self.read(|fs, zone| {
165            fs.read_snapshot(|r| {
166                let Some(file) = r.file(zone, OUTPUT_FILE)? else { return Ok(None) };
167                r.bytes(zone, OUTPUT_FILE, 0, file.size)
168            })
169        })
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::backend::obj::Block;
177    use crate::backend::storage::filestore::{FileMeta, FileOpts};
178
179    const BLOCK: &str = "blk-source";
180    const DEF: &str = "def-source-1";
181
182    fn stores() -> (FileStore, FileStore, Store) {
183        (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap(), Store::open_in_memory().unwrap())
184    }
185
186    fn block(mstore: &Store, agent_id: Option<&str>, archived: bool) {
187        let mut meta = crate::backend::obj::MetaMapType::default();
188        if let Some(a) = agent_id {
189            meta.insert("agentId".into(), serde_json::json!(a));
190        }
191        if archived {
192            meta.insert(crate::backend::session_archive::META_SESSION_ARCHIVED_AT.into(), serde_json::json!(1_700_000_000_000i64));
193        }
194        let mut b = Block { oid: BLOCK.into(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
195        mstore.insert(&mut b).unwrap();
196    }
197
198    fn put(fs: &FileStore, zone: &str, body: &str) {
199        fs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
200        fs.append_lines(zone, "output", body.as_bytes()).unwrap();
201    }
202
203    fn zone() -> String {
204        crate::backend::agent_session::agent_current_zone(DEF)
205    }
206
207    #[test]
208    fn an_agent_block_reads_the_agents_zone_when_it_has_content() {
209        let (own, global, mstore) = stores();
210        block(&mstore, Some(DEF), false);
211        put(&own, BLOCK, "{\"copy\":\"block\"}\n");
212        put(&global, &zone(), "{\"copy\":\"global\"}\n{\"n\":2}\n");
213        let s = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
214        assert!(s.global);
215        assert_eq!(s.zone, zone());
216        assert_eq!(s.read_all().unwrap(), b"{\"copy\":\"global\"}\n{\"n\":2}\n");
217        let tail = s.tail(1024).unwrap();
218        assert_eq!(tail.bytes, b"{\"copy\":\"global\"}\n{\"n\":2}\n");
219        assert_eq!(tail.size, tail.bytes.len() as i64);
220        assert_eq!(s.stat().unwrap().0, tail.size);
221    }
222
223    #[test]
224    fn a_block_with_no_global_content_no_agent_id_or_an_archive_reads_its_own_copy() {
225        let (own, global, mstore) = stores();
226        put(&own, BLOCK, "{\"copy\":\"block\"}\n");
227        // No block row, no global store.
228        assert!(!TranscriptSource::resolve_with(&own, None, &mstore, BLOCK).global);
229        // A block row without an agentId (a terminal, a /btw throwaway).
230        block(&mstore, None, false);
231        put(&global, &zone(), "{\"copy\":\"global\"}\n");
232        assert!(!TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK).global);
233    }
234
235    #[test]
236    fn an_agent_block_with_an_empty_global_zone_falls_back_to_its_own_copy() {
237        let (own, global, mstore) = stores();
238        block(&mstore, Some(DEF), false);
239        put(&own, BLOCK, "{\"copy\":\"block\"}\n");
240        global.make_file(&zone(), "output", FileMeta::default(), FileOpts::default()).unwrap();
241        let s = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
242        assert!(!s.global);
243        assert_eq!(s.read_all().unwrap(), b"{\"copy\":\"block\"}\n");
244    }
245
246    #[test]
247    fn an_archived_session_reads_its_own_copy() {
248        let (own, global, mstore) = stores();
249        block(&mstore, Some(DEF), true);
250        put(&own, BLOCK, "{\"copy\":\"block\"}\n");
251        put(&global, &zone(), "{\"copy\":\"global\"}\n");
252        assert!(!TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK).global);
253    }
254
255    #[test]
256    fn a_quick_launch_pane_whose_agent_id_is_a_provider_key_keeps_its_own_copy() {
257        let (own, global, mstore) = stores();
258        block(&mstore, Some("claude"), false);
259        put(&own, BLOCK, "{\"copy\":\"block\"}\n");
260        // Every pane of the provider shares this zone.
261        put(&global, &crate::backend::agent_session::agent_current_zone("claude"), "{\"copy\":\"all panes\"}\n");
262        let s = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
263        assert!(!s.global, "a provider-key zone is not one conversation");
264        assert_eq!(s.read_all().unwrap(), b"{\"copy\":\"block\"}\n");
265    }
266
267    #[test]
268    fn the_own_copy_wins_only_when_it_has_content_and_is_clearly_newer() {
269        let zone = Some((100, 1_000_000));
270        assert!(own_is_newer(Some((5, 1_010_000)), zone, OWN_NEWER_SLACK_MS), "ten seconds ahead");
271        assert!(!own_is_newer(Some((5, 1_004_000)), zone, OWN_NEWER_SLACK_MS), "within the slack: both are written per line");
272        assert!(!own_is_newer(Some((5, 999_000)), zone, OWN_NEWER_SLACK_MS), "older than the zone");
273        assert!(!own_is_newer(Some((0, 2_000_000)), zone, OWN_NEWER_SLACK_MS), "an empty own copy never wins");
274        assert!(!own_is_newer(None, zone, OWN_NEWER_SLACK_MS) && !own_is_newer(Some((5, 2_000_000)), None, OWN_NEWER_SLACK_MS));
275    }
276
277    #[test]
278    fn a_zone_that_stopped_growing_is_not_read_while_the_block_keeps_writing() {
279        // A container agent's later turns reached the block's own copy but not the zone: every reader quoted the zone's last line.
280        let (own, global, mstore) = stores();
281        block(&mstore, Some(DEF), false);
282        put(&global, &zone(), "{\"copy\":\"stale zone\"}\n");
283        std::thread::sleep(std::time::Duration::from_millis(30));
284        put(&own, BLOCK, "{\"copy\":\"live block\"}\n");
285        let s = TranscriptSource::resolve_with_slack(&own, Some(&global), &mstore, BLOCK, 0);
286        assert!(!s.global, "the newer own copy is read");
287        assert_eq!(s.read_all().unwrap(), b"{\"copy\":\"live block\"}\n");
288        // With the default slack the two are one session written together, and the zone (the full record) is read.
289        assert!(TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK).global);
290    }
291
292    #[test]
293    fn a_zone_written_after_the_own_copy_is_still_read() {
294        let (own, global, mstore) = stores();
295        block(&mstore, Some(DEF), false);
296        put(&own, BLOCK, "{\"copy\":\"block\"}\n");
297        std::thread::sleep(std::time::Duration::from_millis(30));
298        put(&global, &zone(), "{\"copy\":\"zone\"}\n");
299        assert!(TranscriptSource::resolve_with_slack(&own, Some(&global), &mstore, BLOCK, 0).global);
300    }
301
302    #[test]
303    fn a_missing_file_has_no_tail_and_no_size() {
304        let (own, _global, mstore) = stores();
305        let s = TranscriptSource::resolve_with(&own, None, &mstore, BLOCK);
306        assert!(s.tail(1024).is_none() && s.stat().is_none() && s.read_all().is_none());
307    }
308
309    #[test]
310    fn a_tail_is_the_end_of_the_file() {
311        let (own, _g, mstore) = stores();
312        put(&own, BLOCK, &format!("{}\n{}\n", "a".repeat(5000), "b".repeat(5000)));
313        let s = TranscriptSource::resolve_with(&own, None, &mstore, BLOCK);
314        let tail = s.tail(100).unwrap();
315        assert_eq!(tail.bytes.len(), 100);
316        assert!(tail.bytes.iter().rev().skip(1).all(|b| *b == b'b'));
317        assert_eq!(tail.size, 10002);
318    }
319
320    #[test]
321    fn a_global_zone_that_turns_out_corrupt_is_read_from_the_blocks_own_copy() {
322        use crate::backend::transcript::damage::{self, test_support};
323        let def = "def-source-corrupt-1";
324        let zone = crate::backend::agent_session::agent_current_zone(def);
325        let (own, global, mstore) = stores();
326        block(&mstore, Some(def), false);
327        put(&own, BLOCK, "{\"copy\":\"block\"}
328");
329        put(&global, &zone, "{\"copy\":\"global\"}
330");
331        let s = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
332        assert!(s.global, "it was healthy when the source was chosen");
333        test_support::corrupt(&global);
334        let tail = s.tail(1024).expect("answered from the block's copy");
335        assert_eq!(tail.bytes, b"{\"copy\":\"block\"}
336");
337        assert!(damage::is_damaged(&zone));
338        assert_eq!(s.read_all().unwrap(), b"{\"copy\":\"block\"}
339");
340        assert_eq!(s.read_range(0, 5).unwrap(), b"{\"cop");
341        assert_eq!(s.stat().unwrap().0, tail.size);
342        // The next lookup does not choose the damaged zone, and does not touch it.
343        let again = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
344        assert!(!again.global);
345        assert_eq!(again.read_all().unwrap(), b"{\"copy\":\"block\"}
346");
347    }
348
349    #[test]
350    fn a_global_zone_that_cannot_be_sized_at_all_is_not_chosen() {
351        use crate::backend::transcript::damage::{self, test_support};
352        let def = "def-source-corrupt-2";
353        let zone = crate::backend::agent_session::agent_current_zone(def);
354        let (own, global, mstore) = stores();
355        block(&mstore, Some(def), false);
356        put(&own, BLOCK, "{\"copy\":\"block\"}
357");
358        put(&global, &zone, "{\"copy\":\"global\"}
359");
360        test_support::corrupt(&global);
361        let s = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
362        assert!(!s.global);
363        assert_eq!(s.read_all().unwrap(), b"{\"copy\":\"block\"}
364");
365        assert!(damage::is_damaged(&zone), "the failed size read is the incident, not only a fallback");
366    }
367
368    #[test]
369    fn a_failed_read_that_is_not_corruption_is_not_a_fallback() {
370        // A zone with no file answers None, as before: the block's copy is not substituted.
371        let def = "def-source-corrupt-3";
372        let zone = crate::backend::agent_session::agent_current_zone(def);
373        let (own, global, mstore) = stores();
374        block(&mstore, Some(def), false);
375        put(&own, BLOCK, "{\"copy\":\"block\"}
376");
377        put(&global, &zone, "{\"copy\":\"global\"}
378");
379        let s = TranscriptSource::resolve_with(&own, Some(&global), &mstore, BLOCK);
380        global.delete_file(&zone, "output").unwrap();
381        assert!(s.tail(1024).is_none());
382        assert!(!crate::backend::transcript::damage::is_damaged(&zone));
383    }
384}