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,
action: &'static str,
detail: String,
idle: bool,
}
#[derive(Debug, Clone, Serialize)]
struct Skipped {
group_id: String,
reason: String,
}
fn plan(
s: &Snapshot,
protect: &ProtectContext,
actuator: &SignalActuator,
only: &[String],
) -> (ActionPlan, Vec<PlannedRow>, Vec<Skipped>) {
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;
}
};
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;
}
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)
}
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) {
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
}
}
fn wait_for_exit(plan: &ActionPlan, wait: Duration) -> Vec<usize> {
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));
}
}
fn say(json: bool, text: &str) {
if json {
err_out(text);
} else {
out(text);
}
}
pub fn run(ctx: &Ctx, a: ReclaimArgs) -> Result<i32> {
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();
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() {
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);
}
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
),
);
}
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(", ")
),
);
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",
);
}
}
}
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,
};
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)
}
#[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);
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);
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");
}
#[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() {
assert!(wait_for_exit(&ActionPlan::default(), Duration::MAX).is_empty());
}
}