agentmux_srv_core/backend/
history_usage.rs1use std::path::{Path, PathBuf};
15
16use crate::backend::rpc_types::{HistoryReclaim, HistoryUsage, HistoryUsageAgent, HistoryUsageKind, HistoryUsageProblem};
17use crate::backend::storage::filestore::FileStore;
18
19#[derive(Debug, Clone)]
21pub struct Roots {
22 pub transcripts_db: PathBuf,
24}
25
26impl Roots {
27 pub fn on_this_machine() -> Option<Roots> {
29 Some(Roots { transcripts_db: crate::registry::resolve_shared_transcripts_dir()?.join("filestore.db") })
30 }
31}
32
33fn file_size(path: &Path) -> u64 {
34 match std::fs::metadata(path) {
35 Ok(m) if m.is_file() => m.len(),
36 _ => 0,
37 }
38}
39
40pub fn compute(
43 roots: &Roots,
44 transcripts: Option<&FileStore>,
45 name_of: impl Fn(&str) -> Option<String>,
46 now_ms: u64,
47) -> HistoryUsage {
48 let (total_bytes, unreadable) = stored_bytes(roots, transcripts);
51 let mut problem = unreadable.or_else(|| waiting_problem(roots.transcripts_db.parent()));
52 let kinds = match transcripts {
53 Some(t) => kinds_of(t, total_bytes).unwrap_or_else(|e| {
54 problem.get_or_insert_with(|| HistoryUsageProblem { key: "breakdown_unreadable".into(), detail: Some(e.to_string()) });
55 Vec::new()
56 }),
57 None => Vec::new(),
58 };
59 HistoryUsage { total_bytes, kinds, problem, agents: largest_agents(transcripts, name_of), computed_at_ms: now_ms }
60}
61
62fn stored_bytes(roots: &Roots, transcripts: Option<&FileStore>) -> (u64, Option<HistoryUsageProblem>) {
66 let mut problem = None;
67 let stats = transcripts.and_then(|t| match t.page_stats() {
68 Ok(s) => Some(s),
69 Err(e) => {
70 tracing::warn!(error = %e, "history.usage: couldn't read the transcript store's page counts");
71 problem = Some(HistoryUsageProblem { key: "store_unreadable".into(), detail: None });
72 None
73 }
74 });
75 if let Some((page_size, page_count, free_pages, _)) = stats {
76 let (size, count, free) = (page_size.max(0) as u64, page_count.max(0) as u64, free_pages.max(0) as u64);
77 return (count.saturating_sub(free) * size, None);
78 }
79 let mut bytes = file_size(&roots.transcripts_db);
80 for ext in ["-wal", "-shm"] {
81 let mut name = roots.transcripts_db.as_os_str().to_owned();
82 name.push(ext);
83 bytes += file_size(Path::new(&name));
84 }
85 (bytes, problem)
86}
87
88fn kinds_of(store: &FileStore, total: u64) -> Result<Vec<HistoryUsageKind>, crate::backend::storage::error::StoreError> {
93 use crate::backend::transcript::kinds::{self, Kind, KINDS};
94 let counted = kinds::totals(store);
95 let logical = store.logical_bytes()?.max(0) as u64;
96 let whole = logical.max(counted.sum()).max(1) as u128;
98 let share = |k: Kind| (u128::from(total) * u128::from(counted.get(k)) / whole) as u64;
99 let named: u64 = KINDS.iter().filter(|(k, _)| *k != Kind::Other).map(|(k, _)| share(*k)).sum();
100 Ok(KINDS
101 .iter()
102 .map(|(k, key)| HistoryUsageKind {
103 key: (*key).to_string(),
104 bytes: if *k == Kind::Other { total.saturating_sub(named) } else { share(*k) },
105 })
106 .collect())
107}
108
109fn waiting_problem(store_dir: Option<&Path>) -> Option<HistoryUsageProblem> {
113 use crate::backend::transcript::framer;
114 if !framer::enabled() {
115 return None;
116 }
117 store_dir
118 .and_then(framer::who_blocks)
119 .map(|who| HistoryUsageProblem { key: "compression_waiting".into(), detail: Some(who) })
120}
121
122pub fn waiting_now() -> Option<HistoryUsageProblem> {
125 let roots = Roots::on_this_machine()?;
126 waiting_problem(roots.transcripts_db.parent())
127}
128
129pub fn reclaim_of(db: &Path) -> HistoryReclaim {
131 let (marker, last) = crate::backend::storage::filestore::reclaim::status(db);
132 let last = last.unwrap_or_default();
133 HistoryReclaim {
134 pending: marker.is_some(),
135 waiting_for: marker.as_ref().and_then(|m| m.waiting_for.clone()),
136 last_error: marker.as_ref().and_then(|m| m.last_error.clone()).or(last.error.clone()),
137 last_done_ms: if last.error.is_none() { last.at_ms } else { 0 },
138 last_before_bytes: last.before_bytes,
139 last_after_bytes: last.after_bytes,
140 }
141}
142
143fn largest_agents(transcripts: Option<&FileStore>, name_of: impl Fn(&str) -> Option<String>) -> Vec<HistoryUsageAgent> {
145 const TOP: usize = 12;
146 let Some(fs) = transcripts else { return Vec::new() };
147 let Ok(zones) = fs.zone_ids_with_prefix("agent:") else { return Vec::new() };
148 let mut agents: Vec<HistoryUsageAgent> = zones
149 .iter()
150 .filter_map(|zone| {
151 let id = zone.strip_prefix("agent:")?.strip_suffix(":current")?;
152 if crate::backend::transcript::damage::is_damaged(zone) {
153 return None;
154 }
155 let file = match fs.stat(zone, crate::backend::agent_session::OUTPUT_FILE) {
156 Ok(file) => file?,
157 Err(e) => {
158 crate::backend::transcript::damage::note_if_shared(fs, zone, "history size", &e);
159 return None;
160 }
161 };
162 let bytes = file.size.max(0) as u64;
163 (bytes > 0).then(|| HistoryUsageAgent {
164 definition_id: id.to_string(),
165 name: name_of(id).unwrap_or_else(|| id.to_string()),
166 bytes,
167 })
168 })
169 .collect();
170 agents.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.name.cmp(&b.name)));
171 agents.truncate(TOP);
172 agents
173}
174
175#[cfg(test)]
176#[path = "history_usage_tests.rs"]
177mod tests;