oomtop-cli 0.2.3

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! `oomtop reclaim` (SPEC §7, §8.1, §13): idle build daemons, orphans and idle model servers.
//!
//! Safety rules, in order:
//! 1. Only reclaim candidates (`can_fit::reclaim_candidates`), never oomtop's own group, never a group whose
//!    root is protected or owned by another user (`actions::is_protected_process`), group roots only.
//! 2. Model servers with an adapter action are unloaded gently (no signal) before anything else.
//! 3. Nothing happens without confirmation: an interactive `[y/N]`, or `--yes` for exactly the listed plan.
//! 4. SIGTERM first. SIGKILL only for groups still alive after `--wait`, and only after a second,
//!    interactive confirmation — `--yes` never escalates.
//! 5. `--replay` never signals anything (the fixture's pids are not this machine's processes).
//! 6. `--dry-run` leaves no trace: the state store is read, never written or created.
//!
//! Output: without `--json` everything goes to stdout. With `--json`, stdout is exactly one JSON document
//! on every path (dry run, nothing to do, cancelled, refused, replay, executed) and the human text — the
//! plan shown before the question, progress, "still running" — goes to stderr.
//!
//! Exit: 0 done / dry run / cancelled · 1 a signal or unload failed, no confirmation was possible, or
//! `--groups` named only groups that cannot be reclaimed (nothing was done).

use super::{confirm, err_out, json_pretty, out, Ctx};
use crate::actuator::SignalActuator;
use crate::engine::Engine;
use crate::ReclaimArgs;
use anyhow::{bail, Result};
use oomtop_adapters::{stop_guard, StopGuard};
use oomtop_core::actions::{
    is_protected_process, plan_group, ActionKind, ActionOutcome, ActionPlan, Actuator, ProtectContext,
};
use oomtop_core::can_fit::{reclaim_candidates, ReclaimCandidate, EXIT_ERROR};
use oomtop_core::provider::SnapshotProvider;
use oomtop_core::units::format_duration;
use oomtop_core::Snapshot;
use serde::Serialize;
use std::time::{Duration, Instant};

#[derive(Debug, Clone, Serialize)]
struct PlannedRow {
    #[serde(flatten)]
    candidate: ReclaimCandidate,
    /// "sigterm" | "graceful"
    action: &'static str,
    /// Human description (e.g. "ollama: unload llama3:8b").
    detail: String,
    /// The group is idle by the SPEC §7 rule (not just quiet for a while).
    idle: bool,
}

#[derive(Debug, Clone, Serialize)]
struct Skipped {
    group_id: String,
    reason: String,
}

