garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

cartopolis-agent · 2026-11-27T10:28:03Z

fix(node): short of disk, free other checkouts' builds too, not only the warm one

The guard trimmed only the warm checkout's target/, and only down to the
ceiling's 24 GB floor, however full /work was. On vps-1, whose /work is
the VPS's shared /data, it trimmed itself back to 24 GB all afternoon
while /data stood at 0 free and every session's builds and git writes
failed (2026-11-26); the 10 GB of builds under /work/repos were never
looked at.

Below LOW_DISK (10 GB) free, the guard now frees what costs least, on
every checkout: incremental state first, then the build directories of
repositories nobody built in two days, oldest first, until the warmer's
20 GB reserve is free or nothing cheap is left. Only below 10 GB: a disk
that holds other things too may never reach the reserve, and dropping
incremental state every five minutes there would slow every build. The
warm checkout's target/ keeps its floor; trim_target still owns it.
src/node.rs | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/warm.rs |   2 +-
 2 files changed, 141 insertions(+), 1 deletion(-)

diff --git a/src/node.rs b/src/node.rs
index 00cc7fe..ffa7cc3 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -367,6 +367,7 @@ pub fn guard() -> Result<i32> {
             std::thread::spawn(|| {
                 measure_target();
                 trim_target(&config());
+                free_up_disk(&config());
             });
         }
         if tick % 30 == 0 {
@@ -884,6 +885,120 @@ fn trim_target(cfg: &Config) {
     }
 }
 
