garage44.eu/jeroen/midas

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

.. /src/stats.rs

raw

//! `midas stats`: what the build record and the log say about how long things
//! take — per command and node, cold against warm, waiting in line, warming.

use std::collections::BTreeMap;

use anyhow::Result;
use serde_json::Value;

use crate::client;
use crate::events;

fn pct(sorted: &[f64], p: f64) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    let i = ((sorted.len() - 1) as f64 * p).round() as usize;
    sorted[i.min(sorted.len() - 1)]
}

/// 42 → "42s", 300 → "5.0m", 7200 → "2.0h".
pub fn dur(s: f64) -> String {
    if s < 90.0 {
        format!("{s:.0}s")
    } else if s < 5400.0 {
        format!("{:.1}m", s / 60.0)
    } else {
        format!("{:.1}h", s / 3600.0)
    }
}

struct Group {
    times: Vec<f64>,
    ok: usize,
    first: Vec<f64>,
    later: Vec<f64>,
}

/// Rows of (command shape, node) → count, success, median, p90, cold and warm medians.
pub fn table(builds: &[Value], all: bool) -> Vec<(String, String, usize, usize, f64, f64, Option<f64>, Option<f64>)> {
    let mut groups: BTreeMap<(String, String), Group> = BTreeMap::new();
    for b in builds {
        let shape = b["shape"].as_str().unwrap_or("").to_string();
        if shape.is_empty() || (!all && !shape.starts_with("cargo")) {
            continue;
        }
        let Some(secs) = b["seconds"].as_f64() else { continue };
        let g = groups.entry((shape, b["node"].as_str().unwrap_or("?").to_string()))
            .or_insert(Group { times: vec![], ok: 0, first: vec![], later: vec![] });
        g.times.push(secs);
        g.ok += (b["exit"].as_i64() == Some(0)) as usize;
        if b["first_build_in_lease"] == true { g.first.push(secs) } else { g.later.push(secs) }
    }
    let med = |v: &mut Vec<f64>| -> Option<f64> {
        v.sort_by(|a, b| a.partial_cmp(b).unwrap());
        (!v.is_empty()).then(|| pct(v, 0.5))
    };
    let mut rows: Vec<_> = groups.into_iter().map(|((shape, node), mut g)| {
        g.times.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let (m, p) = (pct(&g.times, 0.5), pct(&g.times, 0.9));
        (shape, node, g.times.len(), g.ok, m, p, med(&mut g.first), med(&mut g.later))
    }).collect();
    // Where the time goes first: count × median.
    rows.sort_by(|a, b| (b.2 as f64 * b.4).partial_cmp(&(a.2 as f64 * a.4)).unwrap());
    rows
}