/// Plans the reclaim: returns the confirmed-able plan, the rows shown to the user, and what was skipped.
fn plan(
    s: &Snapshot,
    protect: &ProtectContext,
    actuator: &SignalActuator,
    only: &[String],
) -> (ActionPlan, Vec<PlannedRow>, Vec<Skipped>) {
    // `--groups` takes raw ids and the exported form MCP / `json` hand out (`app:redacted-1a2b3c4d`).
    let only: Vec<String> = only
        .iter()
        .map(|id| oomtop_mcp::resolve_group_id(s, id).unwrap_or_else(|| id.clone()))
        .collect();
    let only = &only[..];
    let me = Engine::self_group(s);
    let mut cands = reclaim_candidates(s);
    cands.retain(|c| Some(&c.group_id) != me.as_ref());
    let mut skipped = Vec::new();
    if !only.is_empty() {
        for id in only {
            if !cands.iter().any(|c| &c.group_id == id) {
                let reason = match s.group(id) {
                    None => "no such group in this snapshot".to_string(),
                    Some(_) if Some(id) == me.as_ref() => "oomtop's own group".to_string(),
                    Some(_) => {
                        "not a reclaim candidate (not idle, orphaned or an idle model server)".to_string()
                    }
                };
                skipped.push(Skipped {
                    group_id: id.clone(),
                    reason,
                });
            }
        }
        cands.retain(|c| only.contains(&c.group_id));
    }
    let mut plan = ActionPlan::default();
    let mut rows = Vec::new();
    for c in cands {
        let Some(g) = s.group(&c.group_id) else { continue };
        let gentle = actuator.gentle_for(&g.id);
        let kind = if gentle.is_empty() {
            ActionKind::Terminate
        } else {
            ActionKind::Graceful
        };
        let mut t = match plan_group(g, kind, protect) {
            Ok(t) => t,
            Err(r) => {
                skipped.push(Skipped {
                    group_id: c.group_id.clone(),
                    reason: r.to_string(),
                });
                continue;
            }
        };
        // Other users' processes and protected names/ancestors are never targets (SPEC §13).
        if let Some(root) = s.process(t.root) {
            if is_protected_process(root, s, protect) {
                skipped.push(Skipped {
                    group_id: c.group_id.clone(),
                    reason: format!(
                        "root {} (pid {}) is protected or owned by another user",
                        root.name, root.id.pid
                    ),
                });
                continue;
            }
        } else {
            skipped.push(Skipped {
                group_id: c.group_id.clone(),
                reason: "root process not in this snapshot".into(),
            });
            continue;
        }
        // SPEC §10: never interrupt a running job silently. A busy server is skipped unless it was named
        // with --groups; an unconfirmed idle state is said out loud in the plan. This holds for a gentle
        // unload as much as for SIGTERM (as in MCP `reclaim`): unloading the model ends the job too.
        let mut guard_note = String::new();
        if let Some(ms) = s
            .model_servers
            .iter()
            .find(|m| m.group_id.as_deref() == Some(g.id.as_str()))
        {
            match stop_guard(ms) {
                StopGuard::Allowed => {}
                StopGuard::Busy(why) if !only.contains(&g.id) => {
                    skipped.push(Skipped {
                        group_id: c.group_id.clone(),
                        reason: format!("busy ({why}); name it with --groups to stop it anyway"),
                    });
                    continue;
                }
                StopGuard::Busy(why) => guard_note = format!(" — interrupts {why}"),
                StopGuard::Unknown(why) => guard_note = format!(" — idle not confirmed ({why})"),
            }
        }
        let detail = if kind == ActionKind::Graceful {
            let d: Vec<String> = gentle.iter().map(|a| a.describe()).collect();
            let d = d.join("; ");
            t.graceful = Some(d.clone());
            format!("{d}{guard_note}")
        } else {
            format!("SIGTERM pid {}{guard_note}", t.root.pid)
        };
        rows.push(PlannedRow {
            candidate: c,
            action: if kind == ActionKind::Graceful {
                "graceful"
            } else {
                "sigterm"
            },
            detail,
            idle: g.idle,
        });
        plan.targets.push(t);
    }
    (plan, rows, skipped)
}

/// The plan as text: every candidate with its action and estimated gain, then what was skipped and why.
fn plan_text(ctx: &Ctx, rows: &[PlannedRow], skipped: &[Skipped]) -> String {
    let mut o = String::new();
    if rows.is_empty() {
        o.push_str("Nothing to reclaim: no idle build daemons, orphans or idle model servers.\n");
    } else {
        o.push_str("Reclaim candidates (RAM freed is an estimate):\n");
        for r in rows {
            let c = &r.candidate;
            let mut tags = Vec::new();
            if let Some(s) = c.idle_for_s.filter(|s| *s > 0) {
                // "idle" only when the group meets the idle rule (SPEC §7: 30 min below the CPU threshold);
                // a daemon that has merely been quiet for a while says so.
                let word = if r.idle { "idle" } else { "quiet" };
                tags.push(format!("{word} {}", format_duration(s)));
            }
            if c.orphan {
                tags.push("orphan".into());
            }
            if let Some(sw) = c.swap_gain.filter(|s| *s > 0) {
                tags.push(format!("+{} swap", ctx.fmt(sw)));
            }
            let tags = if tags.is_empty() {
                String::new()
            } else {
                format!(" · {}", tags.join(" · "))
            };
            o.push_str(&format!(
                "  {:<28} {:<7} ≈{:>10}  {}{tags}\n      {}\n",
                truncate(&c.label, 28),
                c.kind.alias(),
                ctx.fmt(c.gain),
                r.detail,
                c.group_id
            ));
        }
        let total: u64 = rows.iter().map(|r| r.candidate.gain).sum();
        o.push_str(&format!("Total ≈{} RAM\n", ctx.fmt(total)));
    }
    for s in skipped {
        o.push_str(&format!("  skipped {}: {}\n", s.group_id, s.reason));
    }
    o
}

