Skip to main content

oomtop_core/
why.rs

1//! `oomtop why` / MCP `explain_slowdown` (SPEC §9): ranked likely causes of slowness / memory trouble, each
2//! with evidence lines ("swap in +600M/min for 5m", "GPU at 42% of max clock with thermal pressure heavy",
3//! "Low Power Mode on", "on battery at 29%") and, where there is one, a concrete fix.
4//!
5//! Throttle-related causes (thermal, Low Power Mode, battery, GPU clocks) are reported **only under load**:
6//! Apple Silicon down-clocks at idle and Low Power Mode costs nothing while nothing runs (acceptance #5).
7
8use crate::headroom::is_reclaim_candidate;
9use crate::history::History;
10use crate::model::{ForecastTarget, GroupKind, OomKiller, PressureLevel, Snapshot, ThermalPressure};
11use crate::throttle::{is_busy, speed_label, unit_factor, BUSY_PCT, THROTTLED_BELOW};
12use crate::units::{format_bytes_short, format_duration};
13use serde::{Deserialize, Serialize};
14
15/// Swap traffic (in + out per minute) above which swapping is reported as a cause.
16pub const SWAP_STORM_BYTES_PER_MIN: u64 = 100 * 1024 * 1024;
17/// Linux PSI memory `some avg10` above which memory pressure is reported (UX §3).
18pub const PSI_SOME_PCT: f64 = 20.0;
19/// Battery charge below which being on battery is reported under load.
20pub const LOW_BATTERY_PCT: f64 = 30.0;
21/// Whole-machine CPU utilization above which the CPU is reported as saturated.
22pub const CPU_SATURATED_PCT: f64 = 90.0;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
25#[serde(rename_all = "snake_case")]
26pub enum CauseKind {
27    OomImminent,
28    SwapStorm,
29    MemoryPressure,
30    ThermalThrottle,
31    LowPowerMode,
32    LowBattery,
33    GpuThrottle,
34    CpuSaturated,
35}
36
37impl CauseKind {
38    /// True for causes that are only meaningful under load (never reported on an idle machine).
39    pub fn is_throttle_related(self) -> bool {
40        matches!(
41            self,
42            CauseKind::ThermalThrottle
43                | CauseKind::LowPowerMode
44                | CauseKind::LowBattery
45                | CauseKind::GpuThrottle
46        )
47    }
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct Cause {
52    pub kind: CauseKind,
53    /// 0..1, higher = more likely / more severe. Causes are sorted by this, descending.
54    pub score: f64,
55    pub title: String,
56    pub evidence: Vec<String>,
57    /// Suggested fix, e.g. "stop 2 idle build daemons (≈5.9G)".
58    pub fix: Option<String>,
59}
60
61fn thermal_label(p: ThermalPressure) -> &'static str {
62    match p {
63        ThermalPressure::Nominal => "nominal",
64        ThermalPressure::Moderate => "moderate",
65        ThermalPressure::Heavy => "heavy",
66        ThermalPressure::Trapping => "trapping",
67        ThermalPressure::Sleeping => "sleeping",
68    }
69}
70
71fn killer_label(k: OomKiller) -> &'static str {
72    match k {
73        OomKiller::Kernel => "the kernel OOM killer",
74        OomKiller::SystemdOomd => "systemd-oomd",
75        OomKiller::Earlyoom => "earlyoom",
76        OomKiller::Jetsam => "jetsam",
77    }
78}
79
80fn plural(n: usize, one: &str, many: &str) -> String {
81    if n == 1 {
82        format!("1 {one}")
83    } else {
84        format!("{n} {many}")
85    }
86}
87
88/// True if anything is working hard enough for clocks/power to matter: a busy CPU cluster or GPU unit, an
89/// available throttle factor, a busy accelerator, or ≥ 50 % whole-machine CPU.
90pub fn under_load(s: &Snapshot) -> bool {
91    s.thermal.throttle_factor.value.is_some()
92        || s.thermal.clusters.iter().any(is_busy)
93        || s.accelerators
94            .iter()
95            .any(|a| a.util_pct.value.map(|u| u >= BUSY_PCT).unwrap_or(false))
96        || s.cpu.total_pct.value.map(|c| c >= BUSY_PCT).unwrap_or(false)
97}
98
99/// "stop 2 idle build daemons + 1 orphan (≈5.9G)" from the snapshot's reclaim candidates.
100pub fn reclaim_fix(s: &Snapshot) -> Option<String> {
101    let cands: Vec<_> = s
102        .groups
103        .iter()
104        .filter(|g| is_reclaim_candidate(g))
105        .filter_map(|g| Some((g, g.reclaim_gain.value.filter(|v| *v > 0)?)))
106        .collect();
107    if cands.is_empty() {
108        return None;
109    }
110    let total: u64 = cands.iter().map(|(_, v)| *v).sum();
111    let orphans = cands.iter().filter(|(g, _)| g.orphan).count();
112    let daemons = cands
113        .iter()
114        .filter(|(g, _)| !g.orphan && g.kind == GroupKind::BuildDaemon)
115        .count();
116    let idle_daemons = cands
117        .iter()
118        .filter(|(g, _)| !g.orphan && g.kind == GroupKind::BuildDaemon && g.idle)
119        .count();
120    let models = cands
121        .iter()
122        .filter(|(g, _)| !g.orphan && g.kind == GroupKind::ModelServer)
123        .count();
124    let mut parts = Vec::new();
125    if daemons > 0 {
126        parts.push(if idle_daemons == daemons {
127            plural(daemons, "idle build daemon", "idle build daemons")
128        } else {
129            plural(daemons, "build daemon", "build daemons")
130        });
131    }
132    if models > 0 {
133        parts.push(plural(models, "idle model server", "idle model servers"));
134    }
135    if orphans > 0 {
136        parts.push(plural(orphans, "orphan", "orphans"));
137    }
138    Some(format!(
139        "stop {} (≈{})",
140        parts.join(" + "),
141        format_bytes_short(total)
142    ))
143}
144
145/// "largest: sd-server 9.9G, Google Chrome 2.1G".
146fn largest_line(s: &Snapshot) -> Option<String> {
147    let mut gs: Vec<_> = s
148        .groups
149        .iter()
150        .filter_map(|g| Some((g, g.totals.footprint.value?)))
151        .filter(|(_, v)| *v > 0)
152        .collect();
153    gs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.id.cmp(&b.0.id)));
154    let top: Vec<String> = gs
155        .iter()
156        .take(3)
157        .map(|(g, v)| {
158            format!(
159                "{} {}{}",
160                g.label,
161                format_bytes_short(*v),
162                if g.lower_bound { "+" } else { "" }
163            )
164        })
165        .collect();
166    (!top.is_empty()).then(|| format!("largest: {}", top.join(", ")))
167}
168
169/// How long swap used has been rising (seconds) and by how much, from the history tail. The run ends at the
170/// newest sample and starts where the growth starts: a flat lead-in before it is **not** part of the run
171/// (10 flat minutes followed by one minute of growth is "1 min", at that minute's rate).
172fn swap_growth_s(history: &History) -> Option<(u64, u64)> {
173    let pts: Vec<(u64, u64)> = history
174        .iter()
175        .filter_map(|p| Some((p.t_ms, p.swap_used?)))
176        .collect();
177    let (&(t_last, v_last), rest) = pts.split_last()?;
178    // Non-decreasing run, newest first (`run[0]` is the newest sample).
179    let mut run = vec![(t_last, v_last)];
180    let mut next_v = v_last;
181    for &(t, v) in rest.iter().rev() {
182        // tolerate small dips (1 %) so sampling noise doesn't cut the run
183        if v > next_v.saturating_add(next_v / 100) {
184            break;
185        }
186        run.push((t, v));
187        next_v = v;
188    }
189    // Trim the flat lead-in: growth starts at the newest sample that is still at the run's floor (within
190    // 1 % of the total growth, for noise).
191    let floor = run.iter().map(|p| p.1).min().unwrap_or(v_last);
192    let noise = v_last.saturating_sub(floor) / 100;
193    let start = run
194        .iter()
195        .find(|p| p.1 <= floor.saturating_add(noise))
196        .copied()
197        .unwrap_or((t_last, v_last));
198    let dur = t_last.saturating_sub(start.0) / 1000;
199    let grown = v_last.saturating_sub(start.1);
200    (dur >= 60 && grown > 0).then_some((dur, grown))
201}
202
203/// True if `evidence` says nothing the title does not already say (case-insensitive, ignoring "is").
204fn title_repeats(title: &str, evidence: &str) -> bool {
205    let norm = |x: &str| {
206        x.to_lowercase()
207            .split_whitespace()
208            .filter(|w| *w != "is")
209            .collect::<Vec<_>>()
210            .join(" ")
211    };
212    let (t, e) = (norm(title), norm(evidence));
213    !e.is_empty() && t.contains(&e)
214}
215
216/// Ranks causes. `history` is used for sustained trends (e.g. swap growth over minutes).
217pub fn explain(s: &Snapshot, history: &History) -> Vec<Cause> {
218    let mut out = Vec::new();
219    let mem = &s.memory;
220    let reclaim = reclaim_fix(s);
221    let loaded = under_load(s);
222
223    // --- OOM forecast --------------------------------------------------------------------------------
224    if let Some(f) = &s.oom.forecast {
225        let eta = format_duration(f.eta_s);
226        let title = match f.target {
227            ForecastTarget::SwapExhaustion => format!("Swap full in ~{eta} at this rate"),
228            ForecastTarget::AvailableExhaustion => format!("Out of memory in ~{eta} at this rate"),
229            ForecastTarget::KillerThreshold => format!(
230                "{} acts in ~{eta} at this rate",
231                f.killer.map(killer_label).unwrap_or("the OOM killer")
232            ),
233        };
234        // A pressure (PSI %) threshold, or a swap-% one without a known swap size, has no byte rate
235        // (`rate_per_min` is 0): say that it is rising, never "0B/min".
236        let has_rate = f.rate_per_min.is_finite() && f.rate_per_min.abs() >= 1.0;
237        let rate = format_bytes_short(f.rate_per_min.abs() as u64);
238        let trend = match f.target {
239            ForecastTarget::SwapExhaustion if has_rate => format!("swap used +{rate}/min"),
240            ForecastTarget::SwapExhaustion => "swap used rising".to_string(),
241            ForecastTarget::AvailableExhaustion if has_rate => format!("available −{rate}/min"),
242            ForecastTarget::AvailableExhaustion => "available falling".to_string(),
243            ForecastTarget::KillerThreshold if has_rate => format!("{rate}/min toward the threshold"),
244            ForecastTarget::KillerThreshold => "rising steadily toward the threshold".to_string(),
245        };
246        let mut evidence = vec![format!(
247            "{trend} over {} (R² {:.2})",
248            format_duration(f.window_s),
249            f.confidence
250        )];
251        if let Some(v) = &s.oom.likely_victim {
252            evidence.push(format!("likely victim: {} ({})", v.name, v.reason));
253        }
254        out.push(Cause {
255            kind: CauseKind::OomImminent,
256            score: 1.0,
257            title,
258            evidence,
259            fix: reclaim.clone(),
260        });
261    }
262
263    // --- swap storm ------------------------------------------------------------------------------------
264    let swap_in = mem.swap_in_per_min.value.unwrap_or(0);
265    let swap_out = mem.swap_out_per_min.value.unwrap_or(0);
266    let traffic = swap_in.saturating_add(swap_out);
267    let rates_known = mem.swap_in_per_min.value.is_some() || mem.swap_out_per_min.value.is_some();
268    let growth = swap_growth_s(history);
269    // Without swap-in/out rates, sustained growth of swap used at storm pace is the evidence.
270    let growth_rate = growth
271        .map(|(d, grown)| grown.saturating_mul(60) / d.max(1))
272        .unwrap_or(0);
273    if !rates_known && growth_rate >= SWAP_STORM_BYTES_PER_MIN {
274        let (d, grown) = growth.unwrap_or_default();
275        let mut ev = vec![format!(
276            "swap used +{} in {} (≈{}/min; swap in/out rates unavailable)",
277            format_bytes_short(grown),
278            format_duration(d),
279            format_bytes_short(growth_rate)
280        )];
281        if let (Some(u), Some(t)) = (mem.swap_used.value, mem.swap_total.value) {
282            ev.push(format!(
283                "swap {} / {}",
284                format_bytes_short(u),
285                format_bytes_short(t)
286            ));
287        }
288        ev.extend(largest_line(s));
289        let gib = growth_rate as f64 / (1024.0 * 1024.0 * 1024.0);
290        out.push(Cause {
291            kind: CauseKind::SwapStorm,
292            score: (0.45 + gib * 0.4 + (d as f64 / 600.0).min(0.1)).clamp(0.45, 0.95),
293            title: "Swapping heavily".into(),
294            evidence: ev,
295            fix: reclaim.clone(),
296        });
297    }
298    if traffic >= SWAP_STORM_BYTES_PER_MIN {
299        let dur = growth
300            .map(|(d, _)| format!(" for {}", format_duration(d)))
301            .unwrap_or_default();
302        let mut ev = vec![format!(
303            "swap in +{}/min, out +{}/min{dur}",
304            format_bytes_short(swap_in),
305            format_bytes_short(swap_out)
306        )];
307        if let Some((d, grown)) = growth {
308            ev.push(format!(
309                "swap used +{} in {}",
310                format_bytes_short(grown),
311                format_duration(d)
312            ));
313        }
314        if let (Some(u), Some(t)) = (mem.swap_used.value, mem.swap_total.value) {
315            ev.push(format!(
316                "swap {} / {}",
317                format_bytes_short(u),
318                format_bytes_short(t)
319            ));
320        }
321        ev.extend(largest_line(s));
322        let gib = traffic as f64 / (1024.0 * 1024.0 * 1024.0);
323        let sustained = growth.map(|(d, _)| (d as f64 / 600.0).min(0.1)).unwrap_or(0.0);
324        out.push(Cause {
325            kind: CauseKind::SwapStorm,
326            score: (0.45 + gib * 0.4 + sustained).clamp(0.45, 0.95),
327            title: "Swapping heavily".into(),
328            evidence: ev,
329            fix: reclaim.clone(),
330        });
331    }
332
333    // --- memory pressure -------------------------------------------------------------------------------
334    let pressure = mem.pressure.value.unwrap_or_default();
335    let psi = mem.psi.value.map(|p| p.some_avg10).unwrap_or(0.0);
336    let psi_full = mem.psi.value.map(|p| p.full_avg10).unwrap_or(0.0);
337    if pressure >= PressureLevel::Warn || psi > PSI_SOME_PCT {
338        let mut ev = Vec::new();
339        if pressure >= PressureLevel::Warn {
340            ev.push(format!(
341                "memory pressure {}",
342                if pressure == PressureLevel::Critical {
343                    "critical"
344                } else {
345                    "warn"
346                }
347            ));
348        }
349        if let Some(level) = mem.memorystatus_level.value {
350            ev.push(format!("memorystatus level {level}% available"));
351        }
352        if mem.psi.value.is_some() && psi > 0.0 {
353            ev.push(format!("memory PSI some {psi:.0}%, full {psi_full:.0}% (10 s)"));
354        }
355        if let Some(a) = mem.available.value {
356            ev.push(format!("available {}", format_bytes_short(a)));
357        }
358        if let (Some(u), Some(t)) = (mem.swap_used.value, mem.swap_total.value) {
359            ev.push(format!(
360                "swap {} / {}",
361                format_bytes_short(u),
362                format_bytes_short(t)
363            ));
364        }
365        ev.extend(largest_line(s));
366        out.push(Cause {
367            kind: CauseKind::MemoryPressure,
368            score: if pressure == PressureLevel::Critical {
369                0.9
370            } else {
371                (0.6 + (psi / 250.0).min(0.25) + (psi_full / 500.0).min(0.05)).min(0.9)
372            },
373            title: if pressure == PressureLevel::Critical {
374                "Critical memory pressure".into()
375            } else {
376                "Memory pressure".into()
377            },
378            evidence: ev,
379            fix: reclaim.clone(),
380        });
381    }
382
383    // --- throttling (only under load) ------------------------------------------------------------------
384    let t = &s.thermal;
385    let on_battery = t.on_battery.value == Some(true);
386    let battery = t.battery_pct.value;
387    if loaded {
388        let factor = t.throttle_factor.value;
389        let tp = t.pressure.value;
390        let trip = t.trip_point_hit.value == Some(true);
391        let hot = tp.map(|p| p >= ThermalPressure::Heavy).unwrap_or(false) || trip;
392        let slow = factor.map(|f| f < THROTTLED_BELOW).unwrap_or(false);
393        let lpm = t.low_power_mode.value == Some(true);
394        // Any thermal evidence: a fanless Mac already clocks down at *moderate* pressure.
395        let warm = tp.map(|p| p >= ThermalPressure::Moderate).unwrap_or(false) || trip;
396        // Slow clocks with Low Power Mode on and no thermal evidence are Low Power Mode, not heat.
397        if hot || (slow && (warm || !lpm)) {
398            let mut ev = Vec::new();
399            if let Some(f) = factor {
400                ev.push(speed_label(f));
401            }
402            let with_pressure = tp
403                .filter(|p| *p >= ThermalPressure::Moderate)
404                .map(|p| format!(" with thermal pressure {}", thermal_label(p)))
405                .unwrap_or_default();
406            for u in &t.clusters {
407                if let Some(uf) = unit_factor(u).filter(|f| *f < THROTTLED_BELOW) {
408                    ev.push(format!(
409                        "{} at {:.0}% of max clock ({:.0}% busy){with_pressure}",
410                        u.name,
411                        uf * 100.0,
412                        u.active_pct
413                    ));
414                }
415            }
416            if let Some(p) = tp {
417                ev.push(format!("thermal pressure {}", thermal_label(p)));
418            }
419            if trip {
420                ev.push("thermal trip point hit".into());
421            }
422            if let Some(hottest) = t
423                .temps
424                .iter()
425                .filter(|x| x.celsius.is_finite())
426                .max_by(|a, b| a.celsius.total_cmp(&b.celsius))
427            {
428                ev.push(format!(
429                    "hottest sensor {} {:.0}°C",
430                    hottest.name, hottest.celsius
431                ));
432            }
433            if let Some(w) = t.package_power_w.value {
434                ev.push(format!("package power {w:.1} W"));
435            }
436            if on_battery {
437                ev.push(match battery {
438                    Some(b) => format!("on battery at {b:.0}%"),
439                    None => "on battery".into(),
440                });
441            }
442            // "running at 49% speed" outranks a mere pressure warning, but not a swap storm
443            let base = factor
444                .map(|f| (0.35 + (1.0 - f) * 0.6).clamp(0.3, 0.85))
445                .unwrap_or(0.5);
446            let bump = if hot { 0.05 } else { 0.0 };
447            out.push(Cause {
448                kind: CauseKind::ThermalThrottle,
449                score: (base + bump).min(0.9),
450                title: match (factor, warm) {
451                    (Some(f), true) if slow => format!("Thermal throttling — {}", speed_label(f)),
452                    (_, true) => "Thermal throttling".into(),
453                    // clocks are down without any thermal evidence (power limits, governor, unknown)
454                    (Some(f), false) => format!("Clocks reduced — {}", speed_label(f)),
455                    (None, false) => "Clocks reduced".into(),
456                },
457                evidence: ev,
458                fix: Some(match (warm, on_battery) {
459                    (true, true) => "plug in and pause heavy work until it cools".into(),
460                    (true, false) => "improve airflow or pause heavy work until it cools".into(),
461                    (false, true) => "plug in or pause heavy work".into(),
462                    (false, false) => "pause heavy work or check the power profile".into(),
463                }),
464            });
465        }
466
467        if lpm {
468            let mut ev = vec!["Low Power Mode on".to_string()];
469            if let Some(f) = factor {
470                ev.push(speed_label(f));
471            }
472            ev.extend(t.clusters.iter().filter_map(|u| {
473                let uf = unit_factor(u).filter(|f| *f < THROTTLED_BELOW)?;
474                Some(format!(
475                    "{} at {:.0}% of max clock ({:.0}% busy)",
476                    u.name,
477                    uf * 100.0,
478                    u.active_pct
479                ))
480            }));
481            // the main cause when clocks are down without heat
482            let score = match (slow, warm) {
483                (true, false) => factor
484                    .map(|f| (0.4 + (1.0 - f) * 0.6).clamp(0.6, 0.85))
485                    .unwrap_or(0.6),
486                (true, true) => 0.6,
487                _ => 0.5,
488            };
489            out.push(Cause {
490                kind: CauseKind::LowPowerMode,
491                score,
492                title: "Low Power Mode is on".into(),
493                evidence: ev,
494                fix: Some("turn off Low Power Mode (System Settings → Battery)".into()),
495            });
496        }
497
498        if on_battery {
499            if let Some(pct) = battery.filter(|p| *p < LOW_BATTERY_PCT) {
500                let mut ev = vec![format!("on battery at {pct:.0}%")];
501                if let Some(w) = t.adapter_watts.value.filter(|w| *w > 0.0) {
502                    ev.push(format!("adapter {w:.0} W"));
503                }
504                out.push(Cause {
505                    kind: CauseKind::LowBattery,
506                    score: if slow { 0.45 } else { 0.35 },
507                    title: "On battery, low charge".into(),
508                    evidence: ev,
509                    fix: Some("plug in".into()),
510                });
511            }
512        }
513
514        for a in &s.accelerators {
515            let busy = a.util_pct.value.map(|u| u >= BUSY_PCT).unwrap_or(false);
516            if !busy {
517                continue;
518            }
519            if let (Some(c), Some(m)) = (a.clock_mhz.value, a.max_clock_mhz.value) {
520                if m > 0.0 && c / m < THROTTLED_BELOW {
521                    let ratio = (c / m).clamp(0.0, 1.0);
522                    let with_pressure = tp
523                        .filter(|p| *p >= ThermalPressure::Moderate)
524                        .map(|p| format!(" with thermal pressure {}", thermal_label(p)))
525                        .unwrap_or_default();
526                    let mut ev = vec![format!(
527                        "{} at {:.0}% of max clock{with_pressure}",
528                        a.name,
529                        ratio * 100.0
530                    )];
531                    if let Some(temp) = a.temp_c.value {
532                        ev.push(format!("{} at {temp:.0}°C", a.name));
533                    }
534                    if let Some(w) = a.power_w.value {
535                        ev.push(format!("{} drawing {w:.0} W", a.name));
536                    }
537                    ev.extend(a.throttle_reasons.iter().map(|r| format!("throttle reason: {r}")));
538                    out.push(Cause {
539                        kind: CauseKind::GpuThrottle,
540                        score: (1.0 - ratio).clamp(0.3, 0.85),
541                        title: format!("{} is throttled", if a.name.is_empty() { "GPU" } else { &a.name }),
542                        evidence: ev,
543                        fix: None,
544                    });
545                }
546            }
547        }
548    }
549
550    // --- CPU saturation --------------------------------------------------------------------------------
551    if let Some(cpu) = s.cpu.total_pct.value.filter(|c| *c > CPU_SATURATED_PCT) {
552        let mut ev = vec![format!("CPU {cpu:.0}% of all cores")];
553        let mut top: Vec<_> = s
554            .groups
555            .iter()
556            .filter_map(|g| Some((g, g.totals.cpu_pct.value?)))
557            .filter(|(_, c)| *c >= 10.0)
558            .collect();
559        top.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.id.cmp(&b.0.id)));
560        let names: Vec<String> = top
561            .iter()
562            .take(3)
563            .map(|(g, c)| format!("{} {c:.0}%", g.label))
564            .collect();
565        if !names.is_empty() {
566            ev.push(format!("busiest: {}", names.join(", ")));
567        }
568        if let Some(l) = s.cpu.load_avg_1.value {
569            ev.push(format!("load average {l:.1}"));
570        }
571        out.push(Cause {
572            kind: CauseKind::CpuSaturated,
573            score: 0.4,
574            title: "CPU saturated".into(),
575            evidence: ev,
576            fix: None,
577        });
578    }
579
580    for c in &mut out {
581        c.score = (c.score.clamp(0.0, 1.0) * 1000.0).round() / 1000.0;
582        // The title already states it ("Clocks reduced — running at 35% speed", "Low Power Mode is on"):
583        // an evidence bullet that only repeats the headline adds nothing.
584        let title = c.title.clone();
585        c.evidence.retain(|e| !title_repeats(&title, e));
586    }
587    out.sort_by(|a, b| b.score.total_cmp(&a.score).then_with(|| a.kind.cmp(&b.kind)));
588    out
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594    use crate::model::{ClusterFreq, Measured};
595
596    fn swap_history(points: &[(u64, u64)]) -> History {
597        let mut h = History::default();
598        for &(t_s, used) in points {
599            h.push(crate::history::HistoryPoint {
600                t_ms: t_s * 1000,
601                swap_used: Some(used),
602                swap_total: Some(16 << 30),
603                ..Default::default()
604            });
605        }
606        h
607    }
608
609    #[test]
610    fn flat_lead_in_is_not_swap_growth() {
611        const MIB: u64 = 1 << 20;
612        // Flat at 2 GiB for 8 min, then +5 MiB/s (300 MiB/min) for 2 min.
613        let pts: Vec<(u64, u64)> = (0..=120u64)
614            .map(|i| {
615                let t = i * 5;
616                (t, 2048 * MIB + t.saturating_sub(480) * 5 * MIB)
617            })
618            .collect();
619        let h = swap_history(&pts);
620        let (dur, grown) = swap_growth_s(&h).expect("growth");
621        assert_eq!(dur, 120, "the 8 flat minutes are not growth");
622        assert_eq!(grown, 600 * MIB);
623
624        // Without in/out rates the storm is judged at the growth's own pace (300 MiB/min ≥ 100), not at
625        // 600 MiB spread over 10 min (60 MiB/min, which used to hide it).
626        let s = Snapshot::default();
627        let causes = explain(&s, &h);
628        let storm = causes
629            .iter()
630            .find(|c| c.kind == CauseKind::SwapStorm)
631            .expect("swap storm");
632        assert!(storm.evidence[0].contains("in 2m"), "{:?}", storm.evidence);
633
634        // With rates, the duration next to them is the growth's, not the whole history's.
635        let mut s = Snapshot::default();
636        s.memory.swap_in_per_min = Measured::exact(200 * MIB, "t");
637        s.memory.swap_out_per_min = Measured::exact(300 * MIB, "t");
638        let causes = explain(&s, &h);
639        let storm = causes.iter().find(|c| c.kind == CauseKind::SwapStorm).unwrap();
640        assert!(storm.evidence[0].ends_with("for 2m"), "{:?}", storm.evidence);
641
642        // Entirely flat: no growth. Steady growth from the start: the whole run.
643        let flat: Vec<(u64, u64)> = (0..=60u64).map(|i| (i * 5, 2048 * MIB)).collect();
644        assert_eq!(swap_growth_s(&swap_history(&flat)), None);
645        let steady: Vec<(u64, u64)> = (0..=60u64).map(|i| (i * 5, 2048 * MIB + i * MIB)).collect();
646        assert_eq!(swap_growth_s(&swap_history(&steady)), Some((300, 60 * MIB)));
647    }
648
649    #[test]
650    fn forecast_without_a_byte_rate_never_prints_zero_per_minute() {
651        use crate::model::Forecast;
652        let mut s = Snapshot::default();
653        // systemd-oomd memory-pressure threshold: PSI has no byte rate.
654        s.oom.forecast = Some(Forecast {
655            target: ForecastTarget::KillerThreshold,
656            killer: Some(OomKiller::SystemdOomd),
657            eta_s: 400,
658            confidence: 0.93,
659            rate_per_min: 0.0,
660            window_s: 180,
661        });
662        let causes = explain(&s, &History::default());
663        let c = causes.iter().find(|c| c.kind == CauseKind::OomImminent).unwrap();
664        assert_eq!(
665            c.evidence[0],
666            "rising steadily toward the threshold over 3m (R² 0.93)"
667        );
668        assert!(c.evidence.iter().all(|e| !e.contains("0B")), "{:?}", c.evidence);
669        // A byte rate is still shown when there is one.
670        s.oom.forecast.as_mut().unwrap().rate_per_min = 250.0 * 1024.0 * 1024.0;
671        let causes = explain(&s, &History::default());
672        assert_eq!(
673            causes[0].evidence[0],
674            "250M/min toward the threshold over 3m (R² 0.93)"
675        );
676    }
677
678    #[test]
679    fn idle_machine_reports_nothing_throttle_related() {
680        let mut s = Snapshot::default();
681        s.thermal.clusters = vec![ClusterFreq {
682            name: "p".into(),
683            cur_mhz: 600.0,
684            max_mhz: 4000.0,
685            active_pct: 2.0,
686        }];
687        s.thermal.throttle_factor = crate::throttle::throttle_factor(&s.thermal.clusters);
688        s.thermal.low_power_mode = Measured::exact(true, "t");
689        s.thermal.pressure = Measured::exact(ThermalPressure::Heavy, "t");
690        s.thermal.on_battery = Measured::exact(true, "t");
691        s.thermal.battery_pct = Measured::exact(12.0, "t");
692        assert!(explain(&s, &History::default()).is_empty());
693    }
694
695    #[test]
696    fn low_power_mode_is_not_called_heat() {
697        let mut s = Snapshot::default();
698        s.thermal.clusters = vec![ClusterFreq {
699            name: "P-cluster".into(),
700            cur_mhz: 1800.0,
701            max_mhz: 4000.0,
702            active_pct: 90.0,
703        }];
704        s.thermal.throttle_factor = crate::throttle::throttle_factor(&s.thermal.clusters);
705        s.thermal.low_power_mode = Measured::exact(true, "t");
706        s.thermal.pressure = Measured::exact(ThermalPressure::Nominal, "t");
707        let c = explain(&s, &History::default());
708        assert_eq!(c[0].kind, CauseKind::LowPowerMode, "{c:#?}");
709        assert!(c[0].evidence.iter().any(|e| e.starts_with("running at 45%")));
710        assert!(c.iter().all(|c| c.kind != CauseKind::ThermalThrottle));
711        // with heat as well, both are reported and heat is called heat
712        s.thermal.pressure = Measured::exact(ThermalPressure::Heavy, "t");
713        let c = explain(&s, &History::default());
714        let th = c.iter().find(|c| c.kind == CauseKind::ThermalThrottle).unwrap();
715        assert!(th.title.starts_with("Thermal throttling"));
716        assert!(c.iter().any(|c| c.kind == CauseKind::LowPowerMode));
717        // a fanless Mac at *moderate* pressure with slow clocks is thermal throttling
718        s.thermal.low_power_mode = Measured::exact(false, "t");
719        s.thermal.pressure = Measured::exact(ThermalPressure::Moderate, "t");
720        let c = explain(&s, &History::default());
721        assert_eq!(c[0].title, "Thermal throttling — running at 45% speed");
722        // slow clocks without heat or LPM: "clocks reduced", not "thermal"
723        s.thermal.pressure = Measured::exact(ThermalPressure::Nominal, "t");
724        s.thermal.low_power_mode = Measured::exact(false, "t");
725        let c = explain(&s, &History::default());
726        assert_eq!(c[0].title, "Clocks reduced — running at 45% speed");
727        assert_eq!(
728            c[0].evidence,
729            [
730                "P-cluster at 45% of max clock (90% busy)",
731                "thermal pressure nominal"
732            ],
733            "the headline is not repeated as the first bullet"
734        );
735    }
736
737    #[test]
738    fn evidence_never_repeats_the_title() {
739        assert!(title_repeats(
740            "Clocks reduced — running at 35% speed",
741            "running at 35% speed"
742        ));
743        assert!(title_repeats("Low Power Mode is on", "Low Power Mode on"));
744        assert!(!title_repeats("Low Power Mode is on", "running at 35% speed"));
745        assert!(!title_repeats("Swapping heavily", ""));
746        let mut s = Snapshot::default();
747        s.thermal.clusters = vec![ClusterFreq {
748            name: "P-cluster".into(),
749            cur_mhz: 1800.0,
750            max_mhz: 4000.0,
751            active_pct: 90.0,
752        }];
753        s.thermal.throttle_factor = crate::throttle::throttle_factor(&s.thermal.clusters);
754        s.thermal.low_power_mode = Measured::exact(true, "t");
755        for c in explain(&s, &History::default()) {
756            for e in &c.evidence {
757                assert!(!title_repeats(&c.title, e), "{c:?}");
758            }
759        }
760    }
761
762    #[test]
763    fn swap_storm_from_history_when_rates_are_unavailable() {
764        use crate::history::HistoryPoint;
765        let mut h = History::default();
766        let t0 = 1_000_000u64;
767        for k in 0..11u64 {
768            h.push(HistoryPoint {
769                t_ms: t0 + k * 30_000,
770                swap_used: Some((1024 + k * 150) * 1024 * 1024),
771                ..Default::default()
772            });
773        }
774        let mut s = Snapshot {
775            taken_at_ms: t0 + 300_000,
776            ..Default::default()
777        };
778        s.memory.swap_in_per_min = Measured::unavailable("vm_stat", "n/a");
779        let c = explain(&s, &h);
780        let sw = c
781            .iter()
782            .find(|c| c.kind == CauseKind::SwapStorm)
783            .expect("swap storm");
784        assert!(sw.evidence[0].contains("in 5m"), "{:?}", sw.evidence);
785        assert!(sw.evidence[0].contains("rates unavailable"));
786        // with measured (quiet) rates, growth alone does not duplicate the cause
787        s.memory.swap_in_per_min = Measured::exact(0, "t");
788        s.memory.swap_out_per_min = Measured::exact(0, "t");
789        assert!(explain(&s, &h).iter().all(|c| c.kind != CauseKind::SwapStorm));
790    }
791
792    #[test]
793    fn throttled_run_and_swap() {
794        let mut s = Snapshot::default();
795        s.thermal.throttle_factor = Measured::estimate(0.45, "t");
796        s.thermal.pressure = Measured::exact(ThermalPressure::Heavy, "t");
797        s.memory.swap_in_per_min = Measured::exact(600 * 1024 * 1024, "t");
798        let c = explain(&s, &History::default());
799        let kinds: Vec<CauseKind> = c.iter().map(|c| c.kind).collect();
800        assert!(kinds.contains(&CauseKind::ThermalThrottle));
801        assert!(kinds.contains(&CauseKind::SwapStorm));
802        let th = c.iter().find(|c| c.kind == CauseKind::ThermalThrottle).unwrap();
803        // the headline carries the speed; the evidence does not repeat it
804        assert_eq!(th.title, "Thermal throttling — running at 45% speed");
805        assert!(!th.evidence.iter().any(|e| e == "running at 45% speed"), "{th:?}");
806        assert!(th.evidence.contains(&"thermal pressure heavy".to_string()));
807        assert!(c.windows(2).all(|w| w[0].score >= w[1].score));
808    }
809}