oomtop-core 0.2.1

oomtop core: pure data model, units, attribution, headroom, forecast, throttle, query and ranking logic (no I/O)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Per-limit OOM forecast (SPEC §8.3 "Per-limit forecast"): every container, pod, cgroup or engine VM that
//! has a memory limit gets usage, limit, percent, growth, an ETA with confidence and its OOM kills.
//!
//! The math is the host forecast's ([`crate::forecast::eta_to_threshold`]): the same windows (2–5 min,
//! earliest qualifying ETA wins), the same honesty rules (R² ≥ 0.6, ≥ 8 points over ≥ 2 min, both halves
//! trending the same way, no single step over half of the change, ETA < 30 min) — so a one-off step such
//! as a container warming its cache never raises an alarm. Usage is the **working set** (`memory.current −
//! inactive_file`, what `docker stats` and the kubelet report): the kernel reclaims inactive page cache
//! before it OOM-kills, so counting it would forecast kills that never happen.
//!
//! [`LimitTracker`] is the only state: per limit id, the observed `(time, usage)` points (each reading once:
//! a cached engine reading repeated by later samples is not a new point) and the OOM-kill counter baseline.
//! It is pure (no I/O); the engine owns one and feeds it every snapshot.

use crate::forecast::{
    eta_to_threshold, linear_fit, MemoryEvents, MAX_STALE_S, WINDOWS_MS, WINDOW_MS, WINDOW_SLACK_MS,
};
use crate::model::Measured;
use crate::units::{format_bytes, format_duration, UnitSystem};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, VecDeque};

/// Usage at or above this share of the limit is "near".
pub const NEAR_PCT: f64 = 90.0;
/// Usage at or above this share of the limit is "at the limit".
pub const AT_LIMIT_PCT: f64 = 99.0;
/// Points kept per limit (newest), and how long a limit that stopped reporting is remembered.
pub const MAX_POINTS: usize = 400;
pub const RETENTION_MS: u64 = WINDOW_MS + 2 * WINDOW_SLACK_MS;
/// A growth rate needs at least this many points over at least this span.
pub const TREND_MIN_POINTS: usize = 3;
pub const TREND_MIN_SPAN_S: f64 = 30.0;

/// cgroup v2 memory accounting of one cgroup (Linux; `/sys/fs/cgroup/<path>/memory.*`, all world-readable).
/// Decoded from the process source for container / pod cgroups and every cgroup with a limit (SPEC §11).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct CgroupMem {
    /// cgroup path relative to the v2 root (`/kubepods.slice/…`).
    pub path: String,
    /// `memory.current`.
    pub current: Option<u64>,
    /// `memory.max`; `None` = `max` (no limit) or not read (`limits_read` says which).
    pub max: Option<u64>,
    /// `memory.high` (the throttle point: the kernel reclaims hard above it but does not kill).
    pub high: Option<u64>,
    /// `memory.max` / `memory.high` were read (absent files mean the memory controller is off here).
    pub limits_read: bool,
    /// `memory.peak` (kernel ≥ 5.19).
    pub peak: Option<u64>,
    /// `memory.swap.current`.
    pub swap_current: Option<u64>,
    /// `memory.stat` `inactive_file` / `anon` / `file`.
    pub inactive_file: Option<u64>,
    pub anon: Option<u64>,
    pub file: Option<u64>,
    /// `memory.events` (counters since the cgroup was created; `oom_kill` = kernel OOM kills inside it).
    pub events: Option<MemoryEvents>,
    /// When the values were read (ms since the epoch).
    pub at_ms: u64,
}

impl CgroupMem {
    /// `memory.current − inactive_file` (what the kubelet and `docker stats` call the working set).
    pub fn working_set(&self) -> Option<u64> {
        let cur = self.current?;
        Some(cur.saturating_sub(self.inactive_file.unwrap_or(0)))
    }

    /// The working set with its source (an estimate when `memory.stat` was not read).
    pub fn working_set_measured(&self) -> Measured<u64> {
        match (self.current, self.inactive_file) {
            (Some(c), Some(i)) => Measured::exact(
                c.saturating_sub(i),
                "cgroup memory.current − memory.stat:inactive_file",
            ),
            (Some(c), None) => Measured::estimate(c, "cgroup memory.current (page cache included)"),
            _ => Measured::unavailable("cgroup memory.current", "not read"),
        }
    }