fn truncate(s: &str, n: usize) -> String {
    if s.chars().count() <= n {
        s.to_string()
    } else {
        let mut t: String = s.chars().take(n.saturating_sub(1)).collect();
        t.push('…');
        t
    }
}

/// Waits until every target's root is gone (identity-checked) or the deadline passes; returns survivors.
fn wait_for_exit(plan: &ActionPlan, wait: Duration) -> Vec<usize> {
    // `--wait` is capped at parse time; an unrepresentable deadline still must not panic after SIGTERM.
    let start = Instant::now();
    let deadline = start
        .checked_add(wait)
        .unwrap_or_else(|| start + Duration::from_secs(86_400));
    loop {
        let alive: Vec<usize> = plan
            .targets
            .iter()
            .enumerate()
            .filter(|(_, t)| t.kind == ActionKind::Terminate && oomtop_collect::signal::is_alive(t.root))
            .map(|(i, _)| i)
            .collect();
        if alive.is_empty() || Instant::now() >= deadline {
            return alive;
        }
        std::thread::sleep(Duration::from_millis(200));
    }
}

/// Human text: stdout normally, stderr with `--json` (stdout then carries only the JSON document).
fn say(json: bool, text: &str) {
    if json {
        err_out(text);
    } else {
        out(text);
    }
}

