Skip to main content

vtcode_commons/
memory.rs

1//! Resident Set Size (RSS) sampling for memory diagnostics.
2//!
3//! Used by the allocator benchmark (`vtcode bench-allocator`) to measure whether
4//! the global allocator returns memory to the OS after bursty/sparse workloads.
5//! Unlike `performance_profiler::get_memory_usage_mb` (Linux `/proc` only, fake
6//! fallback on macOS), this returns a real value on every supported platform.
7use std::time::Duration;
8
9/// Returns the current process Resident Set Size in **megabytes**, or `None` if
10/// it cannot be determined on the current platform.
11#[cfg(target_os = "macos")]
12#[allow(deprecated, unsafe_code, unused_qualifications)] // libc::mach_task_self is deprecated; qualification is required here
13pub fn resident_set_size_mb() -> Option<f64> {
14    // SAFETY: `mach_task_basic_info` is a plain old data struct; zeroing it
15    // produces a valid (all-zero) starting value before `task_info` fills it.
16    let mut info: libc::mach_task_basic_info = unsafe { std::mem::zeroed() };
17    let mut count = (std::mem::size_of::<libc::mach_task_basic_info>() / std::mem::size_of::<libc::integer_t>())
18        as libc::mach_msg_type_number_t;
19    // SAFETY: `mach_task_self()` returns a send-right to the current task with
20    // no preconditions; it cannot fail to produce a valid port name.
21    let task = unsafe { libc::mach_task_self() };
22    // SAFETY: `task` is our own task port; `info` and `count` are valid
23    // out-pointers of the expected size, and `task_info` only writes them on
24    // success.
25    let ret = unsafe {
26        libc::task_info(task, libc::MACH_TASK_BASIC_INFO, &mut info as *mut _ as *mut libc::integer_t, &mut count)
27    };
28    if ret != libc::KERN_SUCCESS {
29        return None;
30    }
31    Some(info.resident_size as f64 / (1024.0 * 1024.0))
32}
33
34/// Returns the current process Resident Set Size in **megabytes**, or `None` if
35/// it cannot be determined on the current platform.
36#[cfg(target_os = "linux")]
37#[allow(unsafe_code)]
38pub fn resident_set_size_mb() -> Option<f64> {
39    let contents = std::fs::read_to_string("/proc/self/statm").ok()?;
40    let field = contents.split_whitespace().nth(1)?;
41    let pages: f64 = field.parse().ok()?;
42    // SAFETY: `_SC_PAGESIZE` is a compile-time constant selector passed by value.
43    // `sysconf` only reads the selector and returns a `c_long`; it performs no
44    // mutable aliasing against process memory and has no preconditions on this
45    // input. The result is a stable system constant for the process lifetime.
46    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as f64;
47    Some(pages * page_size / (1024.0 * 1024.0))
48}
49
50/// Fallback for unsupported platforms.
51#[cfg(not(any(target_os = "macos", target_os = "linux")))]
52pub fn resident_set_size_mb() -> Option<f64> {
53    None
54}
55
56/// Sample RSS once and return the value in MB (0.0 if unavailable).
57pub fn sample_rss_mb() -> f64 {
58    resident_set_size_mb().unwrap_or(0.0)
59}
60
61/// Sample RSS repeatedly, returning the maximum observed value in MB.
62/// Useful for capturing peak memory during a burst of activity.
63pub fn sample_peak_rss_mb(duration: Duration, poll_interval: Duration) -> f64 {
64    let start = std::time::Instant::now();
65    let mut peak = 0.0;
66    while start.elapsed() < duration {
67        let v = sample_rss_mb();
68        if v > peak {
69            peak = v;
70        }
71        std::thread::sleep(poll_interval);
72    }
73    peak
74}