Skip to main content

schedr_agent/
memory.rs

1//! The memory watchdog (see archive/PROJECT.md, Worker memory protection and crash recovery): every
2//! task shares the pod's memory, and the kernel's out-of-memory killer would take every task
3//! and the agent with it, so the agent measures each task and kills only the one over its
4//! budget.
5//!
6//! - **The limit** is the smallest cgroup v2 `memory.max` from the agent's own cgroup up to
7//!   the root (`/proc/self/cgroup`), so it is found in a pod and on a host alike. None found
8//!   (`max`, cgroup v1): no task is killed but one asking for its own budget, peak memory is
9//!   still measured. No `/proc`: nothing is measured and nothing is killed.
10//! - **The budget** per task is its own (`memory=`, decision 436), else `[worker]
11//!   memory_budget`, else (limit − 10 %) ÷ slots. A task asking for more than the limit less
12//!   the reserve is turned away (decision 437); its cleanup, moved here, gets at most that.
13//! - **A task's memory** is the PSS (`/proc/<pid>/smaps_rollup`) of every process in its
14//!   process group (what SIGTERM and SIGKILL reach), RSS where PSS can't be read: PSS splits
15//!   shared pages between the processes sharing them, so a tree isn't counted many times. Not
16//!   for a forked task: its RSS counts the pages it shares with its fork server, so a sample
17//!   without every PSS is skipped (no kill on it).
18//! - **Sampling** every `memory_check_interval` (1 s); over the budget the group is
19//!   killed at once (SIGKILL: a spike can't wait for a grace period), and the attempt ends
20//!   `oom_killed`. The highest sample is the attempt's peak memory.
21
22use std::io;
23use std::path::{Path, PathBuf};
24use std::sync::{Arc, Mutex, PoisonError};
25use std::time::Duration;
26
27use prometheus_client::metrics::counter::Counter;
28use rustix::process::{Pid, Signal, kill_process_group};
29use tokio::task::JoinHandle;
30
31use crate::status::StopReason;
32use crate::supervise::StopSender;
33
34#[cfg(test)]
35mod tests;
36
37/// The smallest `[worker] memory_budget` accepted: below it no Python process starts.
38pub const MIN_BUDGET: u64 = 16 << 20;
39
40/// The part of the pod's memory limit kept out of the task budgets: for schedr's own process
41/// (the agent, and in standalone the master and the API too).
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Reserve {
44    /// A percentage of the limit.
45    Percent(u8),
46    /// A fixed number of bytes.
47    Bytes(u64),
48}
49
50/// The reserve of `schedr worker` when `[worker] memory_reserve` isn't set.
51pub const WORKER_RESERVE: Reserve = Reserve::Percent(10);
52
53/// The reserve of `schedr standalone` (its process also runs the master and the API) when
54/// `[worker] memory_reserve` isn't set.
55pub const STANDALONE_RESERVE: Reserve = Reserve::Percent(25);
56
57/// How the watchdog watches.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct MemoryWatch {
60    /// Each task's budget; `None`: measured, never killed.
61    pub budget: Option<u64>,
62    /// The most one task may ask for (`memory=`, decision 437): the limit less the reserve;
63    /// `None` without a limit (any is taken).
64    pub ceiling: Option<u64>,
65    /// `schedr` itself, for `schedr task-exec` (a hard memory cap, decision 50); `None`:
66    /// this worker can't cap a task.
67    pub task_exec: Option<PathBuf>,
68    /// How often a task's memory is sampled.
69    pub interval: Duration,
70    /// Where `/proc` is (a fake directory in tests).
71    pub proc_root: PathBuf,
72}
73
74impl Default for MemoryWatch {
75    /// No budget, sampled every second from `/proc`.
76    fn default() -> Self {
77        Self {
78            budget: None,
79            ceiling: None,
80            task_exec: None,
81            interval: Duration::from_secs(1),
82            proc_root: PathBuf::from("/proc"),
83        }
84    }
85}
86
87impl MemoryWatch {
88    /// This watch for a task asking for its own budget (`memory=`, decision 436), at most the
89    /// ceiling: a moved cleanup, never turned away, gets what this worker can give.
90    #[must_use]
91    pub fn for_task(&self, own: Option<u64>) -> Self {
92        let own = own.map(|own| self.ceiling.map_or(own, |ceiling| own.min(ceiling)));
93        Self {
94            budget: own.or(self.budget),
95            ..self.clone()
96        }
97    }
98}
99
100/// What the watchdog saw of one attempt.
101#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
102pub struct MemorySeen {
103    /// The highest sample, in bytes (0: never measured).
104    pub peak: u64,
105    /// The latest sample, in bytes (0: never measured): what the heartbeat reports
106    /// (decision 463).
107    pub last: u64,
108    /// The sample over the budget that got the task killed.
109    pub over: Option<u64>,
110}
111
112/// The watchdog's record of one attempt, shared with whoever reports it.
113pub type SharedSeen = Arc<Mutex<MemorySeen>>;
114
115/// The running tasks' memory, each named, as their watchdogs last measured it (decision 463):
116/// what the heartbeat reports (cheap to clone; clones share it).
117#[derive(Debug, Clone, Default)]
118pub struct RunningMemory(
119    Arc<Mutex<std::collections::BTreeMap<String, (schedr_model::usage::TaskMemory, SharedSeen)>>>,
120);
121
122/// A task in [`RunningMemory`] until it is dropped.
123#[derive(Debug)]
124pub struct Watched {
125    memory: RunningMemory,
126    attempt_id: String,
127}
128
129impl Drop for Watched {
130    fn drop(&mut self) {
131        self.memory.inner().remove(&self.attempt_id);
132    }
133}
134
135impl RunningMemory {
136    fn inner(
137        &self,
138    ) -> std::sync::MutexGuard<
139        '_,
140        std::collections::BTreeMap<String, (schedr_model::usage::TaskMemory, SharedSeen)>,
141    > {
142        self.0.lock().unwrap_or_else(PoisonError::into_inner)
143    }
144
145    /// Counts the task `named` (its `bytes` ignored) with what its watchdog records in `seen`,
146    /// until the returned value is dropped.
147    #[must_use]
148    pub fn watch(&self, named: schedr_model::usage::TaskMemory, seen: SharedSeen) -> Watched {
149        let attempt_id = named.attempt_id.clone();
150        self.inner().insert(attempt_id.clone(), (named, seen));
151        Watched {
152            memory: self.clone(),
153            attempt_id,
154        }
155    }
156
157    /// Each running task with its latest sample, largest first.
158    #[must_use]
159    pub fn now(&self) -> Vec<schedr_model::usage::TaskMemory> {
160        let mut tasks: Vec<schedr_model::usage::TaskMemory> = self
161            .inner()
162            .values()
163            .map(|(named, seen)| schedr_model::usage::TaskMemory {
164                bytes: seen.lock().unwrap_or_else(PoisonError::into_inner).last,
165                ..named.clone()
166            })
167            .collect();
168        tasks.sort_by(|a, b| {
169            b.bytes
170                .cmp(&a.bytes)
171                .then_with(|| a.attempt_id.cmp(&b.attempt_id))
172        });
173        tasks
174    }
175}
176
177/// The smallest cgroup v2 `memory.max` on the way from the agent's cgroup (in
178/// `<proc_root>/self/cgroup`) up to `cgroup_root`; `None` when there is none (unlimited,
179/// cgroup v1).
180///
181/// # Errors
182///
183/// An I/O error if `<proc_root>/self/cgroup` can't be read.
184pub fn cgroup_limit(proc_root: &Path, cgroup_root: &Path) -> io::Result<Option<u64>> {
185    let cgroups = std::fs::read_to_string(proc_root.join("self/cgroup"))?;
186    // cgroup v2 is the line `0::<path>`.
187    let Some(path) = cgroups.lines().find_map(|line| line.strip_prefix("0::")) else {
188        return Ok(None);
189    };
190    let mut dir = cgroup_root.join(path.trim_start_matches('/'));
191    let mut limit: Option<u64> = None;
192    loop {
193        if let Ok(text) = std::fs::read_to_string(dir.join("memory.max"))
194            && let Ok(bytes) = text.trim().parse::<u64>()
195        {
196            limit = Some(limit.map_or(bytes, |l| l.min(bytes)));
197        }
198        if dir == cgroup_root || !dir.pop() || !dir.starts_with(cgroup_root) {
199            return Ok(limit);
200        }
201    }
202}
203
204/// The memory of the agent's own cgroup v2 now (its `memory.current`, from its line in
205/// `<proc_root>/self/cgroup`); `None` outside a cgroup v2 or where it can't be read.
206#[must_use]
207pub fn cgroup_current(proc_root: &Path, cgroup_root: &Path) -> Option<u64> {
208    let cgroups = std::fs::read_to_string(proc_root.join("self/cgroup")).ok()?;
209    let path = cgroups.lines().find_map(|line| line.strip_prefix("0::"))?;
210    let dir = cgroup_root.join(path.trim_start_matches('/'));
211    std::fs::read_to_string(dir.join("memory.current"))
212        .ok()?
213        .trim()
214        .parse()
215        .ok()
216}
217
218/// This process's memory and CPU from `proc_root` (`self/stat`, `self/statm`), in pages of
219/// `page` bytes and `ticks` a second, and its container's from `cgroup_root` (decision 463);
220/// `None` without `/proc`.
221#[must_use]
222pub fn node_usage(
223    proc_root: &Path,
224    cgroup_root: &Path,
225    page: u64,
226    ticks: u64,
227) -> Option<schedr_model::usage::NodeUsage> {
228    let stat = std::fs::read_to_string(proc_root.join("self/stat")).ok()?;
229    let statm = std::fs::read_to_string(proc_root.join("self/statm")).ok()?;
230    // After the command (field 2, in parentheses): field 3 is [0].
231    let fields: Vec<&str> = stat[stat.rfind(')')? + 1..].split_whitespace().collect();
232    let field = |n: usize| fields.get(n - 3)?.parse::<u64>().ok();
233    let resident_pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
234    #[expect(clippy::cast_precision_loss, reason = "seconds from clock ticks")]
235    let cpu_seconds = (field(14)? + field(15)?) as f64 / ticks.max(1) as f64;
236    Some(schedr_model::usage::NodeUsage {
237        resident_bytes: resident_pages.saturating_mul(page),
238        cpu_seconds,
239        container_bytes: cgroup_current(proc_root, cgroup_root),
240        container_limit_bytes: cgroup_limit(proc_root, cgroup_root).ok().flatten(),
241    })
242}
243
244/// [`node_usage`] of this process, from `/proc` and `/sys/fs/cgroup`.
245#[must_use]
246pub fn this_node() -> Option<schedr_model::usage::NodeUsage> {
247    node_usage(
248        Path::new("/proc"),
249        Path::new("/sys/fs/cgroup"),
250        u64::try_from(rustix::param::page_size()).unwrap_or(4096),
251        rustix::param::clock_ticks_per_second(),
252    )
253}
254
255/// The most one task may take of `limit`: what `reserve` leaves (decision 437).
256#[must_use]
257pub fn ceiling(limit: u64, reserve: Reserve) -> u64 {
258    let kept = match reserve {
259        Reserve::Percent(percent) => limit / 100 * u64::from(percent),
260        Reserve::Bytes(bytes) => bytes,
261    };
262    limit.saturating_sub(kept)
263}
264
265/// Each task's budget: `configured`, else (`limit` − `reserve`) ÷ `slots`; `None` without
266/// either.
267#[must_use]
268pub fn budget(
269    configured: Option<u64>,
270    limit: Option<u64>,
271    slots: u32,
272    reserve: Reserve,
273) -> Option<u64> {
274    configured.or_else(|| Some(ceiling(limit?, reserve) / u64::from(slots.max(1))))
275}
276
277/// The memory of the processes in group `pgid`, in bytes (PSS, else RSS where
278/// `rss_fallback`); 0 when none is left. A zombie counts as nothing. `None` when a process's PSS can't be read and RSS
279/// mustn't stand in: a forked process's RSS counts the pages it shares with its fork server
280/// (most of the server's), so it would look far bigger than it is.
281#[must_use]
282pub fn group_memory(proc_root: &Path, pgid: i32, rss_fallback: bool) -> Option<u64> {
283    let Ok(entries) = std::fs::read_dir(proc_root) else {
284        return Some(0);
285    };
286    let page = page_size();
287    let mut total = 0;
288    for entry in entries.flatten() {
289        let name = entry.file_name();
290        if !name.to_string_lossy().bytes().all(|b| b.is_ascii_digit()) {
291            continue;
292        }
293        let dir = entry.path();
294        // A process that ends meanwhile is simply not counted.
295        let Ok(stat) = std::fs::read_to_string(dir.join("stat")) else {
296            continue;
297        };
298        if process_group(&stat) != Some(pgid) {
299            continue;
300        }
301        // An unreaped child has no memory left, and no PSS to read (B54). A process whose
302        // main thread ended while others run still has its memory, read through one of them
303        // (the main thread's own files no longer show it).
304        let dir = if crate::process::stat_fields(&stat)
305            .is_some_and(|(state, _)| crate::process::ended(state))
306        {
307            match crate::process::live_thread(&dir) {
308                Ok(Some(thread)) => thread,
309                Ok(None) => continue,
310                Err(_) => dir,
311            }
312        } else {
313            dir
314        };
315        match pss(&dir) {
316            Some(bytes) => total += bytes,
317            None if rss_fallback => total += rss(&dir, page).unwrap_or(0),
318            None => return None,
319        }
320    }
321    Some(total)
322}
323
324/// The process group in a `/proc/<pid>/stat` line (field 5; the command, field 2, is in
325/// parentheses and may hold spaces or parentheses itself).
326#[must_use]
327pub fn process_group(stat: &str) -> Option<i32> {
328    let after = &stat[stat.rfind(')')? + 1..];
329    after.split_whitespace().nth(2)?.parse().ok()
330}
331
332fn pss(dir: &Path) -> Option<u64> {
333    let rollup = std::fs::read_to_string(dir.join("smaps_rollup")).ok()?;
334    let kib: u64 = rollup
335        .lines()
336        .find_map(|line| line.strip_prefix("Pss:"))?
337        .trim()
338        .trim_end_matches("kB")
339        .trim()
340        .parse()
341        .ok()?;
342    Some(kib * 1024)
343}
344
345fn rss(dir: &Path, page: u64) -> Option<u64> {
346    let statm = std::fs::read_to_string(dir.join("statm")).ok()?;
347    let pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
348    Some(pages * page)
349}
350
351fn page_size() -> u64 {
352    u64::try_from(rustix::param::page_size()).unwrap_or(4096)
353}
354
355/// Samples group `pgid` every `watch.interval`, recording the peak in `seen`; completes with
356/// the sample once one is over the budget (never without a budget). A sample that can't be
357/// read (see [`group_memory`]) is skipped: no kill on a guess.
358pub async fn over_budget(
359    watch: &MemoryWatch,
360    pgid: i32,
361    seen: &SharedSeen,
362    rss_fallback: bool,
363) -> u64 {
364    let mut tick = tokio::time::interval(watch.interval);
365    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
366    loop {
367        tick.tick().await;
368        let root = watch.proc_root.clone();
369        let Some(used) =
370            tokio::task::spawn_blocking(move || group_memory(&root, pgid, rss_fallback))
371                .await
372                .unwrap_or(None)
373        else {
374            continue;
375        };
376        let mut record = seen.lock().unwrap_or_else(PoisonError::into_inner);
377        record.peak = record.peak.max(used);
378        record.last = used;
379        if let Some(budget) = watch.budget
380            && used > budget
381        {
382            record.over = Some(used);
383            return used;
384        }
385    }
386}
387
388/// A group's watch, running until it is dropped (so a process group ID the kernel gives to
389/// someone else later is never watched, let alone killed).
390#[derive(Debug)]
391pub struct GroupWatch {
392    task: JoinHandle<()>,
393}
394
395impl Drop for GroupWatch {
396    fn drop(&mut self) {
397        self.task.abort();
398    }
399}
400
401/// Watches group `pgid` (recording in `seen`) from now until the returned watch is dropped:
402/// over the budget it tells `stop` ([`StopReason::OomKilled`]), kills the group at once
403/// (SIGKILL) and counts it in `kills`. The reason goes first, so the supervisor has it before
404/// the process's end. Started as soon as the process is, it covers a runner's start and a
405/// stopped task's grace period too. `forked`: the group's processes share pages with a fork
406/// server, so RSS never stands in for PSS (see [`group_memory`]).
407#[must_use]
408pub fn watch_group(
409    watch: MemoryWatch,
410    pgid: i32,
411    seen: SharedSeen,
412    stop: StopSender,
413    kills: Counter,
414    forked: bool,
415) -> GroupWatch {
416    let task = tokio::spawn(async move {
417        over_budget(&watch, pgid, &seen, !forked).await;
418        let _ = stop.send(StopReason::OomKilled);
419        if let Some(group) = Pid::from_raw(pgid) {
420            // A group that is gone already is fine.
421            let _ = kill_process_group(group, Signal::KILL);
422        }
423        kills.inc();
424    });
425    GroupWatch { task }
426}
427
428/// `bytes` as people read sizes: `512 B`, `64 KiB`, `1.5 GiB`.
429#[must_use]
430pub fn show_size(bytes: u64) -> String {
431    const UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"];
432    if bytes < 1024 {
433        return format!("{bytes} B");
434    }
435    #[expect(
436        clippy::cast_precision_loss,
437        reason = "a size shown to one decimal place"
438    )]
439    let mut value = bytes as f64 / 1024.0;
440    let mut unit = 0;
441    while value >= 1024.0 && unit < UNITS.len() - 1 {
442        value /= 1024.0;
443        unit += 1;
444    }
445    let text = format!("{value:.1}");
446    let text = text.strip_suffix(".0").unwrap_or(&text);
447    format!("{text} {}", UNITS[unit])
448}
449
450/// The message of an attempt killed for its memory.
451#[must_use]
452pub fn over_budget_message(budget: u64, used: u64) -> String {
453    format!(
454        "exceeded memory budget {} ({} used)",
455        show_size(budget),
456        show_size(used)
457    )
458}