//! What a coding session on this Mac is holding, and what it will want back. //! //! A Mac admits work by MEASURING it. The machine-wide build lock //! (`scripts/with-build-lock.sh`) answers one question — is somebody building //! — and answers it for the whole machine, so a Mac with 128 GB and one small //! `cargo check` in flight looks exactly as busy as a Mac with 16 GB running a //! full Xcode archive. //! //! **THE KERNEL MEASURES WHAT IS IN USE; THIS MEASURES ONLY THE HEADROOM.** //! Summed RSS is not an answer to "how full is this Mac" — it counts every //! shared page once per process, and a wide build tree over-reports by more //! than half (37.9 GB on a 24 GB Mac, measured 2026-09-22). `vm_stat` already //! answers that question properly. What the kernel cannot know is what a //! session is about to want: one sitting at 0.3 GB that has been seen peaking //! at 1.4 GB will take 1.1 GB more before it is done. That difference is the //! only thing computed here, and [`committed_gb`] adds it to the kernel's own //! figure. //! //! **THE READING IS SPLIT FROM THE ARITHMETIC**, exactly as `machine.rs` //! splits it. [`snapshot`] is the one function that runs anything; everything //! else is a pure function over a `Vec` with its own test, so the //! rule a budget lives or dies by is checked against an invented process tree //! rather than against whatever happened to be running. use std::collections::BTreeSet; /// One line of the process table. #[derive(Debug, Clone, PartialEq)] pub struct ProcessRow { /// The process. pub pid: u32, /// Its parent, which is the only thing that makes a tree out of this list. pub ppid: u32, /// Resident set size in KILOBYTES — `ps` reports it that way on macOS and /// on Linux, and the conversion happens once, in [`rss_gb`]. pub rss_kb: u64, /// `%CPU` as `ps` computes it: 100 is one core saturated, and a machine /// with twelve cores can report 1200. pub cpu_pct: f64, /// The executable, as `comm=` spells it — usually an absolute path. pub command: String, } /// One live coding session, as the budget sees it. #[derive(Debug, Clone, Copy, PartialEq)] pub struct SessionUsage { /// The agent's own pid; its tree is everything the session started. pub root: u32, /// The largest that tree has been measured at, gigabytes. pub peak_gb: f64, } /// Kilobytes in a gigabyte, as [`rss_gb`] reports it. const KB_PER_GB: f64 = 1024.0 * 1024.0; /// The process table, or an EMPTY vec when it could not be read. /// /// The one impure function here. An empty answer means **nothing was /// measured**, never "nothing is running" — and the arithmetic above it is /// built so that mistake is made in the safe direction: a session whose tree /// cannot be found reads as holding nothing, so its whole peak counts as /// headroom and the Mac looks fuller than it is. A reading that failed costs a /// Mac some work, never a session its memory. pub fn snapshot() -> Vec { let mut command = std::process::Command::new("/bin/ps"); command.args(["-axo", "pid=,ppid=,rss=,pcpu=,comm="]); let Some(out) = crate::machine::output_within(command, crate::machine::ACCOUNT_ASK_TIMEOUT) else { return Vec::new(); }; if !out.status.success() { return Vec::new(); } parse_ps(&String::from_utf8_lossy(&out.stdout)) } /// One [`ProcessRow`] per line of `ps -axo pid=,ppid=,rss=,pcpu=,comm=`. /// /// `comm` is LAST because it is the only field that can hold a space — /// `/Applications/Android Studio.app/…/emulator` is an ordinary path on a /// developer's Mac. So the first four whitespace fields are the numbers and /// everything after them is the command. A line that is short, or whose /// numbers are not numbers, is SKIPPED: a malformed table costs one row, never /// the daemon. pub fn parse_ps(text: &str) -> Vec { text.lines() .filter_map(|line| { let mut fields = line.split_whitespace(); let pid = fields.next()?.parse().ok()?; let ppid = fields.next()?.parse().ok()?; let rss_kb = fields.next()?.parse().ok()?; let cpu_pct = fields.next()?.parse().ok()?; let command = fields.collect::>().join(" "); (!command.is_empty()).then_some(ProcessRow { pid, ppid, rss_kb, cpu_pct, command, }) }) .collect() } /// `root` and every descendant of it. /// /// **IT TERMINATES ON A CYCLE.** A process table is a tree in principle and a /// list of two numbers in practice; a row that is its own parent, or a pair /// that point at each other, is enough to hang a daemon that walks it /// naively. This absorbs children of the accepted set repeatedly and stops /// after at most one pass per row, which is the most passes a real tree can /// need. pub fn tree(rows: &[ProcessRow], root: u32) -> BTreeSet { let mut held = BTreeSet::from([root]); for _ in 0..rows.len() { let mut grew = false; for row in rows { if row.pid != row.ppid && held.contains(&row.ppid) && held.insert(row.pid) { grew = true; } } if !grew { break; } } held } /// What those processes hold, in gigabytes. /// /// Summed RSS, which double-counts shared pages — sound for comparing ONE /// tree against its own past readings, which is all [`committed_gb`] asks of /// it, and wrong as an answer to how full a machine is. That question belongs /// to the kernel; see the module's own comment. pub fn rss_gb(rows: &[ProcessRow], pids: &BTreeSet) -> f64 { let kb: u64 = rows .iter() .filter(|row| pids.contains(&row.pid)) .map(|row| row.rss_kb) .sum(); kb as f64 / KB_PER_GB } /// **THE MEMORY THIS MAC HAS ALREADY PROMISED**, in gigabytes: /// /// ```text /// committed = used_now + Σ over live sessions of max(0, peak − tree now) /// ``` /// /// `used_now_gb` is the KERNEL'S figure, off the same memory reading the /// sample's free percentage comes from. Everything already running is inside /// it: the build lock's holder, every simulator, every `cargo` and every /// `xcodebuild` a person started by hand — measured by the kernel, shared /// pages and all, rather than summed by us. **That is where the lock holder /// went**, and where the list of heavy process names went with it: a sum over /// named process trees was strictly less accurate than the number the OS /// already keeps, and it could not see a build whose name nobody had listed. /// /// What is added to it is HEADROOM, and only a session has any: a session /// sitting at 0.3 GB that has been measured at 1.4 GB will want 1.1 GB more /// before it is done, and admitting work against its idle footprint is how a /// Mac ends up swapping the moment two sessions compile at once. A session at /// or above its recorded peak adds NOTHING — never a negative, which would let /// one idle-looking session pay for another's headroom. /// /// The answer is therefore never below `used_now_gb`, and it is deliberately /// NOT capped at the machine's memory: a Mac whose sessions have more headroom /// than it has memory left is genuinely over-committed, and the number that /// says so is the one a dispatcher needs. pub fn committed_gb(rows: &[ProcessRow], sessions: &[SessionUsage], used_now_gb: f64) -> f64 { used_now_gb + sessions .iter() .map(|session| { let holding = rss_gb(rows, &tree(rows, session.root)); (session.peak_gb - holding).max(0.0) }) .sum::() } #[cfg(test)] #[path = "processes_tests.rs"] mod processes_tests;