Skip to main content

oomtop_cli/
engine.rs

1//! The sampling pipeline behind every frontend (SPEC §6, §6.2):
2//! `Sampler → attribution (detect) → idle/orphan → adapters → history → OOM forecast → likely victim`,
3//! plus the lineage journal (`oomtop-state`). Implements `oomtop_core::provider::SnapshotProvider`.
4
5use oomtop_adapters::{probe, ProbeOptions};
6use oomtop_collect::replay::{load_fixture, replay};
7use oomtop_collect::{Sampler, SamplerOptions};
8use oomtop_config::Config;
9use oomtop_core::actions::ProtectContext;
10use oomtop_core::attribution::LineageEntry;
11use oomtop_core::forecast::forecast_oom_with;
12use oomtop_core::headroom::HeadroomConfig;
13use oomtop_core::history::History;
14use oomtop_core::idle::{IdleConfig, IdleTracker};
15use oomtop_core::provider::SnapshotProvider;
16use oomtop_core::throttle::throttle_factor;
17use oomtop_core::{GroupKind, ModelServer, ProcId, Sandbox, SandboxKind, Snapshot};
18use oomtop_detect::Detector;
19use oomtop_state::StateDb;
20use std::collections::BTreeMap;
21use std::path::{Path, PathBuf};
22use std::time::Duration;
23
24/// Lineage is persisted at most this often (plus on drop).
25const LINEAGE_FLUSH_MS: u64 = 30_000;
26/// In-memory lineage entries of processes not seen for this long are dropped after they were persisted
27/// (a `(pid, start_time)` never comes back, and the journal keeps them for the next run). Keeps a long TUI
28/// session during builds — thousands of short-lived compilers — from growing without bound (SPEC §14).
29pub const LINEAGE_EVICT_MS: u64 = 5 * 60_000;
30/// Ended-session lookups in the lineage journal are repeated at most this often per session.
31pub const ENDED_SESSION_TTL_MS: u64 = 60_000;
32/// On-demand (MCP) calls reuse the previous call's sample as the CPU baseline when it is this recent.
33pub const ON_DEMAND_BASELINE_MS: u64 = 30_000;
34/// Gap between the two samples of an on-demand call without a recent baseline.
35pub const ON_DEMAND_GAP_MS: u64 = 150;
36
37enum Input {
38    Live(Box<Sampler>),
39    Replay { frames: Vec<Snapshot>, next: usize },
40}
41
42pub struct Engine {
43    input: Input,
44    detector: Detector,
45    state: Option<StateDb>,
46    lineage: BTreeMap<ProcId, LineageEntry>,
47    idle: IdleTracker,
48    idle_cfg: IdleConfig,
49    /// `thresholds.stale_*` (SPEC §7 "Staleness").
50    stale_cfg: oomtop_core::staleness::StalenessConfig,
51    /// Ended agent sessions as the lineage journal remembers them, with when that was looked up.
52    ended_sessions: BTreeMap<String, (u64, Option<oomtop_core::staleness::EndedSession>)>,
53    headroom_cfg: HeadroomConfig,
54    history: History,
55    probe_opts: ProbeOptions,
56    adapters_enabled: bool,
57    /// `general.other_users = false` → drop other users' processes before attribution.
58    own_uid_only: Option<u32>,
59    protected_names: Vec<String>,
60    /// Two samples 150 ms apart per call (MCP / one-shot commands), or one when the previous call's sample
61    /// is recent enough to be the CPU baseline.
62    on_demand: bool,
63    last_on_demand_ms: Option<u64>,
64    last_flush_ms: u64,
65    /// Learning allowed (machine profile refresh); `--no-learn` turns it off. Lineage is always kept.
66    learn: bool,
67    model_folders: Vec<PathBuf>,
68    profile_checked: bool,
69    /// The journal is read lazily for the processes of the first sample (not the whole 30-day journal).
70    lineage_loaded: bool,
71    /// The previous probe's model servers and sandboxes: adapter truth for the next attribution (SPEC §7
72    /// signal #1), since the probe itself needs attributed groups.
73    adapter_truth: (Vec<ModelServer>, Vec<Sandbox>),
74    /// The state store is only read (`reclaim --dry-run`): lineage is loaded so the plan matches a real run,
75    /// but nothing is recorded and the machine profile is not refreshed.
76    state_read_only: bool,
77    pub protect: ProtectContext,
78    pub rule_errors: Vec<String>,
79    /// Per-limit histories and container CPU counters (SPEC §8.3, §11; `oomtop_core::cluster`).
80    isolation: oomtop_core::cluster::IsolationTracker,
81}
82
83impl Engine {
84    /// Live engine for this machine (user rules from the default config dir).
85    pub fn live(cfg: &Config, state: Option<StateDb>, on_demand: bool, offline: bool) -> Self {
86        Self::live_in(cfg, state, on_demand, offline, None)
87    }
88
89    /// Live engine reading user rules from `config_dir/rules.d` (`--config` moves the config dir).
90    pub fn live_in(
91        cfg: &Config,
92        state: Option<StateDb>,
93        on_demand: bool,
94        offline: bool,
95        config_dir: Option<&Path>,
96    ) -> Self {
97        let opts = SamplerOptions {
98            cadence: oomtop_collect::Cadence {
99                host_ms: cfg.general.host_refresh_ms,
100                procs_ms: cfg.general.refresh_ms,
101                expensive_ms: cfg.general.expensive_refresh_ms,
102            },
103            marker_allowlist: cfg.privacy.marker_allowlist.clone(),
104            ..Default::default()
105        };
106        Self::with_input(
107            cfg,
108            state,
109            on_demand,
110            offline,
111            config_dir,
112            Input::Live(Box::new(Sampler::platform_default(&opts))),
113        )
114    }
115
116    /// Engine replaying a fixture file (`--replay`).
117    pub fn replay(cfg: &Config, path: &Path) -> Result<Self, String> {
118        Self::replay_in(cfg, path, None)
119    }
120
121    /// Replay engine with user rules from `config_dir/rules.d`. Never persists state, never probes adapters.
122    pub fn replay_in(cfg: &Config, path: &Path, config_dir: Option<&Path>) -> Result<Self, String> {
123        let fx = load_fixture(path).map_err(|e| e.to_string())?;
124        let frames = replay(&fx);
125        if frames.is_empty() {
126            return Err(format!("{}: fixture has no frames", path.display()));
127        }
128        Ok(Self::with_input(
129            cfg,
130            None,
131            false,
132            true,
133            config_dir,
134            Input::Replay { frames, next: 0 },
135        ))
136    }
137
138    fn with_input(
139        cfg: &Config,
140        state: Option<StateDb>,
141        on_demand: bool,
142        offline: bool,
143        config_dir: Option<&Path>,
144        input: Input,
145    ) -> Self {
146        let paths = match config_dir {
147            Some(d) => oomtop_config::paths::ConfigPaths::new(d),
148            None => oomtop_config::paths::ConfigPaths::default_user(),
149        };
150        let (detector, errs) = Detector::with_user_rules(Some(&paths.rules_d));
151        Engine {
152            input,
153            detector,
154            state,
155            lineage: BTreeMap::new(),
156            idle: IdleTracker::new(),
157            idle_cfg: cfg.idle_config(),
158            stale_cfg: cfg.staleness_config(),
159            ended_sessions: BTreeMap::new(),
160            headroom_cfg: cfg.headroom_config(),
161            history: History::default(),
162            probe_opts: ProbeOptions {
163                timeout: Duration::from_millis(cfg.adapters.timeout_ms),
164                http: !offline,
165                ports: cfg.adapters.ports.clone(),
166            },
167            adapters_enabled: cfg.adapters.enabled,
168            // SAFETY: getuid never fails.
169            own_uid_only: (!cfg.general.other_users).then(|| unsafe { libc::getuid() }),
170            protected_names: cfg.protected.names.clone(),
171            on_demand,
172            last_on_demand_ms: None,
173            last_flush_ms: 0,
174            learn: cfg.personalization.learn,
175            model_folders: cfg
176                .models
177                .folders
178                .iter()
179                .map(|f| oomtop_config::paths::expand_tilde(f))
180                .collect(),
181            profile_checked: false,
182            lineage_loaded: false,
183            adapter_truth: (Vec::new(), Vec::new()),
184            state_read_only: false,
185            protect: ProtectContext::default(),
186            rule_errors: errs.iter().map(|e| e.to_string()).collect(),
187            isolation: oomtop_core::cluster::IsolationTracker::new(),
188        }
189    }
190
191    fn raw_snapshot(&mut self) -> Snapshot {
192        self.raw_snapshot_with(false)
193    }
194
195    /// `force`: run every source now (the TUI's second sample, taken 500 ms after the first so CPU % shows
196    /// within a second, SPEC §6.2/§14).
197    fn raw_snapshot_with(&mut self, force: bool) -> Snapshot {
198        match &mut self.input {
199            Input::Live(s) => {
200                if self.on_demand {
201                    // CPU % needs two samples. A previous call's sample younger than ON_DEMAND_BASELINE_MS
202                    // is the baseline (CPU is then averaged since that call); otherwise take a baseline now.
203                    let now = oomtop_collect::now_ms();
204                    let fresh = self
205                        .last_on_demand_ms
206                        .is_some_and(|t| now.saturating_sub(t) <= ON_DEMAND_BASELINE_MS);
207                    if !fresh {
208                        s.sample_all();
209                        std::thread::sleep(Duration::from_millis(ON_DEMAND_GAP_MS));
210                    }
211                    let snap = s.sample_all();
212                    self.last_on_demand_ms = Some(oomtop_collect::now_ms());
213                    snap
214                } else if force {
215                    s.sample_all()
216                } else {
217                    s.sample_once()
218                }
219            }
220            Input::Replay { frames, next } => {
221                let i = (*next).min(frames.len() - 1);
222                *next += 1;
223                frames[i].clone()
224            }
225        }
226    }
227
228    fn update_protect(&mut self, s: &Snapshot) {
229        let me = s.self_pid.and_then(|p| s.process_by_pid(p));
230        let mut ancestors = Vec::new();
231        let mut cur = me.and_then(|p| p.ppid);
232        while let Some(pid) = cur.filter(|p| *p > 1 && ancestors.len() < 64) {
233            ancestors.push(pid);
234            cur = s.process_by_pid(pid).and_then(|p| p.ppid);
235        }
236        self.protect.self_pid = s.self_pid;
237        self.protect.self_uid = me.and_then(|p| p.uid);
238        self.protect.ancestor_pids = ancestors;
239        self.protect.protected_names = self.protected_names.clone();
240    }
241
242    fn record_lineage(&mut self, s: &Snapshot) {
243        let now = s.taken_at_ms;
244        let by_id: std::collections::HashMap<ProcId, &oomtop_core::Process> =
245            s.processes.iter().map(|p| (p.id, p)).collect();
246        for g in &s.groups {
247            let agent_group = g.kind == GroupKind::AgentSession;
248            for m in &g.members {
249                let p = by_id.get(&m.id).copied();
250                let spawned = agent_group || p.map(|p| p.markers.session_id.is_some()).unwrap_or(false);
251                let e = self.lineage.entry(m.id).or_insert_with(|| LineageEntry {
252                    first_seen_ms: now,
253                    ..Default::default()
254                });
255                let keep_agent = e.spawned_by_agent && !spawned;
256                e.id = m.id;
257                // Keep the original parent: the journal exists to remember it after re-parenting.
258                if e.ppid.map(|pp| pp <= 1).unwrap_or(true) {
259                    e.ppid = p.and_then(|p| p.ppid);
260                }
261                // Assign only what changed: ~700 processes × 3 strings per refresh otherwise (SPEC §14).
262                if !keep_agent {
263                    if e.group_id != g.id {
264                        e.group_id = g.id.clone();
265                    }
266                    e.group_kind = g.kind;
267                    if e.group_label != g.label {
268                        e.group_label = g.label.clone();
269                    }
270                    if e.group_fingerprint != g.fingerprint {
271                        e.group_fingerprint = g.fingerprint.clone();
272                    }
273                }
274                if let Some(sid) = p.and_then(|p| p.markers.session_id.as_ref()) {
275                    if e.session_id.as_ref() != Some(sid) {
276                        e.session_id = Some(sid.clone());
277                    }
278                }
279                e.spawned_by_agent |= spawned;
280                e.last_seen_ms = now;
281                if let Some(t) = self.idle.last_active_ms(m.id) {
282                    e.last_active_ms = e.last_active_ms.max(t);
283                }
284            }
285        }
286        if now.saturating_sub(self.last_flush_ms) >= LINEAGE_FLUSH_MS || self.on_demand {
287            self.flush();
288            self.last_flush_ms = now;
289            self.evict_lineage(now);
290        }
291    }
292
293    /// Loads the journal entries of the processes in the first sample (re-parented children keep their
294    /// agent across oomtop restarts) and seeds the idle tracker with them.
295    fn load_lineage(&mut self, s: &Snapshot) {
296        if self.lineage_loaded {
297            return;
298        }
299        self.lineage_loaded = true;
300        let Some(db) = self.state.as_ref() else { return };
301        let ids: Vec<ProcId> = s.processes.iter().map(|p| p.id).collect();
302        if let Ok(found) = db.lineage_for(&ids) {
303            self.idle.seed(&found);
304            self.lineage.extend(found);
305        }
306    }
307
308    /// Drops entries not seen for [`LINEAGE_EVICT_MS`] (only after a flush, so nothing is lost).
309    fn evict_lineage(&mut self, now: u64) {
310        self.lineage
311            .retain(|_, e| now.saturating_sub(e.last_seen_ms) < LINEAGE_EVICT_MS);
312    }
313
314    /// Rule-file lint (`doctor`): e.g. `match.env` keys outside the marker allowlist, which can never match.
315    pub fn rule_warnings(&self, allowlist: &[String]) -> Vec<String> {
316        self.detector
317            .lint(allowlist)
318            .iter()
319            .map(|w| w.to_string())
320            .collect()
321    }
322
323    /// In-memory lineage entries (tests, `doctor`).
324    pub fn lineage_len(&self) -> usize {
325        self.lineage.len()
326    }
327
328    /// Persists the lineage journal (entries seen since the last flush) and anything else the state store has
329    /// queued.
330    pub fn flush(&mut self) {
331        let since = self.last_flush_ms;
332        let mut latest = since;
333        if self.state_read_only {
334            return;
335        }
336        if let Some(db) = self.state.as_mut() {
337            let entries: Vec<LineageEntry> = self
338                .lineage
339                .values()
340                .filter(|e| e.last_seen_ms >= since)
341                .cloned()
342                .collect();
343            latest = entries.iter().map(|e| e.last_seen_ms).max().unwrap_or(since);
344            if !entries.is_empty() {
345                let _ = db.record_lineage(&entries);
346            }
347            let _ = db.flush();
348        }
349        // Next flush: entries seen since the newest one written now (that sample may be re-sent once).
350        self.last_flush_ms = self.last_flush_ms.max(latest);
351    }
352
353    /// `--no-learn`: the machine profile is not refreshed and the state store records no learning signals.
354    /// The lineage journal is attribution, not learning, and is always kept.
355    pub fn set_learning(&mut self, learn: bool) {
356        self.learn = learn;
357        if let Some(db) = self.state.as_mut() {
358            db.set_learning(learn);
359        }
360    }
361
362    /// Read the state store but never write it (`reclaim --dry-run`). Not reversible for this engine.
363    pub fn set_state_read_only(&mut self) {
364        self.state_read_only = true;
365    }
366
367    /// True once a replay has handed out its last frame (further snapshots repeat it); always false live.
368    pub fn replay_done(&self) -> bool {
369        match &self.input {
370            Input::Live(_) => false,
371            Input::Replay { frames, next } => *next >= frames.len(),
372        }
373    }
374
375    /// True for a live engine (actions may be executed); false when replaying a fixture.
376    pub fn is_live(&self) -> bool {
377        matches!(self.input, Input::Live(_))
378    }
379
380    /// Refreshes the machine profile (UX §6) when it is missing or older than a day. Checked once per engine.
381    fn refresh_profile(&mut self, s: &Snapshot) {
382        if self.profile_checked || !self.learn || self.state_read_only || s.processes.is_empty() {
383            return;
384        }
385        self.profile_checked = true;
386        let Some(db) = self.state.as_mut() else { return };
387        let now = s.taken_at_ms;
388        if !db.machine_profile_stale(now).unwrap_or(false) {
389            return;
390        }
391        let prev: Option<crate::profile::MachineProfile> = db
392            .machine_profile()
393            .ok()
394            .flatten()
395            .and_then(|(j, _)| serde_json::from_value(j).ok());
396        let files = crate::profile::count_model_files(&self.model_folders);
397        let p = crate::profile::build(s, files, prev.as_ref(), now);
398        if let Ok(j) = serde_json::to_value(&p) {
399            let _ = db.set_machine_profile(&j, now);
400        }
401    }
402
403    /// Carries the previous probe's pid mapping into `s` (only pids still alive with the same identity).
404    fn seed_adapter_truth(&self, s: &mut Snapshot) {
405        let alive: std::collections::HashSet<ProcId> = s.processes.iter().map(|p| p.id).collect();
406        s.model_servers = self
407            .adapter_truth
408            .0
409            .iter()
410            .filter(|m| m.pids.iter().any(|p| alive.contains(p)))
411            .cloned()
412            .collect();
413        s.sandboxes = self
414            .adapter_truth
415            .1
416            .iter()
417            .filter(|b| b.host_pids.iter().any(|p| alive.contains(p)))
418            .cloned()
419            .collect();
420    }
421
422    /// True when a probed model server or (non app-owned) sandbox pid sits in a group of another kind, i.e.
423    /// attribution ran without that adapter truth and should run again.
424    fn adapter_truth_missed(s: &Snapshot) -> bool {
425        let kind_of = |id: ProcId| s.group_of(id).map(|g| g.kind);
426        let servers = s
427            .model_servers
428            .iter()
429            .flat_map(|m| m.pids.iter())
430            .any(|p| kind_of(*p).is_some_and(|k| k != GroupKind::ModelServer));
431        let sandboxes = s
432            .sandboxes
433            .iter()
434            .filter(|b| {
435                !(b.kind == SandboxKind::Vm && b.runtime.to_ascii_lowercase().contains("virtualization"))
436            })
437            .flat_map(|b| b.host_pids.iter())
438            .any(|p| kind_of(*p).is_some_and(|k| k != GroupKind::Sandbox));
439        servers || sandboxes
440    }
441
442    /// What the lineage journal (in memory, then on disk) remembers about the agent sessions that left the
443    /// snapshot's cohorts: the session's label and when any of its processes that are now gone was last
444    /// seen. Looked up once per session per [`ENDED_SESSION_TTL_MS`].
445    fn ended_sessions(&mut self, s: &Snapshot) -> BTreeMap<String, oomtop_core::staleness::EndedSession> {
446        let live: std::collections::HashMap<&str, GroupKind> =
447            s.groups.iter().map(|g| (g.id.as_str(), g.kind)).collect();
448        let keys: std::collections::BTreeSet<String> = s
449            .groups
450            .iter()
451            .filter_map(|g| oomtop_core::staleness::cohort_key(g, &live).map(str::to_string))
452            .collect();
453        let alive: std::collections::HashSet<ProcId> = s.processes.iter().map(|p| p.id).collect();
454        let now = s.taken_at_ms;
455        let mut out = BTreeMap::new();
456        for key in keys {
457            let fresh = self
458                .ended_sessions
459                .get(&key)
460                .filter(|(t, _)| now.saturating_sub(*t) < ENDED_SESSION_TTL_MS);
461            let found = match fresh {
462                Some((_, e)) => e.clone(),
463                None => {
464                    let alias = key
465                        .strip_prefix("agent:")
466                        .filter(|h| h.len() == 12 && h.bytes().all(|b| b.is_ascii_hexdigit()));
467                    let mut entries: Vec<LineageEntry> = self
468                        .lineage
469                        .values()
470                        .filter(|e| {
471                            e.group_id == key
472                                || alias.is_some_and(|a| {
473                                    e.session_id.as_deref().is_some_and(|sid| sid.starts_with(a))
474                                })
475                        })
476                        .cloned()
477                        .collect();
478                    if let Some(db) = self.state.as_ref() {
479                        entries.extend(db.session_entries(&key, 2_000).unwrap_or_default());
480                    }
481                    let gone: Vec<&LineageEntry> =
482                        entries.iter().filter(|e| !alive.contains(&e.id)).collect();
483                    let last_seen = gone.iter().map(|e| e.last_seen_ms).max();
484                    let label = gone
485                        .iter()
486                        .filter(|e| e.group_kind == GroupKind::AgentSession && !e.group_label.is_empty())
487                        .max_by_key(|e| e.last_seen_ms)
488                        .map(|e| e.group_label.clone())
489                        .unwrap_or_default();
490                    let e = (last_seen.is_some() || !label.is_empty()).then_some(
491                        oomtop_core::staleness::EndedSession {
492                            label,
493                            last_seen_ms: last_seen,
494                        },
495                    );
496                    self.ended_sessions.insert(key.clone(), (now, e.clone()));
497                    e
498                }
499            };
500            if let Some(e) = found {
501                out.insert(key, e);
502            }
503        }
504        if self.ended_sessions.len() > 256 {
505            self.ended_sessions
506                .retain(|_, (t, _)| now.saturating_sub(*t) < ENDED_SESSION_TTL_MS);
507        }
508        out
509    }
510
511    /// Full enrichment pipeline on one raw snapshot.
512    pub fn enrich(&mut self, mut s: Snapshot) -> Snapshot {
513        if let Some(uid) = self.own_uid_only {
514            s.processes.retain(|p| p.uid.is_none_or(|u| u == uid));
515        }
516        self.load_lineage(&s);
517        self.update_protect(&s);
518        if self.adapters_enabled {
519            self.seed_adapter_truth(&mut s);
520        }
521        s.groups = self.detector.attribute(&s, &self.lineage, &self.protect);
522        self.idle.observe(&s, &self.idle_cfg);
523        self.idle.apply(&mut s, &self.lineage, &self.idle_cfg);
524        if self.adapters_enabled {
525            let p = probe(&s, &self.probe_opts);
526            oomtop_adapters::apply(&mut s, p.clone());
527            // First sample (or a server that just appeared): re-attribute with the adapter truth so the
528            // server's processes form their own group now, not one refresh later.
529            if Self::adapter_truth_missed(&s) {
530                s.groups = self.detector.attribute(&s, &self.lineage, &self.protect);
531                self.idle.apply(&mut s, &self.lineage, &self.idle_cfg);
532                oomtop_adapters::apply(&mut s, p);
533                let group_of = |s: &Snapshot, id: ProcId| s.group_of(id).map(|g| g.id.clone());
534                let fixed: Vec<Option<String>> = s
535                    .model_servers
536                    .iter()
537                    .map(|m| m.pids.iter().find_map(|p| group_of(&s, *p)))
538                    .collect();
539                for (m, gid) in s.model_servers.iter_mut().zip(fixed) {
540                    if gid.is_some() {
541                        m.group_id = gid;
542                    }
543                }
544            }
545            self.adapter_truth = (s.model_servers.clone(), s.sandboxes.clone());
546        }
547        // Ports and links need the groups and the model servers (SPEC §5 "Network").
548        oomtop_core::net::analyze(&mut s);
549        if !s.thermal.clusters.is_empty() {
550            s.thermal.throttle_factor = throttle_factor(&s.thermal.clusters);
551        }
552        // Time and staleness (SPEC §5, §7): ages, duty cycles, idle rent, evidence, cohorts, duplicates.
553        let ended = self.ended_sessions(&s);
554        oomtop_core::staleness::apply(&mut s, &self.stale_cfg, &ended);
555        self.history.push_snapshot(&s);
556        s.oom.forecast = forecast_oom_with(&self.history, &s.oom, s.memory.total.value);
557        // One definition (core): never pid 1 or an unscored process on Linux; the largest non-system,
558        // non-protected group on macOS.
559        s.oom.likely_victim = oomtop_core::forecast::likely_victim(&s);
560        // Containers, clusters, per-limit forecasts, VM slack, namespace sets (SPEC §8.3, §11).
561        self.isolation.update(&mut s);
562        self.record_lineage(&s);
563        self.refresh_profile(&s);
564        s
565    }
566
567    /// Group id containing oomtop itself (for MCP: the calling agent's session).
568    pub fn self_group(s: &Snapshot) -> Option<String> {
569        let pid = s.self_pid?;
570        let p = s.process_by_pid(pid)?;
571        s.group_of(p.id).map(|g| g.id.clone())
572    }
573
574    pub fn state_mut(&mut self) -> Option<&mut StateDb> {
575        self.state.as_mut()
576    }
577}
578
579impl Drop for Engine {
580    fn drop(&mut self) {
581        self.flush();
582    }
583}
584
585impl SnapshotProvider for Engine {
586    fn snapshot(&mut self) -> Snapshot {
587        let raw = self.raw_snapshot();
588        self.enrich(raw)
589    }
590    fn snapshot_now(&mut self) -> Snapshot {
591        let raw = self.raw_snapshot_with(true);
592        self.enrich(raw)
593    }
594    fn history(&self) -> &History {
595        &self.history
596    }
597    fn headroom_config(&self) -> HeadroomConfig {
598        self.headroom_cfg.clone()
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605    use oomtop_core::{OsKind, Process};
606
607    fn proc(pid: u32, ppid: u32, name: &str) -> Process {
608        Process {
609            id: ProcId::new(pid, 1_000 + pid as u64),
610            ppid: Some(ppid),
611            name: name.into(),
612            exe: format!("/usr/bin/{name}"),
613            cmdline: vec![name.into()],
614            uid: Some(501),
615            ..Default::default()
616        }
617    }
618
619    fn snap(at_ms: u64, procs: Vec<Process>) -> Snapshot {
620        let mut s = Snapshot {
621            taken_at_ms: at_ms,
622            processes: procs,
623            self_pid: Some(10),
624            ..Default::default()
625        };
626        s.host.os = OsKind::Macos;
627        s
628    }
629
630    fn replay_engine(frames: Vec<Snapshot>, db: StateDb) -> Engine {
631        let mut cfg = Config::default();
632        cfg.adapters.enabled = false;
633        Engine::with_input(
634            &cfg,
635            Some(db),
636            false,
637            true,
638            None,
639            Input::Replay { frames, next: 0 },
640        )
641    }
642
643    #[test]
644    fn lineage_is_bounded_persisted_and_reloaded_lazily() {
645        let dir = tempfile::tempdir().unwrap();
646        let path = dir.path().join("state.db");
647        let base = vec![proc(10, 1, "oomtop"), proc(20, 1, "zsh")];
648        // A build spawns 500 short-lived compilers, then they're gone for good.
649        let mut burst = base.clone();
650        burst.extend((0..500).map(|i| proc(1_000 + i, 20, "rustc")));
651        let t0 = oomtop_collect::now_ms(); // the journal prunes by wall-clock retention
652        let frames = vec![
653            snap(t0, burst),
654            snap(t0 + 31_000, base.clone()),
655            snap(t0 + 31_000 + LINEAGE_EVICT_MS + 31_000, base.clone()),
656        ];
657        let mut e = replay_engine(frames, StateDb::open(&path).unwrap());
658        e.snapshot();
659        assert_eq!(e.lineage_len(), 502);
660        e.snapshot();
661        assert_eq!(e.lineage_len(), 502, "recently seen entries are kept");
662        e.snapshot();
663        assert_eq!(
664            e.lineage_len(),
665            2,
666            "dead processes are evicted after they were persisted"
667        );
668        drop(e);
669        let db = StateDb::open(&path).unwrap();
670        assert_eq!(
671            db.lineage_all().unwrap().len(),
672            502,
673            "evicted entries stay in the journal"
674        );
675        // A new engine reads only the entries of the processes it sees, not the whole journal.
676        let mut e2 = replay_engine(vec![snap(t0 + 3_600_000, base)], db);
677        e2.snapshot();
678        assert_eq!(e2.lineage_len(), 2);
679        let zsh = e2.lineage.get(&ProcId::new(20, 1_020)).unwrap();
680        assert_eq!(zsh.first_seen_ms, t0, "first_seen survives the restart");
681    }
682
683    /// SPEC §14 "CPU % within 1 s": the TUI's forced second sample 500 ms after the first has host and
684    /// per-process CPU, although neither source is due yet on its cadence.
685    #[cfg(any(target_os = "macos", target_os = "linux"))]
686    #[test]
687    fn forced_second_sample_has_cpu_within_a_second() {
688        let started = std::time::Instant::now();
689        let mut cfg = Config::default();
690        cfg.adapters.enabled = false;
691        let mut e = Engine::live(&cfg, None, false, true);
692        let first = e.snapshot();
693        assert!(first.cpu.total_pct.value.is_none());
694        std::thread::sleep(Duration::from_millis(500));
695        let mut s = e.snapshot_now();
696        // Under a loaded parallel debug test run a source can blow its 50 ms budget (no baseline then); the
697        // next forced sample has one. Seen once in ~20 full-suite runs at load average 3 with one retry.
698        for _ in 0..3 {
699            if s.cpu.total_pct.value.is_some() {
700                break;
701            }
702            std::thread::sleep(Duration::from_millis(200));
703            s = e.snapshot_now();
704        }
705        assert!(started.elapsed() < Duration::from_millis(1500) || cfg!(debug_assertions));
706        assert!(
707            s.cpu.total_pct.value.is_some(),
708            "host CPU after the forced sample: {:?} · {:?}",
709            s.cpu.total_pct,
710            s.source_status
711        );
712        let with_cpu = s.processes.iter().filter(|p| p.cpu_pct.value.is_some()).count();
713        assert!(with_cpu > 0, "per-process CPU after the forced sample");
714        // A plain cadence-gated sample at that point would not have re-read the process listing.
715        let again = e.snapshot();
716        assert_eq!(again.processes.len(), s.processes.len());
717    }
718
719    #[cfg(any(target_os = "macos", target_os = "linux"))]
720    #[test]
721    fn live_pipeline_on_this_machine() {
722        let db = StateDb::open_in_memory().unwrap();
723        let mut e = Engine::live(&Config::default(), Some(db), true, true);
724        let s = e.snapshot();
725        assert!(!s.processes.is_empty());
726        assert!(!s.groups.is_empty());
727        let me = s.self_pid.unwrap();
728        let grouped: usize = s.groups.iter().map(|g| g.members.len()).sum();
729        assert_eq!(
730            grouped,
731            s.processes.len(),
732            "every process attributed exactly once"
733        );
734        assert!(s.groups.iter().all(|g| !g.id.is_empty()));
735        assert!(s.process_by_pid(me).is_some());
736        assert!(e.protect.self_uid.is_some());
737        e.flush();
738        assert!(!e.state_mut().unwrap().lineage_all().unwrap().is_empty());
739    }
740
741    /// `reclaim --dry-run`: the journal is read (same attribution as a real run) and never written.
742    #[test]
743    fn read_only_state_is_loaded_but_never_written() {
744        let dir = tempfile::tempdir().unwrap();
745        let path = dir.path().join("state.db");
746        let t0 = oomtop_collect::now_ms();
747        let base = vec![proc(10, 1, "oomtop"), proc(20, 1, "zsh")];
748        let mut e = replay_engine(vec![snap(t0, base.clone())], StateDb::open(&path).unwrap());
749        e.snapshot();
750        drop(e);
751        let written = StateDb::open(&path).unwrap().lineage_all().unwrap();
752        assert_eq!(written.len(), 2);
753
754        let mut more = base.clone();
755        more.push(proc(30, 20, "java"));
756        let mut e = replay_engine(vec![snap(t0 + 60_000, more)], StateDb::open(&path).unwrap());
757        e.set_state_read_only();
758        e.snapshot();
759        assert_eq!(
760            e.lineage_len(),
761            3,
762            "the journal was loaded and the new process is tracked in memory"
763        );
764        let zsh = e.lineage.get(&ProcId::new(20, 1_020)).unwrap();
765        assert_eq!(zsh.first_seen_ms, t0, "read from the store");
766        e.flush();
767        drop(e);
768        let after = StateDb::open(&path).unwrap().lineage_all().unwrap();
769        assert_eq!(after, written, "nothing recorded, nothing updated");
770    }
771
772    #[test]
773    fn replay_reports_its_last_frame() {
774        let base = vec![proc(10, 1, "oomtop")];
775        let mut e = replay_engine(
776            vec![snap(1_000, base.clone()), snap(3_000, base)],
777            StateDb::open_in_memory().unwrap(),
778        );
779        assert!(!e.replay_done());
780        e.snapshot();
781        assert!(!e.replay_done());
782        e.snapshot();
783        assert!(e.replay_done());
784        assert_eq!(
785            e.snapshot().taken_at_ms,
786            3_000,
787            "further snapshots repeat the last frame"
788        );
789    }
790
791    /// The engine uses core's victim rule: on Linux never pid 1 and never a process the kernel would not
792    /// pick (`oom_score` 0), which the engine's own copy used to return.
793    #[test]
794    fn likely_victim_is_the_core_rule() {
795        let mut init = proc(1, 0, "systemd");
796        init.oom_score = Some(900);
797        let mut unscored = proc(40, 1, "sshd");
798        unscored.oom_score = Some(0);
799        let mut s = snap(1_000, vec![init.clone(), unscored.clone()]);
800        s.host.os = OsKind::Linux;
801        let mut e = replay_engine(vec![s.clone()], StateDb::open_in_memory().unwrap());
802        assert_eq!(e.snapshot().oom.likely_victim, None);
803
804        let mut hog = proc(50, 1, "python");
805        hog.oom_score = Some(700);
806        s.processes.push(hog);
807        let mut e = replay_engine(vec![s], StateDb::open_in_memory().unwrap());
808        let out = e.snapshot();
809        let v = out.oom.likely_victim.clone().expect("a scored process");
810        assert_eq!((v.id.pid, v.heuristic), (50, false));
811        assert_eq!(out.oom.likely_victim, oomtop_core::forecast::likely_victim(&out));
812    }
813}