Skip to main content

lean_ctx/core/
memory_guard.rs

1//! Process-level RAM guardian with adaptive eviction and hard OOM protection.
2//!
3//! Monitors RSS via platform-specific APIs and triggers tiered cache eviction
4//! when memory usage exceeds configurable thresholds (default: 5% of system RAM,
5//! lowered to `mcp_max_rss_mb` — 512 MB — inside a stdio MCP server).
6//! At critical levels, performs aggressive eviction and signals background tasks
7//! to abort. It never exits the process — recovery is always via eviction.
8
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
11
12static PEAK_RSS: AtomicU64 = AtomicU64::new(0);
13static GUARD_RUNNING: AtomicBool = AtomicBool::new(false);
14static ABORT_REQUESTED: AtomicBool = AtomicBool::new(false);
15static CURRENT_PRESSURE: AtomicU8 = AtomicU8::new(0);
16/// Absolute per-process RSS target in bytes (0 = none). The stdio MCP server
17/// sets it at startup: hosts such as the Codex app-server keep one server per
18/// loaded thread alive for days, and on a large machine the percentage target
19/// alone let each of them settle near 1 GB before any eviction ran.
20static PROCESS_RSS_CAP: AtomicU64 = AtomicU64::new(0);
21
22/// Install an absolute RSS target for this process; the effective limit is the
23/// lower of it and the `max_ram_percent` target. `0` removes it.
24pub fn set_process_rss_cap(bytes: u64) {
25    PROCESS_RSS_CAP.store(bytes, Ordering::Relaxed);
26}
27
28/// Current process memory in bytes, or `None` if unavailable: resident set
29/// size on Linux and Windows, physical footprint on macOS (see
30/// `macos_footprint` — resident size there hides compressed pages).
31pub fn get_rss_bytes() -> Option<u64> {
32    #[cfg(target_os = "linux")]
33    {
34        linux_rss()
35    }
36    #[cfg(target_os = "macos")]
37    {
38        macos_rss()
39    }
40    #[cfg(windows)]
41    {
42        windows_rss()
43    }
44    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
45    {
46        None
47    }
48}
49
50/// RSS of an arbitrary process by PID, or `None` if unavailable/dead.
51pub fn get_rss_bytes_for_pid(pid: u32) -> Option<u64> {
52    #[cfg(target_os = "linux")]
53    {
54        linux_rss_for_pid(pid)
55    }
56    #[cfg(target_os = "macos")]
57    {
58        macos_rss_for_pid(pid)
59    }
60    #[cfg(windows)]
61    {
62        windows_rss_for_pid(pid)
63    }
64    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
65    {
66        let _ = pid;
67        None
68    }
69}
70
71/// Total physical RAM in bytes, or `None` if unavailable.
72pub fn get_system_ram_bytes() -> Option<u64> {
73    #[cfg(target_os = "linux")]
74    {
75        linux_memtotal()
76    }
77    #[cfg(target_os = "macos")]
78    {
79        macos_memsize()
80    }
81    #[cfg(windows)]
82    {
83        windows_system_ram()
84    }
85    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
86    {
87        None
88    }
89}
90
91#[cfg(windows)]
92fn windows_rss() -> Option<u64> {
93    use windows_sys::Win32::System::Threading::GetCurrentProcess;
94
95    // SAFETY: GetCurrentProcess returns a pseudo-handle valid for the current
96    // process and it must not be closed.
97    let process = unsafe { GetCurrentProcess() };
98    windows_rss_for_handle(process)
99}
100
101#[cfg(windows)]
102fn windows_rss_for_pid(pid: u32) -> Option<u64> {
103    use windows_sys::Win32::Foundation::CloseHandle;
104    use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};
105
106    // SAFETY: OpenProcess is called with query-only access. A successful real
107    // handle is closed before returning.
108    let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
109
110    if process.is_null() {
111        return None;
112    }
113
114    let rss = windows_rss_for_handle(process);
115
116    // SAFETY: `process` is a real handle returned successfully by OpenProcess.
117    unsafe {
118        let _ = CloseHandle(process);
119    }
120
121    rss
122}
123
124#[cfg(windows)]
125fn windows_rss_for_handle(process: windows_sys::Win32::Foundation::HANDLE) -> Option<u64> {
126    use windows_sys::Win32::System::ProcessStatus::{
127        K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
128    };
129
130    let mut counters = PROCESS_MEMORY_COUNTERS {
131        cb: std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
132        ..PROCESS_MEMORY_COUNTERS::default()
133    };
134
135    // SAFETY: callers pass the current-process pseudo-handle or a live handle
136    // returned by OpenProcess; `counters` is correctly sized and writable.
137    let ok = unsafe { K32GetProcessMemoryInfo(process, &raw mut counters, counters.cb) };
138
139    if ok == 0 {
140        None
141    } else {
142        Some(counters.WorkingSetSize as u64)
143    }
144}
145
146#[cfg(windows)]
147fn windows_system_ram() -> Option<u64> {
148    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
149
150    let mut status = MEMORYSTATUSEX {
151        dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32,
152        ..MEMORYSTATUSEX::default()
153    };
154
155    // SAFETY: `status` has the required `dwLength` and is writable for the call.
156    let ok = unsafe { GlobalMemoryStatusEx(&raw mut status) };
157
158    if ok == 0 {
159        None
160    } else {
161        Some(status.ullTotalPhys)
162    }
163}
164
165/// Returns the RSS limit in bytes: the `max_ram_percent` target, lowered to
166/// the process cap when one is installed ([`set_process_rss_cap`]).
167pub fn rss_limit_bytes() -> Option<u64> {
168    let sys_ram = get_system_ram_bytes()?;
169    let cfg = super::config::Config::load();
170    let pct = super::config::MemoryGuardConfig::effective(&cfg).max_ram_percent;
171    Some(effective_limit(
172        sys_ram / 100 * u64::from(pct),
173        PROCESS_RSS_CAP.load(Ordering::Relaxed),
174    ))
175}
176
177fn effective_limit(percent_limit: u64, cap: u64) -> u64 {
178    if cap == 0 {
179        percent_limit
180    } else {
181        percent_limit.min(cap)
182    }
183}
184
185/// Pressure tier for `rss` against the base `limit` (#790 multipliers:
186/// Soft above 1×, Medium above 1.2×, Hard above 1.5×, Critical above 2×).
187fn pressure_for(rss: u64, limit: u64) -> PressureLevel {
188    if limit == 0 {
189        return PressureLevel::Normal;
190    }
191    let ratio = rss as f64 / limit as f64;
192    if ratio > 2.0 {
193        PressureLevel::Critical
194    } else if ratio > 1.5 {
195        PressureLevel::Hard
196    } else if ratio > 1.2 {
197        PressureLevel::Medium
198    } else if ratio > 1.0 {
199        PressureLevel::Soft
200    } else {
201        PressureLevel::Normal
202    }
203}
204
205/// Computes a memory-bounded work batch from current RSS and the guardian's
206/// hard threshold (1.5× the configured base limit). Falls back to `max_files`
207/// when RSS is unavailable. The lower bound keeps progress deterministic while
208/// allowing callers to reduce in-flight work substantially under low headroom.
209pub fn adaptive_batch_size(
210    min_files: usize,
211    max_files: usize,
212    estimated_bytes_per_file: u64,
213) -> usize {
214    let headroom = match (rss_limit_bytes(), get_rss_bytes()) {
215        (Some(limit), Some(rss)) => hard_headroom_bytes(limit, rss),
216        _ => return max_files.max(1),
217    };
218    batch_size_for_headroom(headroom, min_files, max_files, estimated_bytes_per_file)
219}
220
221fn hard_headroom_bytes(base_limit: u64, rss: u64) -> u64 {
222    base_limit
223        .saturating_mul(3)
224        .saturating_div(2)
225        .saturating_sub(rss)
226}
227
228fn batch_size_for_headroom(
229    headroom_bytes: u64,
230    min_files: usize,
231    max_files: usize,
232    estimated_bytes_per_file: u64,
233) -> usize {
234    let min_files = min_files.max(1);
235    let max_files = max_files.max(min_files);
236    let estimate = estimated_bytes_per_file.max(1);
237    let by_headroom = (headroom_bytes / estimate).min(max_files as u64) as usize;
238    by_headroom.clamp(min_files, max_files)
239}
240
241#[cfg(test)]
242pub mod adaptive_batch_tests {
243    use super::{batch_size_for_headroom, hard_headroom_bytes};
244
245    #[test]
246    fn hard_headroom_uses_guardian_hard_threshold() {
247        assert_eq!(hard_headroom_bytes(1_000, 1_100), 400);
248        assert_eq!(hard_headroom_bytes(1_000, 1_500), 0);
249        assert_eq!(hard_headroom_bytes(1_000, 2_000), 0);
250    }
251
252    #[test]
253    fn batch_size_tracks_headroom_and_bounds() {
254        assert_eq!(batch_size_for_headroom(1_000, 1, 500, 100), 10);
255        assert_eq!(batch_size_for_headroom(0, 1, 500, 100), 1);
256        assert_eq!(batch_size_for_headroom(100_000, 1, 500, 100), 500);
257    }
258
259    #[test]
260    fn batch_size_sanitizes_zero_bounds_and_estimate() {
261        assert_eq!(batch_size_for_headroom(0, 0, 0, 0), 1);
262    }
263}
264
265/// Recorded peak RSS since process start.
266pub fn peak_rss_bytes() -> u64 {
267    PEAK_RSS.load(Ordering::Relaxed)
268}
269
270/// Snapshot of current memory state for diagnostics.
271#[derive(Debug, Clone, serde::Serialize)]
272pub struct MemorySnapshot {
273    pub rss_bytes: u64,
274    pub peak_rss_bytes: u64,
275    pub system_ram_bytes: u64,
276    pub rss_limit_bytes: u64,
277    pub rss_percent: f64,
278    pub pressure_level: PressureLevel,
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
282#[serde(rename_all = "lowercase")]
283#[repr(u8)]
284pub enum PressureLevel {
285    Normal = 0,
286    Soft = 1,
287    Medium = 2,
288    Hard = 3,
289    Critical = 4,
290}
291
292impl PressureLevel {
293    fn from_u8(v: u8) -> Self {
294        match v {
295            1 => Self::Soft,
296            2 => Self::Medium,
297            3 => Self::Hard,
298            4 => Self::Critical,
299            _ => Self::Normal,
300        }
301    }
302}
303
304impl MemorySnapshot {
305    /// Capture memory snapshot of the **current** process.
306    pub fn capture() -> Option<Self> {
307        Self::capture_impl(get_rss_bytes()?)
308    }
309
310    /// Capture memory snapshot for the **daemon** process (by PID).
311    /// Falls back to the current process if the PID is dead or unreadable.
312    pub fn capture_for_pid(pid: u32) -> Option<Self> {
313        let rss = get_rss_bytes_for_pid(pid).or_else(get_rss_bytes)?;
314        Self::capture_impl(rss)
315    }
316
317    fn capture_impl(rss: u64) -> Option<Self> {
318        let sys = get_system_ram_bytes()?;
319        let limit = rss_limit_bytes()?;
320        let pct = if sys > 0 {
321            (rss as f64 / sys as f64) * 100.0
322        } else {
323            0.0
324        };
325
326        PEAK_RSS.fetch_max(rss, Ordering::Relaxed);
327
328        // #790: tightened multipliers so ABORT fires earlier — e.g. 10% config
329        // on 64 GB → Hard at 9.6 GB, Critical at 12.8 GB. Users expect the
330        // limit to be a meaningful cap, not a 3× suggestion. Measured against
331        // bytes so the per-process cap and the percentage share one ladder.
332        let level = pressure_for(rss, limit);
333
334        Some(Self {
335            rss_bytes: rss,
336            peak_rss_bytes: PEAK_RSS.load(Ordering::Relaxed),
337            system_ram_bytes: sys,
338            rss_limit_bytes: limit,
339            rss_percent: pct,
340            pressure_level: level,
341        })
342    }
343}
344
345/// Live heap bytes and allocator-resident bytes (`stats.allocated`,
346/// `stats.resident`), when jemalloc is the allocator. The gap between process
347/// RSS and `allocated` is what eviction cannot reach: allocator retention,
348/// code and thread stacks.
349pub fn allocator_stats() -> Option<(u64, u64)> {
350    #[cfg(all(feature = "jemalloc", not(windows), not(target_env = "musl")))]
351    {
352        tikv_jemalloc_ctl::epoch::advance().ok()?;
353        let allocated = tikv_jemalloc_ctl::stats::allocated::read().ok()?;
354        let resident = tikv_jemalloc_ctl::stats::resident::read().ok()?;
355        Some((allocated as u64, resident as u64))
356    }
357    #[cfg(not(all(feature = "jemalloc", not(windows), not(target_env = "musl"))))]
358    {
359        None
360    }
361}
362
363/// Force-purge all jemalloc arenas to return memory to the OS.
364/// Uses `MALLCTL_ARENAS_ALL` (value 4096) which is the jemalloc sentinel
365/// for "all arenas". Logs errors instead of silently swallowing them.
366pub fn jemalloc_purge() {
367    #[cfg(all(feature = "jemalloc", not(windows), not(target_env = "musl")))]
368    {
369        use tikv_jemalloc_ctl::raw;
370        let purge_mib = b"arena.4096.purge\0";
371        // SAFETY: `purge_mib` is a static, NUL-terminated jemalloc MIB name and
372        // the value type (`u64`) matches the `arena.<i>.purge` ctl; `raw::write`
373        // validates the name and surfaces errors via `Result`.
374        unsafe {
375            if let Err(e) = raw::write(purge_mib, 0u64) {
376                tracing::debug!("[memory_guard] jemalloc purge failed: {e}");
377            }
378        }
379    }
380}
381
382/// Returns `true` if the guardian has requested background tasks to abort.
383pub fn abort_requested() -> bool {
384    ABORT_REQUESTED.load(Ordering::Relaxed)
385}
386
387/// Quick, non-allocating memory pressure check for hot loops (scanners, indexers).
388/// Reads the cached atomic flag set by the guardian thread — O(1), no syscalls.
389pub fn is_under_pressure() -> bool {
390    current_pressure() >= PressureLevel::Soft
391}
392
393/// Returns the current pressure level as last observed by the guardian thread.
394pub fn current_pressure() -> PressureLevel {
395    PressureLevel::from_u8(CURRENT_PRESSURE.load(Ordering::Relaxed))
396}
397
398#[inline]
399const fn pressure_requests_abort(level: PressureLevel) -> bool {
400    level as u8 >= PressureLevel::Hard as u8
401}
402
403#[inline]
404fn publish_pressure(level: PressureLevel) {
405    CURRENT_PRESSURE.store(level as u8, Ordering::Relaxed);
406    ABORT_REQUESTED.store(pressure_requests_abort(level), Ordering::SeqCst);
407}
408
409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410enum EvictionSchedule {
411    RetryAfter(u64),
412    PauseFor(u64),
413}
414
415impl EvictionSchedule {
416    fn poll_secs(self) -> u64 {
417        match self {
418            Self::RetryAfter(secs) | Self::PauseFor(secs) => secs,
419        }
420    }
421}
422
423/// Backoff state for eviction rounds (any pressure level) that reclaimed no memory.
424#[derive(Default)]
425struct EvictionBackoff {
426    consecutive_zero_progress: u32,
427}
428
429impl EvictionBackoff {
430    const BASE_POLL_SECS: u64 = 1;
431    const MAX_POLL_SECS: u64 = 60;
432    const PAUSE_AFTER_ZERO_PROGRESS_ROUNDS: u32 = 10;
433    const PAUSE_SECS: u64 = 5 * 60;
434
435    fn record(&mut self, made_progress: bool) -> EvictionSchedule {
436        if made_progress {
437            self.consecutive_zero_progress = 0;
438            return EvictionSchedule::RetryAfter(Self::BASE_POLL_SECS);
439        }
440
441        self.consecutive_zero_progress = self.consecutive_zero_progress.saturating_add(1);
442        if self.consecutive_zero_progress >= Self::PAUSE_AFTER_ZERO_PROGRESS_ROUNDS {
443            return EvictionSchedule::PauseFor(Self::PAUSE_SECS);
444        }
445
446        let exponent = self.consecutive_zero_progress.saturating_sub(2).min(6);
447        let poll_secs = Self::BASE_POLL_SECS
448            .saturating_mul(1u64 << exponent)
449            .min(Self::MAX_POLL_SECS);
450        EvictionSchedule::RetryAfter(poll_secs)
451    }
452
453    fn reset(&mut self) {
454        self.consecutive_zero_progress = 0;
455    }
456}
457
458/// When the next eviction round may run. Sampling continues every second
459/// under pressure; the gate only spaces out rounds that reclaimed nothing,
460/// and lets a rise to a higher pressure level through at once.
461#[derive(Default)]
462struct EvictionGate {
463    backoff: EvictionBackoff,
464    last: Option<(PressureLevel, std::time::Instant)>,
465}
466
467impl EvictionGate {
468    fn due(&self, level: PressureLevel, now: std::time::Instant) -> bool {
469        self.last
470            .is_none_or(|(last_level, next_at)| level > last_level || now >= next_at)
471    }
472
473    fn record(
474        &mut self,
475        level: PressureLevel,
476        made_progress: bool,
477        now: std::time::Instant,
478    ) -> EvictionSchedule {
479        if self.last.is_some_and(|(last_level, _)| level > last_level) {
480            self.backoff.reset();
481        }
482        let schedule = self.backoff.record(made_progress);
483        self.last = Some((
484            level,
485            now + std::time::Duration::from_secs(schedule.poll_secs()),
486        ));
487        schedule
488    }
489}
490
491/// Start the background memory guardian task (idempotent).
492/// Polls every 3s (normal), 1s (under pressure), or up to 15s once RSS has been
493/// stably calm (idle backoff). Eviction rounds that reclaim nothing back off to
494/// 60s, then pause for five minutes, at every pressure level; pressure logs
495/// repeat at most once a minute per level. The callback returns whether it reclaimed
496/// memory so the guard can distinguish a real retry from an empty-cache loop.
497pub fn start_guard(eviction_callback: Arc<dyn Fn(PressureLevel) -> bool + Send + Sync>) {
498    // The guardian is a long-lived background monitor for the running
499    // server/daemon. Under `cargo test` a single OS process executes the entire
500    // suite, so its RSS routinely exceeds the per-operation pressure threshold
501    // (default 5% of system RAM). A test that constructs a server (e.g. the
502    // `http_server` tests via `new_shared_with_context`) would start this thread,
503    // which then flips the process-global `CURRENT_PRESSURE` / `ABORT_REQUESTED`
504    // flags. Unrelated later tests in the same binary read those flags and skip
505    // work — notably `graph_index::build_edges_with_cache` aborts edge-building
506    // under pressure, leaving indexed files with no edges. That manifested as an
507    // intermittent, macOS-only flake ("No files depend on Base.gd"). The guardian
508    // has no purpose inside the test harness, so never start it there. Production
509    // and the daemon compile without `cfg!(test)` and are unaffected.
510    if cfg!(test) {
511        return;
512    }
513    if GUARD_RUNNING.swap(true, Ordering::SeqCst) {
514        return;
515    }
516    std::thread::Builder::new()
517        .name("memory-guard".into())
518        .spawn(move || {
519            // Idle backoff: once RSS has stayed below the Soft threshold for
520            // CALM_TICKS_BEFORE_BACKOFF consecutive samples, stretch the poll
521            // interval to IDLE_POLL_SECS. An idle server allocates nothing, so 3s
522            // RSS sampling is just wasted wakeups; any pressure resets the cadence
523            // instantly (below), leaving OOM reaction time during real work
524            // unchanged (#453 idle hygiene).
525            const CALM_TICKS_BEFORE_BACKOFF: u64 = 5;
526            const IDLE_POLL_SECS: u64 = 15;
527            let mut poll_secs = 3u64;
528            let mut calm_ticks = 0u64;
529            let mut gate = EvictionGate::default();
530
531            // Pressure logging: on every level change, then at most once per
532            // LOG_EVERY while the level holds — a process whose baseline sits
533            // above a small cap must not write a line per second for hours.
534            const LOG_EVERY: std::time::Duration = std::time::Duration::from_mins(1);
535            let mut logged: Option<(PressureLevel, std::time::Instant)> = None;
536
537            // #790: the first sample runs immediately — close the 3s blind
538            // window so builders that start right after start_guard() see
539            // real pressure.
540            let mut first = true;
541            loop {
542                if !first {
543                    std::thread::sleep(std::time::Duration::from_secs(poll_secs));
544                }
545                first = false;
546                let Some(snap) = MemorySnapshot::capture() else {
547                    continue;
548                };
549
550                publish_pressure(snap.pressure_level);
551
552                if snap.pressure_level < PressureLevel::Soft {
553                    gate = EvictionGate::default();
554                    logged = None;
555                    calm_ticks = calm_ticks.saturating_add(1);
556                    poll_secs = if calm_ticks >= CALM_TICKS_BEFORE_BACKOFF {
557                        IDLE_POLL_SECS
558                    } else {
559                        3
560                    };
561                    continue;
562                }
563                calm_ticks = 0;
564                // Under pressure the guard samples every second, so
565                // `publish_pressure` (and with it build aborts) never lags;
566                // only eviction attempts follow the gate's backoff.
567                poll_secs = 1;
568
569                if logged.is_none_or(|(level, at)| {
570                    level != snap.pressure_level || at.elapsed() >= LOG_EVERY
571                }) {
572                    logged = Some((snap.pressure_level, std::time::Instant::now()));
573                    let heap = allocator_stats()
574                        .map(|(allocated, _)| format!(" heap={}MB", allocated >> 20))
575                        .unwrap_or_default();
576                    let line = format!(
577                        "[memory_guard] pressure={:?} RSS={:.0}MB{heap} limit={:.0}MB ({:.1}% of {:.0}GB)",
578                        snap.pressure_level,
579                        snap.rss_bytes as f64 / 1_048_576.0,
580                        snap.rss_limit_bytes as f64 / 1_048_576.0,
581                        snap.rss_percent,
582                        snap.system_ram_bytes as f64 / 1_073_741_824.0,
583                    );
584                    if snap.pressure_level == PressureLevel::Critical {
585                        tracing::error!("{line} — aggressive eviction to prevent OS OOM kill");
586                    } else {
587                        tracing::warn!("{line}");
588                    }
589                }
590
591                let now = std::time::Instant::now();
592                if !gate.due(snap.pressure_level, now) {
593                    continue;
594                }
595                let made_progress = (eviction_callback)(snap.pressure_level);
596                if snap.pressure_level >= PressureLevel::Hard {
597                    jemalloc_purge();
598                }
599
600                // Rounds that reclaim nothing back off (and finally pause) at
601                // every level: what is left above the limit is not evictable.
602                // An escalation to a higher level is due at once regardless.
603                if let EvictionSchedule::PauseFor(secs) =
604                    gate.record(snap.pressure_level, made_progress, now)
605                {
606                    tracing::warn!(
607                        "[memory_guard] eviction made no progress for {} rounds at {:?}; \
608                         pausing eviction for {secs}s unless pressure rises",
609                        gate.backoff.consecutive_zero_progress,
610                        snap.pressure_level,
611                    );
612                }
613            }
614        })
615        .ok();
616}
617
618/// Force immediate purge of all caches and jemalloc arenas.
619pub fn force_purge() {
620    jemalloc_purge();
621    tracing::info!("[memory_guard] force_purge completed");
622}
623
624// --- Platform-specific implementations ---
625
626#[cfg(target_os = "linux")]
627fn linux_rss() -> Option<u64> {
628    linux_rss_for_pid(std::process::id())
629}
630
631#[cfg(target_os = "linux")]
632fn linux_rss_for_pid(pid: u32) -> Option<u64> {
633    let path = format!("/proc/{pid}/status");
634    let status = std::fs::read_to_string(path).ok()?;
635    for line in status.lines() {
636        if let Some(val) = line.strip_prefix("VmRSS:") {
637            let kb: u64 = val.trim().trim_end_matches(" kB").trim().parse().ok()?;
638            return Some(kb * 1024);
639        }
640    }
641    None
642}
643
644#[cfg(target_os = "linux")]
645fn linux_memtotal() -> Option<u64> {
646    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
647    for line in info.lines() {
648        if let Some(val) = line.strip_prefix("MemTotal:") {
649            let kb: u64 = val.trim().trim_end_matches(" kB").trim().parse().ok()?;
650            return Some(kb * 1024);
651        }
652    }
653    None
654}
655
656#[cfg(target_os = "macos")]
657fn macos_rss() -> Option<u64> {
658    macos_footprint(std::process::id()).or_else(macos_resident_size)
659}
660
661/// Physical footprint (`ri_phys_footprint`): the figure Activity Monitor and
662/// the kernel's memory-pressure (jetsam) accounting use. Unlike
663/// `resident_size` it keeps counting pages the memory compressor squeezed out
664/// of RAM, so a long-idle process cannot hide a large heap from the guardian —
665/// measured: an idle MCP server at 40 MB resident still had a ~180 MB heap.
666/// `proc_pid_rusage` is public libproc API and works for any same-user pid.
667#[cfg(target_os = "macos")]
668fn macos_footprint(pid: u32) -> Option<u64> {
669    // SAFETY: `rusage_info_v2` is a plain C struct for which all-zero bytes
670    // are a valid value.
671    let mut info: libc::rusage_info_v2 = unsafe { std::mem::zeroed() };
672    let pid = libc::c_int::try_from(pid).ok()?;
673    // SAFETY: `info` is a live, correctly sized `rusage_info_v2` for the
674    // requested `RUSAGE_INFO_V2` flavour; libproc writes at most that struct.
675    let rc = unsafe {
676        libc::proc_pid_rusage(
677            pid,
678            libc::RUSAGE_INFO_V2,
679            std::ptr::from_mut(&mut info).cast::<libc::rusage_info_t>(),
680        )
681    };
682    (rc == 0).then_some(info.ri_phys_footprint)
683}
684
685#[cfg(target_os = "macos")]
686#[allow(deprecated, clippy::borrow_as_ptr, clippy::ptr_as_ptr)]
687fn macos_resident_size() -> Option<u64> {
688    use std::mem;
689    // SAFETY: `mach_task_basic_info_data_t` is a plain C struct for which an
690    // all-zero bit pattern is a valid initial value.
691    let mut info: libc::mach_task_basic_info_data_t = unsafe { mem::zeroed() };
692    let mut count = (mem::size_of::<libc::mach_task_basic_info_data_t>()
693        / mem::size_of::<libc::natural_t>()) as libc::mach_msg_type_number_t;
694    // SAFETY: `mach_task_self()` returns the current task port; `info` and
695    // `count` are live stack locals passed as out-pointers, sized to match the
696    // requested `MACH_TASK_BASIC_INFO` flavour.
697    let kr = unsafe {
698        libc::task_info(
699            libc::mach_task_self(),
700            libc::MACH_TASK_BASIC_INFO,
701            std::ptr::from_mut(&mut info).cast::<i32>(),
702            std::ptr::from_mut(&mut count),
703        )
704    };
705    if kr == libc::KERN_SUCCESS {
706        Some(info.resident_size)
707    } else {
708        None
709    }
710}
711
712#[cfg(target_os = "macos")]
713fn macos_rss_for_pid(pid: u32) -> Option<u64> {
714    if let Some(footprint) = macos_footprint(pid) {
715        return Some(footprint);
716    }
717    // Fallback: `ps -o rss= -p <pid>` (`task_for_pid` needs entitlements).
718    let output = std::process::Command::new("ps")
719        .args(["-o", "rss=", "-p", &pid.to_string()])
720        .output()
721        .ok()?;
722    if !output.status.success() {
723        return None;
724    }
725    let text = String::from_utf8_lossy(&output.stdout);
726    let kb: u64 = text.trim().parse().ok()?;
727    Some(kb * 1024)
728}
729
730#[cfg(target_os = "macos")]
731#[allow(clippy::borrow_as_ptr, clippy::ptr_as_ptr)]
732fn macos_memsize() -> Option<u64> {
733    use std::mem;
734    let mut memsize: u64 = 0;
735    let mut len = mem::size_of::<u64>();
736    let name = b"hw.memsize\0";
737    // SAFETY: `name` is a static, NUL-terminated sysctl name; `memsize` and
738    // `len` are live stack out-pointers whose sizes match the queried value.
739    let ret = unsafe {
740        libc::sysctlbyname(
741            name.as_ptr().cast(),
742            std::ptr::from_mut(&mut memsize).cast::<libc::c_void>(),
743            std::ptr::from_mut(&mut len),
744            std::ptr::null_mut(),
745            0,
746        )
747    };
748    if ret == 0 { Some(memsize) } else { None }
749}
750
751#[cfg(test)]
752pub mod tests {
753    use super::*;
754
755    /// #1899: jemalloc reads the conf as a C string and rejects
756    /// `background_thread` wherever it lacks pthread support.
757    #[cfg(all(feature = "jemalloc", not(windows), not(target_env = "musl")))]
758    #[test]
759    fn jemalloc_conf_is_c_string_with_platform_safe_options() {
760        let conf = crate::JEMALLOC_CONF;
761        assert_eq!(conf.last(), Some(&0), "must be NUL-terminated");
762        let body = std::str::from_utf8(&conf[..conf.len() - 1]).unwrap();
763        assert!(!body.contains('\0'), "no interior NUL");
764        assert!(body.contains("dirty_decay_ms:1000"));
765        assert_eq!(
766            body.contains("background_thread"),
767            cfg!(target_os = "linux"),
768            "background_thread is only supported on Linux: {body}"
769        );
770    }
771
772    #[test]
773    fn rss_returns_some_on_supported_os() {
774        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
775            let rss = get_rss_bytes();
776            assert!(rss.is_some(), "RSS should be readable");
777            assert!(rss.unwrap() > 0, "RSS should be > 0");
778        }
779    }
780
781    #[test]
782    fn system_ram_returns_some_on_supported_os() {
783        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
784            let ram = get_system_ram_bytes();
785            assert!(ram.is_some(), "System RAM should be readable");
786            assert!(ram.unwrap() > 1_000_000, "System RAM should be > 1MB");
787        }
788    }
789
790    #[test]
791    fn snapshot_captures_correctly() {
792        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
793            let snap = MemorySnapshot::capture();
794            assert!(snap.is_some());
795            let s = snap.unwrap();
796            assert!(s.rss_bytes > 0);
797            assert!(s.system_ram_bytes > s.rss_bytes);
798            assert!(s.rss_percent > 0.0 && s.rss_percent < 100.0);
799        }
800    }
801
802    #[test]
803    fn peak_rss_tracks_maximum() {
804        PEAK_RSS.store(0, Ordering::Relaxed);
805        PEAK_RSS.fetch_max(100, Ordering::Relaxed);
806        PEAK_RSS.fetch_max(50, Ordering::Relaxed);
807        assert_eq!(PEAK_RSS.load(Ordering::Relaxed), 100);
808    }
809
810    #[test]
811    fn pressure_level_roundtrip() {
812        for level in [
813            PressureLevel::Normal,
814            PressureLevel::Soft,
815            PressureLevel::Medium,
816            PressureLevel::Hard,
817            PressureLevel::Critical,
818        ] {
819            assert_eq!(PressureLevel::from_u8(level as u8), level);
820        }
821    }
822
823    #[test]
824    fn process_cap_lowers_but_never_raises_the_percent_limit() {
825        const MB: u64 = 1024 * 1024;
826        assert_eq!(effective_limit(3200 * MB, 0), 3200 * MB);
827        assert_eq!(effective_limit(3200 * MB, 512 * MB), 512 * MB);
828        assert_eq!(effective_limit(256 * MB, 512 * MB), 256 * MB);
829    }
830
831    #[test]
832    fn pressure_ladder_against_a_512mb_cap() {
833        const MB: u64 = 1024 * 1024;
834        let limit = 512 * MB;
835        assert_eq!(pressure_for(500 * MB, limit), PressureLevel::Normal);
836        assert_eq!(pressure_for(520 * MB, limit), PressureLevel::Soft);
837        assert_eq!(pressure_for(650 * MB, limit), PressureLevel::Medium);
838        assert_eq!(pressure_for(800 * MB, limit), PressureLevel::Hard);
839        // The ~1 GB Codex instances land in Critical → emergency drop.
840        assert_eq!(pressure_for(1100 * MB, limit), PressureLevel::Critical);
841        assert_eq!(pressure_for(u64::MAX, 0), PressureLevel::Normal);
842    }
843
844    #[test]
845    fn hard_pressure_requests_abort_immediately() {
846        assert!(!pressure_requests_abort(PressureLevel::Normal));
847        assert!(!pressure_requests_abort(PressureLevel::Soft));
848        assert!(!pressure_requests_abort(PressureLevel::Medium));
849        assert!(pressure_requests_abort(PressureLevel::Hard));
850        assert!(pressure_requests_abort(PressureLevel::Critical));
851    }
852
853    #[test]
854    fn eviction_gate_spaces_fruitless_rounds_but_lets_escalation_through() {
855        let start = std::time::Instant::now();
856        let at = |secs: u64| start + std::time::Duration::from_secs(secs);
857        let mut gate = EvictionGate::default();
858        assert!(gate.due(PressureLevel::Soft, start));
859
860        // Ten fruitless Soft rounds: 1,1,2,4,…,60 s apart, then a 5 min pause.
861        let mut now = start;
862        let mut paused_from = start;
863        let mut schedule = EvictionSchedule::RetryAfter(0);
864        for _ in 0..10 {
865            assert!(gate.due(PressureLevel::Soft, now));
866            paused_from = now;
867            schedule = gate.record(PressureLevel::Soft, false, now);
868            now += std::time::Duration::from_secs(schedule.poll_secs());
869        }
870        assert_eq!(schedule, EvictionSchedule::PauseFor(5 * 60));
871        assert!(!gate.due(
872            PressureLevel::Soft,
873            paused_from + std::time::Duration::from_secs(1)
874        ));
875        assert!(gate.due(
876            PressureLevel::Medium,
877            paused_from + std::time::Duration::from_secs(1)
878        ));
879
880        // A rise to Critical during the pause is evicted at once, with a fresh backoff.
881        assert!(gate.due(
882            PressureLevel::Critical,
883            paused_from + std::time::Duration::from_secs(1)
884        ));
885        assert_eq!(
886            gate.record(PressureLevel::Critical, true, at(1000)),
887            EvictionSchedule::RetryAfter(1)
888        );
889        assert!(!gate.due(PressureLevel::Critical, at(1000)));
890        assert!(gate.due(PressureLevel::Critical, at(1001)));
891    }
892
893    #[test]
894    fn critical_zero_progress_backoff_doubles_then_pauses_and_resets() {
895        let mut backoff = EvictionBackoff::default();
896
897        assert_eq!(backoff.record(false), EvictionSchedule::RetryAfter(1));
898        assert_eq!(backoff.record(false), EvictionSchedule::RetryAfter(1));
899        assert_eq!(backoff.record(false), EvictionSchedule::RetryAfter(2));
900        assert_eq!(backoff.record(false), EvictionSchedule::RetryAfter(4));
901
902        for _ in 0..4 {
903            backoff.record(false);
904        }
905        assert_eq!(backoff.record(false), EvictionSchedule::RetryAfter(60));
906        assert_eq!(backoff.record(false), EvictionSchedule::PauseFor(5 * 60));
907
908        assert_eq!(backoff.record(true), EvictionSchedule::RetryAfter(1));
909        assert_eq!(backoff.consecutive_zero_progress, 0);
910    }
911
912    #[test]
913    fn atomic_pressure_defaults_to_normal() {
914        assert_eq!(current_pressure(), PressureLevel::Normal);
915    }
916
917    #[test]
918    fn start_guard_is_noop_under_test() {
919        // Regression guard: the background guardian must never run inside the
920        // test harness. If it did, its 3s poll would observe the suite's large
921        // RSS, flip the global pressure/abort flags, and silently make unrelated
922        // tests (e.g. graph edge-building) skip work — an order/timing-dependent
923        // flake. `start_guard` must be a no-op under `cfg!(test)`.
924        let fired = Arc::new(AtomicBool::new(false));
925        let fired_cb = fired.clone();
926        start_guard(Arc::new(move |_| {
927            fired_cb.store(true, Ordering::SeqCst);
928            false
929        }));
930
931        assert!(
932            !GUARD_RUNNING.load(Ordering::Relaxed),
933            "guardian thread must not start under cfg!(test)"
934        );
935        assert_eq!(current_pressure(), PressureLevel::Normal);
936        assert!(!abort_requested());
937        assert!(
938            !fired.load(Ordering::Relaxed),
939            "eviction callback must never fire in tests"
940        );
941    }
942
943    #[test]
944    fn rss_for_own_pid_matches_self() {
945        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
946            let self_rss = get_rss_bytes().unwrap();
947            let pid_rss = get_rss_bytes_for_pid(std::process::id()).unwrap();
948            let ratio = self_rss as f64 / pid_rss as f64;
949            assert!(
950                (0.5..2.0).contains(&ratio),
951                "self RSS ({self_rss}) and pid-based RSS ({pid_rss}) should be within 2x"
952            );
953        }
954    }
955
956    #[test]
957    fn rss_for_dead_pid_returns_none() {
958        let dead_pid = 999_999_999u32;
959        assert!(get_rss_bytes_for_pid(dead_pid).is_none());
960    }
961
962    #[test]
963    fn capture_for_pid_falls_back_on_dead_pid() {
964        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
965            let snap = MemorySnapshot::capture_for_pid(999_999_999);
966            assert!(snap.is_some(), "should fall back to self RSS");
967        }
968    }
969}