Skip to main content

agentmux_srv_core/backend/audit_query/
message_stats.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What messages cost, counted from the jekt audit file: per agent per day, how many messages came in, how
5//! many started a turn or joined one, how many waited in a hold, how many replies were refused as saying
6//! nothing, and how many the agent sent (`SPEC_CHEAPER_FLEET_MESSAGING_2026_10_30.md` ยง7).
7
8use std::collections::BTreeMap;
9
10use serde::Serialize;
11
12use super::jekt_file;
13use crate::backend::reactive::types::AuditLogEntry;
14
15const DAY_MS: u64 = 24 * 60 * 60 * 1000;
16/// The most days one ask covers; the file is read from its end back to the first of them.
17pub const MAX_DAYS: u64 = 31;
18
19/// One agent's messages on one UTC day.
20#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
21pub struct DayStat {
22    /// `YYYY-MM-DD`, UTC.
23    pub day: String,
24    pub agent: String,
25    /// Delivered to the agent.
26    pub received: u32,
27    /// Of those, ones that started a turn (the pane had none in flight).
28    pub turns_started: u32,
29    /// Of those, ones that joined a turn already in flight.
30    pub joined: u32,
31    /// Of those, ones that waited in a hold first (`held_delivered`).
32    pub held: u32,
33    /// Replies from this agent refused for saying nothing.
34    pub acks_refused: u32,
35    /// Messages this agent sent that were delivered.
36    pub sent: u32,
37}
38
39/// `YYYY-MM-DD` of a Unix-millisecond time, UTC.
40fn day_of(ms: u64) -> String {
41    let days = (ms / DAY_MS) as i64;
42    // Civil-from-days (Howard Hinnant's algorithm).
43    let z = days + 719_468;
44    let era = z.div_euclid(146_097);
45    let doe = z.rem_euclid(146_097);
46    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
47    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
48    let mp = (5 * doy + 2) / 153;
49    let d = doy - (153 * mp + 2) / 5 + 1;
50    let m = if mp < 10 { mp + 3 } else { mp - 9 };
51    let y = yoe + era * 400 + i64::from(m <= 2);
52    format!("{y:04}-{m:02}-{d:02}")
53}
54
55/// The days' counts of `entries` newer than `since_ms`, oldest day first.
56pub fn count(entries: impl IntoIterator<Item = AuditLogEntry>, since_ms: u64) -> Vec<DayStat> {
57    let mut by: BTreeMap<(String, String), DayStat> = BTreeMap::new();
58    let mut bump = |agent: &str, ms: u64, f: &mut dyn FnMut(&mut DayStat)| {
59        let day = day_of(ms);
60        let stat = by.entry((day.clone(), agent.to_lowercase())).or_insert_with(|| DayStat {
61            day,
62            agent: agent.to_lowercase(),
63            ..Default::default()
64        });
65        f(stat);
66    };
67    // A sensitive-op decision's row (`standing` is set on it, never on a message's) shares a message's shape
68    // (a `delivery`, no outcome, the agent as source and target) but is a decision, not a message.
69    for e in entries.into_iter().filter(|e| e.timestamp >= since_ms && e.event_kind == "delivery" && e.standing.is_none()) {
70        match e.outcome.as_deref() {
71            Some("ack_refused") => {
72                if let Some(from) = e.source_agent.as_deref() {
73                    bump(from, e.timestamp, &mut |s| s.acks_refused += 1);
74                }
75            }
76            None | Some("held_delivered") if e.success => {
77                let held = e.outcome.is_some();
78                let turn = e.turn.clone();
79                bump(&e.target_agent, e.timestamp, &mut |s| {
80                    s.received += 1;
81                    s.held += u32::from(held);
82                    match turn.as_deref() {
83                        Some("started") => s.turns_started += 1,
84                        Some("joined") => s.joined += 1,
85                        _ => {}
86                    }
87                });
88                if let Some(from) = e.source_agent.as_deref().filter(|f| !f.is_empty()) {
89                    bump(from, e.timestamp, &mut |s| s.sent += 1);
90                }
91            }
92            _ => {}
93        }
94    }
95    by.into_values().collect()
96}
97
98/// The last `days` days (at most [`MAX_DAYS`]) counted from the audit files at `paths`, which hold different lines (the
99/// shared file and a srv's own).
100pub fn from_files(paths: &[std::path::PathBuf], now_ms: u64, days: u64) -> Vec<DayStat> {
101    let since = now_ms.saturating_sub(days.clamp(1, MAX_DAYS) * DAY_MS);
102    // Each file is newest first, so stop at its first entry older than the window.
103    let recent = paths.iter().flat_map(move |path| jekt_file::entries::<AuditLogEntry>(path, None).map(|(_, _, e)| e).take_while(move |e| e.timestamp >= since));
104    count(recent, since)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    fn entry(at: u64, from: &str, to: &str, outcome: Option<&str>, turn: Option<&str>, success: bool) -> AuditLogEntry {
112        AuditLogEntry {
113            timestamp: at,
114            source_agent: Some(from.into()),
115            target_agent: to.into(),
116            block_id: "b".into(),
117            message_hash: String::new(),
118            message_length: 0,
119            success,
120            error_message: None,
121            request_id: String::new(),
122            outcome: outcome.map(str::to_string),
123            reason: None,
124            event_kind: "delivery".into(),
125            evicted_block: None,
126            evicted_agent: None,
127            audit_source_uid: String::new(),
128            lan_claimed_uid: String::new(),
129            wan: None,
130            cli_native: None,
131            turn: turn.map(str::to_string),
132            host: None,
133            channel: None,
134            version: None,
135            tier: None,
136            trust: None,
137            msg_id: None,
138            prompt: None,
139            answer: None,
140            level: None,
141            standing: None,
142        }
143    }
144
145    #[test]
146    fn days_are_utc_dates() {
147        assert_eq!(day_of(0), "1970-01-01");
148        assert_eq!(day_of(1_793_348_000_000), "2026-10-30");
149        assert_eq!(day_of(DAY_MS * 59 + 5), "1970-03-01");
150    }
151
152    #[test]
153    fn counts_turns_started_joined_held_refused_and_sent_per_agent_per_day() {
154        let d = 1_793_348_000_000;
155        let stats = count(
156            vec![
157                entry(d, "AgentX", "Agent1", None, Some("started"), true),
158                entry(d + 1, "AgentX", "Agent1", None, Some("joined"), true),
159                entry(d + 2, "AgentY", "Agent1", Some("held_delivered"), Some("started"), true),
160                entry(d + 3, "Agent1", "AgentX", Some("ack_refused"), None, false),
161                entry(d + 4, "AgentX", "Agent1", None, None, false),
162                entry(d - 2 * DAY_MS, "AgentX", "Agent1", None, Some("started"), true),
163            ],
164            d - DAY_MS,
165        );
166        let agent1 = stats.iter().find(|s| s.agent == "agent1").unwrap();
167        assert_eq!((agent1.received, agent1.turns_started, agent1.joined, agent1.held), (3, 2, 1, 1));
168        assert_eq!(agent1.acks_refused, 1, "a refused reply counts for the one who tried to send it");
169        assert_eq!(stats.iter().find(|s| s.agent == "agentx").unwrap().sent, 2);
170        assert_eq!(stats.iter().find(|s| s.agent == "agenty").unwrap().sent, 1);
171        assert!(stats.iter().all(|s| s.day == "2026-10-30"), "the entry from two days ago is outside the window");
172    }
173
174    #[test]
175    fn a_sensitive_op_decision_row_is_not_a_message() {
176        let d = 1_793_348_000_000;
177        let mut grant = entry(d, "Agent1", "Agent1", None, None, true);
178        grant.standing = Some(true);
179        let mut countdown = entry(d + 1, "Agent1", "Agent1", None, None, true);
180        countdown.standing = Some(false);
181        let stats = count(vec![grant, countdown, entry(d + 2, "AgentX", "Agent1", None, Some("started"), true)], d - DAY_MS);
182        let agent1 = stats.iter().find(|s| s.agent == "agent1").unwrap();
183        assert_eq!((agent1.received, agent1.sent), (1, 0), "only the real message counts, for both its receiver and sender");
184        assert_eq!(stats.iter().find(|s| s.agent == "agentx").unwrap().sent, 1);
185    }
186}