1use crate::headroom::{is_reclaim_candidate, Headroom};
13use crate::model::{GroupKind, OsKind, PressureLevel, Snapshot, ThermalPressure};
14use crate::throttle::THROTTLED_BELOW;
15use crate::units::{format_bytes, UnitSystem};
16use serde::{Deserialize, Serialize};
17
18pub const ENTER_AFTER_MS: u64 = 10_000;
19pub const LEAVE_AFTER_MS: u64 = 30_000;
20pub const PSI_SOME_PRESSURE_PCT: f64 = 20.0;
22pub const WORKING_CPU_PCT: f64 = 50.0;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
26#[serde(rename_all = "snake_case")]
27pub enum Mode {
28 #[default]
29 Calm,
30 Pressure,
31 Throttle,
32 Working,
33 Leftovers,
34}
35
36impl Mode {
37 pub const PRIORITY: [Mode; 4] = [Mode::Pressure, Mode::Throttle, Mode::Working, Mode::Leftovers];
39 pub const ALL: [Mode; 5] = [
40 Mode::Calm,
41 Mode::Pressure,
42 Mode::Throttle,
43 Mode::Working,
44 Mode::Leftovers,
45 ];
46
47 pub fn as_str(self) -> &'static str {
48 match self {
49 Mode::Calm => "calm",
50 Mode::Pressure => "pressure",
51 Mode::Throttle => "throttle",
52 Mode::Working => "working",
53 Mode::Leftovers => "leftovers",
54 }
55 }
56
57 pub fn title(self) -> &'static str {
59 match self {
60 Mode::Calm => "Calm",
61 Mode::Pressure => "Pressure",
62 Mode::Throttle => "Throttle",
63 Mode::Working => "Working",
64 Mode::Leftovers => "Leftovers",
65 }
66 }
67
68 pub fn parse(s: &str) -> Option<Mode> {
69 let s = s.trim().to_ascii_lowercase();
70 Mode::ALL.into_iter().find(|m| m.as_str() == s)
71 }
72
73 fn index(self) -> usize {
74 match self {
75 Mode::Calm => 0,
76 Mode::Pressure => 1,
77 Mode::Throttle => 2,
78 Mode::Working => 3,
79 Mode::Leftovers => 4,
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
86#[serde(default)]
87pub struct ModeSignals {
88 pub pressure: bool,
89 pub throttle: bool,
90 pub working: bool,
91 pub leftovers: bool,
92}
93
94impl ModeSignals {
95 pub fn desired(&self) -> Mode {
97 Mode::PRIORITY
98 .into_iter()
99 .find(|m| self.is(*m))
100 .unwrap_or(Mode::Calm)
101 }
102
103 pub fn is(&self, mode: Mode) -> bool {
105 match mode {
106 Mode::Calm => !(self.pressure || self.throttle || self.working || self.leftovers),
107 Mode::Pressure => self.pressure,
108 Mode::Throttle => self.throttle,
109 Mode::Working => self.working,
110 Mode::Leftovers => self.leftovers,
111 }
112 }
113
114 pub fn active(&self) -> Vec<Mode> {
116 Mode::PRIORITY.into_iter().filter(|m| self.is(*m)).collect()
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
122pub struct ModeReason {
123 pub mode: Mode,
124 pub key: String,
128 pub text: String,
129}
130
131fn fmt(b: u64) -> String {
132 format_bytes(b, UnitSystem::Si, 1)
133}
134
135pub fn reasons(s: &Snapshot, h: &Headroom) -> Vec<ModeReason> {
147 let mut out = Vec::new();
148 let mut add = |mode: Mode, key: &str, text: String| {
149 out.push(ModeReason {
150 mode,
151 key: key.to_string(),
152 text,
153 })
154 };
155 let os = s.host.os;
156 let linux = matches!(os, OsKind::Linux | OsKind::Other);
157 let macos = matches!(os, OsKind::Macos | OsKind::Other);
158
159 if let Some(x) = h.headroom.filter(|x| *x < 0) {
161 add(
162 Mode::Pressure,
163 "headroom_negative",
164 format!("{} into the safety margin", fmt(x.unsigned_abs())),
165 );
166 }
167 if h.swap_growing {
168 let rate = s
169 .memory
170 .swap_out_per_min
171 .value
172 .map(|r| format!(" +{}/min", fmt(r)));
173 add(
174 Mode::Pressure,
175 "swap_growing",
176 format!("swap growing{}", rate.unwrap_or_default()),
177 );
178 }
179 if let Some(f) = &s.oom.forecast {
180 add(
181 Mode::Pressure,
182 "oom_forecast",
183 format!("OOM forecast in {}", crate::units::format_duration(f.eta_s)),
184 );
185 }
186 if linux {
187 match s.memory.psi.value {
188 Some(p) if p.some_avg10 > PSI_SOME_PRESSURE_PCT => add(
189 Mode::Pressure,
190 "psi",
191 format!("PSI mem some {:.0}%", p.some_avg10),
192 ),
193 Some(_) => {}
194 None if os == OsKind::Linux => {
195 if let Some(level) = s.memory.pressure.value.filter(|l| *l >= PressureLevel::Warn) {
196 add(
197 Mode::Pressure,
198 "pressure_level",
199 format!("memory pressure {}", level_str(level)),
200 );
201 }
202 }
203 None => {}
204 }
205 }
206 if macos {
207 if let Some(level) = s.memory.pressure.value.filter(|l| *l >= PressureLevel::Warn) {
208 add(
209 Mode::Pressure,
210 "memorystatus",
211 format!("memory pressure {}", level_str(level)),
212 );
213 }
214 }
215
216 let t = &s.thermal;
218 if let Some(f) = t.throttle_factor.value.filter(|f| *f < THROTTLED_BELOW) {
219 add(
220 Mode::Throttle,
221 "throttle_factor",
222 format!("running at {:.0}% speed", f * 100.0),
223 );
224 }
225 if macos {
226 if let Some(p) = t.pressure.value.filter(|p| *p >= ThermalPressure::Heavy) {
227 add(
228 Mode::Throttle,
229 "thermal_pressure",
230 format!("thermal pressure {}", thermal_str(p)),
231 );
232 }
233 }
234 if linux && t.trip_point_hit.value == Some(true) {
235 add(Mode::Throttle, "trip_point", "thermal trip point hit".into());
236 }
237 if t.low_power_mode.value == Some(true) {
238 add(Mode::Throttle, "low_power_mode", "Low Power Mode on".into());
239 }
240
241 for m in &s.model_servers {
243 if m.busy.value == Some(true) {
244 let name = m
245 .group_id
246 .as_deref()
247 .and_then(|g| s.group(g))
248 .map(|g| g.label.clone())
249 .unwrap_or_else(|| m.id.clone());
250 add(Mode::Working, "model_busy", format!("{name} busy"));
251 }
252 }
253 for g in &s.groups {
254 let cpu = g.totals.cpu_pct.value.unwrap_or(0.0);
255 if g.idle || cpu < WORKING_CPU_PCT {
256 continue;
257 }
258 match g.kind {
259 GroupKind::BuildDaemon => add(Mode::Working, "build_active", format!("{} building", g.label)),
260 GroupKind::ModelServer => {
261 let adapter_knows = s
262 .model_servers
263 .iter()
264 .any(|m| m.group_id.as_deref() == Some(g.id.as_str()) && m.busy.value.is_some());
265 if !adapter_knows {
266 add(Mode::Working, "model_cpu", format!("{} active", g.label));
267 }
268 }
269 _ => {}
270 }
271 }
272
273 let orphans = s
275 .groups
276 .iter()
277 .filter(|g| g.orphan && !g.protected && !g.is_self)
278 .count();
279 if orphans > 0 {
280 add(
281 Mode::Leftovers,
282 "orphans",
283 format!("{orphans} orphan{}", if orphans == 1 { "" } else { "s" }),
284 );
285 }
286 let idle = s
287 .groups
288 .iter()
289 .filter(|g| g.idle && !g.orphan && is_reclaim_candidate(g))
290 .count();
291 if idle > 0 {
292 add(
293 Mode::Leftovers,
294 "idle_reclaimable",
295 format!(
296 "{idle} idle reclaimable group{}",
297 if idle == 1 { "" } else { "s" }
298 ),
299 );
300 }
301 out
302}
303
304fn level_str(l: PressureLevel) -> &'static str {
305 match l {
306 PressureLevel::Normal => "normal",
307 PressureLevel::Warn => "warn",
308 PressureLevel::Critical => "critical",
309 }
310}
311
312fn thermal_str(p: ThermalPressure) -> &'static str {
313 match p {
314 ThermalPressure::Nominal => "nominal",
315 ThermalPressure::Moderate => "moderate",
316 ThermalPressure::Heavy => "heavy",
317 ThermalPressure::Trapping => "trapping",
318 ThermalPressure::Sleeping => "sleeping",
319 }
320}
321
322pub fn signals(s: &Snapshot, h: &Headroom) -> ModeSignals {
324 let mut sig = ModeSignals::default();
325 for r in reasons(s, h) {
326 match r.mode {
327 Mode::Pressure => sig.pressure = true,
328 Mode::Throttle => sig.throttle = true,
329 Mode::Working => sig.working = true,
330 Mode::Leftovers => sig.leftovers = true,
331 Mode::Calm => {}
332 }
333 }
334 sig
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
339struct Latch {
340 on: bool,
341 true_since: Option<u64>,
342 false_since: Option<u64>,
343}
344
345#[derive(Debug, Clone, Default, PartialEq)]
347pub struct ModeMachine {
348 current: Mode,
349 latches: [Latch; 5],
350 pinned: Option<Mode>,
351 initialized: bool,
352 last_ms: u64,
353}
354
355impl ModeMachine {
356 pub fn new() -> Self {
357 Self::default()
358 }
359
360 pub fn current(&self) -> Mode {
362 self.pinned.unwrap_or(self.current)
363 }
364
365 pub fn underlying(&self) -> Mode {
367 self.current
368 }
369
370 pub fn latched(&self) -> Vec<Mode> {
372 Mode::PRIORITY
373 .into_iter()
374 .filter(|m| self.latches[m.index()].on)
375 .collect()
376 }
377
378 pub fn pin(&mut self, mode: Option<Mode>) {
380 self.pinned = mode;
381 }
382
383 pub fn is_pinned(&self) -> bool {
384 self.pinned.is_some()
385 }
386
387 pub fn update(&mut self, now_ms: u64, sig: &ModeSignals) -> Mode {
391 if !self.initialized {
392 self.initialized = true;
393 self.last_ms = now_ms;
394 for m in Mode::PRIORITY {
395 let on = sig.is(m);
396 self.latches[m.index()] = Latch {
397 on,
398 true_since: on.then_some(now_ms),
399 false_since: (!on).then_some(now_ms),
400 };
401 }
402 self.recompute();
403 return self.current();
404 }
405 if now_ms < self.last_ms {
406 for l in &mut self.latches {
407 l.true_since = l.true_since.map(|_| now_ms);
408 l.false_since = l.false_since.map(|_| now_ms);
409 }
410 }
411 self.last_ms = now_ms;
412 for m in Mode::PRIORITY {
413 let l = &mut self.latches[m.index()];
414 if sig.is(m) {
415 l.false_since = None;
416 let since = *l.true_since.get_or_insert(now_ms);
417 if !l.on && now_ms.saturating_sub(since) >= ENTER_AFTER_MS {
418 l.on = true;
419 }
420 } else {
421 l.true_since = None;
422 let since = *l.false_since.get_or_insert(now_ms);
423 if l.on && now_ms.saturating_sub(since) >= LEAVE_AFTER_MS {
424 l.on = false;
425 }
426 }
427 }
428 self.recompute();
429 self.current()
430 }
431
432 fn recompute(&mut self) {
433 self.current = Mode::PRIORITY
434 .into_iter()
435 .find(|m| self.latches[m.index()].on)
436 .unwrap_or(Mode::Calm);
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443 use crate::model::{Group, Measured, ModelServer, Psi};
444 use crate::units::GIB;
445
446 fn sig(pressure: bool, throttle: bool) -> ModeSignals {
447 ModeSignals {
448 pressure,
449 throttle,
450 ..Default::default()
451 }
452 }
453
454 #[test]
455 fn hysteresis() {
456 let mut m = ModeMachine::new();
457 let p = sig(true, false);
458 let calm = ModeSignals::default();
459 assert_eq!(
460 ModeMachine::new().update(0, &p),
461 Mode::Pressure,
462 "first sample adopted"
463 );
464 assert_eq!(m.update(0, &calm), Mode::Calm);
465 assert_eq!(m.update(0, &p), Mode::Calm);
466 assert_eq!(m.update(5_000, &p), Mode::Calm);
467 assert_eq!(m.update(10_000, &p), Mode::Pressure);
468 assert_eq!(m.update(20_000, &calm), Mode::Pressure);
469 assert_eq!(m.update(45_000, &calm), Mode::Pressure);
470 assert_eq!(m.update(50_000, &calm), Mode::Calm);
471 m.pin(Some(Mode::Throttle));
472 assert!(m.is_pinned());
473 assert_eq!(m.update(60_000, &calm), Mode::Throttle);
474 assert_eq!(m.underlying(), Mode::Calm);
475 m.pin(None);
476 assert_eq!(m.current(), Mode::Calm);
477 assert_eq!(Mode::parse("Leftovers"), Some(Mode::Leftovers));
478 }
479
480 #[test]
481 fn brief_blips_never_enter_and_short_calm_never_leaves() {
482 let mut m = ModeMachine::new();
483 m.update(0, &ModeSignals::default());
484 let mut t = 0;
486 for _ in 0..5 {
487 for _ in 0..4 {
488 t += 2_000;
489 assert_eq!(m.update(t, &sig(true, false)), Mode::Calm);
490 }
491 t += 2_000;
492 assert_eq!(m.update(t, &ModeSignals::default()), Mode::Calm);
493 }
494 for _ in 0..6 {
496 t += 2_000;
497 m.update(t, &sig(true, false));
498 }
499 assert_eq!(m.current(), Mode::Pressure);
500 for _ in 0..5 {
501 for _ in 0..10 {
502 t += 2_000;
503 assert_eq!(m.update(t, &ModeSignals::default()), Mode::Pressure);
504 }
505 t += 2_000;
506 m.update(t, &sig(true, false));
507 }
508 }
509
510 #[test]
511 fn lower_latched_mode_shows_when_higher_clears() {
512 let mut m = ModeMachine::new();
513 assert_eq!(m.update(0, &sig(true, true)), Mode::Pressure);
514 assert_eq!(m.latched(), vec![Mode::Pressure, Mode::Throttle]);
515 assert_eq!(m.update(10_000, &sig(false, true)), Mode::Pressure);
517 assert_eq!(m.update(40_000, &sig(false, true)), Mode::Throttle);
518 }
519
520 #[test]
521 fn clock_going_backwards_restarts_timers() {
522 let mut m = ModeMachine::new();
523 m.update(100_000, &ModeSignals::default());
524 m.update(105_000, &sig(true, false));
525 assert_eq!(m.update(0, &sig(true, false)), Mode::Calm);
527 assert_eq!(m.update(9_000, &sig(true, false)), Mode::Calm);
528 assert_eq!(m.update(10_000, &sig(true, false)), Mode::Pressure);
529 }
530
531 #[test]
532 fn per_os_triggers() {
533 let h = Headroom {
534 headroom: Some(4 * GIB as i64),
535 ..Default::default()
536 };
537 let mut s = Snapshot::default();
539 s.host.os = OsKind::Linux;
540 s.memory.psi = Measured::exact(
541 Psi {
542 some_avg10: 31.0,
543 ..Default::default()
544 },
545 "/proc/pressure/memory",
546 );
547 assert!(signals(&s, &h).pressure);
548 s.memory.psi = Measured::exact(
549 Psi {
550 some_avg10: 5.0,
551 ..Default::default()
552 },
553 "/proc/pressure/memory",
554 );
555 s.memory.pressure = Measured::estimate(PressureLevel::Warn, "derived");
556 assert!(!signals(&s, &h).pressure);
557 let mut s = Snapshot::default();
559 s.host.os = OsKind::Macos;
560 s.memory.pressure = Measured::exact(PressureLevel::Warn, "kern.memorystatus");
561 assert!(signals(&s, &h).pressure);
562 s.memory.pressure = Measured::exact(PressureLevel::Normal, "kern.memorystatus");
564 s.thermal.pressure = Measured::exact(ThermalPressure::Heavy, "notify");
565 assert!(signals(&s, &h).throttle);
566 s.host.os = OsKind::Linux;
567 assert!(!signals(&s, &h).throttle);
568 s.thermal.trip_point_hit = Measured::exact(true, "thermal_zone");
569 assert!(signals(&s, &h).throttle);
570 let mut s = Snapshot::default();
572 s.thermal.throttle_factor = Measured::unavailable("throttle", "idle");
573 assert_eq!(signals(&s, &h), ModeSignals::default());
574 }
575
576 #[test]
577 fn working_and_leftovers() {
578 let h = Headroom::default();
579 let mut s = Snapshot::default();
580 s.groups.push(Group {
581 id: "model:sd".into(),
582 kind: GroupKind::ModelServer,
583 label: "sd-server".into(),
584 ..Default::default()
585 });
586 s.model_servers.push(ModelServer {
587 id: "sd".into(),
588 group_id: Some("model:sd".into()),
589 busy: Measured::exact(true, "adapter"),
590 ..Default::default()
591 });
592 assert!(signals(&s, &h).working);
593 s.model_servers[0].busy = Measured::exact(false, "adapter");
594 s.groups[0].totals.cpu_pct = Measured::exact(300.0, "cpu");
595 assert!(
596 !signals(&s, &h).working,
597 "adapter says idle; CPU alone doesn't override it"
598 );
599 s.groups.push(Group {
600 id: "daemon:gradle".into(),
601 kind: GroupKind::BuildDaemon,
602 label: "GradleDaemon".into(),
603 idle: true,
604 ..Default::default()
605 });
606 let sig = signals(&s, &h);
607 assert!(sig.leftovers && !sig.working);
608 s.groups[1].idle = false;
609 s.groups[1].totals.cpu_pct = Measured::exact(180.0, "cpu");
610 let sig = signals(&s, &h);
611 assert!(sig.working && !sig.leftovers);
612 let r = reasons(&s, &h);
613 assert!(r
614 .iter()
615 .any(|r| r.key == "build_active" && r.text == "GradleDaemon building"));
616 }
617}