    /// The tightest limit set on this cgroup: `memory.max`, else `memory.high`.
    pub fn has_limit(&self) -> bool {
        self.max.is_some() || self.high.is_some()
    }
}

/// What carries the limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LimitKind {
    /// A container (engine limit or its cgroup).
    #[default]
    Container,
    /// A Kubernetes pod-level cgroup (sum of its containers' limits).
    Pod,
    /// Any other cgroup with `memory.max` / `memory.high` (a systemd unit with `MemoryMax=`, a
    /// `systemd-run -p MemoryMax=` sandbox, a kubelet QoS slice).
    Cgroup,
    /// An engine VM (Docker Desktop, OrbStack, Colima…): Σ container memory against the VM's memory.
    Vm,
}

impl LimitKind {
    pub fn word(self) -> &'static str {
        match self {
            LimitKind::Container => "container",
            LimitKind::Pod => "pod",
            LimitKind::Cgroup => "cgroup",
            LimitKind::Vm => "VM",
        }
    }
}

/// Which limit the forecast runs against.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LimitTarget {
    /// `memory.max` / the engine's hard limit: the kernel OOM-kills inside the cgroup.
    #[default]
    Max,
    /// `memory.high` only: throttled and reclaimed hard, never killed by it.
    High,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LimitState {
    /// Usage unknown.
    #[default]
    Unknown,
    Ok,
    /// ≥ [`NEAR_PCT`] of the limit.
    Near,
    /// ≥ [`AT_LIMIT_PCT`] of the limit, or the cgroup hit `memory.max` since the last reading.
    AtLimit,
}

/// ETA to the limit. Present only under the host forecast's honesty rules (module docs).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct LimitForecast {
    pub target: LimitTarget,
    /// Seconds from the newest reading.
    pub eta_s: u64,
    /// 0..1, the R² of the fit.
    pub confidence: f64,
    /// Growth in bytes per minute.
    pub rate_per_min: f64,
    /// Fit window, seconds.
    pub window_s: u64,
}

/// One limit and how close it is (SPEC §8.3). `summary` is in IEC units; [`LimitStatus::sentence`]
/// re-renders it in the caller's units.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct LimitStatus {
    /// Stable id: `cgroup:<path>`, a sandbox id (`docker:<12 hex>`), `k8s:<ns>/<pod>/<container>`.
    pub id: String,
    pub kind: LimitKind,
    /// Container / pod / unit name.
    pub label: String,
    /// Engine or cluster runtime ("docker", "orbstack", "kubernetes", "systemd").
    pub runtime: Option<String>,
    /// [`crate::model::Sandbox::id`] of the container or VM, when there is one.
    pub sandbox_id: Option<String>,
    /// cgroup path, when the numbers come from cgroup files.
    pub cgroup: Option<String>,
    /// `namespace/pod` for Kubernetes containers and pods.
    pub pod: Option<String>,
    /// Working set (see module docs).
    pub usage: Measured<u64>,
    /// The limit the percent and forecast use (`memory.max`, else `memory.high`; engine limit; VM size).
    pub limit: Measured<u64>,
    pub target: LimitTarget,
    /// `memory.high` when set below `memory.max`.
    pub high: Option<u64>,
    /// Highest usage the kernel recorded (`memory.peak`), when readable.
    pub peak: Measured<u64>,
    /// usage ÷ limit × 100.
    pub pct: Option<f64>,
    /// Growth over the last ≤ 5 min (bytes/min, an estimate; may be noise — the forecast is the
    /// trustworthy signal).
    pub growth_per_min: Measured<f64>,
    pub forecast: Option<LimitForecast>,
    pub state: LimitState,
    /// Kernel OOM kills inside the cgroup since it was created (`memory.events:oom_kill`).
    pub oom_kills: Measured<u64>,
    /// OOM kills that happened while oomtop was watching.
    pub oom_kills_observed: u64,
    /// When the newest observed OOM kill was noticed (ms since the epoch).
    pub last_oom_kill_ms: Option<u64>,
    /// The container's previous run ended in an OOM kill (Docker `State.OOMKilled`, Kubernetes
    /// `lastState.terminated.reason = OOMKilled`).
    pub oom_killed_last_exit: Option<bool>,
    /// Restarts (Docker `RestartCount`, Kubernetes `restartCount`).
    pub restarts: Option<u32>,
    /// "container `web` hits its 2.0 GiB limit in ~4 min" (IEC units).
    pub summary: String,
}