pub fn stats(since: chrono::Duration, node: Option<&str>, all: bool, json: bool, chart: Option<&str>) -> Result<i32> {
    let hist = client::get(&format!("/v1/history?since={}", since.num_seconds()))?;
    let takes = hist["takes"].as_array().cloned().unwrap_or_default();
    let pool = hist["pool"].as_array().cloned().unwrap_or_default();
    if let Some(path) = chart {
        let to = chrono::Utc::now().date_naive();
        let from = to - since + chrono::Duration::days(1);
        let days = crate::chart::days(&takes, &pool, from, to);
        let title = format!("Waiting for a build node, last {} days", since.num_days().max(1));
        std::fs::write(path, crate::chart::svg(&days, &crate::chart::markers(&pool), &title))?;
        eprintln!("chart written to {path}");
    }
    let mut builds: Vec<Value> = client::get(&format!("/v1/builds?since={}", since.num_seconds()))?
        .as_array().cloned().unwrap_or_default();
    if let Some(n) = node {
        builds.retain(|b| b["node"] == n);
    }
    // The warmer's builds are under "warming" below; these are the agents'.
    builds.retain(|b| b["actor"] != "warmer");
    if json {
        println!("{}", serde_json::to_string_pretty(&builds)?);
        return Ok(0);
    }
    let rows = table(&builds, all);
    let total: usize = rows.iter().map(|r| r.2).sum();
    let hours: f64 = rows.iter().map(|r| r.2 as f64 * r.4).sum::<f64>() / 3600.0;
    println!("{} build sessions over the last {} days (about {:.1} h of building){}",
        total, since.num_days().max(1), hours, if all { "" } else { " — cargo only; --all for every command" });
    println!("\n  {:<52} {:<8} {:>5} {:>5} {:>7} {:>7} {:>8} {:>8}", "command", "node", "runs", "ok", "median", "p90", "1st build", "later");
    for (shape, node, n, ok, m, p, first, later) in rows.iter().take(25) {
        let short: String = if shape.chars().count() > 52 { shape.chars().take(51).collect::<String>() + "…" } else { shape.clone() };
        println!("  {:<52} {:<8} {:>5} {:>4}% {:>7} {:>7} {:>8} {:>8}", short, node, n, ok * 100 / n.max(&1),
            dur(*m), dur(*p), first.map(dur).unwrap_or("-".into()), later.map(dur).unwrap_or("-".into()));
    }

    // Waiting in line, and warming, from the log (the last 90 days at most).
    let evs = client::events(&events::Filter {
        since: since.min(chrono::Duration::days(events::KEEP_DAYS)),
        kinds: vec!["claim".into(), "warm_step".into(), "release".into()], node: node.map(str::to_string), actor: None,
    })?;
    let mut waits: Vec<f64> = takes.iter().filter_map(|t| t["waited_s"].as_f64()).filter(|w| *w > 0.0).collect();
    waits.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let claims = takes.iter().filter(|t| t["gave_up"] != true).count();
    let gave_up = takes.iter().filter(|t| t["gave_up"] == true).count();
    println!("\nwaiting for a node: {} of {} takes had to wait{}{}; {:.1} h of waiting in all", waits.len(), claims,
        if waits.is_empty() { String::new() } else { format!(", median {}, p90 {}", dur(pct(&waits, 0.5)), dur(pct(&waits, 0.9))) },
        if gave_up > 0 { format!(" ({gave_up} gave up)") } else { String::new() },
        waits.iter().sum::<f64>() / 3600.0);
    let mut held: Vec<f64> = evs.iter().filter(|e| e["kind"] == "release").filter_map(|e| e["held_s"].as_f64()).collect();
    held.sort_by(|a, b| a.partial_cmp(b).unwrap());
    if !held.is_empty() {
        println!("holding a node: median {}, p90 {}", dur(pct(&held, 0.5)), dur(pct(&held, 0.9)));
    }
    let mut steps: BTreeMap<(String, String), Vec<f64>> = BTreeMap::new();
    for e in evs.iter().filter(|e| e["kind"] == "warm_step" && e["ok"] == true) {
        if let (Some(s), Some(t)) = (e["step"].as_str(), e["seconds"].as_f64()) {
            steps.entry((s.chars().take(52).collect(), e["node"].as_str().unwrap_or("?").to_string())).or_default().push(t);
        }
    }
    if !steps.is_empty() {
        println!("\nwarming (the warmer's steps):");
        for ((s, n), mut v) in steps {
            v.sort_by(|a, b| a.partial_cmp(b).unwrap());
            println!("  {:<52} {:<8} {:>5} runs, median {}", s, n, v.len(), dur(pct(&v, 0.5)));
        }
    }
    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.
#[derive(Default, Debug, serde::Serialize)]
pub struct Week {
    pub week: String,
    pub sessions: usize,
    pub landed: usize,
    pub failed: usize,
    pub abandoned: usize,
    /// Notes by kind: say, overlap, nudge, decision, next, …
    pub notes: BTreeMap<String, usize>,
    /// Median time a note waited to be read, in seconds (logged since 2026-10-20).
    pub note_wait_s: Option<f64>,
    /// Median wait in line for a node, of those that waited at all.
    pub node_wait_s: Option<f64>,
    /// Hours nodes were held by sessions with no command running on them.
    pub idle_held_h: f64,
    pub next_turns: usize,
    pub decisions_asked: usize,
    pub decisions_answered: usize,
    #[serde(skip)]
    who: std::collections::BTreeSet<String>,
}

fn week_of(ev: &Value) -> Option<(String, i64)> {
    use chrono::Datelike;
    let t = chrono::DateTime::parse_from_rfc3339(ev["ts"].as_str()?).ok()?;
    let w = t.iso_week();
    Some((format!("{}-W{:02}", w.year(), w.week()), t.timestamp()))
}

/// What kind of note an event was. Before `note_kind` was logged (2026-10-20)
/// the event's own `kind` hid it, so it is read off the hub's wording.
fn note_kind(ev: &Value) -> String {
    if let Some(k) = ev["note_kind"].as_str() {
        return k.to_string();
    }
    let text = ev["text"].as_str().unwrap_or("");
    match ev["actor"].as_str() {
        Some("hub") if text.contains("is also changing") => "overlap",
        Some("hub") if text.contains("waiting for") => "nudge",
        Some("hub") if text.contains("went back to the pool") => "yield",
        Some("hub") => "hub",
        _ => "say",
    }.to_string()
}

/// Sessions are agents' worktrees; these are the workspace's own.
fn is_service(actor: &str) -> bool {
    matches!(actor, "warmer" | "deployer" | "hub") || actor.contains(':')
}

fn median(mut v: Vec<f64>) -> Option<f64> {
    v.sort_by(f64::total_cmp);
    (!v.is_empty()).then(|| pct(&v, 0.5))
}

/// The log, week by week, oldest first.
pub fn collab_weeks(evs: &[Value]) -> Vec<Week> {
    let mut weeks: BTreeMap<String, Week> = BTreeMap::new();
    let mut note_waits: BTreeMap<String, Vec<f64>> = BTreeMap::new();
    let mut node_waits: BTreeMap<String, Vec<f64>> = BTreeMap::new();
    // (node, actor) → (end, seconds) of each ssh session, for what a hold was busy with.
    let mut ssh: BTreeMap<(String, String), Vec<(i64, i64)>> = BTreeMap::new();
    for ev in evs {
        if ev["kind"] == "ssh_session" && ev["phase"] == "close" {
            if let (Some((_, t)), Some(d)) = (week_of(ev), ev["duration_s"].as_i64()) {
                let key = (ev["node"].as_str().unwrap_or("").to_string(), ev["actor"].as_str().unwrap_or("").to_string());
                ssh.entry(key).or_default().push((t, d));
            }
        }
    }
    for ev in evs {
        let Some((wk, t)) = week_of(ev) else { continue };
        let w = weeks.entry(wk.clone()).or_insert_with(|| Week { week: wk.clone(), ..Default::default() });
        let actor = ev["actor"].as_str().unwrap_or("");
        match ev["kind"].as_str().unwrap_or("") {
            "session_start" if !actor.is_empty() => { w.who.insert(actor.strip_prefix("gate-").unwrap_or(actor).to_string()); }
            "landing_done" => match ev["outcome"].as_str() {
                Some("landed") => w.landed += 1,
                Some("failed") => w.failed += 1,
                _ => w.abandoned += 1,
            },
            "note" => *w.notes.entry(note_kind(ev)).or_default() += 1,
            "notes_taken" => note_waits.entry(wk).or_default().extend(
                ev["notes"].as_array().into_iter().flatten().filter_map(|n| n["age_s"].as_f64())),
            "claim" if !is_service(actor) => if let Some(s) = ev["waited_s"].as_f64().filter(|s| *s > 0.0) {
                node_waits.entry(wk).or_default().push(s);
            },
            "release" | "force_release" | "lease_idle" | "lease_lapsed" => {
                let holder = ev["holder"].as_str().unwrap_or(actor);
                let (Some(node), Some(held)) = (ev["node"].as_str(), ev["held_s"].as_i64()) else { continue };
                if is_service(holder) {
                    continue;
                }
                let from = t - held;
                let busy: i64 = ssh.get(&(node.to_string(), holder.to_string())).into_iter().flatten()
                    .filter(|(end, _)| *end >= from && *end <= t).map(|(_, d)| d).sum();
                w.idle_held_h += (held - busy).max(0) as f64 / 3600.0;
            }
            "next_turn" => w.next_turns += 1,
            "decision_asked" => w.decisions_asked += 1,
            "decision_answered" => w.decisions_answered += 1,
            _ => {}
        }
    }
    for (wk, w) in weeks.iter_mut() {
        w.sessions = w.who.len();
        w.note_wait_s = note_waits.remove(wk).and_then(median);
        w.node_wait_s = node_waits.remove(wk).and_then(median);
    }
    weeks.into_values().collect()
}

/// `midas stats --collab`.
pub fn collab(since: chrono::Duration, json: bool) -> Result<i32> {
    let kinds = ["session_start", "landing_done", "note", "notes_taken", "claim", "release", "force_release",
                 "lease_idle", "lease_lapsed", "ssh_session", "next_turn", "decision_asked", "decision_answered"];
    let evs = client::events(&events::Filter {
        since: since.min(chrono::Duration::days(events::KEEP_DAYS)),
        kinds: kinds.iter().map(|k| k.to_string()).collect(), node: None, actor: None,
    })?;
    let weeks = collab_weeks(&evs);
    if json {
        println!("{}", serde_json::to_string_pretty(&weeks)?);
        return Ok(0);
    }
    println!("How sessions worked together, per week (the log keeps {} days)\n", events::KEEP_DAYS);
    println!("  {:<9} {:>8} {:>13} {:>6} {:>8} {:>6} {:>10} {:>10} {:>9} {:>5} {:>9}",
             "week", "sessions", "landed/failed", "notes", "overlaps", "nudges", "note wait", "node wait", "idle held", "next", "decisions");
    let opt = |v: Option<f64>| v.map(dur).unwrap_or_else(|| "-".into());
    for w in &weeks {
        let notes: usize = w.notes.values().sum();
        println!("  {:<9} {:>8} {:>13} {:>6} {:>8} {:>6} {:>10} {:>10} {:>8.1}h {:>5} {:>9}",
                 w.week, w.sessions, format!("{}/{}", w.landed, w.failed), notes,
                 w.notes.get("overlap").copied().unwrap_or(0), w.notes.get("nudge").copied().unwrap_or(0),
                 opt(w.note_wait_s), opt(w.node_wait_s), w.idle_held_h, w.next_turns,
                 format!("{}/{}", w.decisions_answered, w.decisions_asked));
    }
    println!("\n  landed/failed: landings through the queue, and gates that failed (abandoned ones not counted).\n  \
              note wait: median time a note waited to be read (logged since 2026-10-20).\n  \
              idle held: hours sessions held a node with no command running on it.\n  \
              decisions: answered/asked.");
    Ok(0)
}

// ── Each node's use ──────────────────────────────────────────────────────────

/// Intervals merged where they overlap, in order.
fn union(mut v: Vec<(i64, i64)>) -> Vec<(i64, i64)> {
    v.retain(|(a, b)| b > a);
    v.sort();
    let mut out: Vec<(i64, i64)> = Vec::new();
    for (a, b) in v {
        match out.last_mut() {
            Some(last) if a <= last.1 => last.1 = last.1.max(b),
            _ => out.push((a, b)),
        }
    }
    out
}

fn length(v: &[(i64, i64)]) -> i64 {
    v.iter().map(|(a, b)| b - a).sum()
}

/// How much of `a` is also in `b` (both merged).
fn overlap(a: &[(i64, i64)], b: &[(i64, i64)]) -> i64 {
    let mut n = 0;
    for (x, y) in a {
        for (p, q) in b {
            n += (y.min(q) - x.max(p)).max(0);
        }
    }
    n
}

/// Each node's use between `from` and `to`, from the log: how long sessions
/// held it (`held_s`), and how much of that a command ran on it (`busy_s`, an
/// ssh session open: a build, a test, a run). The difference is held but idle —
/// a node nobody else could take and nobody used, the waste the Workspace page
/// shows. `open` are the holds not given back yet: (node, since). The
/// workspace's own holders (the warmer, deploys) are left out.
pub fn node_use(evs: &[Value], open: &[(String, i64)], from: i64, to: i64) -> BTreeMap<String, Value> {
    let clip = |a: i64, b: i64| (a.max(from), b.min(to));
    let mut held: BTreeMap<String, Vec<(i64, i64)>> = BTreeMap::new();
    let mut busy: BTreeMap<String, Vec<(i64, i64)>> = BTreeMap::new();
    for ev in evs {
        let Some(t) = ev["ts"].as_str().and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()).map(|t| t.timestamp()) else { continue };
        let Some(node) = ev["node"].as_str() else { continue };
        let actor = ev["actor"].as_str().unwrap_or("");
        match ev["kind"].as_str().unwrap_or("") {
            "release" | "force_release" | "lease_idle" | "lease_lapsed" => {
                let holder = ev["holder"].as_str().unwrap_or(actor);
                if let Some(h) = ev["held_s"].as_i64().filter(|_| !is_service(holder)) {
                    held.entry(node.to_string()).or_default().push(clip(t - h, t));
                }
            }
            "ssh_session" if ev["phase"] == "close" && !is_service(actor) => {
                if let Some(d) = ev["duration_s"].as_i64() {
                    busy.entry(node.to_string()).or_default().push(clip(t - d, t));
                }
            }
            _ => {}
        }
    }
    for (node, since) in open {
        held.entry(node.clone()).or_default().push(clip(*since, to));
    }
    held.into_iter().map(|(node, h)| {
        let h = union(h);
        let b = union(busy.remove(&node).unwrap_or_default());
        (node, serde_json::json!({"held_s": length(&h), "busy_s": overlap(&h, &b)}))
    }).collect()
}

