1use 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
23pub const NEAR_PCT: f64 = 90.0;
25pub const AT_LIMIT_PCT: f64 = 99.0;
27pub const MAX_POINTS: usize = 400;
29pub const RETENTION_MS: u64 = WINDOW_MS + 2 * WINDOW_SLACK_MS;
30pub const TREND_MIN_POINTS: usize = 3;
32pub const TREND_MIN_SPAN_S: f64 = 30.0;
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
37#[serde(default)]
38pub struct CgroupMem {
39 pub path: String,
41 pub current: Option<u64>,
43 pub max: Option<u64>,
45 pub high: Option<u64>,
47 pub limits_read: bool,
49 pub peak: Option<u64>,
51 pub swap_current: Option<u64>,
53 pub inactive_file: Option<u64>,
55 pub anon: Option<u64>,
56 pub file: Option<u64>,
57 pub events: Option<MemoryEvents>,
59 pub at_ms: u64,
61}
62
63impl CgroupMem {
64 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 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 pub fn has_limit(&self) -> bool {
84 self.max.is_some() || self.high.is_some()
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
90#[serde(rename_all = "snake_case")]
91pub enum LimitKind {
92 #[default]
94 Container,
95 Pod,
97 Cgroup,
100 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
117#[serde(rename_all = "snake_case")]
118pub enum LimitTarget {
119 #[default]
121 Max,
122 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 #[default]
131 Unknown,
132 Ok,
133 Near,
135 AtLimit,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
141#[serde(default)]
142pub struct LimitForecast {
143 pub target: LimitTarget,
144 pub eta_s: u64,
146 pub confidence: f64,
148 pub rate_per_min: f64,
150 pub window_s: u64,
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
157#[serde(default)]
158pub struct LimitStatus {
159 pub id: String,
161 pub kind: LimitKind,
162 pub label: String,
164 pub runtime: Option<String>,
166 pub sandbox_id: Option<String>,
168 pub cgroup: Option<String>,
170 pub pod: Option<String>,
172 pub usage: Measured<u64>,
174 pub limit: Measured<u64>,
176 pub target: LimitTarget,
177 pub high: Option<u64>,
179 pub peak: Measured<u64>,
181 pub pct: Option<f64>,
183 pub growth_per_min: Measured<f64>,
186 pub forecast: Option<LimitForecast>,
187 pub state: LimitState,
188 pub oom_kills: Measured<u64>,
190 pub oom_kills_observed: u64,
192 pub last_oom_kill_ms: Option<u64>,
194 pub oom_killed_last_exit: Option<bool>,
197 pub restarts: Option<u32>,
199 pub summary: String,
201}
202
203impl LimitStatus {
204 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
259pub 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#[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 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 points: VecDeque<(u64, u64)>,
296 events_first: Option<MemoryEvents>,
298 events_last: Option<MemoryEvents>,
299 hit_max_now: bool,
301 last_kill_ms: Option<u64>,
302 last_seen_ms: u64,
303}
304
305#[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 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 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 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 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 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 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 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 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
455pub 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 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 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 (
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 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 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 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 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 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}