Skip to main content

oomtop_core/
forecast.rs

1//! OOM forecast (SPEC §8.3): which killer applies, its thresholds, a linear-trend ETA, the likely victim and
2//! recent kills — all pure functions over history, config text and snapshots.
3//!
4//! Forecast rules:
5//! - Linear least-squares fit of the last 2–5 min of available memory, swap used and PSI (every window of
6//!   5, 4, 3 and 2 min is tried; the earliest qualifying ETA wins) against the nearest applicable threshold.
7//!   A window is the shortest run of newest samples that spans **at least** its length (the sample just
8//!   before the cutoff is included when it is within [`WINDOW_SLACK_MS`]), so jittered wall-clock timestamps
9//!   still give the 2-min window its full 2 min.
10//! - The memory-pressure series is PSI `some avg10` (SPEC §21).
11//! - The killer-configuration parsers and [`likely_victim`] in this module are the pure reference
12//!   implementations used by the core tests and goldens. The shipping binary builds `Oom` thresholds in
13//!   `oomtop-collect` (`linux/oom.rs`) and picks the victim in `oomtop-cli` (`engine.rs`); keep them in step.
14//! - Shown only when the trend is consistent: R² ≥ 0.6, ≥ 8 points over ≥ 2 min, both halves of the window
15//!   trend the same way, and no single step accounts for more than half of the change — so a single spike
16//!   (or a one-off step such as a model load) never raises an alarm. ETA must be < 30 min.
17//! - Killer semantics: the kernel, systemd-oomd and jetsam act when **any** of their rules is met (oomd
18//!   pressure adds its sustain duration); earlyoom acts only when **all** of its thresholds are met
19//!   (available memory *and* free swap), so its ETA is the latest of its per-metric ETAs. The systemd-oomd
20//!   swap rule is itself an AND: memory used *and* swap used both above `SwapUsedLimit` (systemd
21//!   `oomd_mem_available_below && oomd_swap_free_below`); the memory half is checked when RAM size is known.
22//! - A series whose newest value is older than [`MAX_STALE_S`] is not forecast; a slightly stale one has its
23//!   ETA measured from the newest history point, not from its own last value.
24//! - macOS swap is dynamic (swap files are added on demand), so "swap used → swap total" is not a limit
25//!   when jetsam is the killer; the ceiling there is `swap_limit` (swap used + free space on the swap
26//!   volume — jetsam kills when swap can't grow). With ample disk that ETA is far beyond 30 min: "stable".
27
28use crate::history::{History, HistoryPoint};
29use crate::model::{
30    Forecast, ForecastTarget, GroupKind, Oom, OomKill, OomKiller, OomThreshold, OsKind, ProcId, Snapshot,
31    ThresholdMetric, Victim,
32};
33use crate::units::{parse_duration_s, parse_percent};
34use serde::{Deserialize, Serialize};
35
36pub const MIN_R2: f64 = 0.6;
37pub const MAX_ETA_S: f64 = 30.0 * 60.0;
38/// Fit window (5 min) and minimum span of data required (2 min).
39pub const WINDOW_MS: u64 = 5 * 60 * 1000;
40pub const MIN_SPAN_S: f64 = 120.0;
41/// Minimum number of points for a fit.
42pub const MIN_POINTS: usize = 8;
43/// Windows tried, longest first (SPEC §8.3 "last 2–5 min").
44pub const WINDOWS_MS: [u64; 4] = [5 * 60_000, 4 * 60_000, 3 * 60_000, 2 * 60_000];
45/// How far before a window's cutoff the sample that completes the window may lie (one slow sample
46/// interval). Without it a window only reaches its nominal span when a sample lands exactly on the cutoff
47/// millisecond, and the 2-min window could never satisfy [`MIN_SPAN_S`] on live (jittered) timestamps.
48pub const WINDOW_SLACK_MS: u64 = 10_000;
49/// A single step may account for at most this share of the fitted change over the window.
50pub const MAX_STEP_SHARE: f64 = 0.5;
51/// A metric whose newest sample is older than this (relative to the newest history point) is not forecast.
52pub const MAX_STALE_S: f64 = 30.0;
53
54/// systemd-oomd defaults (oomd.conf(5)).
55pub const OOMD_DEFAULT_SWAP_USED_LIMIT_PCT: f64 = 90.0;
56pub const OOMD_DEFAULT_MEM_PRESSURE_LIMIT_PCT: f64 = 60.0;
57pub const OOMD_DEFAULT_MEM_PRESSURE_DURATION_S: u32 = 30;
58/// earlyoom defaults (`-m 10 -s 10`; SIGKILL at half).
59pub const EARLYOOM_DEFAULT_MEM_PCT: f64 = 10.0;
60pub const EARLYOOM_DEFAULT_SWAP_PCT: f64 = 10.0;
61
62#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
63pub struct LinearFit {
64    /// Units per second.
65    pub slope: f64,
66    pub intercept: f64,
67    pub r2: f64,
68    /// Time span covered, seconds.
69    pub span_s: f64,
70    pub n: usize,
71}
72
73impl LinearFit {
74    /// Fitted value at time `t`.
75    pub fn at(&self, t: f64) -> f64 {
76        self.intercept + self.slope * t
77    }
78}
79
80/// Least-squares fit of `(t_s, y)` points.
81pub fn linear_fit(points: &[(f64, f64)]) -> Option<LinearFit> {
82    let n = points.len();
83    if n < 2 {
84        return None;
85    }
86    if points.iter().any(|(t, y)| !t.is_finite() || !y.is_finite()) {
87        return None;
88    }
89    let nf = n as f64;
90    let mean_t = points.iter().map(|p| p.0).sum::<f64>() / nf;
91    let mean_y = points.iter().map(|p| p.1).sum::<f64>() / nf;
92    let mut sxx = 0.0;
93    let mut sxy = 0.0;
94    let mut syy = 0.0;
95    for (t, y) in points {
96        sxx += (t - mean_t).powi(2);
97        sxy += (t - mean_t) * (y - mean_y);
98        syy += (y - mean_y).powi(2);
99    }
100    if sxx == 0.0 {
101        return None;
102    }
103    let slope = sxy / sxx;
104    let intercept = mean_y - slope * mean_t;
105    let r2 = if syy == 0.0 {
106        0.0
107    } else {
108        (sxy * sxy) / (sxx * syy)
109    };
110    let span_s = points.last()?.0 - points.first()?.0;
111    Some(LinearFit {
112        slope,
113        intercept,
114        r2,
115        span_s,
116        n,
117    })
118}
119
120/// Spike/step guard: both halves of the window trend in the fit's direction, no single step between
121/// consecutive points — **in either direction** — accounts for more than [`MAX_STEP_SHARE`] of the fitted
122/// change, and the newest value is still on the fitted line. A drop against the trend (an OOM kill, a stopped
123/// hog, a reclaim) therefore clears the forecast instead of leaving a stale ETA.
124pub fn trend_is_consistent(points: &[(f64, f64)], fit: &LinearFit) -> bool {
125    if points.len() < MIN_POINTS || fit.slope == 0.0 {
126        return false;
127    }
128    let total_change = (fit.slope * fit.span_s).abs();
129    if total_change <= 0.0 {
130        return false;
131    }
132    let max_step = points
133        .windows(2)
134        .map(|w| (w[1].1 - w[0].1).abs())
135        .fold(0.0, f64::max);
136    if max_step > MAX_STEP_SHARE * total_change {
137        return false;
138    }
139    // The newest actual value must sit near the line (a recent reversal the fit hasn't caught up with).
140    if let Some((t_last, y_last)) = points.last() {
141        if (y_last - fit.at(*t_last)).abs() > MAX_STEP_SHARE * total_change {
142            return false;
143        }
144    }
145    let mid = points.len() / 2;
146    let halves = [&points[..mid], &points[mid..]];
147    halves.iter().all(|h| match linear_fit(h) {
148        Some(f) => f.slope.signum() == fit.slope.signum() && f.slope != 0.0,
149        None => false,
150    })
151}
152
153/// ETA (seconds from the last point) for a series to reach `threshold`, rising (`rising = true`) or falling.
154/// Returns `None` unless the trend is consistent, heading towards the threshold, and ETA < 30 min. The ETA
155/// is measured from the newest **actual** value (not the fitted one) at the fitted rate.
156pub fn eta_to_threshold(points: &[(f64, f64)], threshold: f64, rising: bool) -> Option<(f64, LinearFit)> {
157    if points.len() < MIN_POINTS || !threshold.is_finite() {
158        return None;
159    }
160    let fit = linear_fit(points)?;
161    if fit.span_s < MIN_SPAN_S || fit.r2 < MIN_R2 {
162        return None;
163    }
164    if !trend_is_consistent(points, &fit) {
165        return None;
166    }
167    let (_, y_now) = *points.last()?;
168    let towards = if rising {
169        fit.slope > 0.0 && y_now < threshold
170    } else {
171        fit.slope < 0.0 && y_now > threshold
172    };
173    if !towards {
174        return None;
175    }
176    let eta = (threshold - y_now) / fit.slope;
177    (eta.is_finite() && eta > 0.0 && eta < MAX_ETA_S).then_some((eta, fit))
178}
179
180/// Tries every window in [`WINDOWS_MS`] and returns the earliest qualifying ETA (conservative: a trend that
181/// only started recently is not diluted by the flat minutes before it).
182pub fn eta_in_history(
183    history: &History,
184    f: impl Fn(&HistoryPoint) -> Option<f64>,
185    threshold: f64,
186    rising: bool,
187) -> Option<(f64, LinearFit)> {
188    let now_ms = history.last()?.t_ms;
189    WINDOWS_MS
190        .iter()
191        .filter_map(|w| {
192            let w = &window_reaching(history, *w);
193            // `series` is relative to the window's first point; points where the metric is missing are
194            // dropped, so the series may end before "now".
195            let t0 = history.window(*w).first()?.t_ms;
196            let points = history.series(*w, &f);
197            let stale_s = now_ms.saturating_sub(t0) as f64 / 1000.0 - points.last()?.0;
198            if stale_s > MAX_STALE_S {
199                return None;
200            }
201            let (eta, fit) = eta_to_threshold(&points, threshold, rising)?;
202            let eta = eta - stale_s.max(0.0);
203            (eta > 0.0).then_some((eta, fit))
204        })
205        .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
206}
207
208/// The window length (ms, back from the newest point) that makes a nominal `window_ms` window span at least
209/// `window_ms`: extended to the newest sample at or before the cutoff when that sample is within
210/// [`WINDOW_SLACK_MS`] of it; `window_ms` itself otherwise (history shorter than the window, or a gap).
211pub fn window_reaching(history: &History, window_ms: u64) -> u64 {
212    let Some(now_ms) = history.last().map(|p| p.t_ms) else {
213        return window_ms;
214    };
215    let cutoff = now_ms.saturating_sub(window_ms);
216    history
217        .iter()
218        .map(|p| p.t_ms)
219        .take_while(|t| *t <= cutoff)
220        .last()
221        .filter(|t| cutoff - *t <= WINDOW_SLACK_MS)
222        .map(|t| now_ms - t)
223        .unwrap_or(window_ms)
224}
225
226fn metric_value(p: &HistoryPoint, metric: ThresholdMetric, mem_total: Option<u64>) -> Option<f64> {
227    match metric {
228        ThresholdMetric::SwapUsedPct => {
229            let t = p.swap_total.filter(|t| *t > 0)? as f64;
230            Some(p.swap_used? as f64 / t * 100.0)
231        }
232        ThresholdMetric::MemPressurePct => p.psi_some_avg10,
233        ThresholdMetric::AvailableBytes => p.available.map(|v| v as f64),
234        ThresholdMetric::AvailablePct => {
235            let t = mem_total.filter(|t| *t > 0)? as f64;
236            Some(p.available? as f64 / t * 100.0)
237        }
238    }
239}
240
241/// Swap/available metrics fall towards their threshold or rise towards it.
242fn metric_rising(metric: ThresholdMetric) -> bool {
243    matches!(
244        metric,
245        ThresholdMetric::SwapUsedPct | ThresholdMetric::MemPressurePct
246    )
247}
248
249/// Converts a fitted slope (units/s) into the forecast rate (bytes/min; 0 for PSI, which has no byte rate).
250fn rate_per_min(metric: ThresholdMetric, slope: f64, swap_total: Option<u64>, mem_total: Option<u64>) -> f64 {
251    let per_min = slope.abs() * 60.0;
252    match metric {
253        ThresholdMetric::AvailableBytes => per_min,
254        ThresholdMetric::SwapUsedPct => swap_total.map(|t| per_min * t as f64 / 100.0).unwrap_or(0.0),
255        ThresholdMetric::AvailablePct => mem_total.map(|t| per_min * t as f64 / 100.0).unwrap_or(0.0),
256        ThresholdMetric::MemPressurePct => 0.0,
257    }
258}
259
260/// Whether the threshold is already met at the latest point.
261fn already_met(p: &HistoryPoint, th: &OomThreshold, mem_total: Option<u64>) -> Option<bool> {
262    let v = metric_value(p, th.metric, mem_total)?;
263    Some(if metric_rising(th.metric) {
264        v >= th.value
265    } else {
266        v <= th.value
267    })
268}
269
270/// ETA for one metric to reach `value`: `(0, None)` when already met at the newest point, `(eta, fit)` when
271/// trending towards it, `None` otherwise.
272fn metric_eta(
273    history: &History,
274    last: &HistoryPoint,
275    metric: ThresholdMetric,
276    value: f64,
277    mem_total: Option<u64>,
278) -> Option<(f64, Option<LinearFit>)> {
279    let th = OomThreshold {
280        metric,
281        value,
282        ..Default::default()
283    };
284    if already_met(last, &th, mem_total) == Some(true) {
285        return Some((0.0, None));
286    }
287    let (eta, fit) = eta_in_history(
288        history,
289        |p| metric_value(p, metric, mem_total),
290        value,
291        metric_rising(metric),
292    )?;
293    Some((eta, Some(fit)))
294}
295
296/// Forecasts the nearest OOM target from history and the host's killer thresholds.
297pub fn forecast_oom(history: &History, oom: &Oom) -> Option<Forecast> {
298    forecast_oom_with(history, oom, None)
299}
300
301/// [`forecast_oom`] with the RAM size, which enables `AvailablePct` thresholds (earlyoom `-m`).
302pub fn forecast_oom_with(history: &History, oom: &Oom, mem_total: Option<u64>) -> Option<Forecast> {
303    let last = history.last()?;
304    // Latest known swap size (one sample without swap data must not hide the swap forecast).
305    let swap_total = history.iter().filter_map(|p| p.swap_total).last();
306    let killers: Vec<OomKiller> = if oom.killers.is_empty() {
307        vec![oom.killer]
308    } else {
309        oom.killers.clone()
310    };
311    let jetsam = killers.contains(&OomKiller::Jetsam);
312    let base_killer = if killers.contains(&OomKiller::Kernel) {
313        OomKiller::Kernel
314    } else {
315        oom.killer
316    };
317    let mut best: Option<Forecast> = None;
318    let mut consider = |f: Forecast| {
319        let better = match &best {
320            None => true,
321            Some(b) => f.eta_s < b.eta_s || (f.eta_s == b.eta_s && f.confidence > b.confidence),
322        };
323        if better {
324            best = Some(f);
325        }
326    };
327
328    // Swap exhaustion: swap_used → the swap ceiling. Fixed-size swap: swap_total. Jetsam hosts (macOS) add
329    // swap files on demand, so the ceiling is `swap_limit` (swap used + free space on the swap volume).
330    let ceiling = if jetsam {
331        history.iter().filter_map(|p| p.swap_limit).last()
332    } else {
333        swap_total
334    };
335    if let Some(total) = ceiling.filter(|t| *t > 0) {
336        if let Some((eta, fit)) =
337            eta_in_history(history, |p| p.swap_used.map(|v| v as f64), total as f64, true)
338        {
339            consider(Forecast {
340                target: ForecastTarget::SwapExhaustion,
341                killer: Some(base_killer),
342                eta_s: eta as u64,
343                confidence: fit.r2,
344                rate_per_min: fit.slope.abs() * 60.0,
345                window_s: fit.span_s as u64,
346            });
347        }
348    }
349    // Available memory → 0.
350    if let Some((eta, fit)) = eta_in_history(history, |p| p.available.map(|v| v as f64), 0.0, false) {
351        consider(Forecast {
352            target: ForecastTarget::AvailableExhaustion,
353            killer: Some(base_killer),
354            eta_s: eta as u64,
355            confidence: fit.r2,
356            rate_per_min: fit.slope.abs() * 60.0,
357            window_s: fit.span_s as u64,
358        });
359    }
360
361    // Killer thresholds.
362    for killer in &killers {
363        let ths: Vec<&OomThreshold> = oom.thresholds.iter().filter(|t| t.killer == *killer).collect();
364        if ths.is_empty() {
365            continue;
366        }
367        // Per threshold: (eta, fit of the metric that decides it, that metric).
368        let per: Vec<Option<(f64, Option<LinearFit>, ThresholdMetric)>> = ths
369            .iter()
370            .map(|th| {
371                // earlyoom without swap: "free swap below X %" always holds.
372                let no_swap = th.metric == ThresholdMetric::SwapUsedPct && swap_total == Some(0);
373                if no_swap && *killer == OomKiller::Earlyoom {
374                    return Some((0.0, None, th.metric));
375                }
376                let (eta, fit) = metric_eta(history, last, th.metric, th.value, mem_total)?;
377                let mut out = (eta, fit, th.metric);
378                if *killer == OomKiller::SystemdOomd && th.metric == ThresholdMetric::SwapUsedPct {
379                    // Swap rule = swap used ≥ limit AND memory used ≥ limit (available ≤ 100 − limit).
380                    // Without the RAM size only the swap half can be checked (earlier = conservative).
381                    if mem_total.is_some() {
382                        let avail_pct = (100.0 - th.value).clamp(0.0, 100.0);
383                        let (m_eta, m_fit) =
384                            metric_eta(history, last, ThresholdMetric::AvailablePct, avail_pct, mem_total)?;
385                        // The later half decides ("already met" is ETA 0). Both met → (0, None): oomd is
386                        // acting now, which is not a trend forecast.
387                        if m_eta > out.0 {
388                            out = (m_eta, m_fit, ThresholdMetric::AvailablePct);
389                        }
390                    }
391                }
392                Some((out.0 + th.duration_s.unwrap_or(0) as f64, out.1, out.2))
393            })
394            .collect();
395        let as_forecast = |eta: f64, fit: &LinearFit, metric: ThresholdMetric| Forecast {
396            target: ForecastTarget::KillerThreshold,
397            killer: Some(*killer),
398            eta_s: eta as u64,
399            confidence: fit.r2,
400            rate_per_min: rate_per_min(metric, fit.slope, swap_total, mem_total),
401            window_s: fit.span_s as u64,
402        };
403        if *killer == OomKiller::Earlyoom {
404            // AND: every threshold must be met or forecast; ETA = latest; needs at least one real trend.
405            if per.iter().any(|p| p.is_none()) {
406                continue;
407            }
408            let all: Vec<(f64, Option<LinearFit>, ThresholdMetric)> = per.into_iter().flatten().collect();
409            let latest = all
410                .iter()
411                .filter(|(_, fit, _)| fit.is_some())
412                .max_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
413            if let Some((eta, Some(fit), metric)) = latest {
414                if *eta < MAX_ETA_S {
415                    let mut f = as_forecast(*eta, fit, *metric);
416                    f.confidence = all
417                        .iter()
418                        .filter_map(|(_, fit, _)| fit.map(|x| x.r2))
419                        .fold(1.0, f64::min);
420                    consider(f);
421                }
422            }
423        } else {
424            // OR: the earliest trending threshold.
425            for (eta, fit, metric) in per.into_iter().flatten() {
426                if let Some(fit) = fit {
427                    if eta < MAX_ETA_S {
428                        consider(as_forecast(eta, &fit, metric));
429                    }
430                }
431            }
432        }
433    }
434    best
435}
436
437// -----------------------------------------------------------------------------------------------------
438// Killer configuration (pure parsers; the collector reads the files / argv)
439// -----------------------------------------------------------------------------------------------------
440
441/// systemd-oomd global settings (`/etc/systemd/oomd.conf` + drop-ins, `[OOM]` section).
442#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
443#[serde(default)]
444pub struct OomdConfig {
445    pub swap_used_limit_pct: f64,
446    pub mem_pressure_limit_pct: f64,
447    pub mem_pressure_duration_s: u32,
448    /// "default" or the last file that set a value.
449    pub source: String,
450}
451
452impl Default for OomdConfig {
453    fn default() -> Self {
454        OomdConfig {
455            swap_used_limit_pct: OOMD_DEFAULT_SWAP_USED_LIMIT_PCT,
456            mem_pressure_limit_pct: OOMD_DEFAULT_MEM_PRESSURE_LIMIT_PCT,
457            mem_pressure_duration_s: OOMD_DEFAULT_MEM_PRESSURE_DURATION_S,
458            source: "systemd-oomd default".into(),
459        }
460    }
461}
462
463/// Iterates `key=value` pairs of an INI-style systemd file, yielding `(section, key, value)`.
464fn systemd_pairs(text: &str) -> Vec<(String, String, String)> {
465    let mut section = String::new();
466    let mut out = Vec::new();
467    for raw in text.lines() {
468        let line = raw.trim();
469        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
470            continue;
471        }
472        if line.starts_with('[') && line.ends_with(']') {
473            section = line[1..line.len() - 1].trim().to_string();
474            continue;
475        }
476        if let Some((k, v)) = line.split_once('=') {
477            out.push((section.clone(), k.trim().to_string(), v.trim().to_string()));
478        }
479    }
480    out
481}
482
483/// Parses oomd.conf layers in precedence order (main file first, then drop-ins alphabetically). Each layer
484/// is `(origin, text)`. Invalid values are ignored (the previous value stays).
485pub fn parse_oomd_conf(layers: &[(&str, &str)]) -> OomdConfig {
486    let mut c = OomdConfig::default();
487    for (origin, text) in layers {
488        for (section, k, v) in systemd_pairs(text) {
489            if section != "OOM" {
490                continue;
491            }
492            match k.as_str() {
493                "SwapUsedLimit" => {
494                    if let Ok(p) = parse_percent(&v) {
495                        c.swap_used_limit_pct = p;
496                        c.source = origin.to_string();
497                    }
498                }
499                "DefaultMemoryPressureLimit" => {
500                    if let Ok(p) = parse_percent(&v) {
501                        c.mem_pressure_limit_pct = p;
502                        c.source = origin.to_string();
503                    }
504                }
505                "DefaultMemoryPressureDurationSec" => {
506                    if let Ok(s) = parse_duration_s(&v) {
507                        c.mem_pressure_duration_s = s.round().clamp(0.0, u32::MAX as f64) as u32;
508                        c.source = origin.to_string();
509                    }
510                }
511                _ => {}
512            }
513        }
514    }
515    c
516}
517
518/// A unit's `ManagedOOM*` settings (slice/service/scope files or `systemctl show` output).
519#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
520#[serde(default)]
521pub struct ManagedOom {
522    pub unit: String,
523    pub swap_kill: bool,
524    pub pressure_kill: bool,
525    pub pressure_limit_pct: Option<f64>,
526    pub pressure_duration_s: Option<u32>,
527}
528
529/// Parses `ManagedOOMSwap=`, `ManagedOOMMemoryPressure=`, `ManagedOOMMemoryPressureLimit=` and
530/// `ManagedOOMMemoryPressureDurationSec=` from a unit file or `systemctl show -p …` output.
531pub fn parse_managed_oom(unit: &str, text: &str) -> ManagedOom {
532    let mut m = ManagedOom {
533        unit: unit.to_string(),
534        ..Default::default()
535    };
536    for (_, k, v) in systemd_pairs(text) {
537        match k.as_str() {
538            "ManagedOOMSwap" => m.swap_kill = v == "kill",
539            "ManagedOOMMemoryPressure" => m.pressure_kill = v == "kill",
540            "ManagedOOMMemoryPressureLimit" => {
541                // "0" / "0%" means "use the default".
542                m.pressure_limit_pct = parse_percent(&v).ok().filter(|p| *p > 0.0);
543            }
544            "ManagedOOMMemoryPressureDurationSec" => {
545                m.pressure_duration_s = parse_duration_s(&v)
546                    .ok()
547                    .filter(|s| *s > 0.0)
548                    .map(|s| s.round().clamp(0.0, u32::MAX as f64) as u32);
549            }
550            _ => {}
551        }
552    }
553    m
554}
555
556/// systemd-oomd thresholds. Without unit information both kinds are assumed to be managed (conservative);
557/// with units, only managed kinds apply and the tightest pressure limit wins.
558pub fn oomd_thresholds(cfg: &OomdConfig, units: &[ManagedOom]) -> Vec<OomThreshold> {
559    let mut out = Vec::new();
560    let swap = units.is_empty() || units.iter().any(|u| u.swap_kill);
561    if swap {
562        out.push(OomThreshold {
563            killer: OomKiller::SystemdOomd,
564            metric: ThresholdMetric::SwapUsedPct,
565            value: cfg.swap_used_limit_pct,
566            duration_s: None,
567            source: cfg.source.clone(),
568        });
569    }
570    let pressure_units: Vec<&ManagedOom> = units.iter().filter(|u| u.pressure_kill).collect();
571    if units.is_empty() {
572        out.push(OomThreshold {
573            killer: OomKiller::SystemdOomd,
574            metric: ThresholdMetric::MemPressurePct,
575            value: cfg.mem_pressure_limit_pct,
576            duration_s: Some(cfg.mem_pressure_duration_s),
577            source: cfg.source.clone(),
578        });
579    } else if let Some(u) = pressure_units.iter().min_by(|a, b| {
580        let la = a.pressure_limit_pct.unwrap_or(cfg.mem_pressure_limit_pct);
581        let lb = b.pressure_limit_pct.unwrap_or(cfg.mem_pressure_limit_pct);
582        la.partial_cmp(&lb).unwrap_or(std::cmp::Ordering::Equal)
583    }) {
584        out.push(OomThreshold {
585            killer: OomKiller::SystemdOomd,
586            metric: ThresholdMetric::MemPressurePct,
587            value: u.pressure_limit_pct.unwrap_or(cfg.mem_pressure_limit_pct),
588            duration_s: Some(u.pressure_duration_s.unwrap_or(cfg.mem_pressure_duration_s)),
589            source: if u.pressure_limit_pct.is_some() {
590                format!("{} ManagedOOMMemoryPressureLimit", u.unit)
591            } else {
592                cfg.source.clone()
593            },
594        });
595    }
596    out
597}
598
599/// earlyoom settings from its argv (`-m PERCENT[,KILL]`, `-s PERCENT[,KILL]`, `-M KiB[,KILL]`,
600/// `-S KiB[,KILL]`). SIGTERM thresholds are the ones that matter for a forecast.
601#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
602#[serde(default)]
603pub struct EarlyoomConfig {
604    pub mem_term_pct: f64,
605    pub mem_kill_pct: f64,
606    pub swap_term_pct: f64,
607    pub swap_kill_pct: f64,
608    pub mem_term_kib: Option<u64>,
609    pub mem_kill_kib: Option<u64>,
610    pub swap_term_kib: Option<u64>,
611    pub swap_kill_kib: Option<u64>,
612}
613
614impl Default for EarlyoomConfig {
615    fn default() -> Self {
616        EarlyoomConfig {
617            mem_term_pct: EARLYOOM_DEFAULT_MEM_PCT,
618            mem_kill_pct: EARLYOOM_DEFAULT_MEM_PCT / 2.0,
619            swap_term_pct: EARLYOOM_DEFAULT_SWAP_PCT,
620            swap_kill_pct: EARLYOOM_DEFAULT_SWAP_PCT / 2.0,
621            mem_term_kib: None,
622            mem_kill_kib: None,
623            swap_term_kib: None,
624            swap_kill_kib: None,
625        }
626    }
627}
628
629fn split_pair(v: &str) -> Result<(f64, Option<f64>), String> {
630    let mut it = v.splitn(2, ',');
631    let a: f64 = it
632        .next()
633        .unwrap_or("")
634        .trim()
635        .parse()
636        .map_err(|_| format!("invalid value {v:?}"))?;
637    let b = match it.next() {
638        Some(s) => Some(
639            s.trim()
640                .parse::<f64>()
641                .map_err(|_| format!("invalid value {v:?}"))?,
642        ),
643        None => None,
644    };
645    if !a.is_finite() || a < 0.0 || b.map(|x| !x.is_finite() || x < 0.0).unwrap_or(false) {
646        return Err(format!("invalid value {v:?}"));
647    }
648    Ok((a, b))
649}
650
651/// Parses an earlyoom command line (argv[0] may be included). Unknown options are ignored.
652/// Reference implementation (see the module docs): the collector parses the live argv itself.
653pub fn parse_earlyoom_argv(argv: &[String]) -> Result<EarlyoomConfig, String> {
654    // Short options that take an argument (so their value is not mistaken for an option).
655    const WITH_ARG: &[&str] = &["-r", "-N", "--prefer", "--avoid", "--ignore"];
656    let mut c = EarlyoomConfig::default();
657    let mut i = 0;
658    let args: Vec<&str> = argv.iter().map(String::as_str).collect();
659    while i < args.len() {
660        let a = args[i];
661        // `-m10` style: split after the option letter. argv is another process's command line, so the
662        // letter may be any character: only split on a char boundary ("-é" must not panic).
663        let (flag, attached) =
664            if a.len() > 2 && a.starts_with('-') && !a.starts_with("--") && a.is_char_boundary(2) {
665                (&a[..2], Some(&a[2..]))
666            } else {
667                (a, None)
668            };
669        let value = |i: &mut usize| -> Result<String, String> {
670            if let Some(v) = attached {
671                return Ok(v.to_string());
672            }
673            *i += 1;
674            args.get(*i)
675                .map(|s| s.to_string())
676                .ok_or_else(|| format!("{flag} needs a value"))
677        };
678        match flag {
679            "-m" => {
680                let (t, k) = split_pair(&value(&mut i)?)?;
681                if t > 100.0 {
682                    return Err(format!("-m {t} out of range"));
683                }
684                c.mem_term_pct = t;
685                c.mem_kill_pct = k.unwrap_or(t / 2.0);
686            }
687            "-s" => {
688                let (t, k) = split_pair(&value(&mut i)?)?;
689                if t > 100.0 {
690                    return Err(format!("-s {t} out of range"));
691                }
692                c.swap_term_pct = t;
693                c.swap_kill_pct = k.unwrap_or(t / 2.0);
694            }
695            "-M" => {
696                let (t, k) = split_pair(&value(&mut i)?)?;
697                c.mem_term_kib = Some(t as u64);
698                c.mem_kill_kib = Some(k.unwrap_or(t / 2.0) as u64);
699            }
700            "-S" => {
701                let (t, k) = split_pair(&value(&mut i)?)?;
702                c.swap_term_kib = Some(t as u64);
703                c.swap_kill_kib = Some(k.unwrap_or(t / 2.0) as u64);
704            }
705            f if WITH_ARG.contains(&f) && attached.is_none() => {
706                i += 1;
707            }
708            _ => {}
709        }
710        i += 1;
711    }
712    Ok(c)
713}
714
715/// earlyoom SIGTERM thresholds. `-m`/`-M` and `-s`/`-S`: the lower of the two applies. With known totals
716/// the thresholds are resolved to bytes / swap-used %; without swap (`swap_total == Some(0)`) the swap
717/// condition is always met and no swap threshold is emitted.
718pub fn earlyoom_thresholds(
719    c: &EarlyoomConfig,
720    mem_total: Option<u64>,
721    swap_total: Option<u64>,
722) -> Vec<OomThreshold> {
723    let mut out = Vec::new();
724    let source = "earlyoom argv".to_string();
725    match mem_total.filter(|t| *t > 0) {
726        Some(total) => {
727            let pct_bytes = (total as f64 * c.mem_term_pct / 100.0) as u64;
728            let bytes = match c.mem_term_kib {
729                Some(k) => pct_bytes.min(k.saturating_mul(1024)),
730                None => pct_bytes,
731            };
732            out.push(OomThreshold {
733                killer: OomKiller::Earlyoom,
734                metric: ThresholdMetric::AvailableBytes,
735                value: bytes as f64,
736                duration_s: None,
737                source: source.clone(),
738            });
739        }
740        None => out.push(OomThreshold {
741            killer: OomKiller::Earlyoom,
742            metric: ThresholdMetric::AvailablePct,
743            value: c.mem_term_pct,
744            duration_s: None,
745            source: source.clone(),
746        }),
747    }
748    if swap_total != Some(0) {
749        let mut free_pct = c.swap_term_pct;
750        if let (Some(k), Some(t)) = (c.swap_term_kib, swap_total.filter(|t| *t > 0)) {
751            free_pct = free_pct.min(k as f64 * 1024.0 / t as f64 * 100.0);
752        }
753        out.push(OomThreshold {
754            killer: OomKiller::Earlyoom,
755            metric: ThresholdMetric::SwapUsedPct,
756            value: (100.0 - free_pct).clamp(0.0, 100.0),
757            duration_s: None,
758            source,
759        });
760    }
761    out
762}
763
764/// What the collector found about user-space OOM killers.
765#[derive(Debug, Clone, PartialEq, Default)]
766pub struct OomInputs {
767    pub os: OsKind,
768    /// systemd-oomd is active: its config and the managed units (empty = unknown).
769    pub oomd: Option<(OomdConfig, Vec<ManagedOom>)>,
770    /// earlyoom is running with this argv.
771    pub earlyoom_argv: Option<Vec<String>>,
772    pub mem_total: Option<u64>,
773    pub swap_total: Option<u64>,
774}
775
776/// Reference implementation for tests and goldens: the Linux collector builds the live `Oom` itself
777/// (`oomtop-collect`, `linux/decode.rs` `decode_oom`).
778///
779/// Builds `Oom { killer, killers, thresholds }` (forecast/victim/kills are filled later). The nearest
780/// killer is the most proactive one present: earlyoom, then systemd-oomd, then the kernel; jetsam on macOS.
781/// An unparsable earlyoom argv falls back to earlyoom's defaults.
782pub fn oom_setup(inputs: &OomInputs) -> Oom {
783    let mut oom = Oom::default();
784    match inputs.os {
785        OsKind::Macos => {
786            oom.killer = OomKiller::Jetsam;
787            oom.killers = vec![OomKiller::Jetsam];
788        }
789        _ => {
790            oom.killers.push(OomKiller::Kernel);
791            oom.killer = OomKiller::Kernel;
792            if let Some((cfg, units)) = &inputs.oomd {
793                oom.killers.push(OomKiller::SystemdOomd);
794                oom.thresholds.extend(oomd_thresholds(cfg, units));
795                oom.killer = OomKiller::SystemdOomd;
796            }
797            if let Some(argv) = &inputs.earlyoom_argv {
798                oom.killers.push(OomKiller::Earlyoom);
799                let cfg = parse_earlyoom_argv(argv).unwrap_or_default();
800                oom.thresholds
801                    .extend(earlyoom_thresholds(&cfg, inputs.mem_total, inputs.swap_total));
802                oom.killer = OomKiller::Earlyoom;
803            }
804        }
805    }
806    oom
807}
808
809// -----------------------------------------------------------------------------------------------------
810// Likely victim & recent kills
811// -----------------------------------------------------------------------------------------------------
812
813/// Processes jetsam never picks (kernel, launchd) or that sit in the highest bands.
814const JETSAM_EXEMPT: &[&str] = &["kernel_task", "launchd", "WindowServer", "loginwindow"];
815
816/// Who the killer would likely pick. Linux: highest `oom_score` (readable unprivileged). macOS: jetsam bands
817/// need root, so the largest-footprint non-system group (its root process), labeled as a heuristic.
818///
819/// This is the rule the binary uses: `oomtop-cli`'s engine calls it for every snapshot.
820pub fn likely_victim(s: &Snapshot) -> Option<Victim> {
821    let footprint = |p: &crate::model::Process| p.mem.footprint_or_pss.usable().unwrap_or(0);
822    let scored = s
823        .processes
824        .iter()
825        .filter(|p| p.oom_score.unwrap_or(0) > 0 && p.id.pid > 1)
826        .max_by(|a, b| {
827            a.oom_score
828                .cmp(&b.oom_score)
829                .then_with(|| footprint(a).cmp(&footprint(b)))
830                .then_with(|| b.id.pid.cmp(&a.id.pid))
831        });
832    if s.host.os != OsKind::Macos {
833        if let Some(p) = scored {
834            return Some(Victim {
835                id: p.id,
836                name: p.name.clone(),
837                group_id: s.group_of(p.id).map(|g| g.id.clone()),
838                reason: format!("highest oom_score ({})", p.oom_score.unwrap_or(0)),
839                heuristic: false,
840            });
841        }
842        if s.host.os == OsKind::Linux {
843            return None;
844        }
845    }
846    // macOS (or no oom_score data): largest non-system group by footprint.
847    let group = s
848        .groups
849        .iter()
850        .filter(|g| g.kind != GroupKind::System && !g.is_self && !g.protected)
851        .filter(|g| g.totals.footprint.usable().unwrap_or(0) > 0)
852        .max_by_key(|g| {
853            (
854                g.totals.footprint.usable().unwrap_or(0),
855                std::cmp::Reverse(g.id.clone()),
856            )
857        });
858    let pick = |id: ProcId| {
859        s.process(id)
860            .filter(|p| !JETSAM_EXEMPT.contains(&p.name.as_str()) && p.id.pid > 1)
861    };
862    if let Some(g) = group {
863        let proc_ = g.root.and_then(pick).or_else(|| {
864            g.members
865                .iter()
866                .filter_map(|m| pick(m.id))
867                .max_by_key(|p| footprint(p))
868        });
869        if let Some(p) = proc_ {
870            return Some(Victim {
871                id: p.id,
872                name: if g.label.is_empty() {
873                    p.name.clone()
874                } else {
875                    g.label.clone()
876                },
877                group_id: Some(g.id.clone()),
878                reason: "largest footprint among apps (heuristic: jetsam bands need root)".into(),
879                heuristic: true,
880            });
881        }
882    }
883    let p = s
884        .processes
885        .iter()
886        .filter(|p| p.id.pid > 1 && !JETSAM_EXEMPT.contains(&p.name.as_str()) && Some(p.id.pid) != s.self_pid)
887        .max_by_key(|p| footprint(p))
888        .filter(|p| footprint(p) > 0)?;
889    Some(Victim {
890        id: p.id,
891        name: p.name.clone(),
892        group_id: s.group_of(p.id).map(|g| g.id.clone()),
893        reason: "largest footprint (heuristic: jetsam bands need root)".into(),
894        heuristic: true,
895    })
896}
897
898/// cgroup v2 `memory.events` counters.
899#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
900#[serde(default)]
901pub struct MemoryEvents {
902    pub low: u64,
903    pub high: u64,
904    pub max: u64,
905    pub oom: u64,
906    pub oom_kill: u64,
907    pub oom_group_kill: u64,
908}
909
910/// Parses `memory.events` ("oom_kill 3" lines; unknown keys ignored).
911pub fn parse_memory_events(text: &str) -> MemoryEvents {
912    let mut e = MemoryEvents::default();
913    for line in text.lines() {
914        let mut it = line.split_whitespace();
915        let (Some(k), Some(v)) = (it.next(), it.next()) else {
916            continue;
917        };
918        let Ok(v) = v.parse::<u64>() else { continue };
919        match k {
920            "low" => e.low = v,
921            "high" => e.high = v,
922            "max" => e.max = v,
923            "oom" => e.oom = v,
924            "oom_kill" => e.oom_kill = v,
925            "oom_group_kill" => e.oom_group_kill = v,
926            _ => {}
927        }
928    }
929    e
930}
931
932/// New OOM kills between two reads (counter resets → 0).
933pub fn oom_kills_since(prev: &MemoryEvents, cur: &MemoryEvents) -> u64 {
934    cur.oom_kill.saturating_sub(prev.oom_kill)
935}
936
937/// Days since 1970-01-01 for a civil date (proleptic Gregorian).
938fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
939    let y = if m <= 2 { y - 1 } else { y };
940    let era = if y >= 0 { y } else { y - 399 } / 400;
941    let yoe = y - era * 400;
942    let mp = (m as i64 + 9) % 12;
943    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
944    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
945    era * 146_097 + doe - 719_468
946}
947
948/// Parses an `.ips` timestamp like `"2026-09-29 10:10:10.00 +0100"` to ms since the epoch.
949pub fn parse_ips_timestamp_ms(s: &str) -> Option<u64> {
950    let mut parts = s.split_whitespace();
951    let date = parts.next()?;
952    let time = parts.next()?;
953    let tz = parts.next().unwrap_or("+0000");
954    let mut d = date.split('-');
955    let y: i64 = d.next()?.parse().ok()?;
956    let mo: u32 = d.next()?.parse().ok()?;
957    let da: u32 = d.next()?.parse().ok()?;
958    if !(1..=12).contains(&mo) || !(1..=31).contains(&da) {
959        return None;
960    }
961    let mut t = time.split(':');
962    let h: i64 = t.next()?.parse().ok()?;
963    let mi: i64 = t.next()?.parse().ok()?;
964    let sec: f64 = t.next()?.parse().ok()?;
965    if !(0..24).contains(&h) || !(0..60).contains(&mi) || !(0.0..61.0).contains(&sec) {
966        return None;
967    }
968    let (sign, digits) = match tz.as_bytes().first()? {
969        b'+' => (1, &tz[1..]),
970        b'-' => (-1, &tz[1..]),
971        _ => return None,
972    };
973    if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
974        return None;
975    }
976    let tzh: i64 = digits[..2].parse().ok()?;
977    let tzm: i64 = digits[2..].parse().ok()?;
978    let offset_s = sign * (tzh * 3600 + tzm * 60);
979    let secs = days_from_civil(y, mo, da) * 86_400 + h * 3600 + mi * 60 - offset_s;
980    let ms = secs as f64 * 1000.0 + (sec * 1000.0).round();
981    (ms >= 0.0).then_some(ms as u64)
982}
983
984/// Parses a macOS `JetsamEvent-*.ips` report into kills (processes carrying a `reason`). The first line is
985/// a JSON header, the rest the JSON body; older single-document reports are accepted too.
986pub fn parse_jetsam_event(text: &str, source: &str) -> Vec<OomKill> {
987    let (header, body) = match text.split_once('\n') {
988        Some((h, b)) if !b.trim().is_empty() => (
989            serde_json::from_str::<serde_json::Value>(h).ok(),
990            serde_json::from_str::<serde_json::Value>(b).ok(),
991        ),
992        _ => (None, serde_json::from_str::<serde_json::Value>(text).ok()),
993    };
994    let Some(body) = body else {
995        return Vec::new();
996    };
997    let at_ms = body
998        .get("date")
999        .and_then(|d| d.as_str())
1000        .and_then(parse_ips_timestamp_ms)
1001        .or_else(|| {
1002            header
1003                .as_ref()?
1004                .get("timestamp")?
1005                .as_str()
1006                .and_then(parse_ips_timestamp_ms)
1007        });
1008    body.get("processes")
1009        .and_then(|p| p.as_array())
1010        .map(|procs| {
1011            procs
1012                .iter()
1013                .filter(|p| p.get("reason").and_then(|r| r.as_str()).is_some())
1014                .map(|p| OomKill {
1015                    at_ms,
1016                    killer: OomKiller::Jetsam,
1017                    victim_name: p.get("name").and_then(|n| n.as_str()).map(str::to_string),
1018                    victim_pid: p
1019                        .get("pid")
1020                        .and_then(|n| n.as_u64())
1021                        .and_then(|n| u32::try_from(n).ok()),
1022                    source: format!(
1023                        "{source} ({})",
1024                        p.get("reason").and_then(|r| r.as_str()).unwrap_or("?")
1025                    ),
1026                })
1027                .collect()
1028        })
1029        .unwrap_or_default()
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035    use crate::units::{GIB, MIB};
1036
1037    fn hist(f: impl Fn(u64) -> u64) -> History {
1038        let mut h = History::default();
1039        for i in 0..=60u64 {
1040            h.push(HistoryPoint {
1041                t_ms: i * 5_000,
1042                swap_used: Some(f(i)),
1043                swap_total: Some(7 * GIB),
1044                available: Some(4 * GIB),
1045                ..Default::default()
1046            });
1047        }
1048        h
1049    }
1050
1051    #[test]
1052    fn steady_growth_forecasts() {
1053        // +400 MiB/min: 5 s steps → 400/12 MiB per step, starting at 4 GiB.
1054        let h = hist(|i| 4 * GIB + i * 400 * MIB / 12);
1055        let f = forecast_oom(&h, &Oom::default()).expect("forecast");
1056        assert_eq!(f.target, ForecastTarget::SwapExhaustion);
1057        // remaining at t=300s: 7G - (4G + 2000M) = 1072 MiB → ~160 s
1058        assert!((150..=170).contains(&f.eta_s), "eta {}", f.eta_s);
1059        assert!(f.confidence > 0.99);
1060        assert!((f.rate_per_min - 400.0 * MIB as f64).abs() < MIB as f64);
1061    }
1062
1063    #[test]
1064    fn two_minute_window_qualifies_with_jittered_timestamps() {
1065        // Live samples are wall-clock: ~2 s apart with millisecond jitter, never exactly on a window cutoff.
1066        // Swap falls for 3 min, then grows 5 MiB/s for 126 s: only the 2-min window is all growth (the
1067        // longer ones fail the halves check), and it must still span ≥ 2 min.
1068        let mut h = History::default();
1069        let mut last_t = 0;
1070        for i in 0..=153u64 {
1071            let t_ms = i * 2_000 + (i * 37) % 23 + 7;
1072            let t = t_ms as f64 / 1000.0;
1073            let used = if t <= 180.0 {
1074                5.0 * GIB as f64 - 5.0 * MIB as f64 * t
1075            } else {
1076                5.0 * GIB as f64 - 5.0 * MIB as f64 * 180.0 + 5.0 * MIB as f64 * (t - 180.0)
1077            };
1078            h.push(HistoryPoint {
1079                t_ms,
1080                swap_used: Some(used as u64),
1081                swap_total: Some(7 * GIB),
1082                available: Some(4 * GIB),
1083                ..Default::default()
1084            });
1085            last_t = t_ms;
1086        }
1087        // No sample sits on the 2-min cutoff: the plain window spans less than MIN_SPAN_S.
1088        let plain = h.series(120_000, |p| p.swap_used.map(|v| v as f64));
1089        assert!(plain.last().unwrap().0 - plain[0].0 < MIN_SPAN_S);
1090        let w = window_reaching(&h, 120_000);
1091        assert!((120_000..=124_000).contains(&w), "window {w} ms");
1092        let f = forecast_oom(&h, &Oom::default()).expect("forecast from the 2-min window");
1093        assert_eq!(f.target, ForecastTarget::SwapExhaustion);
1094        assert!((120..=124).contains(&f.window_s), "window {}", f.window_s);
1095        // 7 GiB − (5 GiB − 900 MiB + 630 MiB) = 2318 MiB at 5 MiB/s ≈ 464 s.
1096        assert!((440..=490).contains(&f.eta_s), "eta {}", f.eta_s);
1097        assert!((f.rate_per_min - 300.0 * MIB as f64).abs() < 5.0 * MIB as f64);
1098
1099        // A history shorter than the window is not stretched, and a gap wider than the slack is not bridged.
1100        let mut short = History::default();
1101        for i in 0..=50u64 {
1102            short.push(HistoryPoint {
1103                t_ms: last_t + i * 2_003,
1104                ..Default::default()
1105            });
1106        }
1107        assert_eq!(window_reaching(&short, 120_000), 120_000);
1108        let mut gap = History::default();
1109        for t_ms in [0, 2_000, 40_000, 62_000, 181_000] {
1110            gap.push(HistoryPoint {
1111                t_ms,
1112                ..Default::default()
1113            });
1114        }
1115        assert_eq!(window_reaching(&gap, 120_000), 120_000);
1116        assert_eq!(window_reaching(&History::default(), 120_000), 120_000);
1117    }
1118
1119    #[test]
1120    fn earlyoom_argv_with_a_multibyte_option_letter_does_not_panic() {
1121        let argv: Vec<String> = ["earlyoom", "-é", "-é5", "–m", "-m", "7", "-s3"]
1122            .iter()
1123            .map(|s| s.to_string())
1124            .collect();
1125        let c = parse_earlyoom_argv(&argv).unwrap();
1126        assert_eq!(c.mem_term_pct, 7.0);
1127        assert_eq!(c.swap_term_pct, 3.0);
1128    }
1129
1130    #[test]
1131    fn single_spike_does_not_forecast() {
1132        let h = hist(|i| if i == 60 { 6 * GIB } else { 4 * GIB });
1133        assert!(forecast_oom(&h, &Oom::default()).is_none());
1134    }
1135
1136    #[test]
1137    fn step_does_not_forecast() {
1138        // A model load: swap jumps once by 2 GiB halfway and stays (R² of a line through it is ~0.75).
1139        let h = hist(|i| if i >= 30 { 6 * GIB } else { 4 * GIB });
1140        let s = h.series(WINDOW_MS, |p| p.swap_used.map(|v| v as f64));
1141        assert!(linear_fit(&s).unwrap().r2 > MIN_R2);
1142        assert!(forecast_oom(&h, &Oom::default()).is_none());
1143    }
1144
1145    #[test]
1146    fn flat_is_stable() {
1147        let h = hist(|_| 4 * GIB);
1148        assert!(forecast_oom(&h, &Oom::default()).is_none());
1149    }
1150
1151    #[test]
1152    fn too_little_data() {
1153        let mut h = History::default();
1154        for i in 0..10u64 {
1155            h.push(HistoryPoint {
1156                t_ms: i * 5_000, // 45 s < 2 min
1157                swap_used: Some(GIB + i * 100 * MIB),
1158                swap_total: Some(2 * GIB),
1159                ..Default::default()
1160            });
1161        }
1162        assert!(forecast_oom(&h, &Oom::default()).is_none());
1163        assert!(forecast_oom(&History::default(), &Oom::default()).is_none());
1164    }
1165
1166    #[test]
1167    fn recent_trend_uses_shorter_window() {
1168        // Flat for 3 min, then +300 MiB/min for 2.5 min: the 5-min window fails the halves check, 2 min qualifies.
1169        let h = hist(|i| {
1170            if i <= 36 {
1171                4 * GIB
1172            } else {
1173                4 * GIB + (i - 36) * 25 * MIB
1174            }
1175        });
1176        let f = forecast_oom(&h, &Oom::default()).expect("forecast from recent trend");
1177        assert_eq!(f.target, ForecastTarget::SwapExhaustion);
1178        assert!(f.window_s <= 180, "window {}", f.window_s);
1179    }
1180
1181    #[test]
1182    fn jetsam_ignores_dynamic_swap_total() {
1183        let h = hist(|i| 4 * GIB + i * 400 * MIB / 12);
1184        let oom = Oom {
1185            killer: OomKiller::Jetsam,
1186            killers: vec![OomKiller::Jetsam],
1187            ..Default::default()
1188        };
1189        assert!(forecast_oom(&h, &oom).is_none());
1190    }
1191
1192    #[test]
1193    fn jetsam_forecasts_against_the_swap_ceiling() {
1194        // macOS: swap grows 400 MiB/min; the swap volume leaves room for 7 GiB of swap in total.
1195        let mut h = History::default();
1196        for i in 0..=60u64 {
1197            h.push(HistoryPoint {
1198                t_ms: i * 5_000,
1199                swap_used: Some(4 * GIB + i * 400 * MIB / 12),
1200                swap_total: Some(5 * GIB + i * 400 * MIB / 12), // grows with use: not a limit
1201                swap_limit: Some(7 * GIB),
1202                available: Some(4 * GIB),
1203                ..Default::default()
1204            });
1205        }
1206        let oom = oom_setup(&OomInputs {
1207            os: OsKind::Macos,
1208            ..Default::default()
1209        });
1210        let f = forecast_oom(&h, &oom).expect("forecast against the swap ceiling");
1211        assert_eq!(f.target, ForecastTarget::SwapExhaustion);
1212        assert_eq!(f.killer, Some(OomKiller::Jetsam));
1213        assert!((150..=170).contains(&f.eta_s), "eta {}", f.eta_s);
1214        // Plenty of disk: the ceiling is far away → stable.
1215        let mut roomy = History::default();
1216        for p in h.iter() {
1217            roomy.push(HistoryPoint {
1218                swap_limit: Some(700 * GIB),
1219                ..p.clone()
1220            });
1221        }
1222        assert!(forecast_oom(&roomy, &oom).is_none());
1223    }
1224
1225    #[test]
1226    fn drop_after_growth_clears_the_forecast() {
1227        // Swap grows steadily for 4 min, then an OOM kill (or a stopped hog) frees most of it at once.
1228        let grow = |i: u64| 4 * GIB + i * 400 * MIB / 12;
1229        let h = hist(|i| if i < 50 { grow(i) } else { 2 * GIB });
1230        assert!(
1231            forecast_oom(&h, &Oom::default()).is_none(),
1232            "a drop against the trend must not leave an ETA"
1233        );
1234        // The same growth without the drop does forecast.
1235        assert!(forecast_oom(&hist(grow), &Oom::default()).is_some());
1236    }
1237
1238    #[test]
1239    fn eta_is_measured_from_the_actual_last_value() {
1240        // A perfect line except the last point, which sits a little above it (within the guard).
1241        let mut pts: Vec<(f64, f64)> = (0..=36).map(|i| (i as f64 * 5.0, 100.0 + i as f64)).collect();
1242        pts.last_mut().unwrap().1 += 3.0; // actual 139 vs fitted ~136.x
1243        let (eta, fit) = eta_to_threshold(&pts, 200.0, true).unwrap();
1244        let from_actual = (200.0 - 139.0) / fit.slope;
1245        assert!((eta - from_actual).abs() < 1e-9, "eta {eta} vs {from_actual}");
1246    }
1247
1248    #[test]
1249    fn available_falling_forecasts() {
1250        let mut h = History::default();
1251        for i in 0..=36u64 {
1252            h.push(HistoryPoint {
1253                t_ms: i * 5_000,
1254                available: Some(4 * GIB - i * 50 * MIB),
1255                ..Default::default()
1256            });
1257        }
1258        let f = forecast_oom(&h, &Oom::default()).unwrap();
1259        assert_eq!(f.target, ForecastTarget::AvailableExhaustion);
1260        assert_eq!(f.killer, Some(OomKiller::Kernel));
1261        // 4096 − 1800 = 2296 MiB left at 600 MiB/min → ≈ 230 s
1262        assert!((225..=235).contains(&f.eta_s), "eta {}", f.eta_s);
1263    }
1264
1265    #[test]
1266    fn oomd_pressure_threshold_adds_duration() {
1267        let mut h = History::default();
1268        for i in 0..=36u64 {
1269            h.push(HistoryPoint {
1270                t_ms: i * 5_000,
1271                psi_some_avg10: Some(10.0 + i as f64),
1272                ..Default::default()
1273            });
1274        }
1275        let oom = oom_setup(&OomInputs {
1276            os: OsKind::Linux,
1277            oomd: Some((OomdConfig::default(), vec![])),
1278            ..Default::default()
1279        });
1280        let f = forecast_oom(&h, &oom).unwrap();
1281        assert_eq!(f.target, ForecastTarget::KillerThreshold);
1282        assert_eq!(f.killer, Some(OomKiller::SystemdOomd));
1283        // PSI at 46 → 60 at +1/5 s = 70 s, + 30 s sustain = 100 s.
1284        assert!((98..=102).contains(&f.eta_s), "eta {}", f.eta_s);
1285    }
1286
1287    #[test]
1288    fn earlyoom_needs_both_conditions() {
1289        let total = 16 * GIB;
1290        let mut h = History::default();
1291        for i in 0..=36u64 {
1292            h.push(HistoryPoint {
1293                t_ms: i * 5_000,
1294                // available falls 3 GiB → 1.2 GiB …
1295                available: Some(3 * GIB - i * 50 * MIB),
1296                // … swap has plenty free and is flat
1297                swap_used: Some(GIB),
1298                swap_total: Some(8 * GIB),
1299                ..Default::default()
1300            });
1301        }
1302        let oom = oom_setup(&OomInputs {
1303            os: OsKind::Linux,
1304            earlyoom_argv: Some(vec!["earlyoom".into(), "-m".into(), "5".into()]),
1305            mem_total: Some(total),
1306            swap_total: Some(8 * GIB),
1307            ..Default::default()
1308        });
1309        assert_eq!(oom.killer, OomKiller::Earlyoom);
1310        // Swap never reaches 90 % used → earlyoom does not act; the kernel forecast (available → 0) remains.
1311        let f = forecast_oom(&h, &oom).unwrap();
1312        assert_eq!(f.killer, Some(OomKiller::Kernel));
1313        assert_eq!(f.target, ForecastTarget::AvailableExhaustion);
1314
1315        // Without swap the memory condition alone decides (also when the collector still emits a swap
1316        // threshold for a swapless host).
1317        let mut with_swap_rule = oom_setup(&OomInputs {
1318            os: OsKind::Linux,
1319            earlyoom_argv: Some(vec!["-m".into(), "5".into()]),
1320            mem_total: Some(total),
1321            swap_total: None,
1322            ..Default::default()
1323        });
1324        assert_eq!(with_swap_rule.thresholds.len(), 2);
1325        with_swap_rule.killer = OomKiller::Earlyoom;
1326        let mut swapless = History::default();
1327        for p in h.iter() {
1328            swapless.push(HistoryPoint {
1329                swap_used: Some(0),
1330                swap_total: Some(0),
1331                ..p.clone()
1332            });
1333        }
1334        let f = forecast_oom(&swapless, &with_swap_rule).unwrap();
1335        assert_eq!(f.killer, Some(OomKiller::Earlyoom));
1336        let oom = oom_setup(&OomInputs {
1337            os: OsKind::Linux,
1338            earlyoom_argv: Some(vec!["-m".into(), "5".into()]),
1339            mem_total: Some(total),
1340            swap_total: Some(0),
1341            ..Default::default()
1342        });
1343        let f = forecast_oom(&h, &oom).unwrap();
1344        assert_eq!(f.killer, Some(OomKiller::Earlyoom));
1345        assert_eq!(f.target, ForecastTarget::KillerThreshold);
1346        // 1272 MiB now → 819.2 MiB (5 % of 16 GiB) at 600 MiB/min ≈ 45 s
1347        assert!((43..=47).contains(&f.eta_s), "eta {}", f.eta_s);
1348    }
1349
1350    #[test]
1351    fn oomd_swap_rule_needs_memory_used_too() {
1352        // Swap grows 300 MiB/min from 6 GiB of 8 GiB; oomd SwapUsedLimit 90 % (7.2 GiB) in ≈ 4 min.
1353        let total = 16 * GIB;
1354        let build = |avail: &dyn Fn(u64) -> u64| {
1355            let mut h = History::default();
1356            for i in 0..=36u64 {
1357                h.push(HistoryPoint {
1358                    t_ms: i * 5_000,
1359                    swap_used: Some(5 * GIB + i * 25 * MIB),
1360                    swap_total: Some(8 * GIB),
1361                    available: Some(avail(i)),
1362                    psi_some_avg10: Some(1.0),
1363                    ..Default::default()
1364                });
1365            }
1366            h
1367        };
1368        let oom = oom_setup(&OomInputs {
1369            os: OsKind::Linux,
1370            oomd: Some((OomdConfig::default(), vec![])),
1371            ..Default::default()
1372        });
1373        // Plenty of RAM available (50 %): memory used is far below 90 % → oomd's swap rule cannot fire.
1374        let roomy = build(&|_| 8 * GIB);
1375        let f = forecast_oom_with(&roomy, &oom, Some(total)).expect("kernel swap exhaustion");
1376        assert_eq!(f.killer, Some(OomKiller::Kernel));
1377        assert_eq!(f.target, ForecastTarget::SwapExhaustion);
1378        // Without the RAM size only the swap half is checked (conservative: oomd forecast).
1379        let f = forecast_oom(&roomy, &oom).unwrap();
1380        assert_eq!(f.killer, Some(OomKiller::SystemdOomd));
1381        // Memory already ≥ 90 % used (available 1 GiB < 1.6 GiB): the swap half decides.
1382        let tight = build(&|_| GIB);
1383        let f = forecast_oom_with(&tight, &oom, Some(total)).unwrap();
1384        assert_eq!(f.killer, Some(OomKiller::SystemdOomd));
1385        assert_eq!(f.target, ForecastTarget::KillerThreshold);
1386        // remaining 7.2 GiB − 5.88 GiB ≈ 1352 MiB at 300 MiB/min ≈ 270 s
1387        assert!((260..=280).contains(&f.eta_s), "eta {}", f.eta_s);
1388        // Swap near the limit already, memory falling towards 10 % available: the memory half decides.
1389        let late = {
1390            let mut h = History::default();
1391            for i in 0..=36u64 {
1392                h.push(HistoryPoint {
1393                    t_ms: i * 5_000,
1394                    swap_used: Some(7 * GIB + 512 * MIB),
1395                    swap_total: Some(8 * GIB),
1396                    available: Some(4 * GIB - i * 50 * MIB),
1397                    ..Default::default()
1398                });
1399            }
1400            h
1401        };
1402        let f = forecast_oom_with(&late, &oom, Some(total)).unwrap();
1403        assert_eq!(f.killer, Some(OomKiller::SystemdOomd));
1404        // 2296 MiB now → 1638.4 MiB (10 % of 16 GiB) at 600 MiB/min ≈ 66 s
1405        assert!((60..=72).contains(&f.eta_s), "eta {}", f.eta_s);
1406        assert!((f.rate_per_min - 600.0 * MIB as f64).abs() < 2.0 * MIB as f64);
1407    }
1408
1409    #[test]
1410    fn stale_series_is_not_forecast_from_its_own_end() {
1411        // Swap data stops 20 s before the newest point: the ETA is shortened by those 20 s.
1412        let mut h = hist(|i| 4 * GIB + i * 400 * MIB / 12);
1413        let fresh = forecast_oom(&h, &Oom::default()).unwrap().eta_s;
1414        let mut g = History::default();
1415        for p in h.iter() {
1416            g.push(p.clone());
1417        }
1418        for k in 1..=4u64 {
1419            g.push(HistoryPoint {
1420                t_ms: 300_000 + k * 5_000,
1421                available: Some(4 * GIB),
1422                ..Default::default()
1423            });
1424        }
1425        let f = forecast_oom(&g, &Oom::default()).unwrap();
1426        assert_eq!(f.target, ForecastTarget::SwapExhaustion);
1427        assert!(
1428            (fresh - 22..=fresh - 18).contains(&f.eta_s),
1429            "{} vs {fresh}",
1430            f.eta_s
1431        );
1432        // Stale for more than 30 s → no forecast from that metric.
1433        for k in 5..=12u64 {
1434            h.push(HistoryPoint {
1435                t_ms: 300_000 + k * 5_000,
1436                available: Some(4 * GIB),
1437                ..Default::default()
1438            });
1439        }
1440        let mut stale = History::default();
1441        for p in g.iter().chain(h.iter().filter(|p| p.t_ms > 320_000)) {
1442            stale.push(p.clone());
1443        }
1444        assert!(forecast_oom(&stale, &Oom::default()).is_none());
1445    }
1446
1447    #[test]
1448    fn ips_timestamp_never_panics_on_odd_timezones() {
1449        for tz in ["+1é1", "+é12", "+12345", "+ab12", "Z", "", "+"] {
1450            let s = format!("2026-09-29 12:10:10.00 {tz}");
1451            let _ = parse_ips_timestamp_ms(&s);
1452        }
1453        assert_eq!(parse_ips_timestamp_ms("2026-09-29 12:10:10.00 +1é1"), None);
1454    }
1455
1456    #[test]
1457    fn earlyoom_argv_forms() {
1458        let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1459        let c =
1460            parse_earlyoom_argv(&v(&["/usr/bin/earlyoom", "-r", "3600", "-m", "4,2", "-s", "20"])).unwrap();
1461        assert_eq!((c.mem_term_pct, c.mem_kill_pct), (4.0, 2.0));
1462        assert_eq!((c.swap_term_pct, c.swap_kill_pct), (20.0, 10.0));
1463        let c = parse_earlyoom_argv(&v(&["-m5", "-M", "1048576", "--prefer", "-m 1", "-n"])).unwrap();
1464        assert_eq!(c.mem_term_pct, 5.0);
1465        assert_eq!(c.mem_term_kib, Some(1_048_576));
1466        let d = parse_earlyoom_argv(&v(&["earlyoom"])).unwrap();
1467        assert_eq!(d, EarlyoomConfig::default());
1468        assert!(parse_earlyoom_argv(&v(&["-m"])).is_err());
1469        assert!(parse_earlyoom_argv(&v(&["-m", "x"])).is_err());
1470        assert!(parse_earlyoom_argv(&v(&["-s", "150"])).is_err());
1471        // -M lower than -m wins.
1472        let th = earlyoom_thresholds(&c, Some(64 * GIB), Some(0));
1473        assert_eq!(th.len(), 1);
1474        assert_eq!(th[0].value, GIB as f64);
1475        let th = earlyoom_thresholds(&EarlyoomConfig::default(), None, None);
1476        assert_eq!(th[0].metric, ThresholdMetric::AvailablePct);
1477        assert_eq!(th[1].value, 90.0);
1478    }
1479
1480    #[test]
1481    fn oomd_config_parsing() {
1482        let main = "[OOM]\n#SwapUsedLimit=90%\nDefaultMemoryPressureLimit=50%\n";
1483        let dropin = "[OOM]\nSwapUsedLimit=80%\nDefaultMemoryPressureDurationSec=1min\nBogus=1\n";
1484        let c = parse_oomd_conf(&[
1485            ("/etc/systemd/oomd.conf", main),
1486            ("oomd.conf.d/10-x.conf", dropin),
1487        ]);
1488        assert_eq!(c.swap_used_limit_pct, 80.0);
1489        assert_eq!(c.mem_pressure_limit_pct, 50.0);
1490        assert_eq!(c.mem_pressure_duration_s, 60);
1491        assert_eq!(c.source, "oomd.conf.d/10-x.conf");
1492        let d = parse_oomd_conf(&[("x", "[OOM]\nSwapUsedLimit=lots\n")]);
1493        assert_eq!(d.swap_used_limit_pct, 90.0);
1494
1495        let slice = parse_managed_oom(
1496            "user@1000.service",
1497            "[Service]\nManagedOOMMemoryPressure=kill\nManagedOOMMemoryPressureLimit=40%\n",
1498        );
1499        let root = parse_managed_oom("-.slice", "ManagedOOMSwap=kill\n");
1500        let th = oomd_thresholds(&OomdConfig::default(), &[slice, root]);
1501        assert_eq!(th.len(), 2);
1502        assert_eq!(th[0].metric, ThresholdMetric::SwapUsedPct);
1503        assert_eq!(th[1].value, 40.0);
1504        assert_eq!(th[1].duration_s, Some(30));
1505        let defaults = oomd_thresholds(&OomdConfig::default(), &[]);
1506        assert_eq!(defaults.len(), 2);
1507        let none = oomd_thresholds(&OomdConfig::default(), &[ManagedOom::default()]);
1508        assert!(none.is_empty());
1509    }
1510
1511    #[test]
1512    fn setup_per_os() {
1513        let mac = oom_setup(&OomInputs {
1514            os: OsKind::Macos,
1515            ..Default::default()
1516        });
1517        assert_eq!(mac.killers, vec![OomKiller::Jetsam]);
1518        let linux = oom_setup(&OomInputs {
1519            os: OsKind::Linux,
1520            ..Default::default()
1521        });
1522        assert_eq!(linux.killers, vec![OomKiller::Kernel]);
1523        assert!(linux.thresholds.is_empty());
1524    }
1525
1526    #[test]
1527    fn memory_events() {
1528        let e = parse_memory_events(
1529            "low 0\nhigh 12\nmax 3\noom 2\noom_kill 2\noom_group_kill 0\nnew_key 9\nbad\n",
1530        );
1531        assert_eq!(e.oom_kill, 2);
1532        assert_eq!(e.high, 12);
1533        let later = MemoryEvents { oom_kill: 5, ..e };
1534        assert_eq!(oom_kills_since(&e, &later), 3);
1535        assert_eq!(oom_kills_since(&later, &e), 0);
1536    }
1537
1538    #[test]
1539    fn ips_timestamps_and_jetsam() {
1540        assert_eq!(parse_ips_timestamp_ms("1970-01-01 00:00:00.00 +0000"), Some(0));
1541        assert_eq!(parse_ips_timestamp_ms("1970-01-01 01:00:00.50 +0100"), Some(500));
1542        // 2026-09-29 10:10:10 UTC = 1790676610
1543        assert_eq!(
1544            parse_ips_timestamp_ms("2026-09-29 12:10:10.00 +0200"),
1545            Some(1_790_676_610_000)
1546        );
1547        assert_eq!(parse_ips_timestamp_ms("garbage"), None);
1548        assert_eq!(parse_ips_timestamp_ms("2026-13-01 00:00:00 +0000"), None);
1549        let ips = r#"{"bug_type":"298","timestamp":"2026-09-29 12:10:10.00 +0200","os_version":"macOS 26.6"}
1550{"date":"2026-09-29 12:10:09.50 +0200","largestProcess":"java","processes":[{"name":"java","pid":78921,"reason":"vm-pageshortage","rpages":200000},{"name":"Finder","pid":400,"rpages":1000}]}"#;
1551        let kills = parse_jetsam_event(ips, "JetsamEvent-2026-09-29-121010.ips");
1552        assert_eq!(kills.len(), 1);
1553        assert_eq!(kills[0].victim_name.as_deref(), Some("java"));
1554        assert_eq!(kills[0].victim_pid, Some(78921));
1555        assert_eq!(kills[0].at_ms, Some(1_790_676_609_500));
1556        assert!(kills[0].source.contains("vm-pageshortage"));
1557        assert!(parse_jetsam_event("not json", "x").is_empty());
1558    }
1559}