Skip to main content

agentmux_srv_core/backend/transcript/
counting.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Counting a transcript's lines once, off the request path.
5//!
6//! A transcript with no line epoch (`filestore/counter.rs`) cannot open: `agent:open_tail` has no line
7//! positions to give, and `output.idx` cannot be labelled with a generation, so the index is rebuilt
8//! from byte 0 on every read and, while the file grows under it, never serves one. On a gigabyte
9//! transcript each rebuild is seconds, and the read is then refused. An epoch is lost when bytes inside
10//! the file are rewritten (a fork's copy is signed in place) or an older build appends past the
11//! catch-up window.
12//!
13//! Starting the epoch is one scan of the file (`FileStore::init_line_counter`), which takes the
14//! connection lock one window at a time. This module makes sure it runs once per file at a time:
15//! readers that find no epoch start the count if none is running, then wait for it a little (or answer
16//! "counting" and let the pane ask again), instead of each starting their own scan or rebuilding the
17//! index.
18
19use std::collections::HashMap;
20use std::sync::{Arc, Condvar, Mutex};
21use std::time::Duration;
22
23use crate::backend::storage::filestore::FileStore;
24
25/// A count in progress: finished when `done` is set.
26struct Flight {
27    done: Mutex<bool>,
28    ended: Condvar,
29}
30
31impl Flight {
32    fn wait(&self, wait: Duration) -> bool {
33        let guard = self.done.lock().unwrap();
34        let (guard, _) = self.ended.wait_timeout_while(guard, wait, |done| !*done).unwrap();
35        *guard
36    }
37}
38
39static FLIGHTS: Mutex<Option<HashMap<String, Arc<Flight>>>> = Mutex::new(None);
40
41/// The key of `zone`'s count in `fs`: the store by identity, so two stores' zones of one name stay apart.
42pub fn flight_key(fs: &Arc<FileStore>, zone: &str) -> String {
43    format!("{:p}:{zone}", Arc::as_ptr(fs))
44}
45
46/// Run `work` on a thread of its own unless a flight for `key` is already running, and wait up to
47/// `wait` for it. True when the flight ended in that time.
48pub fn run_once(key: String, wait: Duration, work: impl FnOnce() + Send + 'static) -> bool {
49    let (flight, starts) = {
50        let mut flights = FLIGHTS.lock().unwrap();
51        let map = flights.get_or_insert_with(HashMap::new);
52        match map.get(&key) {
53            Some(f) => (f.clone(), false),
54            None => {
55                let f = Arc::new(Flight { done: Mutex::new(false), ended: Condvar::new() });
56                map.insert(key.clone(), f.clone());
57                (f, true)
58            }
59        }
60    };
61    if starts {
62        let ending = flight.clone();
63        let spawned = std::thread::Builder::new().name("transcript-count".into()).spawn(move || {
64            work();
65            // Leave the map first: a reader that finds the flight over starts a new one if it still needs it.
66            if let Some(map) = FLIGHTS.lock().unwrap().as_mut() {
67                map.remove(&key);
68            }
69            *ending.done.lock().unwrap() = true;
70            ending.ended.notify_all();
71        });
72        if let Err(e) = spawned {
73            tracing::warn!(error = %e, "transcript count: couldn't start its thread");
74            return false;
75        }
76    }
77    flight.wait(wait)
78}
79
80/// Whether `zone`'s `output` has a line epoch now (a valid one, or one only behind, which is caught up).
81fn counted(fs: &FileStore, zone: &str) -> bool {
82    matches!(fs.catch_up_line_counter(zone, "output"), Ok(Some(state)) if state.counted.is_some())
83}
84
85/// `zone`'s `output` counted: true when it has an epoch within `wait`. Cheap when it already has one
86/// (or only needs catching up); otherwise the count starts if none is running and is waited for. False
87/// means it is still being counted, or could not be (the file moved under the scan): ask again later.
88pub fn ensure_counted(fs: &Arc<FileStore>, zone: &str, wait: Duration) -> bool {
89    if counted(fs, zone) {
90        return true;
91    }
92    let (store, name) = (fs.clone(), zone.to_string());
93    let began = std::time::Instant::now();
94    run_once(flight_key(fs, zone), wait, move || match store.init_line_counter(&name, "output") {
95        Ok(Some(_)) => tracing::info!(zone = %name, ms = began.elapsed().as_millis() as u64, "transcript count: counted"),
96        Ok(None) => tracing::info!(zone = %name, "transcript count: the file moved under the scan; the next read counts it again"),
97        Err(e) => tracing::warn!(zone = %name, error = %e, "transcript count: failed"),
98    });
99    counted(fs, zone)
100}
101
102#[cfg(test)]
103#[path = "counting_tests.rs"]
104mod tests;