Skip to main content

khive_runtime/
resource.rs

1//! Process-level resource reads (ADR-103 Stage 1).
2//!
3//! Cumulative CPU time and peak RSS via `getrusage(2)`, plus current RSS
4//! from platform APIs, used by the daemon's phase-span logging (background-task start/completion/cancellation) and
5//! the `comm.health` resource self-report. `libc` is already a workspace
6//! dependency (used elsewhere in this crate for `flock`/`kill`), so this
7//! reuses it rather than adding a new one, per ADR-103 Stage 1's preference
8//! for a small std/libc-based read over a dedicated sysinfo-style crate.
9
10/// A point-in-time snapshot of this process's cumulative resource usage.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ProcessResourceUsage {
13    /// Cumulative user+system CPU time consumed by this process since start,
14    /// in microseconds.
15    pub cpu_us: i64,
16    /// Lifetime peak resident set size in bytes.
17    pub max_rss_bytes: i64,
18}
19
20#[cfg(target_os = "linux")]
21fn linux_rss_from_statm(statm: &str, page_size: i64) -> Option<i64> {
22    let pages: i64 = statm.split_whitespace().nth(1)?.parse().ok()?;
23    if pages <= 0 || page_size <= 0 {
24        return None;
25    }
26    pages.checked_mul(page_size)
27}
28
29#[cfg(target_os = "linux")]
30fn platform_current_rss_bytes() -> Option<i64> {
31    // SAFETY: sysconf has no pointer arguments and returns -1 on failure.
32    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
33    let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
34    linux_rss_from_statm(&statm, page_size as i64)
35}
36
37#[cfg(target_os = "macos")]
38#[allow(deprecated)]
39fn platform_current_rss_bytes() -> Option<i64> {
40    // SAFETY: task_info receives a writable, correctly sized Darwin struct and
41    // its count in integer_t units. The self task port needs no ownership transfer.
42    let mut info: libc::mach_task_basic_info = unsafe { std::mem::zeroed() };
43    let mut count = libc::MACH_TASK_BASIC_INFO_COUNT;
44    let result = unsafe {
45        libc::task_info(
46            libc::mach_task_self(),
47            libc::MACH_TASK_BASIC_INFO,
48            (&mut info as *mut libc::mach_task_basic_info).cast(),
49            &mut count,
50        )
51    };
52    if result != libc::KERN_SUCCESS || count < libc::MACH_TASK_BASIC_INFO_COUNT {
53        return None;
54    }
55    let rss = info.resident_size;
56    i64::try_from(rss).ok().filter(|value| *value > 0)
57}
58
59#[cfg(not(any(target_os = "linux", target_os = "macos")))]
60fn platform_current_rss_bytes() -> Option<i64> {
61    None
62}
63
64/// Current resident bytes for this process, or None if the platform cannot
65/// supply the reading. This independent read is not on the CPU snapshot path.
66pub fn current_rss_bytes() -> Option<i64> {
67    platform_current_rss_bytes()
68}
69
70/// Read cumulative CPU and peak RSS with one getrusage call.
71/// Returns None when getrusage is unavailable or fails.
72#[cfg(unix)]
73pub fn process_resource_usage() -> Option<ProcessResourceUsage> {
74    // SAFETY: getrusage writes only the initialized rusage out-parameter.
75    let usage: libc::rusage = unsafe {
76        let mut usage: libc::rusage = std::mem::zeroed();
77        if libc::getrusage(libc::RUSAGE_SELF, &mut usage) != 0 {
78            return None;
79        }
80        usage
81    };
82    Some(resource_usage_from_rusage(&usage))
83}
84
85#[cfg(unix)]
86#[allow(clippy::unnecessary_cast)] // Unix field widths and signedness vary.
87fn resource_usage_from_rusage(usage: &libc::rusage) -> ProcessResourceUsage {
88    let user_us = (usage.ru_utime.tv_sec as i64)
89        .saturating_mul(1_000_000)
90        .saturating_add(i64::from(usage.ru_utime.tv_usec as i32));
91    let sys_us = (usage.ru_stime.tv_sec as i64)
92        .saturating_mul(1_000_000)
93        .saturating_add(i64::from(usage.ru_stime.tv_usec as i32));
94    let max_rss_bytes = if cfg!(target_os = "macos") {
95        usage.ru_maxrss as i64
96    } else {
97        (usage.ru_maxrss as i64).saturating_mul(1024)
98    };
99    ProcessResourceUsage {
100        cpu_us: user_us.saturating_add(sys_us),
101        max_rss_bytes,
102    }
103}
104
105/// Non-Unix fallback: no portable `getrusage` equivalent is wired up.
106#[cfg(not(unix))]
107pub fn process_resource_usage() -> Option<ProcessResourceUsage> {
108    None
109}
110
111/// CPU time consumed strictly between two [`ProcessResourceUsage`] snapshots,
112/// in microseconds.
113///
114/// `cpu_us` on a snapshot is cumulative process CPU time since process
115/// start, not CPU consumed by any one phase, so per-phase attribution needs
116/// the delta between an entry and exit snapshot. The result is floored at
117/// zero so a spurious (should-never-happen) decrease in cumulative CPU
118/// between two reads never surfaces as a negative delta.
119pub fn cpu_delta_us(
120    start: Option<ProcessResourceUsage>,
121    end: Option<ProcessResourceUsage>,
122) -> Option<i64> {
123    match (start, end) {
124        (Some(start), Some(end)) => Some(end.cpu_us.saturating_sub(start.cpu_us).max(0)),
125        _ => None,
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[cfg(any(target_os = "linux", target_os = "macos"))]
134    #[test]
135    fn process_resource_usage_returns_positive_values() {
136        // Do a small amount of work first so ru_utime/ru_maxrss are
137        // guaranteed non-zero on every platform this runs on.
138        let mut acc: u64 = 0;
139        for i in 0..1_000_000u64 {
140            acc = acc.wrapping_add(i);
141        }
142        std::hint::black_box(acc);
143
144        let usage = process_resource_usage().expect("getrusage must succeed on unix CI runners");
145        assert!(usage.cpu_us >= 0, "cpu_us must be non-negative");
146        let current = current_rss_bytes().expect("current RSS must be available");
147        let peak = usage.max_rss_bytes;
148        assert!(current > 0 && peak > 0, "RSS readings must be positive");
149    }
150
151    // `cpu_delta_us` must report the difference between two snapshots, not
152    // either snapshot's raw cumulative value. Synthetic snapshots (rather
153    // than real `getrusage` reads) make this fail deterministically if the
154    // caller regresses to reporting `end.cpu_us` directly.
155    #[test]
156    fn cpu_delta_us_reports_the_difference_not_the_cumulative_end_value() {
157        let start = ProcessResourceUsage {
158            cpu_us: 500 * 60 * 1_000_000, // 500 CPU-minutes already burned
159            max_rss_bytes: 1_000_000,
160        };
161        let end = ProcessResourceUsage {
162            cpu_us: 500 * 60 * 1_000_000 + 1_500, // +1.5ms of CPU during the phase
163            max_rss_bytes: 1_100_000,
164        };
165
166        let delta = cpu_delta_us(Some(start), Some(end)).expect("both snapshots present");
167        assert_eq!(
168            delta, 1_500,
169            "delta must be end-minus-start, not the cumulative end value"
170        );
171        assert!(
172            delta < start.cpu_us,
173            "a correct delta must be far smaller than the pre-existing cumulative total"
174        );
175    }
176
177    #[test]
178    fn cpu_delta_us_saturates_instead_of_underflowing_on_a_spurious_decrease() {
179        let start = ProcessResourceUsage {
180            cpu_us: 1_000,
181            max_rss_bytes: 0,
182        };
183        let end = ProcessResourceUsage {
184            cpu_us: 500,
185            max_rss_bytes: 0,
186        };
187        assert_eq!(cpu_delta_us(Some(start), Some(end)), Some(0));
188    }
189
190    #[test]
191    fn cpu_delta_us_is_none_when_either_snapshot_is_unavailable() {
192        let snap = ProcessResourceUsage {
193            cpu_us: 10,
194            max_rss_bytes: 0,
195        };
196        assert_eq!(cpu_delta_us(None, Some(snap)), None);
197        assert_eq!(cpu_delta_us(Some(snap), None), None);
198        assert_eq!(cpu_delta_us(None, None), None);
199    }
200    #[cfg(target_os = "linux")]
201    #[test]
202    fn statm_parser_validates_pages_units_and_overflow() {
203        assert_eq!(linux_rss_from_statm("100 7 3 2 0 4 0", 4096), Some(28_672));
204        assert_eq!(linux_rss_from_statm("100", 4096), None);
205        assert_eq!(linux_rss_from_statm("100 invalid", 4096), None);
206        assert_eq!(linux_rss_from_statm("100 0", 4096), None);
207        assert_eq!(linux_rss_from_statm("100 1", 0), None);
208        assert_eq!(linux_rss_from_statm("100 9223372036854775807", 4096), None);
209    }
210
211    #[cfg(any(target_os = "linux", target_os = "macos"))]
212    #[test]
213    fn rss_mapping_child() {
214        if std::env::var_os("KHIVE_TEST_RSS_MAPPING_CHILD").is_none() {
215            return;
216        }
217        const BYTES: usize = 96 * 1024 * 1024;
218        // SAFETY: sysconf has no pointer arguments.
219        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
220        assert!(page > 0, "fixture: page size unavailable");
221        let baseline_rss = platform_current_rss_bytes().expect("fixture: baseline OS current RSS");
222        let baseline_reported = current_rss_bytes();
223        let before = process_resource_usage().expect("fixture: baseline getrusage");
224        assert!(baseline_rss > 0, "fixture: baseline current RSS");
225        assert!(before.max_rss_bytes > 0, "fixture: baseline peak RSS");
226        // SAFETY: anonymous private mapping is exclusively owned by this child.
227        let address = unsafe {
228            libc::mmap(
229                std::ptr::null_mut(),
230                BYTES,
231                libc::PROT_READ | libc::PROT_WRITE,
232                libc::MAP_PRIVATE | libc::MAP_ANON,
233                -1,
234                0,
235            )
236        };
237        assert_ne!(address, libc::MAP_FAILED, "fixture: mmap failed");
238        for offset in (0..BYTES).step_by(page as usize) {
239            // SAFETY: offsets are within the fresh writable mapping.
240            unsafe {
241                (address as *mut u8).add(offset).write_volatile(1);
242            }
243        }
244        let high_rss =
245            platform_current_rss_bytes().expect("fixture: OS current RSS after touching pages");
246        let high = process_resource_usage().expect("fixture: populated mapping sample");
247        let high_peak = high.max_rss_bytes;
248        let high_reported = current_rss_bytes();
249        assert!(
250            high_rss > baseline_rss + 32 * 1024 * 1024,
251            "fixture: touched mapping did not raise observed current RSS enough"
252        );
253        // SAFETY: address and size are the matching live mmap allocation.
254        assert_eq!(
255            unsafe { libc::munmap(address, BYTES) },
256            0,
257            "fixture: munmap failed"
258        );
259        let mut observed_drop = false;
260        for _ in 0..100 {
261            let current =
262                platform_current_rss_bytes().expect("fixture: post-unmap OS current sample");
263            if current < high_rss - 32 * 1024 * 1024 {
264                observed_drop = true;
265                break;
266            }
267            std::thread::sleep(std::time::Duration::from_millis(20));
268        }
269        assert!(observed_drop, "fixture: no observed RSS drop within bound");
270        let after = process_resource_usage().expect("fixture: post-unmap resource sample");
271        let baseline_reported = baseline_reported.expect("reported baseline current RSS");
272        let high_reported = high_reported.expect("reported current RSS with mapping");
273        let current = current_rss_bytes().expect("reported current RSS after unmap");
274        let peak = after.max_rss_bytes;
275        assert!(
276            high_reported > baseline_reported.saturating_add(32 * 1024 * 1024),
277            "reported current RSS must rise with the populated mapping"
278        );
279        assert!(
280            current < high_reported.saturating_sub(32 * 1024 * 1024),
281            "reported current RSS must fall after the observed OS RSS drop"
282        );
283        assert!(peak >= high_peak, "lifetime peak must not fall");
284        assert!(
285            current.saturating_add(32 * 1024 * 1024) <= peak,
286            "current RSS plus the qualified drop must not exceed the peak"
287        );
288    }
289
290    #[cfg(any(target_os = "linux", target_os = "macos"))]
291    #[test]
292    fn current_rss_drops_in_isolated_mmap_child() {
293        use std::process::{Command, Stdio};
294        use std::time::{Duration, Instant};
295        let executable = std::env::current_exe().expect("fixture: test executable");
296        let mut child = Command::new(executable)
297            .arg("--exact")
298            .arg("resource::tests::rss_mapping_child")
299            .arg("--nocapture")
300            .env("KHIVE_TEST_RSS_MAPPING_CHILD", "1")
301            .stdout(Stdio::piped())
302            .stderr(Stdio::piped())
303            .spawn()
304            .expect("fixture: spawn child");
305        let deadline = Instant::now() + Duration::from_secs(15);
306        loop {
307            if child.try_wait().expect("fixture: wait child").is_some() {
308                break;
309            }
310            if Instant::now() >= deadline {
311                let _ = child.kill();
312                let _ = child.wait();
313                panic!("fixture: child timed out");
314            }
315            std::thread::sleep(Duration::from_millis(20));
316        }
317        let output = child.wait_with_output().expect("fixture: collect child");
318        let stdout = String::from_utf8_lossy(&output.stdout);
319        let stderr = String::from_utf8_lossy(&output.stderr);
320        assert!(
321            stdout.contains("running 1 test"),
322            "fixture: expected one test: {stdout} {stderr}"
323        );
324        assert!(output.status.success(), "child failed: {stdout} {stderr}");
325    }
326}