Skip to main content

agentmux_srv_core/backend/
build_cache.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Clearing agents' cargo build caches and warning when a disk runs low
5//! (`docs/specs/SPEC_BUILD_CACHE_CLEANUP_2026_10_26.md`).
6//!
7//! Three hosts nearly filled their disks in two days from agents' `target` folders. On one of
8//! them 67% of 1 TB of targets was `target/<profile>/incremental`, and 90% of that was the
9//! `agentmux_srv` crate: every change to a dependency gives the crate a new incremental
10//! directory (about 10 GB) and the old one is never reused or collected.
11//!
12//! Three things are done here, none of which can break a build (the worst case of a wrong guess is
13//! a slower incremental rebuild):
14//!
15//! - **Orphans**: in each `incremental` folder, the newest few directories per crate are kept and
16//!   older ones idle for a day are removed.
17//! - **A finished task**: the agent's own clones lose all their `incremental` folders.
18//! - **Abandoned clones**: a clone nobody built in for days loses its whole `target` (when a task
19//!   finishes, or the disk is low).
20//!
21//! A clone with a cargo, rustc, linker or test process running in it is never touched. Every
22//! removal is logged, naming the workspace. This file is the file-system and policy part;
23//! `build_cache_service.rs` runs it on a schedule and sends the warnings.
24
25use std::collections::HashMap;
26use std::path::{Path, PathBuf};
27use std::time::{Duration, SystemTime};
28
29/// Settings keys (in the settings file's free-form part).
30pub const KEY_ENABLED: &str = "buildcache:enabled";
31pub const KEY_ORPHANS: &str = "buildcache:orphans";
32pub const KEY_ORPHAN_KEEP: &str = "buildcache:orphan_keep";
33pub const KEY_ORPHAN_IDLE_HOURS: &str = "buildcache:orphan_idle_hours";
34pub const KEY_STALE_DAYS: &str = "buildcache:stale_days";
35pub const KEY_WARN_FREE_GB: &str = "buildcache:warn_free_gb";
36pub const KEY_WARN_FREE_PCT: &str = "buildcache:warn_free_pct";
37
38/// What is cleared, and when the disk warning fires.
39#[derive(Debug, Clone, PartialEq)]
40pub struct Policy {
41    /// Everything below, except the warning, is off when this is false.
42    pub enabled: bool,
43    /// Prune orphan incremental directories (the hourly pass and the low-disk pass).
44    pub orphans: bool,
45    /// How many incremental directories per crate and profile are always kept.
46    pub orphan_keep: usize,
47    /// A directory beyond the newest `orphan_keep` goes only when idle this long.
48    pub orphan_idle: Duration,
49    /// A clone not built in this long loses its `target`; zero turns that off.
50    pub stale: Duration,
51    /// Warn when the free space is below this many bytes...
52    pub warn_free_bytes: u64,
53    /// ...or below this percentage of the disk.
54    pub warn_free_pct: f64,
55}
56
57impl Default for Policy {
58    fn default() -> Self {
59        Self {
60            enabled: true,
61            orphans: true,
62            orphan_keep: 3,
63            orphan_idle: Duration::from_secs(24 * 3600),
64            stale: Duration::from_secs(3 * 24 * 3600),
65            warn_free_bytes: 20 * (1 << 30),
66            warn_free_pct: 10.0,
67        }
68    }
69}
70
71impl Policy {
72    /// The policy the settings ask for; a missing or mistyped key keeps its default.
73    pub fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
74        let d = Self::default();
75        let num = |key: &str| extra.get(key).and_then(|v| v.as_f64()).filter(|n| n.is_finite() && *n >= 0.0);
76        Self {
77            enabled: extra.get(KEY_ENABLED).and_then(|v| v.as_bool()).unwrap_or(d.enabled),
78            orphans: extra.get(KEY_ORPHANS).and_then(|v| v.as_bool()).unwrap_or(d.orphans),
79            // Never fewer than one: the newest directory is the live one.
80            orphan_keep: num(KEY_ORPHAN_KEEP).map_or(d.orphan_keep, |n| (n as usize).max(1)),
81            orphan_idle: num(KEY_ORPHAN_IDLE_HOURS).and_then(|h| Duration::try_from_secs_f64(h * 3600.0).ok()).unwrap_or(d.orphan_idle),
82            stale: num(KEY_STALE_DAYS).and_then(|days| Duration::try_from_secs_f64(days * 86_400.0).ok()).unwrap_or(d.stale),
83            warn_free_bytes: num(KEY_WARN_FREE_GB).map_or(d.warn_free_bytes, |g| (g * (1u64 << 30) as f64) as u64),
84            warn_free_pct: num(KEY_WARN_FREE_PCT).unwrap_or(d.warn_free_pct),
85        }
86    }
87
88    /// Whether `free` of `total` bytes is low enough to warn about.
89    pub fn is_low(&self, free: u64, total: u64) -> bool {
90        total > 0 && (free < self.warn_free_bytes || (free as f64) * 100.0 < self.warn_free_pct * total as f64)
91    }
92}
93
94/// Every cargo clone in an agent's workspace: the workspace itself or a folder directly in it
95/// that has a `Cargo.toml` and a `target` folder.
96pub fn clones_in(workspace: &Path) -> Vec<PathBuf> {
97    let is_clone = |p: &Path| p.join("Cargo.toml").is_file() && p.join("target").is_dir();
98    let mut out = Vec::new();
99    if is_clone(workspace) {
100        out.push(workspace.to_path_buf());
101    }
102    if let Ok(entries) = std::fs::read_dir(workspace) {
103        for e in entries.flatten() {
104            let p = e.path();
105            let name = e.file_name();
106            let name = name.to_string_lossy();
107            if name.starts_with('.') || name == "node_modules" || name == "target" {
108                continue;
109            }
110            if e.file_type().is_ok_and(|t| t.is_dir()) && is_clone(&p) {
111                out.push(p);
112            }
113        }
114    }
115    out.sort();
116    out
117}
118
119/// The `incremental` folders of a `target`: `target/<profile>/incremental` and, for a cross
120/// build, `target/<triple>/<profile>/incremental`.
121pub fn incremental_roots(target: &Path) -> Vec<PathBuf> {
122    let mut out = Vec::new();
123    let subdirs = |p: &Path| -> Vec<PathBuf> {
124        std::fs::read_dir(p)
125            .into_iter()
126            .flatten()
127            .flatten()
128            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
129            .map(|e| e.path())
130            .collect()
131    };
132    for a in subdirs(target) {
133        if a.join("incremental").is_dir() {
134            out.push(a.join("incremental"));
135        }
136        for b in subdirs(&a) {
137            if b.join("incremental").is_dir() {
138                out.push(b.join("incremental"));
139            }
140        }
141    }
142    out.sort();
143    out
144}
145
146fn mtime(p: &Path) -> Option<SystemTime> {
147    std::fs::metadata(p).and_then(|m| m.modified()).ok()
148}
149
150/// The newest change in `dir`, looking two levels down: a crate's incremental folder holds
151/// session folders, which hold the files rustc rewrites on every build.
152fn activity(dir: &Path) -> SystemTime {
153    let mut newest = mtime(dir).unwrap_or(SystemTime::UNIX_EPOCH);
154    let mut bump = |t: Option<SystemTime>| {
155        if let Some(t) = t {
156            newest = newest.max(t);
157        }
158    };
159    for sess in std::fs::read_dir(dir).into_iter().flatten().flatten() {
160        bump(sess.metadata().and_then(|m| m.modified()).ok());
161        if sess.file_type().is_ok_and(|t| t.is_dir()) {
162            for f in std::fs::read_dir(sess.path()).into_iter().flatten().flatten() {
163                bump(f.metadata().and_then(|m| m.modified()).ok());
164            }
165        }
166    }
167    newest
168}
169
170/// The size of everything under `p`, in bytes.
171pub fn dir_size(p: &Path) -> u64 {
172    let mut total = 0u64;
173    let mut stack = vec![p.to_path_buf()];
174    while let Some(d) = stack.pop() {
175        let Ok(entries) = std::fs::read_dir(&d) else { continue };
176        for e in entries.flatten() {
177            match e.file_type() {
178                Ok(t) if t.is_dir() => stack.push(e.path()),
179                Ok(_) => total += e.metadata().map_or(0, |m| m.len()),
180                Err(_) => {}
181            }
182        }
183    }
184    total
185}
186
187/// A crate's incremental directory is named `<crate>-<hash>`; the crate is what comes before
188/// the last dash.
189fn crate_of(name: &str) -> &str {
190    name.rsplit_once('-').map_or(name, |(c, _)| c)
191}
192
193/// The incremental directories under `root` to remove: per crate, everything beyond the newest
194/// `keep` that has been idle for `idle` as of `now`.
195pub fn orphans_in(root: &Path, keep: usize, idle: Duration, now: SystemTime) -> Vec<PathBuf> {
196    let mut by_crate: HashMap<String, Vec<(SystemTime, PathBuf)>> = HashMap::new();
197    for e in std::fs::read_dir(root).into_iter().flatten().flatten() {
198        if !e.file_type().is_ok_and(|t| t.is_dir()) {
199            continue;
200        }
201        let name = e.file_name().to_string_lossy().into_owned();
202        by_crate.entry(crate_of(&name).to_string()).or_default().push((activity(&e.path()), e.path()));
203    }
204    let mut out = Vec::new();
205    for (_, mut dirs) in by_crate {
206        dirs.sort_by(|a, b| b.0.cmp(&a.0));
207        out.extend(
208            dirs.into_iter()
209                .skip(keep.max(1))
210                .filter(|(at, _)| now.duration_since(*at).unwrap_or_default() >= idle)
211                .map(|(_, p)| p),
212        );
213    }
214    out.sort();
215    out
216}
217
218/// When something was last built in `target`: the newest change among the target, its profile
219/// folders and the folders cargo writes to on every build.
220pub fn last_build(target: &Path) -> SystemTime {
221    let mut newest = mtime(target).unwrap_or(SystemTime::UNIX_EPOCH);
222    let subdirs = |p: &Path| -> Vec<PathBuf> {
223        std::fs::read_dir(p)
224            .into_iter()
225            .flatten()
226            .flatten()
227            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
228            .map(|e| e.path())
229            .collect()
230    };
231    let mut look = |p: &Path| {
232        for p in [p.to_path_buf(), p.join(".fingerprint"), p.join("deps"), p.join("incremental")] {
233            if let Some(t) = mtime(&p) {
234                newest = newest.max(t);
235            }
236        }
237    };
238    // `target/<profile>` and, for a cross build, `target/<triple>/<profile>`.
239    for a in subdirs(target) {
240        look(&a);
241        for b in subdirs(&a) {
242            look(&b);
243        }
244    }
245    newest
246}
247
248/// Whether a build seems to be running in `clone`: a process whose working directory,
249/// executable or command line is inside it and which is a compiler, linker, cargo or something
250/// run from the `target` folder. Looks at the machine's processes now.
251pub fn build_running_in(clone: &Path, procs: &sysinfo::System) -> bool {
252    let needle = normal(clone);
253    procs.processes().values().any(|p| {
254        let name = p.name().to_string_lossy().to_ascii_lowercase();
255        let stem = name.strip_suffix(".exe").unwrap_or(&name);
256        let tool = matches!(stem, "cargo" | "rustc" | "link" | "lld-link" | "ld" | "cc" | "cl" | "clang" | "gcc" | "cmake" | "ninja" | "clippy-driver" | "rustdoc");
257        let in_clone = p.cwd().is_some_and(|c| normal(c).starts_with(&needle))
258            || p.exe().is_some_and(|e| normal(e).starts_with(&needle))
259            || p.cmd().iter().any(|a| normal(Path::new(a)).contains(&needle));
260        in_clone && (tool || p.exe().is_some_and(|e| normal(e).starts_with(&needle)))
261    })
262}
263
264fn normal(p: &Path) -> String {
265    let s = p.to_string_lossy().replace('\\', "/").to_ascii_lowercase();
266    // `canonicalize` on Windows gives a `\\?\C:\...` path.
267    s.strip_prefix("//?/").map_or_else(|| s.clone(), str::to_string)
268}
269
270/// A snapshot of the machine's processes, for [`build_running_in`].
271pub fn snapshot_processes() -> sysinfo::System {
272    let mut sys = sysinfo::System::new();
273    sys.refresh_processes_specifics(
274        sysinfo::ProcessesToUpdate::All,
275        true,
276        sysinfo::ProcessRefreshKind::nothing()
277            .with_cwd(sysinfo::UpdateKind::Always)
278            .with_exe(sysinfo::UpdateKind::Always)
279            .with_cmd(sysinfo::UpdateKind::Always),
280    );
281    sys
282}
283
284/// What a pass is for; it goes in the log.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub enum Why {
287    /// An agent finished a task.
288    TaskDone,
289    /// The hourly pass.
290    Hourly,
291    /// The disk is low.
292    LowDisk,
293    /// An agent asked for it as a sensitive request (`disk_cleanup`) and the countdown ended unvetoed.
294    Asked,
295}
296
297impl Why {
298    fn as_str(self) -> &'static str {
299        match self {
300            Why::TaskDone => "task-done",
301            Why::Hourly => "hourly",
302            Why::LowDisk => "low-disk",
303            Why::Asked => "asked",
304        }
305    }
306}
307
308/// One removal.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct Removed {
311    pub path: PathBuf,
312    pub bytes: u64,
313    pub what: &'static str,
314}
315
316/// What a pass over one workspace did.
317#[derive(Debug, Default, Clone, PartialEq, Eq)]
318pub struct Report {
319    pub removed: Vec<Removed>,
320    /// Clones left alone because a build was running in them.
321    pub busy: Vec<PathBuf>,
322}
323
324impl Report {
325    pub fn bytes(&self) -> u64 {
326        self.removed.iter().map(|r| r.bytes).sum()
327    }
328}
329
330/// Where removals are logged (`AGENTMUX_BUILD_CACHE_LOG` overrides it, for tests).
331pub fn log_path() -> Option<PathBuf> {
332    if let Some(p) = std::env::var_os("AGENTMUX_BUILD_CACHE_LOG").filter(|p| !p.is_empty()) {
333        return Some(PathBuf::from(p));
334    }
335    Some(dirs::home_dir()?.join(".agentmux").join("logs").join("build-cache-cleanup.log"))
336}
337
338fn log_removal(log: Option<&Path>, why: Why, workspace: &Path, r: &Removed) {
339    tracing::info!(why = why.as_str(), workspace = %workspace.display(), path = %r.path.display(), bytes = r.bytes, what = r.what, "build cache: removed");
340    let Some(log) = log else { return };
341    if let Some(dir) = log.parent() {
342        let _ = std::fs::create_dir_all(dir);
343    }
344    use std::io::Write;
345    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(log) {
346        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
347        let _ = writeln!(f, "{now}\t{}\t{}\t{}\t{}\t{}", why.as_str(), workspace.display(), r.what, r.bytes, r.path.display());
348    }
349}
350
351fn remove(log: Option<&Path>, why: Why, workspace: &Path, path: PathBuf, what: &'static str, report: &mut Report) {
352    let bytes = dir_size(&path);
353    match std::fs::remove_dir_all(&path) {
354        Ok(()) => {
355            let r = Removed { path, bytes, what };
356            log_removal(log, why, workspace, &r);
357            report.removed.push(r);
358        }
359        Err(e) => tracing::warn!(path = %path.display(), error = %e, "build cache: could not remove"),
360    }
361}
362
363/// One pass over the clones of `workspace`.
364///
365/// `TaskDone` clears every `incremental` folder; the others prune orphans (when the policy
366/// allows). `TaskDone`, `LowDisk` and `Asked` also remove a clone's whole `target` when nothing was built
367/// in it for the policy's `stale` time; the hourly pass leaves a quiet clone alone. A clone with
368/// a build running in it is skipped.
369pub fn run_pass(workspace: &Path, why: Why, policy: &Policy, is_busy: &dyn Fn(&Path) -> bool, now: SystemTime, log: Option<&Path>) -> Report {
370    let mut report = Report::default();
371    if !policy.enabled {
372        return report;
373    }
374    for clone in clones_in(workspace) {
375        if is_busy(&clone) {
376            report.busy.push(clone);
377            continue;
378        }
379        let target = clone.join("target");
380        let stale_applies = matches!(why, Why::TaskDone | Why::LowDisk | Why::Asked);
381        // What to remove from this clone, decided now and checked again before each removal: a
382        // removal takes long, and the agent may start a build here in the meantime (the answer
383        // to its finished task names its next one).
384        let mut todo: Vec<(PathBuf, &'static str)> = Vec::new();
385        if stale_applies && !policy.stale.is_zero() && now.duration_since(last_build(&target)).unwrap_or_default() >= policy.stale {
386            todo.push((target, "stale target"));
387        } else {
388            for root in incremental_roots(&target) {
389                if why == Why::TaskDone {
390                    for e in std::fs::read_dir(&root).into_iter().flatten().flatten() {
391                        if e.file_type().is_ok_and(|t| t.is_dir()) {
392                            todo.push((e.path(), "incremental"));
393                        }
394                    }
395                } else if policy.orphans {
396                    todo.extend(orphans_in(&root, policy.orphan_keep, policy.orphan_idle, now).into_iter().map(|d| (d, "orphan incremental")));
397                }
398            }
399        }
400        for (path, what) in todo {
401            if is_busy(&clone) {
402                report.busy.push(clone);
403                break;
404            }
405            remove(log, why, workspace, path, what, &mut report);
406        }
407    }
408    report
409}
410
411/// The free and total bytes of the disk that holds `path`.
412pub fn disk_of(path: &Path) -> Option<(u64, u64)> {
413    let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
414    let want = normal(&path);
415    let disks = sysinfo::Disks::new_with_refreshed_list();
416    disks
417        .list()
418        .iter()
419        .filter(|d| want.starts_with(&normal(d.mount_point())))
420        .max_by_key(|d| d.mount_point().as_os_str().len())
421        .map(|d| (d.available_space(), d.total_space()))
422}
423
424/// A clone's `target` size and how much of it is `incremental`.
425#[derive(Debug, Clone, PartialEq, Eq)]
426pub struct TargetSize {
427    pub clone: PathBuf,
428    pub target_bytes: u64,
429    pub incremental_bytes: u64,
430}
431
432/// The size of every clone's `target` in `workspace`, largest first.
433pub fn target_sizes(workspace: &Path) -> Vec<TargetSize> {
434    let mut out: Vec<TargetSize> = clones_in(workspace)
435        .into_iter()
436        .map(|clone| {
437            let target = clone.join("target");
438            let incremental_bytes = incremental_roots(&target).iter().map(|r| dir_size(r)).sum();
439            TargetSize { target_bytes: dir_size(&target), incremental_bytes, clone }
440        })
441        .collect();
442    out.sort_by(|a, b| b.target_bytes.cmp(&a.target_bytes));
443    out
444}
445
446/// "193 GB", "4.7 GB", "820 MB".
447pub fn human(bytes: u64) -> String {
448    const GB: f64 = (1u64 << 30) as f64;
449    let b = bytes as f64;
450    if b >= 100.0 * GB {
451        format!("{:.0} GB", b / GB)
452    } else if b >= GB {
453        format!("{:.1} GB", b / GB)
454    } else {
455        format!("{:.0} MB", b / (1u64 << 20) as f64)
456    }
457}
458
459#[cfg(test)]
460#[path = "build_cache_tests.rs"]
461mod tests;