oomtop-core 0.2.1

oomtop core: pure data model, units, attribution, headroom, forecast, throttle, query and ranking logic (no I/O)
Documentation
//! Pivot grouping (SPEC §7): regroup a snapshot's groups by owner, project, kind, sandbox or cohort and
//! total each bucket. Pure — the project of a group is whatever the collectors resolved
//! (`Group::project`: git root of the cwd, else the cwd); nothing here walks the filesystem.
//!
//! Every group lands in exactly one bucket per key, so bucket totals add up to the snapshot's.

use crate::measured::{sum_bytes, sum_f64};
use crate::model::{Bytes, Group, GroupKind, Measured, Quality, Snapshot};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Bucket key (and label) of groups without an owner / project / sandbox / cohort.
pub const NONE_OWNER: &str = "(no owner)";
pub const NONE_PROJECT: &str = "(no project)";
pub const NONE_SANDBOX: &str = "(not sandboxed)";
pub const NONE_COHORT: &str = "(session alive or none)";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PivotKey {
    /// The group that started it (`owner_group`, followed to the top); a group nobody owns is its own
    /// owner when it owns others, else [`NONE_OWNER`].
    Owner,
    /// `Group::project`.
    Project,
    /// `Group::kind`.
    Kind,
    /// The sandbox a group runs in (or is).
    Sandbox,
    /// The ended agent session that left the group (`Group::cohort`).
    Cohort,
}

impl PivotKey {
    pub const ALL: [PivotKey; 5] = [
        PivotKey::Owner,
        PivotKey::Project,
        PivotKey::Kind,
        PivotKey::Sandbox,
        PivotKey::Cohort,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            PivotKey::Owner => "owner",
            PivotKey::Project => "project",
            PivotKey::Kind => "kind",
            PivotKey::Sandbox => "sandbox",
            PivotKey::Cohort => "cohort",
        }
    }

    /// Parses `owner | project | kind | sandbox | cohort` (case-insensitive).
    pub fn parse(s: &str) -> Option<PivotKey> {
        let s = s.trim().to_ascii_lowercase();
        PivotKey::ALL.into_iter().find(|k| k.as_str() == s)
    }
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PivotTotals {
    /// Σ group footprint.
    pub footprint: Measured<Bytes>,
    pub gpu: Measured<Bytes>,
    /// Σ per-core CPU %.
    pub cpu_pct: Measured<f64>,
    /// Σ idle rent, GiB-hours (estimate).
    pub idle_rent_gib_h: Measured<f64>,
    pub group_count: u32,
    pub process_count: u32,
    /// Groups flagged stale.
    pub stale_count: u32,
    pub idle_count: u32,
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PivotBucket {
    /// Stable key: an owner group id, a project path, a kind alias, a sandbox id or a cohort id; one of
    /// the `NONE_*` constants for the rest.
    pub key: String,
    /// What to show: owner / sandbox / cohort label, project path, kind alias.
    pub label: String,
    /// Member groups, largest footprint first.
    pub group_ids: Vec<String>,
    pub totals: PivotTotals,
}

/// Follows `owner_group` to the top-most live owner (bounded, cycle-safe).
fn top_owner<'a>(g: &'a Group, by_id: &BTreeMap<&'a str, &'a Group>) -> Option<&'a Group> {
    let mut cur = g;
    let mut found = None;
    for _ in 0..16 {
        let Some(next) = cur
            .owner_group
            .as_deref()
            .filter(|o| *o != cur.id)
            .and_then(|o| by_id.get(o).copied())
        else {
            break;
        };
        if next.id == g.id {
            break;
        }
        found = Some(next);
        cur = next;
    }
    found
}

/// `(key, label)` of the bucket a group belongs to.
fn bucket_of(g: &Group, s: &Snapshot, key: PivotKey, by_id: &BTreeMap<&str, &Group>) -> (String, String) {
    let none = |k: &str| (k.to_string(), k.to_string());
    match key {
        PivotKey::Kind => (g.kind.alias().to_string(), g.kind.alias().to_string()),
        PivotKey::Project => match g.project.as_deref().filter(|p| !p.is_empty()) {
            Some(p) => (p.to_string(), p.to_string()),
            None => none(NONE_PROJECT),
        },
        PivotKey::Cohort => match g.cohort.as_deref() {
            Some(c) => {
                let label = s
                    .cohorts
                    .iter()
                    .find(|x| x.id == c)
                    .map(|x| x.sentence.clone())
                    .unwrap_or_else(|| c.to_string());
                (c.to_string(), label)
            }
            None => none(NONE_COHORT),
        },
        PivotKey::Owner => match top_owner(g, by_id) {
            Some(o) => (o.id.clone(), o.label.clone()),
            None => {
                // A dead owner (a cohort) keeps its leftovers together; a group that owns others is its
                // own bucket.
                if let Some(c) = g.cohort.as_deref() {
                    let label = s
                        .cohorts
                        .iter()
                        .find(|x| x.id == c)
                        .map(|x| format!("{} (ended)", x.label))
                        .unwrap_or_else(|| c.to_string());
                    return (c.to_string(), label);
                }
                let owns = s
                    .groups
                    .iter()
                    .any(|x| x.id != g.id && x.owner_group.as_deref() == Some(g.id.as_str()));
                if owns {
                    (g.id.clone(), g.label.clone())
                } else {
                    none(NONE_OWNER)
                }
            }
        },
        PivotKey::Sandbox => {
            let rec = s.sandboxes.iter().find(|sb| {
                g.root.is_some_and(|r| sb.host_pids.contains(&r))
                    || sb.host_pids.iter().any(|p| g.members.iter().any(|m| m.id == *p))
            });
            match rec {
                Some(sb) => (sb.id.clone(), sb.label.clone()),
                None if g.kind == GroupKind::Sandbox => (g.id.clone(), g.label.clone()),
                None => none(NONE_SANDBOX),
            }
        }
    }
}

