Skip to main content

oomtop_core/
actions.rs

1//! Action planning and protection rules (SPEC §7 "actions target group roots", §13 safety). Pure: the
2//! frontends build an [`ActionPlan`]; an [`Actuator`] (implemented in the CLI from `oomtop-collect::signal`
3//! and `oomtop-adapters` gentle actions) executes it after explicit confirmation.
4//!
5//! Order: adapter-graceful action first → SIGTERM → SIGKILL only on a second explicit confirmation.
6//! `(pid, start_time)` is re-verified immediately before any signal. Suspend frees no memory and never
7//! appears in reclaim plans.
8
9use crate::model::{Group, GroupKind, ProcId, Process, Snapshot};
10use serde::{Deserialize, Serialize};
11
12/// Process names that are always protected.
13pub const BUILTIN_PROTECTED: &[&str] = &[
14    "kernel_task",
15    "launchd",
16    "init",
17    "systemd",
18    "kthreadd",
19    "WindowServer",
20    "loginwindow",
21    "Finder",
22    "Dock",
23    "SystemUIServer",
24    "coreaudiod",
25    "sshd",
26    "Xorg",
27    "Xwayland",
28    "gnome-shell",
29    "kwin_wayland",
30    "plasmashell",
31];
32
33/// Context for protection decisions.
34#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
35#[serde(default)]
36pub struct ProtectContext {
37    pub self_pid: Option<u32>,
38    pub self_uid: Option<u32>,
39    /// Ancestors of oomtop (its shell, terminal, and for MCP the hosting agent), never offered.
40    pub ancestor_pids: Vec<u32>,
41    /// Extra names from config `protected.names`.
42    pub protected_names: Vec<String>,
43    /// Group id of the agent session hosting an MCP call (excluded from its reclaim candidates).
44    pub caller_group: Option<String>,
45}
46
47/// True for kernel threads, pid ≤ 1, built-in/user protected names, oomtop's own ancestry, and processes
48/// owned by another user.
49pub fn is_protected_process(p: &Process, _snapshot: &Snapshot, ctx: &ProtectContext) -> bool {
50    if p.id.pid <= 1 {
51        return true;
52    }
53    if Some(p.id.pid) == ctx.self_pid || ctx.ancestor_pids.contains(&p.id.pid) {
54        return true;
55    }
56    // Linux kernel threads have no exe and no cmdline.
57    if p.exe.is_empty() && p.cmdline.is_empty() && p.ppid == Some(2) {
58        return true;
59    }
60    if let (Some(uid), Some(me)) = (p.uid, ctx.self_uid) {
61        if uid != me {
62            return true;
63        }
64    }
65    let name = p.name.as_str();
66    BUILTIN_PROTECTED.contains(&name) || ctx.protected_names.iter().any(|n| n == name)
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
70#[serde(rename_all = "snake_case")]
71pub enum ActionKind {
72    /// Adapter-graceful action (e.g. Ollama unload, `lms unload`).
73    Graceful,
74    /// SIGTERM.
75    #[default]
76    Terminate,
77    /// SIGKILL — only after a second explicit confirmation.
78    Kill,
79    /// SIGSTOP — CPU/GPU/thermal relief only; frees no memory.
80    Suspend,
81    /// SIGCONT.
82    Resume,
83}
84
85/// One step of a plan.
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
87#[serde(default)]
88pub struct ActionTarget {
89    pub group_id: String,
90    pub label: String,
91    /// Group root to signal (identity re-verified before signalling).
92    pub root: ProcId,
93    pub kind: ActionKind,
94    pub expected_gain: Option<u64>,
95    /// Graceful action description when `kind == Graceful`, e.g. "ollama unload llama3:8b".
96    pub graceful: Option<String>,
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
100#[serde(default)]
101pub struct ActionPlan {
102    pub targets: Vec<ActionTarget>,
103    /// Must be set by the frontend only after the user confirmed exactly this plan.
104    pub confirmed: bool,
105    /// Required in addition to `confirmed` for `Kill`.
106    pub confirmed_kill: bool,
107}
108
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
110#[serde(default)]
111pub struct ActionOutcome {
112    pub target: ActionTarget,
113    pub ok: bool,
114    pub message: String,
115    /// Re-measured gain after the action ("freed 5.6 GB, est. 5.9").
116    pub measured_gain: Option<u64>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
120pub enum Refusal {
121    #[error("group {0} not found")]
122    NotFound(String),
123    #[error("{0} is protected")]
124    Protected(String),
125    #[error("{0} has no root process")]
126    NoRoot(String),
127    #[error("{0} is the calling agent's own session")]
128    CallerSession(String),
129    #[error("{0} is oomtop itself")]
130    SelfGroup(String),
131}
132
133/// Plans an action on a group root. Helpers are never targeted individually (SPEC §7).
134pub fn plan_group(group: &Group, kind: ActionKind, ctx: &ProtectContext) -> Result<ActionTarget, Refusal> {
135    if group.is_self {
136        return Err(Refusal::SelfGroup(group.label.clone()));
137    }
138    if group.protected || group.kind == GroupKind::System {
139        return Err(Refusal::Protected(group.label.clone()));
140    }
141    if ctx.caller_group.as_deref() == Some(group.id.as_str()) {
142        return Err(Refusal::CallerSession(group.label.clone()));
143    }
144    let root = group.root.ok_or_else(|| Refusal::NoRoot(group.label.clone()))?;
145    if Some(root.pid) == ctx.self_pid || ctx.ancestor_pids.contains(&root.pid) {
146        return Err(Refusal::Protected(group.label.clone()));
147    }
148    let expected_gain = match kind {
149        ActionKind::Suspend | ActionKind::Resume => None,
150        _ => group.reclaim_gain.value,
151    };
152    Ok(ActionTarget {
153        group_id: group.id.clone(),
154        label: group.label.clone(),
155        root,
156        kind,
157        expected_gain,
158        graceful: None,
159    })
160}
161
162/// Plans stopping (SIGTERM) the given groups; unknown or refused groups are returned separately. A group
163/// whose root process is missing from `snapshot` or protected per [`is_protected_process`] is refused.
164pub fn plan_stop(
165    snapshot: &Snapshot,
166    group_ids: &[String],
167    ctx: &ProtectContext,
168) -> (ActionPlan, Vec<Refusal>) {
169    let mut plan = ActionPlan::default();
170    let mut refused = Vec::new();
171    for id in group_ids {
172        match snapshot.group(id) {
173            None => refused.push(Refusal::NotFound(id.clone())),
174            Some(g) => match plan_group(g, ActionKind::Terminate, ctx) {
175                // The root process itself must be in the sample and pass the protect rules (other
176                // users, pid ≤ 1, built-in / configured names) — not only the group flags.
177                Ok(t) => match snapshot.process(t.root) {
178                    Some(root) if !is_protected_process(root, snapshot, ctx) => plan.targets.push(t),
179                    Some(_) => refused.push(Refusal::Protected(g.label.clone())),
180                    None => refused.push(Refusal::NoRoot(g.label.clone())),
181                },
182                Err(r) => refused.push(r),
183            },
184        }
185    }
186    (plan, refused)
187}
188
189/// Executes confirmed plans (implemented outside core).
190pub trait Actuator: Send {
191    fn execute(&mut self, plan: &ActionPlan) -> Vec<ActionOutcome>;
192
193    /// Graceful (adapter) actions that free a group's memory without a signal, described for the user
194    /// (e.g. "ollama: unload llama3:8b"). Empty when the group has none (SPEC §10, §13: try these first).
195    fn graceful_for(&self, _group_id: &str) -> Vec<String> {
196        Vec::new()
197    }
198
199    /// Refreshes per-snapshot state (which model servers currently offer a graceful unload).
200    fn observe(&mut self, _snapshot: &Snapshot) {}
201}
202
203/// An actuator that refuses everything (used by read-only frontends and tests).
204#[derive(Debug, Default, Clone, Copy)]
205pub struct NoopActuator;
206
207impl Actuator for NoopActuator {
208    fn execute(&mut self, plan: &ActionPlan) -> Vec<ActionOutcome> {
209        plan.targets
210            .iter()
211            .map(|t| ActionOutcome {
212                target: t.clone(),
213                ok: false,
214                message: "actions are disabled".into(),
215                measured_gain: None,
216            })
217            .collect()
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use crate::model::Measured;
225
226    #[test]
227    fn refuses_protected_and_self() {
228        let ctx = ProtectContext {
229            self_pid: Some(10),
230            caller_group: Some("agent:x".into()),
231            ..Default::default()
232        };
233        let mut g = Group {
234            id: "daemon:gradle:5".into(),
235            label: "GradleDaemon".into(),
236            kind: GroupKind::BuildDaemon,
237            root: Some(ProcId::new(5, 1)),
238            reclaim_gain: Measured::estimate(3, "t"),
239            ..Default::default()
240        };
241        let t = plan_group(&g, ActionKind::Terminate, &ctx).unwrap();
242        assert_eq!(t.expected_gain, Some(3));
243        assert_eq!(
244            plan_group(&g, ActionKind::Suspend, &ctx).unwrap().expected_gain,
245            None
246        );
247        g.protected = true;
248        assert!(matches!(
249            plan_group(&g, ActionKind::Terminate, &ctx),
250            Err(Refusal::Protected(_))
251        ));
252        g.protected = false;
253        g.id = "agent:x".into();
254        assert!(matches!(
255            plan_group(&g, ActionKind::Terminate, &ctx),
256            Err(Refusal::CallerSession(_))
257        ));
258    }
259
260    #[test]
261    fn protected_processes() {
262        let s = Snapshot::default();
263        let ctx = ProtectContext {
264            self_uid: Some(501),
265            ..Default::default()
266        };
267        let mut p = Process {
268            id: ProcId::new(300, 1),
269            name: "WindowServer".into(),
270            uid: Some(501),
271            ..Default::default()
272        };
273        assert!(is_protected_process(&p, &s, &ctx));
274        p.name = "java".into();
275        assert!(!is_protected_process(&p, &s, &ctx));
276        p.uid = Some(0);
277        assert!(is_protected_process(&p, &s, &ctx));
278    }
279}