impl LimitStatus {
    /// The one-line answer in the caller's units.
    pub fn sentence(&self, units: UnitSystem, decimals: usize) -> String {
        let b = |v: u64| format_bytes(v, units, decimals);
        let what = format!("{} `{}`", self.kind.word(), self.label);
        let limit_word = match self.target {
            LimitTarget::Max => "limit",
            LimitTarget::High => "memory.high",
        };
        let Some(limit) = self.limit.value else {
            return format!("{what}: limit unknown");
        };
        let mut out = if let Some(f) = &self.forecast {
            format!(
                "{what} hits its {} {limit_word} in ~{} (+{}/min, R² {:.2})",
                b(limit),
                format_eta(f.eta_s),
                b(f.rate_per_min.max(0.0) as u64),
                f.confidence
            )
        } else {
            match (self.usage.value, self.state) {
                (Some(u), LimitState::AtLimit) => {
                    format!("{what} is at its {} {limit_word} ({} used)", b(limit), b(u))
                }
                (Some(u), _) => format!(
                    "{what} uses {} of {} ({}){}",
                    b(u),
                    b(limit),
                    self.pct
                        .map(|p| format!("{p:.0}%"))
                        .unwrap_or_else(|| "n/a".into()),
                    if self.state == LimitState::Near {
                        ", near its limit"
                    } else {
                        ""
                    }
                ),
                (None, _) => format!("{what}: {} {limit_word}, usage unknown", b(limit)),
            }
        };
        if self.oom_kills_observed > 0 {
            out.push_str(&format!(
                "; OOM-killed {}× while watched",
                self.oom_kills_observed
            ));
        } else if let Some(k) = self.oom_kills.value.filter(|k| *k > 0) {
            out.push_str(&format!("; {k} OOM kill(s) since it started"));
        }
        if self.oom_killed_last_exit == Some(true) {
            out.push_str("; its last run ended in an OOM kill");
        }
        out
    }
}

/// "4 min" / "45 s" / "1h5m" for an ETA.
pub fn format_eta(eta_s: u64) -> String {
    if eta_s < 60 {
        format!("{eta_s} s")
    } else if eta_s < 3600 {
        format!("{} min", (eta_s + 30) / 60)
    } else {
        format_duration(eta_s)
    }
}

/// What a frontend or the engine knows about one limit at one moment (input to [`evaluate`]).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct LimitInput {
    pub id: String,
    pub kind: LimitKind,
    pub label: String,
    pub runtime: Option<String>,
    pub sandbox_id: Option<String>,
    pub cgroup: Option<String>,
    pub pod: Option<String>,
    pub usage: Measured<u64>,
    /// When `usage` was read; `None` = not a fresh reading (carried over) → not added to the trend.
    pub read_at_ms: Option<u64>,
    pub limit: Measured<u64>,
    pub target: LimitTarget,
    pub high: Option<u64>,
    pub peak: Measured<u64>,
    pub events: Option<MemoryEvents>,
    pub oom_killed_last_exit: Option<bool>,
    pub restarts: Option<u32>,
}

#[derive(Debug, Clone, Default)]
struct Series {
    /// (read time ms, usage bytes), oldest first.
    points: VecDeque<(u64, u64)>,
    /// `memory.events` at the first and newest reading.
    events_first: Option<MemoryEvents>,
    events_last: Option<MemoryEvents>,
    /// `memory.events:max` moved at the newest reading.
    hit_max_now: bool,
    last_kill_ms: Option<u64>,
    last_seen_ms: u64,
}

/// Per-limit history (module docs). One per engine; pure.
#[derive(Debug, Clone, Default)]
pub struct LimitTracker {
    series: BTreeMap<String, Series>,
}

impl LimitTracker {
    pub fn new() -> Self {
        Self::default()
    }

