git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T12:53:02Z
feat(stats): each node's memory, load and disk over time Sizing the machines' nodes (a third VM on the mini, or 18 GB each instead of 24) needs to know what the nodes actually use, and the hub kept only each node's latest reading, overwritten every minute. The hub now appends every heartbeat to usage/YYYY-MM-DD.jsonl, kept 90 days: memory against the limit, load against the CPUs, free disk, the build directory's size, open sessions and OOM kills. A node samples its memory every ten seconds and sends the highest since its last heartbeat as mem_peak, since a link that peaks between two minute readings is what decides a node's size. GET /v1/usage buckets the lines per node, and `midas stats --nodes [--step 1d]` prints them.
docs/usage.md | 10 ++++
src/hub.rs | 9 ++++
src/main.rs | 12 +++++
src/node.rs | 37 +++++++++++++--
src/stats.rs | 54 +++++++++++++++++++++
src/tests.rs | 35 ++++++++++++++
src/usage.rs | 149 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 303 insertions(+), 3 deletions(-)
diff --git a/docs/usage.md b/docs/usage.md
index 83e1054..66eab7e 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -386,6 +386,16 @@ how many nodes were in the pool. `--node`, `--all` (not only cargo) and
spent waiting for a node, against the nodes in the pool, with a marker on the
day a node was added — the picture that shows what another machine buys.
+`midas stats --nodes --since 7d` says what each node used instead: its memory
+(the peak, the 95th percentile and the mean, against its limit), its load
+against the CPUs it may use and how often it went past them, the least free
+disk, the largest `target/`, the share of minutes a session was open, and OOM
+kills. `--step 1d` (or `1h`) gives a row per day through the window; `--node`
+and `--json` as above. The hub keeps every node's minute readings 90 days
+(`usage/` in its state directory); a node samples its memory every ten
+seconds, so a link's peak between two readings is not missed. It is what to
+size a machine's nodes by: how many fit, and how much memory each needs.
+
## On a build machine
```bash
diff --git a/src/hub.rs b/src/hub.rs
index e889dc4..ebf3004 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -4,6 +4,7 @@
//! * reads (open): `GET /v1/health`, `/v1/state`, `/v1/events?…`,
//! `/v1/position?owner=`, `/v1/lease/<node>`, and the history:
//! `/v1/builds`, `/v1/history`, `/v1/landings`, `/v1/sessions` (`?since=` s);
+//! `/v1/usage?since=&step=` (each node's memory, load and disk over time: usage.rs);
//! `/v1/names`, `/v1/notes/count?owner=`, `/v1/reservations`, `/v1/todos` and
//! `/v1/decisions` (collab.rs); `/v1/hosted/stats?since=` (every session's
//! conversation, counted: sessions.rs `stats`); `/v1/hosted/discuss` (whether a session can
@@ -596,6 +597,12 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
let step = q("step").and_then(|s| s.parse::<i64>().ok());
return Ok((200, crate::watch::read(since, step)));
}
+ // What each node used over time (usage.rs): memory, load and disk per `step` seconds.
+ ("GET", "usage") => {
+ let since = since_q(q("since")).min(crate::usage::KEEP_DAYS * 86400);
+ let step = q("step").and_then(|s| s.parse::<i64>().ok());
+ return Ok((200, crate::usage::read(since, step)));
+ }
// What each machine drew (power.rs): average watts and watt-hours per `step` seconds.
("GET", "power") => {
let since = q("since").and_then(|s| s.parse::<i64>().ok()).unwrap_or(86400);
@@ -737,6 +744,8 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
v["at"] = json!(registry::now());
v["from"] = json!(peer);
registry::write_reading(node, &v)?;
+ // Kept over time too; a failed append loses a minute, not the heartbeat.
+ let _ = crate::usage::record(node, &v);
registry::note_hub_url(node, host)?;
// A session open on the node keeps its lease alive: that is what
// "in use" means, and a long build has no other way to say so. So
diff --git a/src/main.rs b/src/main.rs
index 758a88a..0dda97b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -64,6 +64,7 @@ mod tap;
mod templates;
mod tree;
mod update;
+mod usage;
mod util;
mod zedthreads;
mod warm;
@@ -486,6 +487,13 @@ enum Cmd {
/// and hours nodes sat held but unused.
#[arg(long)]
collab: bool,
+ /// What each node used instead: memory (peak, p95, against its limit),
+ /// load against its CPUs, free disk and busy time — kept 90 days.
+ #[arg(long)]
+ nodes: bool,
+ /// With --nodes: one row per this much (1h, 1d …) instead of only the totals.
+ #[arg(long)]
+ step: Option<String>,
},
/// The story of one node: who held it, what ran, what waited, what failed.
Explain {
@@ -1571,6 +1579,10 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
}
Cmd::Power { json } => power::show(json),
Cmd::Stats { since: s, collab: true, json, .. } => stats::collab(since(&s)?, json),
+ Cmd::Stats { since: s, nodes: true, node, json, step, .. } => {
+ let step = step.as_deref().map(since).transpose()?;
+ stats::nodes(since(&s)?, node.as_deref(), step, json)
+ }
Cmd::Stats { since: s, node, all, json, chart, .. } => stats::stats(since(&s)?, node.as_deref(), all, json, chart.as_deref()),
Cmd::Release { node, force, keep_hosted } => {
let owner = who();
diff --git a/src/node.rs b/src/node.rs
index ec303e5..76adda8 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -322,8 +322,7 @@ pub fn reading() -> Value {
"mem_used": num(cg("memory.current")).or_else(|| macos::memory().map(|m| m.0)),
// Process memory: what the limit actually bites on. memory.current also
// counts page cache, which a build fills and the kernel gives back.
- "mem_anon": cg("memory.stat").and_then(|t| t.lines().find_map(|l| l.strip_prefix("anon ").and_then(|v| v.trim().parse::<u64>().ok())))
- .or_else(|| macos::memory().map(|m| m.0)),
+ "mem_anon": mem_anon(),
"mem_max": num(cg("memory.max")).or_else(|| macos::memory().map(|m| m.1)),
"oom_kills": oom,
"disk_free": disk_free,
@@ -356,6 +355,36 @@ pub fn reading() -> Value {
})
}
+/// The process memory in use now: the cgroup's anon pages on Linux, the
+/// machine's active, wired and compressed pages on macOS.
+fn mem_anon() -> Option<u64> {
+ fs::read_to_string("/sys/fs/cgroup/memory.stat").ok()
+ .and_then(|t| t.lines().find_map(|l| l.strip_prefix("anon ").and_then(|v| v.trim().parse::<u64>().ok())))
+ .or_else(|| macos::memory().map(|m| m.0))
+}
+
+/// The highest `mem_anon` since the last heartbeat, sampled every ten seconds:
+/// a link that peaks between two minute readings is what sizes a node, and
+/// one reading a minute misses it (usage.rs keeps them).
+static MEM_PEAK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+fn sample_peak() {
+ if let Some(m) = mem_anon() {
+ MEM_PEAK.fetch_max(m, std::sync::atomic::Ordering::Relaxed);
+ }
+}
+
+/// The reading the heartbeat sends: [`reading`] and the peak since the last one.
+fn heartbeat_reading() -> Value {
+ let mut r = reading();
+ let peak = MEM_PEAK.swap(0, std::sync::atomic::Ordering::Relaxed);
+ let now = r["mem_anon"].as_u64().unwrap_or(0);
+ if peak > 0 || now > 0 {
+ r["mem_peak"] = json!(peak.max(now));
+ }
+ r
+}
+
pub fn guard() -> Result<i32> {
let cfg = config();
let mut warned = false;
@@ -377,7 +406,9 @@ pub fn guard() -> Result<i32> {
// release, a lapse or a `take` in build mode is stopped here, before
// the reading says what runs.
crate::bot::enforce(&cfg);
- let _ = hub::request(&cfg.hub, "POST", &format!("/v1/readings/{}", cfg.node), Some(&reading().to_string()));
+ let _ = hub::request(&cfg.hub, "POST", &format!("/v1/readings/{}", cfg.node), Some(&heartbeat_reading().to_string()));
+ } else if tick % 5 == 0 {
+ sample_peak();
}
tick += 1;
if let Some(g) = gpu() {
diff --git a/src/stats.rs b/src/stats.rs
index 7959e1d..7fa8aaf 100644
--- a/src/stats.rs
+++ b/src/stats.rs
@@ -133,6 +133,60 @@ pub fn stats(since: chrono::Duration, node: Option<&str>, all: bool, json: bool,
Ok(0)
}
+// ── What the nodes used ──────────────────────────────────────────────────────
+
+/// One row of `midas stats --nodes` from a usage bucket (usage.rs `bucket`).
+pub fn usage_row(label: &str, b: &Value) -> String {
+ let gib = |k: &str| b[k].as_f64().map(|v| format!("{:.1}", v / (1u64 << 30) as f64)).unwrap_or("-".into());
+ let gb = |k: &str| b[k].as_f64().map(|v| format!("{:.0}", v / 1e9)).unwrap_or("-".into());
+ let pc = |k: &str| b[k].as_f64().map(|v| format!("{:.0}%", v * 100.0)).unwrap_or("-".into());
+ let num = |k: &str| b[k].as_f64().map(|v| format!("{v:.1}")).unwrap_or("-".into());
+ format!(" {:<16} {:>7} {:>5} {:>6} {:>6} {:>6} {:>6} {:>5} {:>5} {:>4} {:>6} {:>6} {:>7} {:>4}",
+ label, b["minutes"].as_u64().unwrap_or(0), pc("busy"),
+ gib("mem_peak"), gib("mem_p95"), gib("mem_mean"), gib("mem_lim"),
+ num("load_mean"), num("load_max"), b["cpus"].as_f64().map(|c| format!("{c:.0}")).unwrap_or("-".into()), pc("over_cpus"),
+ gb("disk_free_min"), gb("target_max"), b["oom_kills"].as_u64().unwrap_or(0))
+}
+
+/// `midas stats --nodes`: what each node used over the window, and with
+/// `step`, row by row through it.
+pub fn nodes(since: chrono::Duration, node: Option<&str>, step: Option<chrono::Duration>, json: bool) -> Result<i32> {
+ let step_s = step.map(|s| s.num_seconds().max(60));
+ let q = format!("/v1/usage?since={}{}", since.num_seconds(), step_s.map(|s| format!("&step={s}")).unwrap_or_default());
+ let mut u = client::get(&q)?;
+ if let (Some(n), Some(nodes)) = (node, u["nodes"].as_object_mut()) {
+ nodes.retain(|k, _| k == n);
+ }
+ if json {
+ println!("{}", serde_json::to_string_pretty(&u)?);
+ return Ok(0);
+ }
+ let nodes = u["nodes"].as_object().cloned().unwrap_or_default();
+ if nodes.is_empty() {
+ println!("no usage kept for the last {} yet: the hub keeps it from its version of 2026-11-28 on", dur(since.num_seconds() as f64));
+ return Ok(0);
+ }
+ println!("what each node used over the last {} — memory in GiB, disk in GB; a peak is the highest 10 s sample of a minute", dur(since.num_seconds() as f64));
+ println!("(on a node older than that, the minute's own value), load against the CPUs the node may use\n");
+ println!(" {:<16} {:>7} {:>5} {:>6} {:>6} {:>6} {:>6} {:>5} {:>5} {:>4} {:>6} {:>6} {:>7} {:>4}",
+ "", "minutes", "busy", "peak", "p95", "mean", "limit", "load", "max", "cpus", ">cpus", "free≥", "target", "oom");
+ for (n, v) in &nodes {
+ if step.is_some() {
+ println!("{n}");
+ for b in v["buckets"].as_array().into_iter().flatten() {
+ let t = chrono::DateTime::from_timestamp(b["t"].as_i64().unwrap_or(0), 0).unwrap_or_default()
+ .with_timezone(&chrono::Local);
+ let label = if step_s.unwrap_or(0) % 86400 == 0 { t.format("%a %m-%d").to_string() } else { t.format("%m-%d %H:%M").to_string() };
+ println!("{}", usage_row(&label, b));
+ }
+ println!("{}\n", usage_row("whole window", &v["whole"]));
+ } else {
+ println!("{}", usage_row(n, &v["whole"]));
+ }
+ }
+ Ok(0)
+}
+
// ── How sessions worked together ─────────────────────────────────────────────
/// One ISO week of working together, from the log.
diff --git a/src/tests.rs b/src/tests.rs
index 26d272e..bd22a51 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -3075,3 +3075,38 @@ fn forgejo_calls_about_a_hosted_repository_are_answered_by_the_hub() {
assert!(crate::hub::forgejo_for_hosted("GET", "/repos/acme/elsewhere/branches").is_none(), "Forgejo's own");
assert!(crate::hub::forgejo_for_hosted("GET", "/version").is_none());
}
+
+#[test]
+fn a_nodes_readings_are_kept_and_bucketed_over_time() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("usage");
+ let gib = 1u64 << 30;
+ let t = registry::now() - 3 * 60;
+ // Three minutes: a link peaks between two readings in the second; the
+ // third, from a node too old to sample peaks, counts its own value; the
+ // cgroup's OOM count rises once.
+ for (i, (mem, peak, load, oom)) in [(4 * gib, Some(5 * gib), 2.0, 1), (6 * gib, Some(18 * gib), 9.0, 1), (3 * gib, None, 1.0, 2)].into_iter().enumerate() {
+ let mut r = json!({"at": t + i as i64 * 60, "mem_anon": mem, "mem_max": 24 * gib, "load": load, "cpus": 6,
+ "disk_free": 50_000_000_000u64 - i as u64 * 1_000_000_000, "disk_total": 200_000_000_000u64,
+ "target_bytes": 30_000_000_000u64, "sessions": (i == 1) as u64, "oom_kills": oom});
+ if let Some(p) = peak {
+ r["mem_peak"] = json!(p);
+ }
+ crate::usage::record("mac-1", &r).unwrap();
+ }
+ crate::usage::record("mac-2", &json!({"at": t, "mem_anon": gib, "load": 0.5, "cpus": 6})).unwrap();
+ let u = crate::usage::read(3600, Some(3600));
+ let w = &u["nodes"]["mac-1"]["whole"];
+ assert_eq!(w["minutes"], 3);
+ assert_eq!(w["mem_peak"].as_f64(), Some((18 * gib) as f64), "the peak between readings, not the readings");
+ assert_eq!(w["mem_lim"].as_f64(), Some((24 * gib) as f64));
+ assert_eq!(w["load_max"].as_f64(), Some(9.0));
+ assert_eq!(w["over_cpus"].as_f64(), Some(0.333), "one minute in three past 6 CPUs");
+ assert_eq!(w["busy"].as_f64(), Some(0.333));
+ assert_eq!(w["disk_free_min"].as_f64(), Some(48e9));
+ assert_eq!(w["oom_kills"], 1, "kills that happened in the window, not since the cgroup started");
+ assert!(!u["nodes"]["mac-1"]["buckets"].as_array().unwrap().is_empty());
+ assert_eq!(u["nodes"]["mac-2"]["whole"]["minutes"], 1, "each node on its own");
+ // Lines past the window are not read.
+ assert!(crate::usage::read(30, None)["nodes"].as_object().unwrap().is_empty());
+}
diff --git a/src/usage.rs b/src/usage.rs
new file mode 100644
index 0000000..a2cad9b
--- /dev/null
+++ b/src/usage.rs
@@ -0,0 +1,149 @@
+//! What each node used over time: memory, load and disk, minute by minute — what
+//! sizes the machines' nodes (how many on a box, how much memory each), which the
+//! latest reading alone (`readings/<node>.json`, overwritten every minute) could
+//! not say.
+//!
+//! The hub appends one line per heartbeat to `usage/YYYY-MM-DD.jsonl` (UTC days;
+//! about 150 bytes a line, so some 200 kB a node a day), kept [`KEEP_DAYS`] days:
+//!
+//! * `mem`: process memory now (`mem_anon`), and `peak`, the highest of the
+//! node's ten-second samples since its last heartbeat (`node.rs`, a midas of
+//! 2026-11-28 or later; older nodes send none and the minute's value stands);
+//! * `lim`: what the node may use — its cgroup's limit, or a VM's memory;
+//! * `load` (one-minute average) against `cpus`;
+//! * `free` and `disk`: the work volume's free space and size; `target`: the
+//! build directory's size;
+//! * `s`: open ssh sessions, so a quiet node is told from a busy one;
+//! * `oom`: the cgroup's OOM kills since it started (Linux only).
+//!
+//! `GET /v1/usage?since=&step=` buckets them per node; `midas stats --nodes`
+//! reads that.
+
+use std::collections::BTreeMap;
+use std::fs::{self, OpenOptions};
+use std::io::Write;
+use std::path::PathBuf;
+
+use anyhow::Result;
+use chrono::{TimeZone, Utc};
+use serde_json::{json, Value};
+
+use crate::registry;
+
+/// How long lines are kept: long enough to see a pattern over weeks of work.
+pub const KEEP_DAYS: i64 = 90;
+
+fn dir() -> PathBuf {
+ registry::root().join("usage")
+}
+
+fn day(t: i64) -> String {
+ Utc.timestamp_opt(t, 0).single().unwrap_or_else(Utc::now).format("%Y-%m-%d").to_string()
+}
+
+fn day_file(t: i64) -> PathBuf {
+ dir().join(format!("{}.jsonl", day(t)))
+}
+
+/// The line kept for one reading, at `t`.
+pub fn line(node: &str, t: i64, r: &Value) -> Value {
+ let mem = r["mem_anon"].as_u64().or(r["mem_used"].as_u64());
+ json!({
+ "t": t, "n": node, "mem": mem, "peak": r["mem_peak"].as_u64().or(mem), "lim": r["mem_max"],
+ "load": r["load"], "cpus": r["cpus"], "free": r["disk_free"], "disk": r["disk_total"],
+ "target": r["target_bytes"], "s": r["sessions"], "oom": r["oom_kills"],
+ })
+}
+
+/// Keep a node's reading (the hub's heartbeat handler). A day's first line
+/// also forgets the days past [`KEEP_DAYS`].
+pub fn record(node: &str, r: &Value) -> Result<()> {
+ let t = r["at"].as_i64().unwrap_or_else(registry::now);
+ fs::create_dir_all(dir())?;
+ let file = day_file(t);
+ if !file.exists() {
+ prune(t);
+ }
+ OpenOptions::new().create(true).append(true).open(file)?.write_all(format!("{}\n", line(node, t, r)).as_bytes())?;
+ Ok(())
+}
+
+fn prune(t: i64) {
+ let keep = day(t - KEEP_DAYS * 86400);
+ for e in fs::read_dir(dir()).into_iter().flatten().flatten() {
+ let name = e.file_name().to_string_lossy().to_string();
+ if name.ends_with(".jsonl") && name < keep {
+ let _ = fs::remove_file(e.path());
+ }
+ }
+}
+
+/// Every line from `from` to `to`, oldest first.
+fn lines(from: i64, to: i64) -> Vec<Value> {
+ let mut out = vec![];
+ let mut d = from - from.rem_euclid(86400);
+ while d <= to {
+ if let Ok(text) = fs::read_to_string(day_file(d)) {
+ out.extend(text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok())
+ .filter(|v| v["t"].as_i64().is_some_and(|t| t >= from && t <= to)));
+ }
+ d += 86400;
+ }
+ out
+}
+
+/// One bucket of a node's lines, as an object: memory's peak (max), its p95 and
+/// mean; the limit; load's mean, max and the share of minutes it was past the
+/// CPUs; the least free disk; the largest build directory; the share of
+/// minutes a session was open; OOM kills that happened in it; and how many
+/// minutes it holds.
+pub fn bucket(start: i64, s: &[&Value]) -> Value {
+ let f = |k: &str| -> Vec<f64> { s.iter().filter_map(|v| v[k].as_f64()).collect() };
+ let max = |v: &[f64]| v.iter().copied().reduce(f64::max);
+ let min = |v: &[f64]| v.iter().copied().reduce(f64::min);
+ let mean = |v: &[f64]| (!v.is_empty()).then(|| v.iter().sum::<f64>() / v.len() as f64);
+ let share = |n: usize| (n as f64 / s.len().max(1) as f64 * 1000.0).round() / 1000.0;
+ let mut peaks = f("peak");
+ peaks.sort_by(f64::total_cmp);
+ let p95 = (!peaks.is_empty()).then(|| peaks[((peaks.len() - 1) as f64 * 0.95).round() as usize]);
+ let loads = f("load");
+ let over = s.iter().filter(|v| matches!((v["load"].as_f64(), v["cpus"].as_f64()), (Some(l), Some(c)) if l > c)).count();
+ let busy = s.iter().filter(|v| v["s"].as_u64().is_some_and(|n| n > 0)).count();
+ let ooms: Vec<u64> = s.iter().filter_map(|v| v["oom"].as_u64()).collect();
+ let oom: u64 = ooms.windows(2).map(|w| w[1].saturating_sub(w[0])).sum();
+ let round = |x: Option<f64>| x.map(|x| (x * 100.0).round() / 100.0);
+ json!({
+ "t": start, "minutes": s.len(),
+ "mem_peak": max(&peaks), "mem_p95": p95, "mem_mean": mean(&f("mem")).map(f64::round), "mem_lim": max(&f("lim")),
+ "load_mean": round(mean(&loads)), "load_max": round(max(&loads)), "cpus": max(&f("cpus")), "over_cpus": share(over),
+ "disk_free_min": min(&f("free")), "disk": max(&f("disk")), "target_max": max(&f("target")),
+ "busy": share(busy), "oom_kills": oom,
+ })
+}
+
+/// `GET /v1/usage`: each node's lines of the last `since` seconds in buckets of
+/// `step` seconds (an hour unless said), oldest first, and the whole window as
+/// one bucket per node.
+pub fn read(since: i64, step: Option<i64>) -> Value {
+ let to = registry::now();
+ let from = to - since;
+ let step = step.unwrap_or(3600).max(60);
+ let all = lines(from, to);
+ let mut by_node: BTreeMap<String, Vec<&Value>> = BTreeMap::new();
+ for l in &all {
+ by_node.entry(l["n"].as_str().unwrap_or("?").to_string()).or_default().push(l);
+ }
+ let mut nodes = serde_json::Map::new();
+ for (node, ls) in by_node {
+ let mut buckets: BTreeMap<i64, Vec<&Value>> = BTreeMap::new();
+ for l in &ls {
+ let t = l["t"].as_i64().unwrap_or(0);
+ buckets.entry(t - t.rem_euclid(step)).or_default().push(l);
+ }
+ nodes.insert(node, json!({
+ "whole": bucket(from, &ls),
+ "buckets": buckets.iter().map(|(t, s)| bucket(*t, s)).collect::<Vec<_>>(),
+ }));
+ }
+ json!({"from": from, "to": to, "step": step, "nodes": nodes})
+}