Skip to main content

oomtop_core/
pivot.rs

1//! Pivot grouping (SPEC §7): regroup a snapshot's groups by owner, project, kind, sandbox or cohort and
2//! total each bucket. Pure — the project of a group is whatever the collectors resolved
3//! (`Group::project`: git root of the cwd, else the cwd); nothing here walks the filesystem.
4//!
5//! Every group lands in exactly one bucket per key, so bucket totals add up to the snapshot's.
6
7use crate::measured::{sum_bytes, sum_f64};
8use crate::model::{Bytes, Group, GroupKind, Measured, Quality, Snapshot};
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11
12/// Bucket key (and label) of groups without an owner / project / sandbox / cohort.
13pub const NONE_OWNER: &str = "(no owner)";
14pub const NONE_PROJECT: &str = "(no project)";
15pub const NONE_SANDBOX: &str = "(not sandboxed)";
16pub const NONE_COHORT: &str = "(session alive or none)";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum PivotKey {
21    /// The group that started it (`owner_group`, followed to the top); a group nobody owns is its own
22    /// owner when it owns others, else [`NONE_OWNER`].
23    Owner,
24    /// `Group::project`.
25    Project,
26    /// `Group::kind`.
27    Kind,
28    /// The sandbox a group runs in (or is).
29    Sandbox,
30    /// The ended agent session that left the group (`Group::cohort`).
31    Cohort,
32}
33
34impl PivotKey {
35    pub const ALL: [PivotKey; 5] = [
36        PivotKey::Owner,
37        PivotKey::Project,
38        PivotKey::Kind,
39        PivotKey::Sandbox,
40        PivotKey::Cohort,
41    ];
42
43    pub fn as_str(self) -> &'static str {
44        match self {
45            PivotKey::Owner => "owner",
46            PivotKey::Project => "project",
47            PivotKey::Kind => "kind",
48            PivotKey::Sandbox => "sandbox",
49            PivotKey::Cohort => "cohort",
50        }
51    }
52
53    /// Parses `owner | project | kind | sandbox | cohort` (case-insensitive).
54    pub fn parse(s: &str) -> Option<PivotKey> {
55        let s = s.trim().to_ascii_lowercase();
56        PivotKey::ALL.into_iter().find(|k| k.as_str() == s)
57    }
58}
59
60#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
61#[serde(default)]
62pub struct PivotTotals {
63    /// Σ group footprint.
64    pub footprint: Measured<Bytes>,
65    pub gpu: Measured<Bytes>,
66    /// Σ per-core CPU %.
67    pub cpu_pct: Measured<f64>,
68    /// Σ idle rent, GiB-hours (estimate).
69    pub idle_rent_gib_h: Measured<f64>,
70    pub group_count: u32,
71    pub process_count: u32,
72    /// Groups flagged stale.
73    pub stale_count: u32,
74    pub idle_count: u32,
75}
76
77#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
78#[serde(default)]
79pub struct PivotBucket {
80    /// Stable key: an owner group id, a project path, a kind alias, a sandbox id or a cohort id; one of
81    /// the `NONE_*` constants for the rest.
82    pub key: String,
83    /// What to show: owner / sandbox / cohort label, project path, kind alias.
84    pub label: String,
85    /// Member groups, largest footprint first.
86    pub group_ids: Vec<String>,
87    pub totals: PivotTotals,
88}
89
90/// Follows `owner_group` to the top-most live owner (bounded, cycle-safe).
91fn top_owner<'a>(g: &'a Group, by_id: &BTreeMap<&'a str, &'a Group>) -> Option<&'a Group> {
92    let mut cur = g;
93    let mut found = None;
94    for _ in 0..16 {
95        let Some(next) = cur
96            .owner_group
97            .as_deref()
98            .filter(|o| *o != cur.id)
99            .and_then(|o| by_id.get(o).copied())
100        else {
101            break;
102        };
103        if next.id == g.id {
104            break;
105        }
106        found = Some(next);
107        cur = next;
108    }
109    found
110}
111
112/// `(key, label)` of the bucket a group belongs to.
113fn bucket_of(g: &Group, s: &Snapshot, key: PivotKey, by_id: &BTreeMap<&str, &Group>) -> (String, String) {
114    let none = |k: &str| (k.to_string(), k.to_string());
115    match key {
116        PivotKey::Kind => (g.kind.alias().to_string(), g.kind.alias().to_string()),
117        PivotKey::Project => match g.project.as_deref().filter(|p| !p.is_empty()) {
118            Some(p) => (p.to_string(), p.to_string()),
119            None => none(NONE_PROJECT),
120        },
121        PivotKey::Cohort => match g.cohort.as_deref() {
122            Some(c) => {
123                let label = s
124                    .cohorts
125                    .iter()
126                    .find(|x| x.id == c)
127                    .map(|x| x.sentence.clone())
128                    .unwrap_or_else(|| c.to_string());
129                (c.to_string(), label)
130            }
131            None => none(NONE_COHORT),
132        },
133        PivotKey::Owner => match top_owner(g, by_id) {
134            Some(o) => (o.id.clone(), o.label.clone()),
135            None => {
136                // A dead owner (a cohort) keeps its leftovers together; a group that owns others is its
137                // own bucket.
138                if let Some(c) = g.cohort.as_deref() {
139                    let label = s
140                        .cohorts
141                        .iter()
142                        .find(|x| x.id == c)
143                        .map(|x| format!("{} (ended)", x.label))
144                        .unwrap_or_else(|| c.to_string());
145                    return (c.to_string(), label);
146                }
147                let owns = s
148                    .groups
149                    .iter()
150                    .any(|x| x.id != g.id && x.owner_group.as_deref() == Some(g.id.as_str()));
151                if owns {
152                    (g.id.clone(), g.label.clone())
153                } else {
154                    none(NONE_OWNER)
155                }
156            }
157        },
158        PivotKey::Sandbox => {
159            let rec = s.sandboxes.iter().find(|sb| {
160                g.root.is_some_and(|r| sb.host_pids.contains(&r))
161                    || sb.host_pids.iter().any(|p| g.members.iter().any(|m| m.id == *p))
162            });
163            match rec {
164                Some(sb) => (sb.id.clone(), sb.label.clone()),
165                None if g.kind == GroupKind::Sandbox => (g.id.clone(), g.label.clone()),
166                None => none(NONE_SANDBOX),
167            }
168        }
169    }
170}
171
172/// Regroups the snapshot's groups by `key`. Buckets are ordered by footprint (largest first), then key;
173/// the `NONE_*` bucket sorts by the same rule.
174pub fn pivot(s: &Snapshot, key: PivotKey) -> Vec<PivotBucket> {
175    let by_id: BTreeMap<&str, &Group> = s.groups.iter().map(|g| (g.id.as_str(), g)).collect();
176    let mut buckets: BTreeMap<String, (String, Vec<&Group>)> = BTreeMap::new();
177    for g in &s.groups {
178        let (k, label) = bucket_of(g, s, key, &by_id);
179        buckets.entry(k).or_insert_with(|| (label, Vec::new())).1.push(g);
180    }
181    let fp = |g: &Group| g.totals.footprint.value.unwrap_or(0);
182    let mut out: Vec<PivotBucket> = buckets
183        .into_iter()
184        .map(|(k, (label, mut gs))| {
185            gs.sort_by(|a, b| fp(b).cmp(&fp(a)).then(a.id.cmp(&b.id)));
186            let mut rent = sum_f64(gs.iter().map(|g| &g.idle_rent_gib_h), "Σ group idle rent");
187            if rent.value.is_some() {
188                rent.quality = Quality::Estimate;
189            }
190            PivotBucket {
191                key: k,
192                label,
193                group_ids: gs.iter().map(|g| g.id.clone()).collect(),
194                totals: PivotTotals {
195                    footprint: sum_bytes(gs.iter().map(|g| &g.totals.footprint), "Σ group footprint"),
196                    gpu: sum_bytes(gs.iter().map(|g| &g.totals.gpu), "Σ group GPU memory"),
197                    cpu_pct: sum_f64(gs.iter().map(|g| &g.totals.cpu_pct), "Σ group CPU %"),
198                    idle_rent_gib_h: rent,
199                    group_count: gs.len() as u32,
200                    process_count: gs.iter().map(|g| g.totals.process_count).sum(),
201                    stale_count: gs.iter().filter(|g| g.staleness.stale).count() as u32,
202                    idle_count: gs.iter().filter(|g| g.idle).count() as u32,
203                },
204            }
205        })
206        .collect();
207    out.sort_by(|a, b| {
208        b.totals
209            .footprint
210            .value
211            .unwrap_or(0)
212            .cmp(&a.totals.footprint.value.unwrap_or(0))
213            .then(a.key.cmp(&b.key))
214    });
215    out
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::model::{GroupTotals, Member, ProcId, Sandbox};
222    use crate::staleness::{Cohort, Staleness};
223
224    fn g(id: &str, kind: GroupKind, gib: u64) -> Group {
225        Group {
226            id: id.into(),
227            kind,
228            label: id.to_uppercase(),
229            totals: GroupTotals {
230                footprint: Measured::exact(gib << 30, "test"),
231                cpu_pct: Measured::exact(1.0, "test"),
232                process_count: 2,
233                ..Default::default()
234            },
235            idle_rent_gib_h: Measured::estimate(gib as f64, "test"),
236            ..Default::default()
237        }
238    }
239
240    fn snap() -> Snapshot {
241        let mut agent = g("agent:1", GroupKind::AgentSession, 1);
242        agent.project = Some("/w/app".into());
243        let mut daemon = g("daemon:1", GroupKind::BuildDaemon, 3);
244        daemon.owner_group = Some("agent:1".into());
245        daemon.project = Some("/w/app".into());
246        daemon.idle = true;
247        let mut nested = g("other:1", GroupKind::Other, 1);
248        nested.owner_group = Some("daemon:1".into());
249        let mut left = g("daemon:2", GroupKind::BuildDaemon, 4);
250        left.owner_group = Some("agent:deadbeef0001".into());
251        left.cohort = Some("agent:deadbeef0001".into());
252        left.project = Some("/w/old".into());
253        left.staleness = Staleness {
254            score: 0.6,
255            stale: true,
256            evidence: Vec::new(),
257        };
258        let mut vm = g("sandbox:1", GroupKind::Sandbox, 2);
259        vm.root = Some(ProcId::new(9, 1));
260        vm.members = vec![Member {
261            id: ProcId::new(9, 1),
262            ..Default::default()
263        }];
264        let app = g("app:1", GroupKind::App, 5);
265        Snapshot {
266            groups: vec![agent, daemon, nested, left, vm, app],
267            sandboxes: vec![Sandbox {
268                id: "docker:abc".into(),
269                label: "web".into(),
270                host_pids: vec![ProcId::new(9, 1)],
271                ..Default::default()
272            }],
273            cohorts: vec![Cohort {
274                id: "agent:deadbeef0001".into(),
275                label: "Claude Code".into(),
276                sentence: "left by the Claude Code session that ended 3h ago".into(),
277                ..Default::default()
278            }],
279            ..Default::default()
280        }
281    }
282
283    fn keys(b: &[PivotBucket]) -> Vec<(&str, Vec<&str>)> {
284        b.iter()
285            .map(|b| (b.key.as_str(), b.group_ids.iter().map(String::as_str).collect()))
286            .collect()
287    }
288
289    #[test]
290    fn every_group_lands_in_exactly_one_bucket_per_key() {
291        let s = snap();
292        let total: u64 = s.groups.iter().filter_map(|g| g.totals.footprint.value).sum();
293        for key in PivotKey::ALL {
294            let b = pivot(&s, key);
295            let n: usize = b.iter().map(|b| b.group_ids.len()).sum();
296            assert_eq!(n, s.groups.len(), "{key:?}");
297            let sum: u64 = b.iter().filter_map(|b| b.totals.footprint.value).sum();
298            assert_eq!(sum, total, "{key:?}");
299            assert_eq!(PivotKey::parse(key.as_str()), Some(key));
300            // deterministic
301            assert_eq!(pivot(&s, key), b);
302        }
303        assert_eq!(PivotKey::parse("Project "), Some(PivotKey::Project));
304        assert_eq!(PivotKey::parse("nope"), None);
305    }
306
307    #[test]
308    fn by_kind() {
309        let s = snap();
310        let b = pivot(&s, PivotKey::Kind);
311        assert_eq!(
312            keys(&b),
313            vec![
314                ("daemon", vec!["daemon:2", "daemon:1"]),
315                ("app", vec!["app:1"]),
316                ("sandbox", vec!["sandbox:1"]),
317                ("agent", vec!["agent:1"]),
318                ("other", vec!["other:1"]),
319            ]
320        );
321        let d = &b[0].totals;
322        assert_eq!(d.footprint.value, Some(7 << 30));
323        assert_eq!((d.group_count, d.process_count), (2, 4));
324        assert_eq!((d.stale_count, d.idle_count), (1, 1));
325        assert_eq!(d.idle_rent_gib_h.value, Some(7.0));
326        assert_eq!(d.idle_rent_gib_h.quality, Quality::Estimate);
327        assert_eq!(d.cpu_pct.value, Some(2.0));
328    }
329
330    #[test]
331    fn by_owner_follows_the_chain_and_keeps_a_dead_session_together() {
332        let s = snap();
333        let b = pivot(&s, PivotKey::Owner);
334        assert_eq!(
335            keys(&b),
336            vec![
337                (NONE_OWNER, vec!["app:1", "sandbox:1"]),
338                ("agent:1", vec!["daemon:1", "agent:1", "other:1"]),
339                ("agent:deadbeef0001", vec!["daemon:2"]),
340            ]
341        );
342        assert_eq!(b[1].label, "AGENT:1");
343        assert_eq!(b[2].label, "Claude Code (ended)");
344    }
345
346    #[test]
347    fn by_project_sandbox_and_cohort() {
348        let s = snap();
349        let b = pivot(&s, PivotKey::Project);
350        assert_eq!(
351            keys(&b),
352            vec![
353                (NONE_PROJECT, vec!["app:1", "sandbox:1", "other:1"]),
354                ("/w/app", vec!["daemon:1", "agent:1"]),
355                ("/w/old", vec!["daemon:2"]),
356            ]
357        );
358        let b = pivot(&s, PivotKey::Sandbox);
359        assert_eq!(b.len(), 2);
360        assert_eq!(b[1].key, "docker:abc");
361        assert_eq!(b[1].label, "web");
362        assert_eq!(b[1].group_ids, vec!["sandbox:1"]);
363        let b = pivot(&s, PivotKey::Cohort);
364        assert_eq!(b[0].key, NONE_COHORT);
365        assert_eq!(b[1].key, "agent:deadbeef0001");
366        assert_eq!(b[1].label, "left by the Claude Code session that ended 3h ago");
367    }
368
369    #[test]
370    fn owner_cycles_terminate() {
371        let mut a = g("a", GroupKind::Other, 1);
372        let mut b = g("b", GroupKind::Other, 1);
373        a.owner_group = Some("b".into());
374        b.owner_group = Some("a".into());
375        let s = Snapshot {
376            groups: vec![a, b],
377            ..Default::default()
378        };
379        assert_eq!(
380            pivot(&s, PivotKey::Owner)
381                .iter()
382                .map(|b| b.group_ids.len())
383                .sum::<usize>(),
384            2
385        );
386    }
387
388    #[test]
389    fn empty_snapshot_has_no_buckets() {
390        assert!(pivot(&Snapshot::default(), PivotKey::Kind).is_empty());
391    }
392}