    /// Records one reading. A reading not newer than the newest point of `id` (a cached value repeated by a
    /// later snapshot) is ignored; counters are compared with the previous reading.
    pub fn observe(&mut self, id: &str, at_ms: u64, usage: Option<u64>, events: Option<MemoryEvents>) {
        let s = self.series.entry(id.to_string()).or_default();
        s.last_seen_ms = s.last_seen_ms.max(at_ms);
        if let Some(e) = events {
            let prev = s.events_last;
            s.hit_max_now = prev.is_some_and(|p| e.max > p.max);
            if prev.is_some_and(|p| e.oom_kill > p.oom_kill) {
                s.last_kill_ms = Some(at_ms);
            }
            // A counter that went backwards is a new cgroup under the same path: restart the baseline.
            if prev.is_none_or(|p| e.oom_kill < p.oom_kill || e.max < p.max) {
                s.events_first = Some(e);
            }
            s.events_last = Some(e);
        }
        let Some(u) = usage else { return };
        if s.points.back().is_some_and(|(t, _)| at_ms <= *t) {
            return;
        }
        s.points.push_back((at_ms, u));
        while s.points.len() > MAX_POINTS
            || s.points
                .front()
                .is_some_and(|(t, _)| at_ms.saturating_sub(*t) > RETENTION_MS)
        {
            s.points.pop_front();
        }
    }

    /// Forgets limits not seen for [`RETENTION_MS`].
    pub fn gc(&mut self, now_ms: u64) {
        self.series
            .retain(|_, s| now_ms.saturating_sub(s.last_seen_ms) <= RETENTION_MS);
    }

    pub fn len(&self) -> usize {
        self.series.len()
    }

    pub fn is_empty(&self) -> bool {
        self.series.is_empty()
    }

    /// Points of `id` (oldest first), for tests and sparklines.
    pub fn points(&self, id: &str) -> Vec<(u64, u64)> {
        self.series
            .get(id)
            .map(|s| s.points.iter().copied().collect())
            .unwrap_or_default()
    }

    /// OOM kills observed while watching and when the newest was noticed.
    pub fn kills(&self, id: &str) -> (u64, Option<u64>) {
        let Some(s) = self.series.get(id) else {
            return (0, None);
        };
        let n = match (s.events_first, s.events_last) {
            (Some(a), Some(b)) => b.oom_kill.saturating_sub(a.oom_kill),
            _ => 0,
        };
        (n, s.last_kill_ms)
    }

    /// Growth rate (bytes/min) over the newest ≤ 5 min: an estimate, without the forecast's consistency
    /// guards (for an arrow next to a gauge).
    pub fn growth_per_min(&self, id: &str) -> Measured<f64> {
        let src = "linear fit of the working set over the last ≤ 5 min";
        let Some(s) = self.series.get(id) else {
            return Measured::unavailable(src, "no readings yet");
        };
        let Some(&(t_last, _)) = s.points.back() else {
            return Measured::unavailable(src, "no readings yet");
        };
        let pts: Vec<(f64, f64)> = s
            .points
            .iter()
            .filter(|(t, _)| t_last - t <= WINDOW_MS)
            .map(|(t, u)| ((*t as f64) / 1000.0, *u as f64))
            .collect();
        let span = pts.last().map(|p| p.0).unwrap_or(0.0) - pts.first().map(|p| p.0).unwrap_or(0.0);
        if pts.len() < TREND_MIN_POINTS || span < TREND_MIN_SPAN_S {
            return Measured::unavailable(src, "needs ≥ 3 readings over ≥ 30 s");
        }
        match linear_fit(&pts) {
            Some(f) => Measured::estimate(f.slope * 60.0, src),
            None => Measured::unavailable(src, "no fit"),
        }
    }