/// The workspace's nodes over the last `since_s` seconds (`GET /v1/history?use=1`).
pub fn node_use_now(since_s: i64) -> BTreeMap<String, Value> {
    let to = crate::registry::now();
    let evs = events::read(&events::Filter {
        since: chrono::Duration::seconds(since_s.min(7 * 86400)),
        kinds: ["release", "force_release", "lease_idle", "lease_lapsed", "ssh_session"].map(String::from).to_vec(),
        node: None, actor: None,
    });
    let state = crate::registry::snapshot().unwrap_or(Value::Null);
    let open: Vec<(String, i64)> = state["leases"].as_object().into_iter().flatten()
        .filter(|(_, l)| !is_service(l["owner"].as_str().unwrap_or("")))
        .filter_map(|(n, l)| Some((n.clone(), l["claimed_at"].as_i64()?))).collect();
    node_use(&evs, &open, to - since_s.min(7 * 86400), to)
}

#[cfg(test)]
mod use_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn a_node_held_an_hour_and_built_on_for_twenty_minutes_was_idle_forty() {
        let ev = |kind: &str, ts: &str, f: Value| {
            let mut e = json!({"kind": kind, "ts": ts});
            for (k, v) in f.as_object().unwrap() {
                e[k] = v.clone();
            }
            e
        };
        let evs = vec![
            // Two builds that overlap count once; one outside the hold does not count.
            ev("ssh_session", "2026-10-24T10:20:00Z", json!({"phase": "close", "node": "n1", "actor": "s1", "duration_s": 900})),
            ev("ssh_session", "2026-10-24T10:25:00Z", json!({"phase": "close", "node": "n1", "actor": "s1", "duration_s": 600})),
            ev("ssh_session", "2026-10-24T12:00:00Z", json!({"phase": "close", "node": "n1", "actor": "s1", "duration_s": 600})),
            ev("release", "2026-10-24T11:00:00Z", json!({"node": "n1", "actor": "s1", "holder": "s1", "held_s": 3600})),
            // The warmer's holds are the workspace's, not waste.
            ev("release", "2026-10-24T13:00:00Z", json!({"node": "n1", "actor": "warmer", "holder": "warmer", "held_s": 1800})),
        ];
        let from = chrono::DateTime::parse_from_rfc3339("2026-10-24T00:00:00Z").unwrap().timestamp();
        let u = node_use(&evs, &[], from, from + 86400);
        assert_eq!(u["n1"]["held_s"], 3600);
        assert_eq!(u["n1"]["busy_s"], 1200);
        // A hold still going counts up to now.
        let u = node_use(&[], &[("n2".into(), from + 3600)], from, from + 7200);
        assert_eq!(u["n2"]["held_s"], 3600);
    }
}