Skip to main content

agentmux_srv_core/backend/audit_query/
totals.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What every entry a filter matches cost, not only a page's. The audit file and the activity day files are only
5//! ever appended to, so a sum is kept per file and filter and carried on from where the last scan of the file ended:
6//! the first asks reads the file, the next ones only what was written since.
7
8use std::collections::HashMap;
9use std::path::Path;
10use std::sync::Mutex;
11
12use super::activity::{day_end_ms, entry_of};
13use super::{from_audit, jekt_file, Ctx, Filter, Sources, KIND_ACTION, KIND_JEKT, KIND_REGISTRY, KIND_THOUGHT, KIND_TOOL, KIND_TURN};
14use crate::backend::audit_activity::{day_files, ActivityRow};
15use crate::backend::rpc_types::AuditTotals;
16
17/// Sums kept: a file and a filter each, and a month of day files is thirty files for each filter a view asks totals of.
18const KEPT: usize = 128;
19
20struct Kept {
21    /// The file's bytes read, and the sum of the entries in them.
22    read: u64,
23    sum: AuditTotals,
24    used: u64,
25}
26
27static KEPT_SUMS: Mutex<Option<HashMap<String, Kept>>> = Mutex::new(None);
28
29/// Links aren't part of a sum: this keeps looking them up out of a scan of the whole file.
30fn no_links() -> Ctx<'static> {
31    Ctx { slug_of_uid: &|_| None, uid_of_slug: &|_| None, pane_of_agent: &|_| None, block_exists: &|_| false }
32}
33
34fn add(sum: &mut AuditTotals, e: &crate::backend::rpc_types::AuditEntry) {
35    // The sender's half of a message is the same row as the receiver's in the list: it is not counted twice.
36    if e.provenance.as_ref().is_some_and(|p| p.sent_only == Some(true)) {
37        return;
38    }
39    sum.entries += 1;
40    if let Some(cost) = &e.cost {
41        sum.input += cost.input;
42        sum.cache_read += cost.cache_read;
43        sum.output += cost.output;
44        if let Some(usd) = cost.usd {
45            *sum.usd.get_or_insert(0.0) += usd;
46        }
47        sum.estimated |= cost.basis != "measured";
48    }
49}
50
51/// The sum over the audit file's and the ledger's entries `filter` matches.
52pub(super) fn of(src: &Sources, filter: &Filter) -> AuditTotals {
53    let mut sum = AuditTotals::default();
54    if let Some(store) = src.segments {
55        if filter.kinds.contains(super::KIND_AGENT_START) || filter.kinds.contains(super::KIND_AGENT_END) {
56            for e in super::segments::entries(store, filter.agent.as_deref(), &src.ctx).iter().filter(|e| filter.keep(e)) {
57                add(&mut sum, e);
58            }
59        }
60    }
61    let wants_file = [KIND_JEKT, KIND_ACTION, KIND_REGISTRY].iter().any(|k| filter.kinds.contains(*k));
62    // The two files hold different lines (a line goes to one), so their sums add.
63    for path in [src.jekt_file, src.own_file].into_iter().flatten().filter(|_| wants_file) {
64        add_file(&mut sum, path, filter, |from, s| scan_into(path, from, filter, s));
65    }
66    add_activity(&mut sum, src, filter);
67    sum
68}
69
70/// Adds the tool, turn and thought rows of the activity day files `filter` matches. A turn's row carries what the
71/// turn cost, so leaving these out left the totals short of every turn.
72fn add_activity(sum: &mut AuditTotals, src: &Sources, filter: &Filter) {
73    if ![KIND_TOOL, KIND_TURN, KIND_THOUGHT].iter().any(|k| filter.kinds.contains(*k)) {
74        return;
75    }
76    // A row names its agent by UID: the filter names it by slug. Nothing else of the links is read.
77    let ctx = Ctx { slug_of_uid: src.ctx.slug_of_uid, uid_of_slug: &|_| None, pane_of_agent: &|_| None, block_exists: &|_| false };
78    for dir in [src.activity_dir, src.own_activity_dir].into_iter().flatten() {
79        // A day that ended before the window began holds none of it.
80        for file in day_files(dir).into_iter().filter(|f| day_end_ms(&f.day) >= filter.since) {
81            add_file(sum, &file.path, filter, |from, s| scan_activity(&file.path, &file.day, from, filter, &ctx, s));
82        }
83    }
84}
85
86/// Adds to `sum` what `scan` finds in the file at `path` for `filter`: `scan(from, sum)` reads from byte `from` and
87/// returns where it ended.
88fn add_file(sum: &mut AuditTotals, path: &Path, filter: &Filter, scan: impl Fn(u64, &mut AuditTotals) -> std::io::Result<u64>) {
89    let key = format!("{}|{}", path.display(), filter.key());
90    let (mut read, mut from_file) = (0u64, AuditTotals::default());
91    let mut guard = KEPT_SUMS.lock().unwrap_or_else(|e| e.into_inner());
92    if let Some(kept) = guard.as_mut().and_then(|m| m.get(&key)) {
93        // A file shorter than what was read was replaced: start again.
94        if std::fs::metadata(path).is_ok_and(|m| m.len() >= kept.read) {
95            (read, from_file) = (kept.read, kept.sum.clone());
96        }
97    }
98    drop(guard);
99    // The scan's sum is kept with where it ended only if it ended cleanly: one that failed partway would
100    // otherwise be counted again from the old position next time.
101    let mut scanned = from_file.clone();
102    match scan(read, &mut scanned) {
103        Ok(end) => {
104            let (read, from_file_now) = (end, scanned);
105            let mut guard = KEPT_SUMS.lock().unwrap_or_else(|e| e.into_inner());
106            let map = guard.get_or_insert_with(HashMap::new);
107            if map.len() >= KEPT && !map.contains_key(&key) {
108                if let Some(oldest) = map.iter().min_by_key(|(_, k)| k.used).map(|(k, _)| k.clone()) {
109                    map.remove(&oldest);
110                }
111            }
112            let used = map.values().map(|k| k.used).max().unwrap_or(0) + 1;
113            map.insert(key, Kept { read, sum: from_file_now.clone(), used });
114            from_file = from_file_now;
115        }
116        // A day file that went away between listing and opening (rotated or pruned) has nothing to add: not a warning.
117        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
118            tracing::debug!(path = %path.display(), "audit.query totals: the audit file is gone; answering from what was read before")
119        }
120        Err(e) => {
121            tracing::warn!(path = %path.display(), error = %e, "audit.query totals: the audit file couldn't be read to its end; answering from what was read before")
122        }
123    }
124    sum.entries += from_file.entries;
125    sum.input += from_file.input;
126    sum.cache_read += from_file.cache_read;
127    sum.output += from_file.output;
128    sum.usd = match (sum.usd, from_file.usd) {
129        (None, None) => None,
130        (a, b) => Some(a.unwrap_or(0.0) + b.unwrap_or(0.0)),
131    };
132    sum.estimated |= from_file.estimated;
133}
134
135fn scan_into(path: &Path, from: u64, filter: &Filter, sum: &mut AuditTotals) -> std::io::Result<u64> {
136    let ctx = no_links();
137    jekt_file::scan(path, from, |raw: crate::backend::reactive::types::AuditLogEntry| {
138        let e = from_audit(0, &raw, &ctx);
139        if filter.keep(&e) {
140            add(sum, &e);
141        }
142    })
143}
144
145fn scan_activity(path: &Path, day: &str, from: u64, filter: &Filter, ctx: &Ctx, sum: &mut AuditTotals) -> std::io::Result<u64> {
146    jekt_file::scan(path, from, |row: ActivityRow| {
147        let e = entry_of('t', day, 0, &row, ctx);
148        if filter.keep(&e) {
149            add(sum, &e);
150        }
151    })
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use std::collections::HashSet;
158
159    fn jekt_filter() -> Filter {
160        Filter { agent: None, kinds: HashSet::from([KIND_JEKT.to_string()]), since: 0, until: u64::MAX, text: String::new(), channel: None }
161    }
162
163    /// A day file pruned between the listing and the open adds nothing and is no failure: the scan says why it
164    /// couldn't read (so the warning can), and the sum is left as it was.
165    #[test]
166    fn a_file_that_is_gone_adds_nothing_and_says_why() {
167        let dir = tempfile::tempdir().unwrap();
168        let missing = dir.path().join("2026-11-17.jsonl");
169        let filter = jekt_filter();
170
171        let mut scanned = AuditTotals::default();
172        let err = scan_into(&missing, 0, &filter, &mut scanned).unwrap_err();
173        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
174
175        let mut sum = AuditTotals::default();
176        add_file(&mut sum, &missing, &filter, |from, s| scan_into(&missing, from, &filter, s));
177        assert_eq!(sum, AuditTotals::default());
178    }
179
180    /// A line the writer was cut in the middle of is not read, and the scan still succeeds.
181    #[test]
182    fn a_cut_last_line_is_not_a_failure() {
183        let dir = tempfile::tempdir().unwrap();
184        let path = dir.path().join("audit.jsonl");
185        std::fs::write(&path, b"{\"half\":").unwrap();
186        let mut sum = AuditTotals::default();
187        assert_eq!(scan_into(&path, 0, &jekt_filter(), &mut sum).unwrap(), 0);
188        assert_eq!(sum, AuditTotals::default());
189    }
190}