1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ProcessResourceUsage {
13 pub cpu_us: i64,
16 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 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 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
64pub fn current_rss_bytes() -> Option<i64> {
67 platform_current_rss_bytes()
68}
69
70#[cfg(unix)]
73pub fn process_resource_usage() -> Option<ProcessResourceUsage> {
74 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)] fn 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#[cfg(not(unix))]
107pub fn process_resource_usage() -> Option<ProcessResourceUsage> {
108 None
109}
110
111pub 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 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 #[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, max_rss_bytes: 1_000_000,
160 };
161 let end = ProcessResourceUsage {
162 cpu_us: 500 * 60 * 1_000_000 + 1_500, 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 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 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 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 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}