pub fn run(ctx: &Ctx, a: ReclaimArgs) -> Result<i32> {
    // A dry run reads the lineage journal (same plan as a real run) and writes nothing.
    let mut e = if a.dry_run {
        ctx.engine_read_only(true)?
    } else {
        ctx.engine(true)?
    };
    let s = e.snapshot();
    let mut actuator = SignalActuator::new();
    actuator.register_gentle(&s);
    let (mut plan, rows, skipped) = plan(&s, &e.protect, &actuator, &a.groups);
    let total: u64 = rows.iter().map(|r| r.candidate.gain).sum();
    // The one JSON document of this run: the plan, plus what happened.
    let doc = |status: &str, more: serde_json::Value| -> serde_json::Value {
        let mut v = serde_json::json!({
            "dry_run": a.dry_run,
            "status": status,
            "candidates": rows,
            "skipped": skipped,
            "total_gain": total,
            "as_of_ms": s.taken_at_ms,
        });
        if let (Some(o), serde_json::Value::Object(m)) = (v.as_object_mut(), more) {
            o.extend(m);
        }
        v
    };

    if a.dry_run || plan.targets.is_empty() {
        // `--groups a,b` where nothing named can be reclaimed is a failure a script must see, not "ok".
        let none_usable = !a.groups.is_empty() && plan.targets.is_empty();
        let status = if none_usable {
            "refused"
        } else if a.dry_run {
            "dry_run"
        } else {
            "nothing_to_do"
        };
        if a.json {
            out(&json_pretty(&doc(status, serde_json::Value::Null))?);
        } else {
            out(&plan_text(ctx, &rows, &skipped));
        }
        if none_usable {
            err_out("oomtop: none of the requested groups can be reclaimed; nothing was stopped\n");
            return Ok(EXIT_ERROR);
        }
        return Ok(0);
    }
    // The plan is always shown before the question — on stderr when stdout is reserved for JSON.
    say(a.json, &plan_text(ctx, &rows, &skipped));
    if !a.yes {
        let q = format!(
            "Stop {} group(s) (gentle unload / SIGTERM), freeing ≈{}?",
            plan.targets.len(),
            ctx.fmt(total)
        );
        match confirm(&q)? {
            Some(true) => {}
            Some(false) => {
                say(a.json, "Cancelled; nothing was stopped.\n");
                if a.json {
                    out(&json_pretty(&doc("cancelled", serde_json::Value::Null))?);
                }
                return Ok(0);
            }
            None => {
                let msg = "refusing to stop processes without confirmation: stdin is not a terminal (review with --dry-run, then pass --yes)";
                if a.json {
                    out(&json_pretty(&doc(
                        "needs_confirmation",
                        serde_json::json!({ "message": msg }),
                    ))?);
                }
                bail!(msg)
            }
        }
    }
    if !e.is_live() {
        say(
            a.json,
            "Replay mode: plan confirmed but nothing executed (fixture processes are not on this machine).\n",
        );
        if a.json {
            out(&json_pretty(&doc("replay", serde_json::Value::Null))?);
        }
        return Ok(0);
    }
    plan.confirmed = true;
    let before = s.memory.available.value;
    let mut outcomes: Vec<ActionOutcome> = actuator.execute(&plan);
    for o in &outcomes {
        say(
            a.json,
            &format!(
                "  {}: {}{}\n",
                o.target.label,
                if o.ok { "" } else { "failed: " },
                o.message
            ),
        );
    }
    // Only targets that were actually signalled can survive.
    let mut sent = plan.clone();
    sent.targets = outcomes
        .iter()
        .filter(|o| o.ok)
        .map(|o| o.target.clone())
        .collect();
    let survivors = wait_for_exit(&sent, a.wait);
    let mut still_running: Vec<String> = Vec::new();
    if !survivors.is_empty() {
        let names: Vec<String> = survivors.iter().map(|i| sent.targets[*i].label.clone()).collect();
        say(
            a.json,
            &format!(
                "Still running after {}: {}\n",
                format_duration(a.wait.as_secs().max(1)),
                names.join(", ")
            ),
        );
        // Second, explicit confirmation — never implied by --yes.
        let q = format!("Force-stop {} group(s) with SIGKILL?", survivors.len());
        match confirm(&q)? {
            Some(true) => {
                let kill = ActionPlan {
                    targets: survivors
                        .iter()
                        .map(|i| {
                            let mut t = sent.targets[*i].clone();
                            t.kind = ActionKind::Kill;
                            t
                        })
                        .collect(),
                    confirmed: true,
                    confirmed_kill: true,
                };
                let ko = actuator.execute(&kill);
                for o in &ko {
                    say(a.json, &format!("  {}: {}\n", o.target.label, o.message));
                }
                still_running = ko
                    .iter()
                    .filter(|o| !o.ok)
                    .map(|o| o.target.group_id.clone())
                    .collect();
                outcomes.extend(ko);
            }
            _ => {
                still_running = survivors
                    .iter()
                    .map(|i| sent.targets[*i].group_id.clone())
                    .collect();
                say(
                    a.json,
                    "Left running (SIGKILL needs an interactive second confirmation).\n",
                );
            }
        }
    }
    // Measure what was actually freed.
    std::thread::sleep(Duration::from_millis(500));
    let after = e.snapshot().memory.available.value;
    let freed = match (before, after) {
        (Some(b), Some(a)) => Some(a.saturating_sub(b)),
        _ => None,
    };
    let ok = outcomes.iter().all(|o| o.ok);
    if a.json {
        let status = if !ok {
            "failed"
        } else if still_running.is_empty() {
            "done"
        } else {
            "still_running"
        };
        out(&json_pretty(&doc(
            status,
            serde_json::json!({
                "outcomes": outcomes,
                "still_running": still_running,
                "estimated_gain": total,
                "measured_gain": freed,
            }),
        ))?);
    } else {
        out(&format!(
            "Freed {} (estimated ≈{}); memory settles over a few seconds.\n",
            ctx.fmt_opt(freed),
            ctx.fmt(total)
        ));
    }
    Ok(if ok { 0 } else { EXIT_ERROR })
}

#[cfg(test)]
mod tests {
    use super::*;
    use oomtop_core::{
        Group, GroupKind, LoadedModel, Measured, ModelServer, ModelServerKind, ProcId, Process, SourceStatus,
    };

    /// An idle Ollama server (so a reclaim candidate) with a loaded model and an unload action.
    fn ollama(busy: Measured<bool>) -> Snapshot {
        let id = ProcId::new(4_242, 1_000);
        let mut p = Process {
            id,
            ppid: Some(1),
            name: "ollama".into(),
            exe: "/usr/local/bin/ollama".into(),
            cmdline: vec!["ollama".into(), "serve".into()],
            uid: Some(501),
            ..Default::default()
        };
        p.mem.footprint_or_pss = Measured::exact(6 << 30, "test");
        let mut s = Snapshot {
            taken_at_ms: 1,
            processes: vec![p],
            ..Default::default()
        };
        s.groups.push(Group {
            id: "model:ollama".into(),
            kind: GroupKind::ModelServer,
            label: "Ollama".into(),
            root: Some(id),
            idle: true,
            idle_for_s: Some(3_600),
            reclaim_gain: Measured::estimate(6 << 30, "test"),
            ..Default::default()
        });
        s.model_servers.push(ModelServer {
            id: "ollama".into(),
            kind: ModelServerKind::Ollama,
            endpoint: Some("http://127.0.0.1:11434".into()),
            pids: vec![id],
            group_id: Some("model:ollama".into()),
            models: vec![LoadedModel {
                name: "llama3:8b".into(),
                ..Default::default()
            }],
            busy,
            status: SourceStatus::Available,
            ..Default::default()
        });
        s
    }