+/// Where the other repositories' checkouts are (`flush.rs`): `/work/repos/owner/name`.
+const REPOS: &str = "/work/repos";
+
+/// A repository's build directory untouched this long is dropped when /work
+/// runs short: its next build there is a cold one, which a session that comes
+/// back to it after two days pays anyway.
+const STALE_TARGET: Duration = Duration::from_secs(2 * 86400);
+
+/// Below [`LOW_DISK`] free on /work, frees what costs least until
+/// [`crate::warm::DISK_RESERVE`] is free or nothing cheap is left, on every
+/// checkout of the node and not only the warm one: incremental
+/// state first, then the build directories of repositories nobody built in
+/// two days, oldest first; never the warm checkout's target/ beyond what
+/// [`trim_target`] takes. The ceiling alone counts the warm checkout, and its
+/// 24 GB floor holds however full the disk: on vps-1, whose /work is the VPS's
+/// shared /data, the node trimmed itself back to 24 GB all afternoon while
+/// /data stood at 0 free and every session's builds and git writes failed
+/// (2026-11-26), with 10 GB of other repositories' builds never looked at.
+fn free_up_disk(cfg: &Config) {
+    let free = || crate::util::disk_space(Path::new("/work")).map_or(u64::MAX, |d| d.0);
+    let from = free();
+    // Only when short: a disk that holds other things too (vps-1's /data) may
+    // never have the reserve free, and dropping incremental state every five
+    // minutes there would make every build a slow one.
+    if from >= LOW_DISK {
+        return;
+    }
+    let mut targets = vec![Path::new(CHECKOUT).join("target")];
+    targets.extend(repo_targets(Path::new(REPOS)));
+    let mut candidates: Vec<PathBuf> = targets.iter().flat_map(|t| incremental_dirs(t)).collect();
+    candidates.extend(stale_targets(Path::new(REPOS), std::time::SystemTime::now(), STALE_TARGET));
+    let mut dropped = Vec::new();
+    for d in candidates {
+        if free() >= crate::warm::DISK_RESERVE {
+            break;
+        }
+        // A build in progress keeps what it builds in.
+        if ssh_sessions() > 0 || !crate::bot::reading().is_null() {
+            break;
+        }
+        let _ = fs::remove_dir_all(TRASH);
+        if fs::rename(&d, TRASH).is_err() {
+            continue;
+        }
+        let _ = fs::remove_dir_all(TRASH);
+        dropped.push(d.to_string_lossy().to_string());
+    }
+    if !dropped.is_empty() {
+        measure_target();
+        emit(cfg, "trim", json!({"actor": "guard", "reason": "disk", "dropped": dropped, "free_from": from, "free_to": free()}));
+    }
+}
+
+/// The build directories of the checkouts under `repos` (`owner/name/target`).
+fn repo_targets(repos: &Path) -> Vec<PathBuf> {
+    let subdirs = |p: &Path| -> Vec<PathBuf> {
+        fs::read_dir(p)
+            .map(|r| r.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()).collect())
+            .unwrap_or_default()
+    };
+    subdirs(repos)
+        .iter()
+        .flat_map(|owner| subdirs(owner))
+        .map(|repo| repo.join("target"))
+        .filter(|t| t.is_dir())
+        .collect()
+}
+
+/// Every `incremental` directory of a build directory: `<profile>/incremental`
+/// and `<triple>/<profile>/incremental`.
+fn incremental_dirs(target: &Path) -> Vec<PathBuf> {
+    let mut out = Vec::new();
+    let Ok(entries) = fs::read_dir(target) else {
+        return out;
+    };
+    for e in entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) {
+        let p = e.path();
+        if p.join("incremental").is_dir() {
+            out.push(p.join("incremental"));
+        }
+        if let Ok(inner) = fs::read_dir(&p) {
+            for i in inner.flatten() {
+                let q = i.path().join("incremental");
+                if i.file_type().is_ok_and(|t| t.is_dir()) && q.is_dir() {
+                    out.push(q);
+                }
+            }
+        }
+    }
+    out.sort();
+    out
+}
+
+/// The build directories under `repos` last written more than `age` before
+/// `now`, oldest first. A build writes into its profile directory, so the
+/// newest of target/ and its children is when it was last built.
+fn stale_targets(repos: &Path, now: std::time::SystemTime, age: Duration) -> Vec<PathBuf> {
+    let mtime = |p: &Path| fs::metadata(p).and_then(|m| m.modified()).ok();
+    let mut found: Vec<(std::time::SystemTime, PathBuf)> = repo_targets(repos)
+        .into_iter()
+        .filter_map(|t| {
+            let mut newest = mtime(&t)?;
+            for e in fs::read_dir(&t).ok()?.flatten() {
+                if let Some(m) = mtime(&e.path()) {
+                    newest = newest.max(m);
+                }
+            }
+            (now.duration_since(newest).ok()? > age).then_some((newest, t))
+        })
+        .collect();
+    found.sort();
+    found.into_iter().map(|(_, t)| t).collect()
+}
+
 /// What a trim drops next: incremental state, then the oldest of target/'s
 /// other profiles and triples, then target/ itself.
 fn next_to_drop(target: &Path) -> Option<std::path::PathBuf> {
@@ -1049,6 +1164,31 @@ mod tests {
 
     use super::*;
 
+    #[test]
+    fn short_of_disk_the_guard_finds_incremental_state_and_cold_repositories() {
+        let root = tempfile::tempdir().unwrap();
+        let repos = root.path().join("repos");
+        let mk = |p: &Path| fs::create_dir_all(p).unwrap();
+        let mithril = repos.join("jeroen/mithril/target");
+        let pinnacle = repos.join("jeroen/pinnacle/target");
+        mk(&mithril.join("debug/incremental"));
+        mk(&mithril.join("wasm32-unknown-unknown/debug/incremental"));
+        mk(&mithril.join("release/deps"));
+        mk(&pinnacle.join("aarch64-unknown-none/release/deps"));
+        mk(&repos.join("jeroen/frits/src")); // no target/: not a candidate
+        assert_eq!(repo_targets(&repos).len(), 2);
+        assert_eq!(
+            incremental_dirs(&mithril),
+            vec![mithril.join("debug/incremental"), mithril.join("wasm32-unknown-unknown/debug/incremental")]
+        );
+        assert!(incremental_dirs(&pinnacle).is_empty());
+        // Just built: nothing is stale. Three days on: both are, oldest first.
+        let now = std::time::SystemTime::now();
+        assert!(stale_targets(&repos, now, STALE_TARGET).is_empty());
+        let later = now + Duration::from_secs(3 * 86400);
+        assert_eq!(stale_targets(&repos, later, STALE_TARGET).len(), 2);
+    }
+
     #[test]
     fn a_running_command_is_counted_until_its_session_is_gone() {
         let dir = std::env::temp_dir().join(format!("midas-running-{}", std::process::id()));
diff --git a/src/warm.rs b/src/warm.rs
index b7a70b6..7719c08 100644
--- a/src/warm.rs
+++ b/src/warm.rs
@@ -35,7 +35,7 @@ const TTL: i64 = 5400;
 const CEILING_FLOOR: u64 = 24_000_000_000;
 const CEILING_CAP: u64 = 80_000_000_000;
 /// What the warmer keeps free on /work for everything else a node does.
-const DISK_RESERVE: u64 = 20_000_000_000;
+pub(crate) const DISK_RESERVE: u64 = 20_000_000_000;
 const STALE_S: u64 = 3 * 86400;
 
 /// How big target/ may grow on a node, from its size now and what is free on