Skip to main content

agentmux_srv_core/backend/
disk_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! When the low-disk note goes out and what it says (`build_cache_service::disk_check` sends it).
5//! Pure functions, so the decisions are tested without a disk, a clock or a running agent.
6//!
7//! The first version went to the owners of the three largest workspaces whatever their size, once
8//! an hour for as long as the free space hovered at the threshold, as a message that starts a
9//! turn. On one host an agent with a 3.5 GB folder was woken eight times in three hours, and the
10//! text set "43 GB free" next to "below the 20 GB / 10% level". Now:
11//!
12//! - a note goes out again only after free space falls a further [`MORE_DROP`], or the level gets
13//!   worse (warning to critical), and at most once an hour: never on a timer alone;
14//! - the disk counts as recovered only with room to spare ([`recovered`]), so free space
15//!   bouncing across the threshold is one event, not many;
16//! - the text says which rule tripped and which did not;
17//! - a warning is held for the agent's next turn; only a critical level starts one.
18
19use std::path::Path;
20
21use crate::backend::build_cache::{human, Policy};
22
23/// How low the disk is.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
25pub enum Level {
26    Ok,
27    /// Under the warning level: free space below `warn_free_bytes` or `warn_free_pct`.
28    Warning,
29    /// Under half of the warning level on either rule.
30    Critical,
31}
32
33/// Free space must fall this much below what the last note reported to be worth another note, and
34/// rise this much above the warning level to count as recovered.
35pub const MORE_DROP: u64 = 5 << 30;
36/// Percentage points above the warning percentage that count as recovered.
37pub const RECOVER_PCT: f64 = 1.0;
38/// A note goes out at most this often (seconds), unless the level got worse.
39pub const MIN_GAP_SECS: u64 = 3600;
40/// A workspace whose build folders total this much hears of the warning.
41pub const BIG_WORKSPACE: u64 = 10 << 30;
42/// Or whose incremental caches total this much.
43pub const BIG_INCREMENTAL: u64 = 2 << 30;
44
45fn pct_free(free: u64, total: u64) -> f64 {
46    if total > 0 {
47        free as f64 * 100.0 / total as f64
48    } else {
49        0.0
50    }
51}
52
53/// The level of `free` of `total` bytes under `policy`.
54pub fn level(policy: &Policy, free: u64, total: u64) -> Level {
55    if total == 0 {
56        return Level::Ok;
57    }
58    if free < policy.warn_free_bytes / 2 || pct_free(free, total) < policy.warn_free_pct / 2.0 {
59        Level::Critical
60    } else if policy.is_low(free, total) {
61        Level::Warning
62    } else {
63        Level::Ok
64    }
65}
66
67/// Whether the disk is back above the warning level with room to spare, so the next drop is a new
68/// event. Right at the threshold it is not: free space that bounces across it stays one event.
69pub fn recovered(policy: &Policy, free: u64, total: u64) -> bool {
70    total > 0 && free >= policy.warn_free_bytes.saturating_add(MORE_DROP) && pct_free(free, total) >= policy.warn_free_pct + RECOVER_PCT
71}
72
73/// The last note that went out.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct Sent {
76    pub level: Level,
77    /// Free bytes it reported.
78    pub free: u64,
79    /// Unix seconds.
80    pub at: u64,
81}
82
83impl Sent {
84    fn render(&self) -> String {
85        let word = if self.level == Level::Critical { "critical" } else { "warning" };
86        format!("{word} {} {}", self.free, self.at)
87    }
88
89    fn parse(text: &str) -> Option<Sent> {
90        let mut it = text.split_whitespace();
91        let level = match it.next()? {
92            "warning" => Level::Warning,
93            "critical" => Level::Critical,
94            _ => return None,
95        };
96        Some(Sent { level, free: it.next()?.parse().ok()?, at: it.next()?.parse().ok()? })
97    }
98}
99
100/// The record of the last note, shared by every AgentMux on the host. A file from the first version
101/// holds only a time: that note reported nothing about free space, so it counts as one sent at
102/// today's free space and nothing follows until it drops further.
103pub fn read_sent(marker: &Path, free_now: u64) -> Option<Sent> {
104    let text = std::fs::read_to_string(marker).ok()?;
105    Sent::parse(&text).or_else(|| text.trim().parse::<u64>().ok().map(|at| Sent { level: Level::Warning, free: free_now, at }))
106}
107
108/// Records that a note went out. Only called once someone received it: a note nobody got must not
109/// use up the drop.
110pub fn write_sent(marker: &Path, sent: &Sent) -> bool {
111    if let Some(dir) = marker.parent() {
112        let _ = std::fs::create_dir_all(dir);
113    }
114    std::fs::write(marker, sent.render()).is_ok()
115}
116
117/// Forgets the last note, because the disk recovered.
118pub fn clear_sent(marker: &Path) {
119    let _ = std::fs::remove_file(marker);
120}
121
122/// Whether a note goes out now. `prev` is the last one, `now_level` the level now (not `Ok`),
123/// `free` the free bytes now and `now_s` unix seconds.
124pub fn should_send(prev: Option<&Sent>, now_level: Level, free: u64, now_s: u64) -> bool {
125    if now_level == Level::Ok {
126        return false;
127    }
128    let Some(prev) = prev else { return true };
129    if now_level > prev.level {
130        return true;
131    }
132    if now_s.saturating_sub(prev.at) < MIN_GAP_SECS {
133        return false;
134    }
135    free.saturating_add(MORE_DROP) <= prev.free
136}
137
138/// Why `free` of `total` is low, in numbers, and which rule tripped: the percentage, the size, or
139/// both. Both are shown with the one that did not trip marked as such, so "43 GB free" never sits
140/// next to a 20 GB level as if it were below it.
141pub fn why(policy: &Policy, level: Level, free: u64, total: u64) -> String {
142    let (pct_limit, gb_limit) = if level == Level::Critical {
143        (policy.warn_free_pct / 2.0, policy.warn_free_bytes / 2)
144    } else {
145        (policy.warn_free_pct, policy.warn_free_bytes)
146    };
147    let kind = if level == Level::Critical { "critical" } else { "warning" };
148    let pct = pct_free(free, total);
149    let by_pct = pct < pct_limit;
150    let by_size = free < gb_limit;
151    let pct_part = format!("under {pct_limit:.0}% free ({pct:.1}% is free)");
152    let size_part = format!("under {} free ({} is free)", human(gb_limit), human(free));
153    match (by_pct, by_size) {
154        (true, true) => format!("Both {kind} rules tripped: {pct_part} and {size_part}."),
155        (true, false) => format!("The {kind} rule that tripped is the percentage: {pct_part}. The size rule ({}) is not reached.", human(gb_limit)),
156        (false, true) => format!("The {kind} rule that tripped is the size: {size_part}. The percentage rule ({pct_limit:.0}%) is not reached."),
157        // The level can only be Warning or Critical here because one of the rules tripped.
158        (false, false) => format!("The {kind} level was reached ({pct:.1}% / {} free).", human(free)),
159    }
160}
161
162/// The note: how low the disk is, which rule tripped, and `lines` (the folders it is about) under
163/// `heading`.
164pub fn note_text(policy: &Policy, level: Level, free: u64, total: u64, heading: &str, lines: &[String]) -> String {
165    let low = if level == Level::Critical { "critically low" } else { "running low" };
166    let mut out = vec![format!(
167        "[AgentMux] This computer's disk is {low}: {} free of {} ({:.1}%). {}",
168        human(free),
169        human(total),
170        pct_free(free, total),
171        why(policy, level, free, total)
172    )];
173    if !lines.is_empty() {
174        out.push(heading.to_string());
175        out.extend(lines.iter().cloned());
176    }
177    out.push(
178        "AgentMux already clears an agent's incremental cache when it completes a task and prunes old incremental folders every hour. Nothing is needed from you unless you are done with one of these clones: then delete its `target` folder (only your own, by path)."
179            .to_string(),
180    );
181    out.join("\n")
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    const GB: u64 = 1 << 30;
189
190    fn pol() -> Policy {
191        Policy::default() // warn under 20 GB or 10%
192    }
193
194    #[test]
195    fn the_level_follows_either_rule_and_critical_is_half_of_it() {
196        let total = 440 * GB;
197        assert_eq!(level(&pol(), 60 * GB, total), Level::Ok);
198        assert_eq!(level(&pol(), 43 * GB, total), Level::Warning, "9.8% is under 10% though 43 GB is over 20 GB");
199        assert_eq!(level(&pol(), 44 * GB, total), Level::Ok, "exactly 10% is not under it");
200        assert_eq!(level(&pol(), 19 * GB, 100 * GB), Level::Warning, "19% free but under 20 GB");
201    }
202
203    #[test]
204    fn critical_is_under_half_of_either_level() {
205        assert_eq!(level(&pol(), 9 * GB, 1000 * GB), Level::Critical, "under 10 GB");
206        assert_eq!(level(&pol(), 21 * GB, 1000 * GB), Level::Critical, "2.1% free is under 5%");
207        assert_eq!(level(&pol(), 21 * GB, 200 * GB), Level::Ok, "10.5% free and over 20 GB is fine");
208        assert_eq!(level(&pol(), 15 * GB, 200 * GB), Level::Warning, "7.5% free and 15 GB: warning, not critical");
209        assert_eq!(level(&pol(), 15 * GB, 0), Level::Ok, "no disk size, no verdict");
210    }
211
212    #[test]
213    fn a_disk_hovering_at_the_threshold_gets_one_note() {
214        // The observed case: about 440 GB, free space 43.7 to 42.4 GB, 9.6 to 9.9%.
215        let total = 440 * GB;
216        let p = pol();
217        let mb = GB / 1000;
218        let first = Sent { level: Level::Warning, free: 43_900 * mb, at: 1000 };
219        assert!(should_send(None, level(&p, 43_900 * mb, total), 43_900 * mb, 1000), "the first drop is told");
220        for (i, f) in [43_700u64, 43_500, 43_300, 42_400, 43_900, 43_100].into_iter().enumerate() {
221            let free = f * mb;
222            let now = 1000 + 3600 * (i as u64 + 2);
223            assert!(!should_send(Some(&first), level(&p, free, total), free, now), "{f} MB free hours later is not a new event");
224        }
225    }
226
227    #[test]
228    fn a_real_further_drop_or_a_worse_level_is_told_again() {
229        let p = pol();
230        let total = 440 * GB;
231        let prev = Sent { level: Level::Warning, free: 44 * GB, at: 1000 };
232        assert!(should_send(Some(&prev), level(&p, 38 * GB, total), 38 * GB, 1000 + 4000), "6 GB further down, an hour on");
233        assert!(!should_send(Some(&prev), level(&p, 38 * GB, total), 38 * GB, 1000 + 600), "but not within the hour");
234        assert!(should_send(Some(&prev), level(&p, 9 * GB, total), 9 * GB, 1000 + 60), "critical is told at once, whatever the hour");
235        let crit = Sent { level: Level::Critical, free: 9 * GB, at: 1000 };
236        assert!(!should_send(Some(&crit), Level::Warning, 30 * GB, 1000 + 9000), "a better level is not a drop");
237        // Free space bouncing across the critical line: the record stays critical, so a dip back
238        // into it, hours later, is the same event.
239        assert!(!should_send(Some(&crit), Level::Critical, 9 * GB + GB / 2, 1000 + 5 * 3600), "back into critical at about the same free space");
240        assert!(should_send(Some(&crit), Level::Critical, 3 * GB, 1000 + 2 * 3600), "but a real further drop is told");
241        assert!(!should_send(Some(&prev), Level::Ok, 90 * GB, 99999), "nothing to say when the disk is fine");
242    }
243
244    #[test]
245    fn recovery_needs_room_to_spare() {
246        let p = pol();
247        let total = 440 * GB;
248        assert!(!recovered(&p, 44 * GB, total), "9.99% is not recovered: just under 11%");
249        assert!(!recovered(&p, 46 * GB, total), "10.5% is over the line but not by a point");
250        assert!(recovered(&p, 50 * GB, total), "11.4% and over 25 GB");
251        assert!(!recovered(&p, 24 * GB, 100 * GB), "24% free but under 25 GB: not by the 5 GB margin");
252        assert!(recovered(&p, 26 * GB, 100 * GB), "26% and over 25 GB");
253    }
254
255    #[test]
256    fn the_record_survives_a_round_trip_and_a_file_from_the_first_version() {
257        let dir = tempfile::tempdir().unwrap();
258        let marker = dir.path().join("locks").join("build-cache-warn");
259        assert!(read_sent(&marker, 5).is_none());
260        let sent = Sent { level: Level::Critical, free: 9 * GB, at: 1234 };
261        assert!(write_sent(&marker, &sent));
262        assert_eq!(read_sent(&marker, 5), Some(sent));
263        std::fs::write(&marker, "1793900000").unwrap();
264        assert_eq!(
265            read_sent(&marker, 42 * GB),
266            Some(Sent { level: Level::Warning, free: 42 * GB, at: 1793900000 }),
267            "the first version kept only a time: treated as a note sent at today's free space"
268        );
269        clear_sent(&marker);
270        assert!(read_sent(&marker, 5).is_none());
271    }
272
273    #[test]
274    fn the_text_says_which_rule_tripped_and_which_did_not() {
275        let p = pol();
276        let by_pct = why(&p, Level::Warning, 43 * GB, 440 * GB);
277        assert!(by_pct.contains("percentage"), "{by_pct}");
278        assert!(by_pct.contains("under 10% free (9.8% is free)"), "{by_pct}");
279        assert!(by_pct.contains("size rule (20.0 GB) is not reached"), "{by_pct}");
280        let by_size = why(&p, Level::Warning, 15 * GB, 100 * GB);
281        assert!(by_size.contains("rule that tripped is the size"), "{by_size}");
282        assert!(by_size.contains("percentage rule (10%) is not reached") || by_size.contains("Both"), "{by_size}");
283        let both = why(&p, Level::Warning, 15 * GB, 400 * GB);
284        assert!(both.starts_with("Both warning rules tripped"), "{both}");
285        let crit = why(&p, Level::Critical, 9 * GB, 100 * GB);
286        assert!(crit.contains("critical"), "{crit}");
287        assert!(crit.contains("under 10.0 GB free"), "{crit}");
288    }
289
290    #[test]
291    fn the_note_leads_with_the_numbers_then_the_folders() {
292        let p = pol();
293        let lines = vec!["- /a/w1/agentmux : 24 GB (3.0 GB of it incremental)".to_string()];
294        let text = note_text(&p, Level::Warning, 43 * GB, 440 * GB, "Your largest build folders:", &lines);
295        assert!(text.starts_with("[AgentMux] This computer's disk is running low: 43.0 GB free of 440 GB (9.8%)."), "{text}");
296        assert!(text.contains("Your largest build folders:\n- /a/w1/agentmux : 24 GB"), "{text}");
297        assert!(text.contains("Nothing is needed from you unless"), "an informational note asks nothing: {text}");
298        let crit = note_text(&p, Level::Critical, 9 * GB, 440 * GB, "x", &[]);
299        assert!(crit.contains("critically low"), "{crit}");
300        assert!(!crit.contains("\nx\n"), "no heading without folders: {crit}");
301    }
302}