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")]
37pub fn resident_set_size_mb() -> Option<f64> {
38    let contents = std::fs::read_to_string("/proc/self/statm").ok()?;
39    let field = contents.split_whitespace().nth(1)?;
40    let pages: f64 = field.parse().ok()?;
41    // SAFETY: `_SC_PAGESIZE` is a compile-time constant selector passed by value.
42    // `sysconf` only reads the selector and returns a `c_long`; it performs no
43    // mutable aliasing against process memory and has no preconditions on this
44    // input. The result is a stable system constant for the process lifetime.
45    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as f64;
46    Some(pages * page_size / (1024.0 * 1024.0))
47}
48
49/// Fallback for unsupported platforms.
50#[cfg(not(any(target_os = "macos", target_os = "linux")))]
51pub fn resident_set_size_mb() -> Option<f64> {
52    None
53}
54
55/// Sample RSS once and return the value in MB (0.0 if unavailable).
56pub fn sample_rss_mb() -> f64 {
57    resident_set_size_mb().unwrap_or(0.0)
58}
59
60/// Sample RSS repeatedly, returning the maximum observed value in MB.
61/// Useful for capturing peak memory during a burst of activity.
62pub fn sample_peak_rss_mb(duration: Duration, poll_interval: Duration) -> f64 {
63    let start = std::time::Instant::now();
64    let mut peak = 0.0;
65    while start.elapsed() < duration {
66        let v = sample_rss_mb();
67        if v > peak {
68            peak = v;
69        }
70        std::thread::sleep(poll_interval);
71    }
72    peak
73}