/// Regroups the snapshot's groups by `key`. Buckets are ordered by footprint (largest first), then key;
/// the `NONE_*` bucket sorts by the same rule.
pub fn pivot(s: &Snapshot, key: PivotKey) -> Vec<PivotBucket> {
    let by_id: BTreeMap<&str, &Group> = s.groups.iter().map(|g| (g.id.as_str(), g)).collect();
    let mut buckets: BTreeMap<String, (String, Vec<&Group>)> = BTreeMap::new();
    for g in &s.groups {
        let (k, label) = bucket_of(g, s, key, &by_id);
        buckets.entry(k).or_insert_with(|| (label, Vec::new())).1.push(g);
    }
    let fp = |g: &Group| g.totals.footprint.value.unwrap_or(0);
    let mut out: Vec<PivotBucket> = buckets
        .into_iter()
        .map(|(k, (label, mut gs))| {
            gs.sort_by(|a, b| fp(b).cmp(&fp(a)).then(a.id.cmp(&b.id)));
            let mut rent = sum_f64(gs.iter().map(|g| &g.idle_rent_gib_h), "Σ group idle rent");
            if rent.value.is_some() {
                rent.quality = Quality::Estimate;
            }
            PivotBucket {
                key: k,
                label,
                group_ids: gs.iter().map(|g| g.id.clone()).collect(),
                totals: PivotTotals {
                    footprint: sum_bytes(gs.iter().map(|g| &g.totals.footprint), "Σ group footprint"),
                    gpu: sum_bytes(gs.iter().map(|g| &g.totals.gpu), "Σ group GPU memory"),
                    cpu_pct: sum_f64(gs.iter().map(|g| &g.totals.cpu_pct), "Σ group CPU %"),
                    idle_rent_gib_h: rent,
                    group_count: gs.len() as u32,
                    process_count: gs.iter().map(|g| g.totals.process_count).sum(),
                    stale_count: gs.iter().filter(|g| g.staleness.stale).count() as u32,
                    idle_count: gs.iter().filter(|g| g.idle).count() as u32,
                },
            }
        })
        .collect();
    out.sort_by(|a, b| {
        b.totals
            .footprint
            .value
            .unwrap_or(0)
            .cmp(&a.totals.footprint.value.unwrap_or(0))
            .then(a.key.cmp(&b.key))
    });
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{GroupTotals, Member, ProcId, Sandbox};
    use crate::staleness::{Cohort, Staleness};

    fn g(id: &str, kind: GroupKind, gib: u64) -> Group {
        Group {
            id: id.into(),
            kind,
            label: id.to_uppercase(),
            totals: GroupTotals {
                footprint: Measured::exact(gib << 30, "test"),
                cpu_pct: Measured::exact(1.0, "test"),
                process_count: 2,
                ..Default::default()
            },
            idle_rent_gib_h: Measured::estimate(gib as f64, "test"),
            ..Default::default()
        }
    }

    fn snap() -> Snapshot {
        let mut agent = g("agent:1", GroupKind::AgentSession, 1);
        agent.project = Some("/w/app".into());
        let mut daemon = g("daemon:1", GroupKind::BuildDaemon, 3);
        daemon.owner_group = Some("agent:1".into());
        daemon.project = Some("/w/app".into());
        daemon.idle = true;
        let mut nested = g("other:1", GroupKind::Other, 1);
        nested.owner_group = Some("daemon:1".into());
        let mut left = g("daemon:2", GroupKind::BuildDaemon, 4);
        left.owner_group = Some("agent:deadbeef0001".into());
        left.cohort = Some("agent:deadbeef0001".into());
        left.project = Some("/w/old".into());
        left.staleness = Staleness {
            score: 0.6,
            stale: true,
            evidence: Vec::new(),
        };
        let mut vm = g("sandbox:1", GroupKind::Sandbox, 2);
        vm.root = Some(ProcId::new(9, 1));
        vm.members = vec![Member {
            id: ProcId::new(9, 1),
            ..Default::default()
        }];
        let app = g("app:1", GroupKind::App, 5);
        Snapshot {
            groups: vec![agent, daemon, nested, left, vm, app],
            sandboxes: vec![Sandbox {
                id: "docker:abc".into(),
                label: "web".into(),
                host_pids: vec![ProcId::new(9, 1)],
                ..Default::default()
            }],
            cohorts: vec![Cohort {
                id: "agent:deadbeef0001".into(),
                label: "Claude Code".into(),
                sentence: "left by the Claude Code session that ended 3h ago".into(),
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    fn keys(b: &[PivotBucket]) -> Vec<(&str, Vec<&str>)> {
        b.iter()
            .map(|b| (b.key.as_str(), b.group_ids.iter().map(String::as_str).collect()))
            .collect()
    }

    #[test]
    fn every_group_lands_in_exactly_one_bucket_per_key() {
        let s = snap();
        let total: u64 = s.groups.iter().filter_map(|g| g.totals.footprint.value).sum();
        for key in PivotKey::ALL {
            let b = pivot(&s, key);
            let n: usize = b.iter().map(|b| b.group_ids.len()).sum();
            assert_eq!(n, s.groups.len(), "{key:?}");
            let sum: u64 = b.iter().filter_map(|b| b.totals.footprint.value).sum();
            assert_eq!(sum, total, "{key:?}");
            assert_eq!(PivotKey::parse(key.as_str()), Some(key));
            // deterministic
            assert_eq!(pivot(&s, key), b);
        }
        assert_eq!(PivotKey::parse("Project "), Some(PivotKey::Project));
        assert_eq!(PivotKey::parse("nope"), None);
    }

    #[test]
    fn by_kind() {
        let s = snap();
        let b = pivot(&s, PivotKey::Kind);
        assert_eq!(
            keys(&b),
            vec![
                ("daemon", vec!["daemon:2", "daemon:1"]),
                ("app", vec!["app:1"]),
                ("sandbox", vec!["sandbox:1"]),
                ("agent", vec!["agent:1"]),
                ("other", vec!["other:1"]),
            ]
        );
        let d = &b[0].totals;
        assert_eq!(d.footprint.value, Some(7 << 30));
        assert_eq!((d.group_count, d.process_count), (2, 4));
        assert_eq!((d.stale_count, d.idle_count), (1, 1));
        assert_eq!(d.idle_rent_gib_h.value, Some(7.0));
        assert_eq!(d.idle_rent_gib_h.quality, Quality::Estimate);
        assert_eq!(d.cpu_pct.value, Some(2.0));
    }

    #[test]
    fn by_owner_follows_the_chain_and_keeps_a_dead_session_together() {
        let s = snap();
        let b = pivot(&s, PivotKey::Owner);
        assert_eq!(
            keys(&b),
            vec![
                (NONE_OWNER, vec!["app:1", "sandbox:1"]),
                ("agent:1", vec!["daemon:1", "agent:1", "other:1"]),
                ("agent:deadbeef0001", vec!["daemon:2"]),
            ]
        );
        assert_eq!(b[1].label, "AGENT:1");
        assert_eq!(b[2].label, "Claude Code (ended)");
    }

    #[test]
    fn by_project_sandbox_and_cohort() {
        let s = snap();
        let b = pivot(&s, PivotKey::Project);
        assert_eq!(
            keys(&b),
            vec![
                (NONE_PROJECT, vec!["app:1", "sandbox:1", "other:1"]),
                ("/w/app", vec!["daemon:1", "agent:1"]),
                ("/w/old", vec!["daemon:2"]),
            ]
        );
        let b = pivot(&s, PivotKey::Sandbox);
        assert_eq!(b.len(), 2);
        assert_eq!(b[1].key, "docker:abc");
        assert_eq!(b[1].label, "web");
        assert_eq!(b[1].group_ids, vec!["sandbox:1"]);
        let b = pivot(&s, PivotKey::Cohort);
        assert_eq!(b[0].key, NONE_COHORT);
        assert_eq!(b[1].key, "agent:deadbeef0001");
        assert_eq!(b[1].label, "left by the Claude Code session that ended 3h ago");
    }

    #[test]
    fn owner_cycles_terminate() {
        let mut a = g("a", GroupKind::Other, 1);
        let mut b = g("b", GroupKind::Other, 1);
        a.owner_group = Some("b".into());
        b.owner_group = Some("a".into());
        let s = Snapshot {
            groups: vec![a, b],
            ..Default::default()
        };
        assert_eq!(
            pivot(&s, PivotKey::Owner)
                .iter()
                .map(|b| b.group_ids.len())
                .sum::<usize>(),
            2
        );
    }

    #[test]
    fn empty_snapshot_has_no_buckets() {
        assert!(pivot(&Snapshot::default(), PivotKey::Kind).is_empty());
    }
}