    fn planned(s: &Snapshot, only: &[String]) -> (ActionPlan, Vec<PlannedRow>, Vec<Skipped>) {
        let mut act = SignalActuator::new();
        act.register_gentle(s);
        assert!(
            !act.gentle_for("model:ollama").is_empty(),
            "the fixture has an unload action"
        );
        plan(s, &ProtectContext::default(), &act, only)
    }

    /// The busy guard covers gentle unloads too (it used to apply to SIGTERM targets only, so a server in
    /// the middle of a request was unloaded without a word).
    #[test]
    fn busy_guard_applies_to_graceful_unloads() {
        let busy = ollama(Measured::exact(true, "ollama /api/ps"));
        let (p, rows, skipped) = planned(&busy, &[]);
        assert!(p.targets.is_empty() && rows.is_empty(), "{rows:?}");
        assert_eq!(skipped.len(), 1);
        assert!(skipped[0].reason.starts_with("busy ("), "{}", skipped[0].reason);

        // Named with --groups: planned, and the plan says what it interrupts.
        let (p, rows, skipped) = planned(&busy, &["model:ollama".to_string()]);
        assert!(skipped.is_empty());
        assert_eq!(p.targets[0].kind, ActionKind::Graceful);
        assert_eq!(rows[0].action, "graceful");
        assert!(rows[0].detail.contains("unload llama3:8b"), "{}", rows[0].detail);
        assert!(rows[0].detail.contains("interrupts"), "{}", rows[0].detail);

        // "Idle" that is only a CPU heuristic is said out loud; an API-confirmed idle server has no note.
        let unsure = ollama(Measured::estimate(false, "cpu heuristic"));
        let (_, rows, _) = planned(&unsure, &[]);
        assert!(
            rows[0].detail.contains("idle not confirmed"),
            "{}",
            rows[0].detail
        );
        let idle = ollama(Measured::exact(false, "ollama /api/ps"));
        let (p, rows, _) = planned(&idle, &[]);
        assert_eq!(p.targets.len(), 1);
        assert_eq!(rows[0].detail, "ollama: unload llama3:8b");
    }

    /// `--groups` accepts the exported id (what MCP and `json` print) as well as the raw one.
    #[test]
    fn groups_accepts_the_exported_form_of_an_id() {
        let mut s = ollama(Measured::exact(false, "ollama /api/ps"));
        let label = "Ollama API_KEY=hunter2secretvalue";
        let raw = format!("model:{}", oomtop_core::attribution::slug(label));
        s.groups[0].id = raw.clone();
        s.groups[0].label = label.into();
        s.model_servers[0].group_id = Some(raw.clone());
        let exported = oomtop_mcp::exported_group_id(&s, &raw);
        assert!(
            exported.contains("redacted-") && !exported.contains("hunter2"),
            "{exported}"
        );
        for id in [exported, raw.clone()] {
            let (p, _, skipped) = plan(&s, &ProtectContext::default(), &SignalActuator::new(), &[id]);
            assert!(
                skipped.is_empty(),
                "{:?}",
                skipped.iter().map(|k| &k.reason).collect::<Vec<_>>()
            );
            assert_eq!(p.targets.len(), 1);
            assert_eq!(p.targets[0].group_id, raw);
        }
        let (p, _, skipped) = plan(
            &s,
            &ProtectContext::default(),
            &SignalActuator::new(),
            &["model:redacted-00000000".to_string()],
        );
        assert!(p.targets.is_empty());
        assert!(skipped[0].reason.contains("no such group"));
    }

    #[test]
    fn waiting_for_exit_never_overflows_the_clock() {
        // No Terminate target alive: returns at once, whatever the wait.
        assert!(wait_for_exit(&ActionPlan::default(), Duration::MAX).is_empty());
    }
}