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    sample_peak_rss_mb_while(duration, poll_interval, || true)
82}
83
84/// Like [`sample_peak_rss_mb`], but stops early once `should_continue` returns
85/// `false`. The predicate is checked before each sample, so a caller measuring a
86/// burst can release the sampler as soon as the burst ends instead of waiting out
87/// a worst-case timeout. Intended for blocking threads (e.g. `spawn_blocking`):
88/// each poll is a syscall followed by `thread::sleep`, which must not run on a
89/// Tokio worker.
90pub fn sample_peak_rss_mb_while(
91    duration: Duration,
92    poll_interval: Duration,
93    mut should_continue: impl FnMut() -> bool,
94) -> f64 {
95    let start = std::time::Instant::now();
96    let mut peak: f64 = 0.0;
97    while should_continue() && start.elapsed() < duration {
98        peak = peak.max(sample_rss_mb());
99        std::thread::sleep(poll_interval);
100    }
101    peak
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn peak_sampler_stops_before_first_sample_when_predicate_is_false() {
110        let peak = sample_peak_rss_mb_while(Duration::from_secs(60), Duration::from_millis(1), || false);
111        assert_eq!(peak, 0.0);
112    }
113
114    #[test]
115    fn peak_sampler_observes_every_iteration_until_predicate_flips() {
116        let mut polls = 0;
117        let peak = sample_peak_rss_mb_while(Duration::from_secs(60), Duration::from_millis(1), || {
118            polls += 1;
119            polls <= 3
120        });
121        // Asymmetric predicate: three `true` answers, then `false`; the loop must
122        // not take a fourth sample even though the duration has not elapsed.
123        assert_eq!(polls, 4);
124        assert!(peak >= 0.0);
125    }
126}