    /// ETA of `id` to `limit` bytes, under the host forecast's rules (module docs). `now_ms` is the
    /// snapshot time: a series whose newest reading is older than [`MAX_STALE_S`] is not forecast, and a
    /// slightly stale one has its ETA measured from now.
    pub fn forecast(&self, id: &str, limit: u64, target: LimitTarget, now_ms: u64) -> Option<LimitForecast> {
        let s = self.series.get(id)?;
        let &(t_last, _) = s.points.back()?;
        let stale_s = now_ms.saturating_sub(t_last) as f64 / 1000.0;
        if stale_s > MAX_STALE_S {
            return None;
        }
        WINDOWS_MS
            .iter()
            .filter_map(|w| {
                let cutoff = t_last.saturating_sub(*w);
                // The newest point at or before the cutoff completes the window when it is close enough
                // (same rule as `forecast::window_reaching`).
                let first = s
                    .points
                    .iter()
                    .map(|(t, _)| *t)
                    .take_while(|t| *t <= cutoff)
                    .last()
                    .filter(|t| cutoff - *t <= WINDOW_SLACK_MS)
                    .unwrap_or(cutoff);
                let pts: Vec<(f64, f64)> = s
                    .points
                    .iter()
                    .filter(|(t, _)| *t >= first)
                    .map(|(t, u)| ((t - first) as f64 / 1000.0, *u as f64))
                    .collect();
                let (eta, fit) = eta_to_threshold(&pts, limit as f64, true)?;
                let eta = eta - stale_s;
                (eta > 0.0).then(|| LimitForecast {
                    target,
                    eta_s: eta.round() as u64,
                    confidence: fit.r2,
                    rate_per_min: fit.slope * 60.0,
                    window_s: fit.span_s.round() as u64,
                })
            })
            .min_by_key(|f| f.eta_s)
    }

    fn hit_max_now(&self, id: &str) -> bool {
        self.series.get(id).is_some_and(|s| s.hit_max_now)
    }
}

