1use 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
24const LINEAGE_FLUSH_MS: u64 = 30_000;
26pub const LINEAGE_EVICT_MS: u64 = 5 * 60_000;
30pub const ENDED_SESSION_TTL_MS: u64 = 60_000;
32pub const ON_DEMAND_BASELINE_MS: u64 = 30_000;
34pub 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 stale_cfg: oomtop_core::staleness::StalenessConfig,
51 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 own_uid_only: Option<u32>,
59 protected_names: Vec<String>,
60 on_demand: bool,
63 last_on_demand_ms: Option<u64>,
64 last_flush_ms: u64,
65 learn: bool,
67 model_folders: Vec<PathBuf>,
68 profile_checked: bool,
69 lineage_loaded: bool,
71 adapter_truth: (Vec<ModelServer>, Vec<Sandbox>),
74 state_read_only: bool,
77 pub protect: ProtectContext,
78 pub rule_errors: Vec<String>,
79 isolation: oomtop_core::cluster::IsolationTracker,
81}
82
83impl Engine {
84 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 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 pub fn replay(cfg: &Config, path: &Path) -> Result<Self, String> {
118 Self::replay_in(cfg, path, None)
119 }
120
121 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 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 fn raw_snapshot_with(&mut self, force: bool) -> Snapshot {
198 match &mut self.input {
199 Input::Live(s) => {
200 if self.on_demand {
201 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 if e.ppid.map(|pp| pp <= 1).unwrap_or(true) {
259 e.ppid = p.and_then(|p| p.ppid);
260 }
261 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 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 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 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 pub fn lineage_len(&self) -> usize {
325 self.lineage.len()
326 }
327
328 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 self.last_flush_ms = self.last_flush_ms.max(latest);
351 }
352
353 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 pub fn set_state_read_only(&mut self) {
364 self.state_read_only = true;
365 }
366
367 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 pub fn is_live(&self) -> bool {
377 matches!(self.input, Input::Live(_))
378 }
379
380 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 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 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 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 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 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 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 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 s.oom.likely_victim = oomtop_core::forecast::likely_victim(&s);
560 self.isolation.update(&mut s);
562 self.record_lineage(&s);
563 self.refresh_profile(&s);
564 s
565 }
566
567 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 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(); 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 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 #[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 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 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 #[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 #[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}