Skip to main content

oomtop_core/
limits.rs

1//! Per-limit OOM forecast (SPEC §8.3 "Per-limit forecast"): every container, pod, cgroup or engine VM that
2//! has a memory limit gets usage, limit, percent, growth, an ETA with confidence and its OOM kills.
3//!
4//! The math is the host forecast's ([`crate::forecast::eta_to_threshold`]): the same windows (2–5 min,
5//! earliest qualifying ETA wins), the same honesty rules (R² ≥ 0.6, ≥ 8 points over ≥ 2 min, both halves
6//! trending the same way, no single step over half of the change, ETA < 30 min) — so a one-off step such
7//! as a container warming its cache never raises an alarm. Usage is the **working set** (`memory.current −
8//! inactive_file`, what `docker stats` and the kubelet report): the kernel reclaims inactive page cache
9//! before it OOM-kills, so counting it would forecast kills that never happen.
10//!
11//! [`LimitTracker`] is the only state: per limit id, the observed `(time, usage)` points (each reading once:
12//! a cached engine reading repeated by later samples is not a new point) and the OOM-kill counter baseline.
13//! It is pure (no I/O); the engine owns one and feeds it every snapshot.
14
15use crate::forecast::{
16    eta_to_threshold, linear_fit, MemoryEvents, MAX_STALE_S, WINDOWS_MS, WINDOW_MS, WINDOW_SLACK_MS,
17};
18use crate::model::Measured;
19use crate::units::{format_bytes, format_duration, UnitSystem};
20use serde::{Deserialize, Serialize};
21use std::collections::{BTreeMap, VecDeque};
22
23/// Usage at or above this share of the limit is "near".
24pub const NEAR_PCT: f64 = 90.0;
25/// Usage at or above this share of the limit is "at the limit".
26pub const AT_LIMIT_PCT: f64 = 99.0;
27/// Points kept per limit (newest), and how long a limit that stopped reporting is remembered.
28pub const MAX_POINTS: usize = 400;
29pub const RETENTION_MS: u64 = WINDOW_MS + 2 * WINDOW_SLACK_MS;
30/// A growth rate needs at least this many points over at least this span.
31pub const TREND_MIN_POINTS: usize = 3;
32pub const TREND_MIN_SPAN_S: f64 = 30.0;
33
34/// cgroup v2 memory accounting of one cgroup (Linux; `/sys/fs/cgroup/<path>/memory.*`, all world-readable).
35/// Decoded from the process source for container / pod cgroups and every cgroup with a limit (SPEC §11).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
37#[serde(default)]
38pub struct CgroupMem {
39    /// cgroup path relative to the v2 root (`/kubepods.slice/…`).
40    pub path: String,
41    /// `memory.current`.
42    pub current: Option<u64>,
43    /// `memory.max`; `None` = `max` (no limit) or not read (`limits_read` says which).
44    pub max: Option<u64>,
45    /// `memory.high` (the throttle point: the kernel reclaims hard above it but does not kill).
46    pub high: Option<u64>,
47    /// `memory.max` / `memory.high` were read (absent files mean the memory controller is off here).
48    pub limits_read: bool,
49    /// `memory.peak` (kernel ≥ 5.19).
50    pub peak: Option<u64>,
51    /// `memory.swap.current`.
52    pub swap_current: Option<u64>,
53    /// `memory.stat` `inactive_file` / `anon` / `file`.
54    pub inactive_file: Option<u64>,
55    pub anon: Option<u64>,
56    pub file: Option<u64>,
57    /// `memory.events` (counters since the cgroup was created; `oom_kill` = kernel OOM kills inside it).
58    pub events: Option<MemoryEvents>,
59    /// When the values were read (ms since the epoch).
60    pub at_ms: u64,
61}
62
63impl CgroupMem {
64    /// `memory.current − inactive_file` (what the kubelet and `docker stats` call the working set).
65    pub fn working_set(&self) -> Option<u64> {
66        let cur = self.current?;
67        Some(cur.saturating_sub(self.inactive_file.unwrap_or(0)))
68    }
69
70    /// The working set with its source (an estimate when `memory.stat` was not read).
71    pub fn working_set_measured(&self) -> Measured<u64> {
72        match (self.current, self.inactive_file) {
73            (Some(c), Some(i)) => Measured::exact(
74                c.saturating_sub(i),
75                "cgroup memory.current − memory.stat:inactive_file",
76            ),
77            (Some(c), None) => Measured::estimate(c, "cgroup memory.current (page cache included)"),
78            _ => Measured::unavailable("cgroup memory.current", "not read"),
79        }
80    }
81
82    /// The tightest limit set on this cgroup: `memory.max`, else `memory.high`.
83    pub fn has_limit(&self) -> bool {
84        self.max.is_some() || self.high.is_some()
85    }
86}
87
88/// What carries the limit.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
90#[serde(rename_all = "snake_case")]
91pub enum LimitKind {
92    /// A container (engine limit or its cgroup).
93    #[default]
94    Container,
95    /// A Kubernetes pod-level cgroup (sum of its containers' limits).
96    Pod,
97    /// Any other cgroup with `memory.max` / `memory.high` (a systemd unit with `MemoryMax=`, a
98    /// `systemd-run -p MemoryMax=` sandbox, a kubelet QoS slice).
99    Cgroup,
100    /// An engine VM (Docker Desktop, OrbStack, Colima…): Σ container memory against the VM's memory.
101    Vm,
102}
103
104impl LimitKind {
105    pub fn word(self) -> &'static str {
106        match self {
107            LimitKind::Container => "container",
108            LimitKind::Pod => "pod",
109            LimitKind::Cgroup => "cgroup",
110            LimitKind::Vm => "VM",
111        }
112    }
113}
114
115/// Which limit the forecast runs against.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
117#[serde(rename_all = "snake_case")]
118pub enum LimitTarget {
119    /// `memory.max` / the engine's hard limit: the kernel OOM-kills inside the cgroup.
120    #[default]
121    Max,
122    /// `memory.high` only: throttled and reclaimed hard, never killed by it.
123    High,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
127#[serde(rename_all = "snake_case")]
128pub enum LimitState {
129    /// Usage unknown.
130    #[default]
131    Unknown,
132    Ok,
133    /// ≥ [`NEAR_PCT`] of the limit.
134    Near,
135    /// ≥ [`AT_LIMIT_PCT`] of the limit, or the cgroup hit `memory.max` since the last reading.
136    AtLimit,
137}
138
139/// ETA to the limit. Present only under the host forecast's honesty rules (module docs).
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
141#[serde(default)]
142pub struct LimitForecast {
143    pub target: LimitTarget,
144    /// Seconds from the newest reading.
145    pub eta_s: u64,
146    /// 0..1, the R² of the fit.
147    pub confidence: f64,
148    /// Growth in bytes per minute.
149    pub rate_per_min: f64,
150    /// Fit window, seconds.
151    pub window_s: u64,
152}
153
154/// One limit and how close it is (SPEC §8.3). `summary` is in IEC units; [`LimitStatus::sentence`]
155/// re-renders it in the caller's units.
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
157#[serde(default)]
158pub struct LimitStatus {
159    /// Stable id: `cgroup:<path>`, a sandbox id (`docker:<12 hex>`), `k8s:<ns>/<pod>/<container>`.
160    pub id: String,
161    pub kind: LimitKind,
162    /// Container / pod / unit name.
163    pub label: String,
164    /// Engine or cluster runtime ("docker", "orbstack", "kubernetes", "systemd").
165    pub runtime: Option<String>,
166    /// [`crate::model::Sandbox::id`] of the container or VM, when there is one.
167    pub sandbox_id: Option<String>,
168    /// cgroup path, when the numbers come from cgroup files.
169    pub cgroup: Option<String>,
170    /// `namespace/pod` for Kubernetes containers and pods.
171    pub pod: Option<String>,
172    /// Working set (see module docs).
173    pub usage: Measured<u64>,
174    /// The limit the percent and forecast use (`memory.max`, else `memory.high`; engine limit; VM size).
175    pub limit: Measured<u64>,
176    pub target: LimitTarget,
177    /// `memory.high` when set below `memory.max`.
178    pub high: Option<u64>,
179    /// Highest usage the kernel recorded (`memory.peak`), when readable.
180    pub peak: Measured<u64>,
181    /// usage ÷ limit × 100.
182    pub pct: Option<f64>,
183    /// Growth over the last ≤ 5 min (bytes/min, an estimate; may be noise — the forecast is the
184    /// trustworthy signal).
185    pub growth_per_min: Measured<f64>,
186    pub forecast: Option<LimitForecast>,
187    pub state: LimitState,
188    /// Kernel OOM kills inside the cgroup since it was created (`memory.events:oom_kill`).
189    pub oom_kills: Measured<u64>,
190    /// OOM kills that happened while oomtop was watching.
191    pub oom_kills_observed: u64,
192    /// When the newest observed OOM kill was noticed (ms since the epoch).
193    pub last_oom_kill_ms: Option<u64>,
194    /// The container's previous run ended in an OOM kill (Docker `State.OOMKilled`, Kubernetes
195    /// `lastState.terminated.reason = OOMKilled`).
196    pub oom_killed_last_exit: Option<bool>,
197    /// Restarts (Docker `RestartCount`, Kubernetes `restartCount`).
198    pub restarts: Option<u32>,
199    /// "container `web` hits its 2.0 GiB limit in ~4 min" (IEC units).
200    pub summary: String,
201}
202
203impl LimitStatus {
204    /// The one-line answer in the caller's units.
205    pub fn sentence(&self, units: UnitSystem, decimals: usize) -> String {
206        let b = |v: u64| format_bytes(v, units, decimals);
207        let what = format!("{} `{}`", self.kind.word(), self.label);
208        let limit_word = match self.target {
209            LimitTarget::Max => "limit",
210            LimitTarget::High => "memory.high",
211        };
212        let Some(limit) = self.limit.value else {
213            return format!("{what}: limit unknown");
214        };
215        let mut out = if let Some(f) = &self.forecast {
216            format!(
217                "{what} hits its {} {limit_word} in ~{} (+{}/min, R² {:.2})",
218                b(limit),
219                format_eta(f.eta_s),
220                b(f.rate_per_min.max(0.0) as u64),
221                f.confidence
222            )
223        } else {
224            match (self.usage.value, self.state) {
225                (Some(u), LimitState::AtLimit) => {
226                    format!("{what} is at its {} {limit_word} ({} used)", b(limit), b(u))
227                }
228                (Some(u), _) => format!(
229                    "{what} uses {} of {} ({}){}",
230                    b(u),
231                    b(limit),
232                    self.pct
233                        .map(|p| format!("{p:.0}%"))
234                        .unwrap_or_else(|| "n/a".into()),
235                    if self.state == LimitState::Near {
236                        ", near its limit"
237                    } else {
238                        ""
239                    }
240                ),
241                (None, _) => format!("{what}: {} {limit_word}, usage unknown", b(limit)),
242            }
243        };
244        if self.oom_kills_observed > 0 {
245            out.push_str(&format!(
246                "; OOM-killed {}× while watched",
247                self.oom_kills_observed
248            ));
249        } else if let Some(k) = self.oom_kills.value.filter(|k| *k > 0) {
250            out.push_str(&format!("; {k} OOM kill(s) since it started"));
251        }
252        if self.oom_killed_last_exit == Some(true) {
253            out.push_str("; its last run ended in an OOM kill");
254        }
255        out
256    }
257}
258
259/// "4 min" / "45 s" / "1h5m" for an ETA.
260pub fn format_eta(eta_s: u64) -> String {
261    if eta_s < 60 {
262        format!("{eta_s} s")
263    } else if eta_s < 3600 {
264        format!("{} min", (eta_s + 30) / 60)
265    } else {
266        format_duration(eta_s)
267    }
268}
269
270/// What a frontend or the engine knows about one limit at one moment (input to [`evaluate`]).
271#[derive(Debug, Clone, PartialEq, Default)]
272pub struct LimitInput {
273    pub id: String,
274    pub kind: LimitKind,
275    pub label: String,
276    pub runtime: Option<String>,
277    pub sandbox_id: Option<String>,
278    pub cgroup: Option<String>,
279    pub pod: Option<String>,
280    pub usage: Measured<u64>,
281    /// When `usage` was read; `None` = not a fresh reading (carried over) → not added to the trend.
282    pub read_at_ms: Option<u64>,
283    pub limit: Measured<u64>,
284    pub target: LimitTarget,
285    pub high: Option<u64>,
286    pub peak: Measured<u64>,
287    pub events: Option<MemoryEvents>,
288    pub oom_killed_last_exit: Option<bool>,
289    pub restarts: Option<u32>,
290}
291
292#[derive(Debug, Clone, Default)]
293struct Series {
294    /// (read time ms, usage bytes), oldest first.
295    points: VecDeque<(u64, u64)>,
296    /// `memory.events` at the first and newest reading.
297    events_first: Option<MemoryEvents>,
298    events_last: Option<MemoryEvents>,
299    /// `memory.events:max` moved at the newest reading.
300    hit_max_now: bool,
301    last_kill_ms: Option<u64>,
302    last_seen_ms: u64,
303}
304
305/// Per-limit history (module docs). One per engine; pure.
306#[derive(Debug, Clone, Default)]
307pub struct LimitTracker {
308    series: BTreeMap<String, Series>,
309}
310
311impl LimitTracker {
312    pub fn new() -> Self {
313        Self::default()
314    }
315
316    /// Records one reading. A reading not newer than the newest point of `id` (a cached value repeated by a
317    /// later snapshot) is ignored; counters are compared with the previous reading.
318    pub fn observe(&mut self, id: &str, at_ms: u64, usage: Option<u64>, events: Option<MemoryEvents>) {
319        let s = self.series.entry(id.to_string()).or_default();
320        s.last_seen_ms = s.last_seen_ms.max(at_ms);
321        if let Some(e) = events {
322            let prev = s.events_last;
323            s.hit_max_now = prev.is_some_and(|p| e.max > p.max);
324            if prev.is_some_and(|p| e.oom_kill > p.oom_kill) {
325                s.last_kill_ms = Some(at_ms);
326            }
327            // A counter that went backwards is a new cgroup under the same path: restart the baseline.
328            if prev.is_none_or(|p| e.oom_kill < p.oom_kill || e.max < p.max) {
329                s.events_first = Some(e);
330            }
331            s.events_last = Some(e);
332        }
333        let Some(u) = usage else { return };
334        if s.points.back().is_some_and(|(t, _)| at_ms <= *t) {
335            return;
336        }
337        s.points.push_back((at_ms, u));
338        while s.points.len() > MAX_POINTS
339            || s.points
340                .front()
341                .is_some_and(|(t, _)| at_ms.saturating_sub(*t) > RETENTION_MS)
342        {
343            s.points.pop_front();
344        }
345    }
346
347    /// Forgets limits not seen for [`RETENTION_MS`].
348    pub fn gc(&mut self, now_ms: u64) {
349        self.series
350            .retain(|_, s| now_ms.saturating_sub(s.last_seen_ms) <= RETENTION_MS);
351    }
352
353    pub fn len(&self) -> usize {
354        self.series.len()
355    }
356
357    pub fn is_empty(&self) -> bool {
358        self.series.is_empty()
359    }
360
361    /// Points of `id` (oldest first), for tests and sparklines.
362    pub fn points(&self, id: &str) -> Vec<(u64, u64)> {
363        self.series
364            .get(id)
365            .map(|s| s.points.iter().copied().collect())
366            .unwrap_or_default()
367    }
368
369    /// OOM kills observed while watching and when the newest was noticed.
370    pub fn kills(&self, id: &str) -> (u64, Option<u64>) {
371        let Some(s) = self.series.get(id) else {
372            return (0, None);
373        };
374        let n = match (s.events_first, s.events_last) {
375            (Some(a), Some(b)) => b.oom_kill.saturating_sub(a.oom_kill),
376            _ => 0,
377        };
378        (n, s.last_kill_ms)
379    }
380
381    /// Growth rate (bytes/min) over the newest ≤ 5 min: an estimate, without the forecast's consistency
382    /// guards (for an arrow next to a gauge).
383    pub fn growth_per_min(&self, id: &str) -> Measured<f64> {
384        let src = "linear fit of the working set over the last ≤ 5 min";
385        let Some(s) = self.series.get(id) else {
386            return Measured::unavailable(src, "no readings yet");
387        };
388        let Some(&(t_last, _)) = s.points.back() else {
389            return Measured::unavailable(src, "no readings yet");
390        };
391        let pts: Vec<(f64, f64)> = s
392            .points
393            .iter()
394            .filter(|(t, _)| t_last - t <= WINDOW_MS)
395            .map(|(t, u)| ((*t as f64) / 1000.0, *u as f64))
396            .collect();
397        let span = pts.last().map(|p| p.0).unwrap_or(0.0) - pts.first().map(|p| p.0).unwrap_or(0.0);
398        if pts.len() < TREND_MIN_POINTS || span < TREND_MIN_SPAN_S {
399            return Measured::unavailable(src, "needs ≥ 3 readings over ≥ 30 s");
400        }
401        match linear_fit(&pts) {
402            Some(f) => Measured::estimate(f.slope * 60.0, src),
403            None => Measured::unavailable(src, "no fit"),
404        }
405    }
406
407    /// ETA of `id` to `limit` bytes, under the host forecast's rules (module docs). `now_ms` is the
408    /// snapshot time: a series whose newest reading is older than [`MAX_STALE_S`] is not forecast, and a
409    /// slightly stale one has its ETA measured from now.
410    pub fn forecast(&self, id: &str, limit: u64, target: LimitTarget, now_ms: u64) -> Option<LimitForecast> {
411        let s = self.series.get(id)?;
412        let &(t_last, _) = s.points.back()?;
413        let stale_s = now_ms.saturating_sub(t_last) as f64 / 1000.0;
414        if stale_s > MAX_STALE_S {
415            return None;
416        }
417        WINDOWS_MS
418            .iter()
419            .filter_map(|w| {
420                let cutoff = t_last.saturating_sub(*w);
421                // The newest point at or before the cutoff completes the window when it is close enough
422                // (same rule as `forecast::window_reaching`).
423                let first = s
424                    .points
425                    .iter()
426                    .map(|(t, _)| *t)
427                    .take_while(|t| *t <= cutoff)
428                    .last()
429                    .filter(|t| cutoff - *t <= WINDOW_SLACK_MS)
430                    .unwrap_or(cutoff);
431                let pts: Vec<(f64, f64)> = s
432                    .points
433                    .iter()
434                    .filter(|(t, _)| *t >= first)
435                    .map(|(t, u)| ((t - first) as f64 / 1000.0, *u as f64))
436                    .collect();
437                let (eta, fit) = eta_to_threshold(&pts, limit as f64, true)?;
438                let eta = eta - stale_s;
439                (eta > 0.0).then(|| LimitForecast {
440                    target,
441                    eta_s: eta.round() as u64,
442                    confidence: fit.r2,
443                    rate_per_min: fit.slope * 60.0,
444                    window_s: fit.span_s.round() as u64,
445                })
446            })
447            .min_by_key(|f| f.eta_s)
448    }
449
450    fn hit_max_now(&self, id: &str) -> bool {
451        self.series.get(id).is_some_and(|s| s.hit_max_now)
452    }
453}
454
455/// Feeds `inputs` into `tracker` and returns their status, most urgent first (forecast ETA, then percent).
456pub fn evaluate(tracker: &mut LimitTracker, inputs: Vec<LimitInput>, now_ms: u64) -> Vec<LimitStatus> {
457    let mut out = Vec::with_capacity(inputs.len());
458    for i in inputs {
459        let fresh = i.read_at_ms.filter(|_| i.usage.is_available());
460        match fresh {
461            Some(at) => tracker.observe(&i.id, at, i.usage.value, i.events),
462            None => {
463                if let Some(e) = i.events {
464                    tracker.observe(&i.id, now_ms, None, Some(e));
465                }
466            }
467        }
468        let pct = match (i.usage.value, i.limit.value) {
469            (Some(u), Some(l)) if l > 0 => Some(u as f64 / l as f64 * 100.0),
470            _ => None,
471        };
472        let state = match pct {
473            None => LimitState::Unknown,
474            Some(_) if tracker.hit_max_now(&i.id) && i.target == LimitTarget::Max => LimitState::AtLimit,
475            Some(p) if p >= AT_LIMIT_PCT => LimitState::AtLimit,
476            Some(p) if p >= NEAR_PCT => LimitState::Near,
477            Some(_) => LimitState::Ok,
478        };
479        let forecast = match (i.limit.value, state) {
480            (Some(l), LimitState::Ok | LimitState::Near) => tracker.forecast(&i.id, l, i.target, now_ms),
481            _ => None,
482        };
483        let (observed, last_kill) = tracker.kills(&i.id);
484        let mut st = LimitStatus {
485            growth_per_min: tracker.growth_per_min(&i.id),
486            oom_kills: match &i.events {
487                Some(e) => Measured::exact(e.oom_kill, "cgroup memory.events:oom_kill"),
488                None => Measured::unavailable(
489                    i.runtime.clone().unwrap_or_default(),
490                    "no kill counter (not a readable cgroup)",
491                ),
492            },
493            oom_kills_observed: observed,
494            last_oom_kill_ms: last_kill,
495            id: i.id,
496            kind: i.kind,
497            label: i.label,
498            runtime: i.runtime,
499            sandbox_id: i.sandbox_id,
500            cgroup: i.cgroup,
501            pod: i.pod,
502            usage: i.usage,
503            limit: i.limit,
504            target: i.target,
505            high: i.high,
506            peak: i.peak,
507            pct,
508            forecast,
509            state,
510            oom_killed_last_exit: i.oom_killed_last_exit,
511            restarts: i.restarts,
512            summary: String::new(),
513        };
514        st.summary = st.sentence(UnitSystem::Iec, 1);
515        out.push(st);
516    }
517    tracker.gc(now_ms);
518    out.sort_by(|a, b| {
519        let eta = |s: &LimitStatus| s.forecast.as_ref().map_or(u64::MAX, |f| f.eta_s);
520        b.state
521            .cmp(&a.state)
522            .then(eta(a).cmp(&eta(b)))
523            .then(
524                b.pct
525                    .unwrap_or(-1.0)
526                    .partial_cmp(&a.pct.unwrap_or(-1.0))
527                    .unwrap_or(std::cmp::Ordering::Equal),
528            )
529            .then(a.id.cmp(&b.id))
530    });
531    out
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537    use crate::model::Quality;
538
539    const MIB: u64 = 1 << 20;
540    const GIB: u64 = 1 << 30;
541
542    fn input(id: &str, at: u64, usage: u64, limit: u64) -> LimitInput {
543        LimitInput {
544            id: id.into(),
545            kind: LimitKind::Container,
546            label: "web".into(),
547            runtime: Some("docker".into()),
548            usage: Measured::exact(usage, "t"),
549            read_at_ms: Some(at),
550            limit: Measured::exact(limit, "t"),
551            ..Default::default()
552        }
553    }
554
555    /// Feeds `(t_s, usage)` rows (one reading each) and returns the last status.
556    fn run(rows: &[(u64, u64)], limit: u64) -> LimitStatus {
557        let mut tr = LimitTracker::new();
558        let mut last = None;
559        for (t, u) in rows {
560            let now = 1_000_000 + t * 1000;
561            last = evaluate(&mut tr, vec![input("c", now, *u, limit)], now).pop();
562        }
563        last.unwrap()
564    }
565
566    fn ramp(n: u64, step_s: u64, start: u64, per_step: u64) -> Vec<(u64, u64)> {
567        (0..n).map(|i| (i * step_s, start + i * per_step)).collect()
568    }
569
570    /// Trend table: steady growth, flat, noise, a one-off step, a reversal, too little data, far away.
571    /// name, rows (t_ms, bytes), expected ETA range in seconds (or None).
572    type TrendCase = (&'static str, Vec<(u64, u64)>, Option<(u64, u64)>);
573
574    #[test]
575    fn trend_table() {
576        let limit = 2 * GIB;
577        let cases: Vec<TrendCase> = vec![
578            // +10 MiB every 10 s = 60 MiB/min; 3 min of data; at 1.5 GiB + 180 MiB … ETA ≈ (2048-1716)/60 min
579            (
580                "steady growth",
581                ramp(19, 10, 1536 * MIB, 10 * MIB),
582                Some((300, 360)),
583            ),
584            ("flat", ramp(30, 10, GIB, 0), None),
585            (
586                "noise around a level",
587                (0..30)
588                    .map(|i| (i * 10, GIB + if i % 2 == 0 { 50 * MIB } else { 0 }))
589                    .collect(),
590                None,
591            ),
592            (
593                "one-off step (cache warm-up)",
594                (0..30)
595                    .map(|i| (i * 10, if i < 15 { GIB } else { GIB + 700 * MIB }))
596                    .collect(),
597                None,
598            ),
599            (
600                "growth then a drop (OOM kill / restart)",
601                (0..30)
602                    .map(|i| (i * 10, if i < 28 { GIB + i * 20 * MIB } else { 300 * MIB }))
603                    .collect(),
604                None,
605            ),
606            ("too short (60 s)", ramp(7, 10, 1536 * MIB, 10 * MIB), None),
607            ("too slow (ETA > 30 min)", ramp(30, 10, GIB, MIB), None),
608        ];
609        for (name, rows, want) in cases {
610            let st = run(&rows, limit);
611            match (want, &st.forecast) {
612                (None, None) => {}
613                (Some((lo, hi)), Some(f)) => {
614                    assert!(
615                        (lo..=hi).contains(&f.eta_s),
616                        "{name}: eta {} not in {lo}..{hi}",
617                        f.eta_s
618                    );
619                    assert!(f.confidence >= 0.6, "{name}");
620                    assert!((f.rate_per_min - 60.0 * MIB as f64).abs() < MIB as f64, "{name}");
621                }
622                (w, f) => panic!("{name}: want {w:?}, got {f:?}"),
623            }
624        }
625    }
626
627    #[test]
628    fn sentence_and_state() {
629        let st = run(&ramp(19, 10, 1536 * MIB, 10 * MIB), 2 * GIB);
630        assert!(
631            st.summary
632                .starts_with("container `web` hits its 2.0 GiB limit in ~"),
633            "{}",
634            st.summary
635        );
636        assert!(
637            st.summary.contains("min (+60.0 MiB/min, R² 1.00)"),
638            "{}",
639            st.summary
640        );
641        assert_eq!(st.state, LimitState::Ok);
642        assert!(st.growth_per_min.value.unwrap() > 59.0 * MIB as f64);
643        // Near and at the limit; no forecast at the limit (it is already there).
644        let st = run(&[(0, 1900 * MIB)], 2 * GIB);
645        assert_eq!(st.state, LimitState::Near);
646        assert_eq!(
647            st.summary,
648            "container `web` uses 1.9 GiB of 2.0 GiB (93%), near its limit"
649        );
650        let st = run(&[(0, 2 * GIB - MIB)], 2 * GIB);
651        assert_eq!(st.state, LimitState::AtLimit);
652        assert_eq!(
653            st.summary,
654            "container `web` is at its 2.0 GiB limit (2.0 GiB used)"
655        );
656        // SI rendering for a frontend configured that way.
657        assert!(st.sentence(UnitSystem::Si, 1).contains("2.1 GB limit"));
658    }
659
660    #[test]
661    fn repeated_cached_readings_are_one_point_and_kills_are_counted() {
662        let mut tr = LimitTracker::new();
663        let ev = |kill: u64, max: u64| MemoryEvents {
664            oom_kill: kill,
665            max,
666            ..Default::default()
667        };
668        let mut i = input("c", 1000, 100, 1000);
669        i.events = Some(ev(2, 5));
670        evaluate(&mut tr, vec![i.clone()], 1000);
671        // Same reading seen by the next snapshot (engine cache): not a new point.
672        evaluate(&mut tr, vec![i.clone()], 3000);
673        assert_eq!(tr.points("c").len(), 1);
674        i.read_at_ms = Some(11_000);
675        i.events = Some(ev(3, 9));
676        let st = evaluate(&mut tr, vec![i.clone()], 11_000).pop().unwrap();
677        assert_eq!(tr.points("c").len(), 2);
678        assert_eq!(st.oom_kills.value, Some(3));
679        assert_eq!(st.oom_kills_observed, 1);
680        assert_eq!(st.last_oom_kill_ms, Some(11_000));
681        assert_eq!(st.state, LimitState::AtLimit, "memory.events:max moved");
682        assert!(
683            st.summary.contains("OOM-killed 1× while watched"),
684            "{}",
685            st.summary
686        );
687        // A counter reset (new cgroup at the same path) restarts the baseline.
688        i.read_at_ms = Some(21_000);
689        i.events = Some(ev(0, 0));
690        let st = evaluate(&mut tr, vec![i], 21_000).pop().unwrap();
691        assert_eq!(st.oom_kills_observed, 0);
692        assert_eq!(st.state, LimitState::Ok);
693    }
694
695    #[test]
696    fn stale_series_and_unknown_usage_are_not_forecast() {
697        let mut tr = LimitTracker::new();
698        for (t, u) in ramp(19, 10, 1536 * MIB, 10 * MIB) {
699            tr.observe("c", t * 1000, Some(u), None);
700        }
701        assert!(tr.forecast("c", 2 * GIB, LimitTarget::Max, 180_000).is_some());
702        assert!(tr
703            .forecast("c", 2 * GIB, LimitTarget::Max, 180_000 + 31_000)
704            .is_none());
705        let mut i = input("d", 1, 0, GIB);
706        i.usage = Measured::unavailable("docker", "stats not read yet");
707        let st = evaluate(&mut tr, vec![i], 1).pop().unwrap();
708        assert_eq!(st.state, LimitState::Unknown);
709        assert_eq!(st.summary, "container `web`: 1.0 GiB limit, usage unknown");
710        // gc drops what stopped reporting
711        tr.gc(10_000_000);
712        assert!(tr.is_empty());
713    }
714
715    #[test]
716    fn urgency_order() {
717        let mut tr = LimitTracker::new();
718        let mut a = input("a", 1, 100, 1000);
719        a.label = "a".into();
720        let mut b = input("b", 1, 950, 1000);
721        b.label = "b".into();
722        let out = evaluate(&mut tr, vec![a, b], 1);
723        assert_eq!(out[0].id, "b");
724    }
725
726    #[test]
727    fn working_set() {
728        let c = CgroupMem {
729            current: Some(1000),
730            inactive_file: Some(300),
731            ..Default::default()
732        };
733        assert_eq!(c.working_set(), Some(700));
734        assert_eq!(c.working_set_measured().quality, Quality::Exact);
735        let c = CgroupMem {
736            current: Some(1000),
737            ..Default::default()
738        };
739        assert_eq!(c.working_set_measured().quality, Quality::Estimate);
740        assert!(!c.has_limit());
741        assert_eq!(format_eta(240), "4 min");
742        assert_eq!(format_eta(45), "45 s");
743    }
744}