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
22fn 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(task, libc::MACH_TASK_BASIC_INFO, &mut info as *mut _ as *mut libc::integer_t, &mut count)
36    };
37    if ret != libc::KERN_SUCCESS {
38        return None;
39    }
40    Some(info.resident_size as f64 / (1024.0 * 1024.0))
41}
42
43/// Returns the current process Resident Set Size in **megabytes**, or `None` if
44/// it cannot be determined on the current platform.
45#[cfg(target_os = "linux")]
46#[allow(
47    unsafe_code,
48    reason = "Intentional compatibility, platform, or test-only suppression."
49)]
50pub fn resident_set_size_mb() -> Option<f64> {
51    let contents = std::fs::read_to_string("/proc/self/statm").ok()?;
52    let field = contents.split_whitespace().nth(1)?;
53    let pages: f64 = field.parse().ok()?;
54    // SAFETY: `_SC_PAGESIZE` is a compile-time constant selector passed by value.
55    // `sysconf` only reads the selector and returns a `c_long`; it performs no
56    // mutable aliasing against process memory and has no preconditions on this
57    // input. The result is a stable system constant for the process lifetime.
58    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as f64;
59    Some(pages * page_size / (1024.0 * 1024.0))
60}
61
62/// Fallback for unsupported platforms.
63#[cfg(not(any(target_os = "macos", target_os = "linux")))]
64pub fn resident_set_size_mb() -> Option<f64> {
65    None
66}
67
68/// Sample RSS once and return the value in MB (0.0 if unavailable).
69pub fn sample_rss_mb() -> f64 {
70    resident_set_size_mb().unwrap_or(0.0)
71}
72
73/// Sample RSS repeatedly, returning the maximum observed value in MB.
74/// Useful for capturing peak memory during a burst of activity.
75pub fn sample_peak_rss_mb(duration: Duration, poll_interval: Duration) -> f64 {
76    let start = std::time::Instant::now();
77    let mut peak = 0.0;
78    while start.elapsed() < duration {
79        let v = sample_rss_mb();
80        if v > peak {
81            peak = v;
82        }
83        std::thread::sleep(poll_interval);
84    }
85    peak
86}