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#[expect(
13    clippy::cast_possible_truncation,
14    reason = "The macOS Mach message count is defined as the platform ABI's bounded integer type."
15)]
16#[allow(
17    deprecated,
18    unsafe_code,
19    unused_qualifications,
20    reason = "Intentional compatibility, platform, or test-only suppression."
21)] // libc::mach_task_self is deprecated; qualification is required here
22pub fn resident_set_size_mb() -> Option<f64> {
23    // SAFETY: `mach_task_basic_info` is a plain old data struct; zeroing it
24    // produces a valid (all-zero) starting value before `task_info` fills it.
25    let mut info: libc::mach_task_basic_info = unsafe { std::mem::zeroed() };
26    let mut count = (std::mem::size_of::<libc::mach_task_basic_info>() / std::mem::size_of::<libc::integer_t>())
27        as libc::mach_msg_type_number_t;
28    // SAFETY: `mach_task_self()` returns a send-right to the current task with
29    // no preconditions; it cannot fail to produce a valid port name.
30    let task = unsafe { libc::mach_task_self() };
31    // SAFETY: `task` is our own task port; `info` and `count` are valid
32    // out-pointers of the expected size, and `task_info` only writes them on
33    // success.
34    let ret = unsafe {
35        libc::task_info(
36            task,
37            libc::MACH_TASK_BASIC_INFO,
38            std::ptr::addr_of_mut!(info).cast::<libc::integer_t>(),
39            &mut count,
40        )
41    };
42    if ret != libc::KERN_SUCCESS {
43        return None;
44    }
45    Some(info.resident_size as f64 / (1024.0 * 1024.0))
46}
47
48/// Returns the current process Resident Set Size in **megabytes**, or `None` if
49/// it cannot be determined on the current platform.
50#[cfg(target_os = "linux")]
51#[allow(
52    unsafe_code,
53    reason = "Intentional compatibility, platform, or test-only suppression."
54)]
55pub fn resident_set_size_mb() -> Option<f64> {
56    let contents = std::fs::read_to_string("/proc/self/statm").ok()?;
57    let field = contents.split_whitespace().nth(1)?;
58    let pages: f64 = field.parse().ok()?;
59    // SAFETY: `_SC_PAGESIZE` is a compile-time constant selector passed by value.
60    // `sysconf` only reads the selector and returns a `c_long`; it performs no
61    // mutable aliasing against process memory and has no preconditions on this
62    // input. The result is a stable system constant for the process lifetime.
63    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as f64;
64    Some(pages * page_size / (1024.0 * 1024.0))
65}
66
67/// Fallback for unsupported platforms.
68#[cfg(not(any(target_os = "macos", target_os = "linux")))]
69pub fn resident_set_size_mb() -> Option<f64> {
70    None
71}
72
73/// Sample RSS once and return the value in MB (0.0 if unavailable).
74pub fn sample_rss_mb() -> f64 {
75    resident_set_size_mb().unwrap_or(0.0)
76}
77
78/// Sample RSS repeatedly, returning the maximum observed value in MB.
79/// Useful for capturing peak memory during a burst of activity.
80pub fn sample_peak_rss_mb(duration: Duration, poll_interval: Duration) -> f64 {
81    let start = std::time::Instant::now();
82    let mut peak = 0.0;
83    while start.elapsed() < duration {
84        let v = sample_rss_mb();
85        if v > peak {
86            peak = v;
87        }
88        std::thread::sleep(poll_interval);
89    }
90    peak
91}