/// Feeds `inputs` into `tracker` and returns their status, most urgent first (forecast ETA, then percent).
pub fn evaluate(tracker: &mut LimitTracker, inputs: Vec<LimitInput>, now_ms: u64) -> Vec<LimitStatus> {
    let mut out = Vec::with_capacity(inputs.len());
    for i in inputs {
        let fresh = i.read_at_ms.filter(|_| i.usage.is_available());
        match fresh {
            Some(at) => tracker.observe(&i.id, at, i.usage.value, i.events),
            None => {
                if let Some(e) = i.events {
                    tracker.observe(&i.id, now_ms, None, Some(e));
                }
            }
        }
        let pct = match (i.usage.value, i.limit.value) {
            (Some(u), Some(l)) if l > 0 => Some(u as f64 / l as f64 * 100.0),
            _ => None,
        };
        let state = match pct {
            None => LimitState::Unknown,
            Some(_) if tracker.hit_max_now(&i.id) && i.target == LimitTarget::Max => LimitState::AtLimit,
            Some(p) if p >= AT_LIMIT_PCT => LimitState::AtLimit,
            Some(p) if p >= NEAR_PCT => LimitState::Near,
            Some(_) => LimitState::Ok,
        };
        let forecast = match (i.limit.value, state) {
            (Some(l), LimitState::Ok | LimitState::Near) => tracker.forecast(&i.id, l, i.target, now_ms),
            _ => None,
        };
        let (observed, last_kill) = tracker.kills(&i.id);
        let mut st = LimitStatus {
            growth_per_min: tracker.growth_per_min(&i.id),
            oom_kills: match &i.events {
                Some(e) => Measured::exact(e.oom_kill, "cgroup memory.events:oom_kill"),
                None => Measured::unavailable(
                    i.runtime.clone().unwrap_or_default(),
                    "no kill counter (not a readable cgroup)",
                ),
            },
            oom_kills_observed: observed,
            last_oom_kill_ms: last_kill,
            id: i.id,
            kind: i.kind,
            label: i.label,
            runtime: i.runtime,
            sandbox_id: i.sandbox_id,
            cgroup: i.cgroup,
            pod: i.pod,
            usage: i.usage,
            limit: i.limit,
            target: i.target,
            high: i.high,
            peak: i.peak,
            pct,
            forecast,
            state,
            oom_killed_last_exit: i.oom_killed_last_exit,
            restarts: i.restarts,
            summary: String::new(),
        };
        st.summary = st.sentence(UnitSystem::Iec, 1);
        out.push(st);
    }
    tracker.gc(now_ms);
    out.sort_by(|a, b| {
        let eta = |s: &LimitStatus| s.forecast.as_ref().map_or(u64::MAX, |f| f.eta_s);
        b.state
            .cmp(&a.state)
            .then(eta(a).cmp(&eta(b)))
            .then(
                b.pct
                    .unwrap_or(-1.0)
                    .partial_cmp(&a.pct.unwrap_or(-1.0))
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
            .then(a.id.cmp(&b.id))
    });
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Quality;

    const MIB: u64 = 1 << 20;
    const GIB: u64 = 1 << 30;

    fn input(id: &str, at: u64, usage: u64, limit: u64) -> LimitInput {
        LimitInput {
            id: id.into(),
            kind: LimitKind::Container,
            label: "web".into(),
            runtime: Some("docker".into()),
            usage: Measured::exact(usage, "t"),
            read_at_ms: Some(at),
            limit: Measured::exact(limit, "t"),
            ..Default::default()
        }
    }

    /// Feeds `(t_s, usage)` rows (one reading each) and returns the last status.
    fn run(rows: &[(u64, u64)], limit: u64) -> LimitStatus {
        let mut tr = LimitTracker::new();
        let mut last = None;
        for (t, u) in rows {
            let now = 1_000_000 + t * 1000;
            last = evaluate(&mut tr, vec![input("c", now, *u, limit)], now).pop();
        }
        last.unwrap()
    }

    fn ramp(n: u64, step_s: u64, start: u64, per_step: u64) -> Vec<(u64, u64)> {
        (0..n).map(|i| (i * step_s, start + i * per_step)).collect()
    }

    /// Trend table: steady growth, flat, noise, a one-off step, a reversal, too little data, far away.
    /// name, rows (t_ms, bytes), expected ETA range in seconds (or None).
    type TrendCase = (&'static str, Vec<(u64, u64)>, Option<(u64, u64)>);

    #[test]
    fn trend_table() {
        let limit = 2 * GIB;
        let cases: Vec<TrendCase> = vec![
            // +10 MiB every 10 s = 60 MiB/min; 3 min of data; at 1.5 GiB + 180 MiB … ETA ≈ (2048-1716)/60 min
            (
                "steady growth",
                ramp(19, 10, 1536 * MIB, 10 * MIB),
                Some((300, 360)),
            ),
            ("flat", ramp(30, 10, GIB, 0), None),
            (
                "noise around a level",
                (0..30)
                    .map(|i| (i * 10, GIB + if i % 2 == 0 { 50 * MIB } else { 0 }))
                    .collect(),
                None,
            ),
            (
                "one-off step (cache warm-up)",
                (0..30)
                    .map(|i| (i * 10, if i < 15 { GIB } else { GIB + 700 * MIB }))
                    .collect(),
                None,
            ),
            (
                "growth then a drop (OOM kill / restart)",
                (0..30)
                    .map(|i| (i * 10, if i < 28 { GIB + i * 20 * MIB } else { 300 * MIB }))
                    .collect(),
                None,
            ),
            ("too short (60 s)", ramp(7, 10, 1536 * MIB, 10 * MIB), None),
            ("too slow (ETA > 30 min)", ramp(30, 10, GIB, MIB), None),
        ];
        for (name, rows, want) in cases {
            let st = run(&rows, limit);
            match (want, &st.forecast) {
                (None, None) => {}
                (Some((lo, hi)), Some(f)) => {
                    assert!(
                        (lo..=hi).contains(&f.eta_s),
                        "{name}: eta {} not in {lo}..{hi}",
                        f.eta_s
                    );
                    assert!(f.confidence >= 0.6, "{name}");
                    assert!((f.rate_per_min - 60.0 * MIB as f64).abs() < MIB as f64, "{name}");
                }
                (w, f) => panic!("{name}: want {w:?}, got {f:?}"),
            }
        }
    }

    #[test]
    fn sentence_and_state() {
        let st = run(&ramp(19, 10, 1536 * MIB, 10 * MIB), 2 * GIB);
        assert!(
            st.summary
                .starts_with("container `web` hits its 2.0 GiB limit in ~"),
            "{}",
            st.summary
        );
        assert!(
            st.summary.contains("min (+60.0 MiB/min, R² 1.00)"),
            "{}",
            st.summary
        );
        assert_eq!(st.state, LimitState::Ok);
        assert!(st.growth_per_min.value.unwrap() > 59.0 * MIB as f64);
        // Near and at the limit; no forecast at the limit (it is already there).
        let st = run(&[(0, 1900 * MIB)], 2 * GIB);
        assert_eq!(st.state, LimitState::Near);
        assert_eq!(
            st.summary,
            "container `web` uses 1.9 GiB of 2.0 GiB (93%), near its limit"
        );
        let st = run(&[(0, 2 * GIB - MIB)], 2 * GIB);
        assert_eq!(st.state, LimitState::AtLimit);
        assert_eq!(
            st.summary,
            "container `web` is at its 2.0 GiB limit (2.0 GiB used)"
        );
        // SI rendering for a frontend configured that way.
        assert!(st.sentence(UnitSystem::Si, 1).contains("2.1 GB limit"));
    }

    #[test]
    fn repeated_cached_readings_are_one_point_and_kills_are_counted() {
        let mut tr = LimitTracker::new();
        let ev = |kill: u64, max: u64| MemoryEvents {
            oom_kill: kill,
            max,
            ..Default::default()
        };
        let mut i = input("c", 1000, 100, 1000);
        i.events = Some(ev(2, 5));
        evaluate(&mut tr, vec![i.clone()], 1000);
        // Same reading seen by the next snapshot (engine cache): not a new point.
        evaluate(&mut tr, vec![i.clone()], 3000);
        assert_eq!(tr.points("c").len(), 1);
        i.read_at_ms = Some(11_000);
        i.events = Some(ev(3, 9));
        let st = evaluate(&mut tr, vec![i.clone()], 11_000).pop().unwrap();
        assert_eq!(tr.points("c").len(), 2);
        assert_eq!(st.oom_kills.value, Some(3));
        assert_eq!(st.oom_kills_observed, 1);
        assert_eq!(st.last_oom_kill_ms, Some(11_000));
        assert_eq!(st.state, LimitState::AtLimit, "memory.events:max moved");
        assert!(
            st.summary.contains("OOM-killed 1× while watched"),
            "{}",
            st.summary
        );
        // A counter reset (new cgroup at the same path) restarts the baseline.
        i.read_at_ms = Some(21_000);
        i.events = Some(ev(0, 0));
        let st = evaluate(&mut tr, vec![i], 21_000).pop().unwrap();
        assert_eq!(st.oom_kills_observed, 0);
        assert_eq!(st.state, LimitState::Ok);
    }

    #[test]
    fn stale_series_and_unknown_usage_are_not_forecast() {
        let mut tr = LimitTracker::new();
        for (t, u) in ramp(19, 10, 1536 * MIB, 10 * MIB) {
            tr.observe("c", t * 1000, Some(u), None);
        }
        assert!(tr.forecast("c", 2 * GIB, LimitTarget::Max, 180_000).is_some());
        assert!(tr
            .forecast("c", 2 * GIB, LimitTarget::Max, 180_000 + 31_000)
            .is_none());
        let mut i = input("d", 1, 0, GIB);
        i.usage = Measured::unavailable("docker", "stats not read yet");
        let st = evaluate(&mut tr, vec![i], 1).pop().unwrap();
        assert_eq!(st.state, LimitState::Unknown);
        assert_eq!(st.summary, "container `web`: 1.0 GiB limit, usage unknown");
        // gc drops what stopped reporting
        tr.gc(10_000_000);
        assert!(tr.is_empty());
    }

    #[test]
    fn urgency_order() {
        let mut tr = LimitTracker::new();
        let mut a = input("a", 1, 100, 1000);
        a.label = "a".into();
        let mut b = input("b", 1, 950, 1000);
        b.label = "b".into();
        let out = evaluate(&mut tr, vec![a, b], 1);
        assert_eq!(out[0].id, "b");
    }

    #[test]
    fn working_set() {
        let c = CgroupMem {
            current: Some(1000),
            inactive_file: Some(300),
            ..Default::default()
        };
        assert_eq!(c.working_set(), Some(700));
        assert_eq!(c.working_set_measured().quality, Quality::Exact);
        let c = CgroupMem {
            current: Some(1000),
            ..Default::default()
        };
        assert_eq!(c.working_set_measured().quality, Quality::Estimate);
        assert!(!c.has_limit());
        assert_eq!(format_eta(240), "4 min");
        assert_eq!(format_eta(45), "45 s");
    }
}