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//! At critical levels, performs aggressive eviction and signals background tasks
6//! to abort. It never exits the process — recovery is always via eviction.
7
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
10
11static PEAK_RSS: AtomicU64 = AtomicU64::new(0);
12static GUARD_RUNNING: AtomicBool = AtomicBool::new(false);
13static ABORT_REQUESTED: AtomicBool = AtomicBool::new(false);
14static CURRENT_PRESSURE: AtomicU8 = AtomicU8::new(0);
15
16/// Current process RSS in bytes, or `None` if unavailable.
17pub fn get_rss_bytes() -> Option<u64> {
18    #[cfg(target_os = "linux")]
19    {
20        linux_rss()
21    }
22    #[cfg(target_os = "macos")]
23    {
24        macos_rss()
25    }
26    #[cfg(windows)]
27    {
28        windows_rss()
29    }
30    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
31    {
32        None
33    }
34}
35
36/// RSS of an arbitrary process by PID, or `None` if unavailable/dead.
37pub fn get_rss_bytes_for_pid(pid: u32) -> Option<u64> {
38    #[cfg(target_os = "linux")]
39    {
40        linux_rss_for_pid(pid)
41    }
42    #[cfg(target_os = "macos")]
43    {
44        macos_rss_for_pid(pid)
45    }
46    #[cfg(windows)]
47    {
48        windows_rss_for_pid(pid)
49    }
50    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
51    {
52        let _ = pid;
53        None
54    }
55}
56
57/// Total physical RAM in bytes, or `None` if unavailable.
58pub fn get_system_ram_bytes() -> Option<u64> {
59    #[cfg(target_os = "linux")]
60    {
61        linux_memtotal()
62    }
63    #[cfg(target_os = "macos")]
64    {
65        macos_memsize()
66    }
67    #[cfg(windows)]
68    {
69        windows_system_ram()
70    }
71    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
72    {
73        None
74    }
75}
76
77#[cfg(windows)]
78fn windows_rss() -> Option<u64> {
79    use windows_sys::Win32::System::Threading::GetCurrentProcess;
80
81    // SAFETY: GetCurrentProcess returns a pseudo-handle valid for the current
82    // process and it must not be closed.
83    let process = unsafe { GetCurrentProcess() };
84    windows_rss_for_handle(process)
85}
86
87#[cfg(windows)]
88fn windows_rss_for_pid(pid: u32) -> Option<u64> {
89    use windows_sys::Win32::Foundation::CloseHandle;
90    use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};
91
92    // SAFETY: OpenProcess is called with query-only access. A successful real
93    // handle is closed before returning.
94    let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
95
96    if process.is_null() {
97        return None;
98    }
99
100    let rss = windows_rss_for_handle(process);
101
102    // SAFETY: `process` is a real handle returned successfully by OpenProcess.
103    unsafe {
104        let _ = CloseHandle(process);
105    }
106
107    rss
108}
109
110#[cfg(windows)]
111fn windows_rss_for_handle(process: windows_sys::Win32::Foundation::HANDLE) -> Option<u64> {
112    use windows_sys::Win32::System::ProcessStatus::{
113        K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
114    };
115
116    let mut counters = PROCESS_MEMORY_COUNTERS::default();
117    counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
118
119    // SAFETY: `counters` has the documented size in `cb` and remains valid and
120    // writable for the duration of the call.
121    let ok = unsafe { K32GetProcessMemoryInfo(process, &mut counters, counters.cb) };
122
123    if ok == 0 {
124        None
125    } else {
126        Some(counters.WorkingSetSize as u64)
127    }
128}
129
130#[cfg(windows)]
131fn windows_system_ram() -> Option<u64> {
132    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
133
134    let mut status = MEMORYSTATUSEX::default();
135    status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
136
137    // SAFETY: `status` has the required `dwLength` and is writable for the call.
138    let ok = unsafe { GlobalMemoryStatusEx(&mut status) };
139
140    if ok == 0 {
141        None
142    } else {
143        Some(status.ullTotalPhys)
144    }
145}
146
147/// Returns the RSS limit in bytes based on `max_ram_percent` config.
148pub fn rss_limit_bytes() -> Option<u64> {
149    let sys_ram = get_system_ram_bytes()?;
150    let cfg = super::config::Config::load();
151    let pct = super::config::MemoryGuardConfig::effective(&cfg).max_ram_percent;
152    Some(sys_ram / 100 * u64::from(pct))
153}
154
155/// Computes a memory-bounded work batch from current RSS and the guardian's
156/// hard threshold (1.5× the configured base limit). Falls back to `max_files`
157/// when RSS is unavailable. The lower bound keeps progress deterministic while
158/// allowing callers to reduce in-flight work substantially under low headroom.
159pub fn adaptive_batch_size(
160    min_files: usize,
161    max_files: usize,
162    estimated_bytes_per_file: u64,
163) -> usize {
164    let headroom = match (rss_limit_bytes(), get_rss_bytes()) {
165        (Some(limit), Some(rss)) => hard_headroom_bytes(limit, rss),
166        _ => return max_files.max(1),
167    };
168    batch_size_for_headroom(headroom, min_files, max_files, estimated_bytes_per_file)
169}
170
171fn hard_headroom_bytes(base_limit: u64, rss: u64) -> u64 {
172    base_limit
173        .saturating_mul(3)
174        .saturating_div(2)
175        .saturating_sub(rss)
176}
177
178fn batch_size_for_headroom(
179    headroom_bytes: u64,
180    min_files: usize,
181    max_files: usize,
182    estimated_bytes_per_file: u64,
183) -> usize {
184    let min_files = min_files.max(1);
185    let max_files = max_files.max(min_files);
186    let estimate = estimated_bytes_per_file.max(1);
187    let by_headroom = (headroom_bytes / estimate).min(max_files as u64) as usize;
188    by_headroom.clamp(min_files, max_files)
189}
190
191#[cfg(test)]
192pub mod adaptive_batch_tests {
193    use super::{batch_size_for_headroom, hard_headroom_bytes};
194
195    #[test]
196    fn hard_headroom_uses_guardian_hard_threshold() {
197        assert_eq!(hard_headroom_bytes(1_000, 1_100), 400);
198        assert_eq!(hard_headroom_bytes(1_000, 1_500), 0);
199        assert_eq!(hard_headroom_bytes(1_000, 2_000), 0);
200    }
201
202    #[test]
203    fn batch_size_tracks_headroom_and_bounds() {
204        assert_eq!(batch_size_for_headroom(1_000, 1, 500, 100), 10);
205        assert_eq!(batch_size_for_headroom(0, 1, 500, 100), 1);
206        assert_eq!(batch_size_for_headroom(100_000, 1, 500, 100), 500);
207    }
208
209    #[test]
210    fn batch_size_sanitizes_zero_bounds_and_estimate() {
211        assert_eq!(batch_size_for_headroom(0, 0, 0, 0), 1);
212    }
213}
214
215/// Recorded peak RSS since process start.
216pub fn peak_rss_bytes() -> u64 {
217    PEAK_RSS.load(Ordering::Relaxed)
218}
219
220/// Snapshot of current memory state for diagnostics.
221#[derive(Debug, Clone, serde::Serialize)]
222pub struct MemorySnapshot {
223    pub rss_bytes: u64,
224    pub peak_rss_bytes: u64,
225    pub system_ram_bytes: u64,
226    pub rss_limit_bytes: u64,
227    pub rss_percent: f64,
228    pub pressure_level: PressureLevel,
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
232#[serde(rename_all = "lowercase")]
233#[repr(u8)]
234pub enum PressureLevel {
235    Normal = 0,
236    Soft = 1,
237    Medium = 2,
238    Hard = 3,
239    Critical = 4,
240}
241
242impl PressureLevel {
243    fn from_u8(v: u8) -> Self {
244        match v {
245            1 => Self::Soft,
246            2 => Self::Medium,
247            3 => Self::Hard,
248            4 => Self::Critical,
249            _ => Self::Normal,
250        }
251    }
252}
253
254impl MemorySnapshot {
255    /// Capture memory snapshot of the **current** process.
256    pub fn capture() -> Option<Self> {
257        Self::capture_impl(get_rss_bytes()?)
258    }
259
260    /// Capture memory snapshot for the **daemon** process (by PID).
261    /// Falls back to the current process if the PID is dead or unreadable.
262    pub fn capture_for_pid(pid: u32) -> Option<Self> {
263        let rss = get_rss_bytes_for_pid(pid).or_else(get_rss_bytes)?;
264        Self::capture_impl(rss)
265    }
266
267    fn capture_impl(rss: u64) -> Option<Self> {
268        let sys = get_system_ram_bytes()?;
269        let limit = rss_limit_bytes()?;
270        let pct = if sys > 0 {
271            (rss as f64 / sys as f64) * 100.0
272        } else {
273            0.0
274        };
275
276        PEAK_RSS.fetch_max(rss, Ordering::Relaxed);
277
278        let cfg = super::config::Config::load();
279        let guard_cfg = super::config::MemoryGuardConfig::effective(&cfg);
280        let base = f64::from(guard_cfg.max_ram_percent);
281
282        // #790: tightened multipliers so ABORT fires earlier:
283        // - Critical: 2× (was 3×) — e.g. 10% config on 64 GB → 12.8 GB (was 19.2 GB)
284        // - Hard:     1.5× (was 2×) — 9.6 GB (was 12.8 GB)
285        // - Medium:   1.2× (was 1.4×)
286        // Users expect max_ram_percent to be a meaningful cap, not a 3× suggestion.
287        let level = if pct > base * 2.0 {
288            PressureLevel::Critical
289        } else if pct > base * 1.5 {
290            PressureLevel::Hard
291        } else if pct > base * 1.2 {
292            PressureLevel::Medium
293        } else if pct > base {
294            PressureLevel::Soft
295        } else {
296            PressureLevel::Normal
297        };
298
299        Some(Self {
300            rss_bytes: rss,
301            peak_rss_bytes: PEAK_RSS.load(Ordering::Relaxed),
302            system_ram_bytes: sys,
303            rss_limit_bytes: limit,
304            rss_percent: pct,
305            pressure_level: level,
306        })
307    }
308}
309
310/// Force-purge all jemalloc arenas to return memory to the OS.
311/// Uses `MALLCTL_ARENAS_ALL` (value 4096) which is the jemalloc sentinel
312/// for "all arenas". Logs errors instead of silently swallowing them.
313pub fn jemalloc_purge() {
314    #[cfg(all(feature = "jemalloc", not(windows), not(target_env = "musl")))]
315    {
316        use tikv_jemalloc_ctl::raw;
317        let purge_mib = b"arena.4096.purge\0";
318        // SAFETY: `purge_mib` is a static, NUL-terminated jemalloc MIB name and
319        // the value type (`u64`) matches the `arena.<i>.purge` ctl; `raw::write`
320        // validates the name and surfaces errors via `Result`.
321        unsafe {
322            if let Err(e) = raw::write(purge_mib, 0u64) {
323                tracing::debug!("[memory_guard] jemalloc purge failed: {e}");
324            }
325        }
326    }
327}
328
329/// Returns `true` if the guardian has requested background tasks to abort.
330pub fn abort_requested() -> bool {
331    ABORT_REQUESTED.load(Ordering::Relaxed)
332}
333
334/// Quick, non-allocating memory pressure check for hot loops (scanners, indexers).
335/// Reads the cached atomic flag set by the guardian thread — O(1), no syscalls.
336pub fn is_under_pressure() -> bool {
337    current_pressure() >= PressureLevel::Soft
338}
339
340/// Returns the current pressure level as last observed by the guardian thread.
341pub fn current_pressure() -> PressureLevel {
342    PressureLevel::from_u8(CURRENT_PRESSURE.load(Ordering::Relaxed))
343}
344
345#[inline]
346const fn pressure_requests_abort(level: PressureLevel) -> bool {
347    level as u8 >= PressureLevel::Hard as u8
348}
349
350#[inline]
351fn publish_pressure(level: PressureLevel) {
352    CURRENT_PRESSURE.store(level as u8, Ordering::Relaxed);
353    ABORT_REQUESTED.store(pressure_requests_abort(level), Ordering::SeqCst);
354}
355
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357enum CriticalEvictionSchedule {
358    RetryAfter(u64),
359    PauseFor(u64),
360}
361
362impl CriticalEvictionSchedule {
363    fn poll_secs(self) -> u64 {
364        match self {
365            Self::RetryAfter(secs) | Self::PauseFor(secs) => secs,
366        }
367    }
368}
369
370/// Backoff state for critical eviction rounds that reclaimed no memory.
371#[derive(Default)]
372struct CriticalEvictionBackoff {
373    consecutive_zero_progress: u32,
374}
375
376impl CriticalEvictionBackoff {
377    const BASE_POLL_SECS: u64 = 1;
378    const MAX_POLL_SECS: u64 = 60;
379    const PAUSE_AFTER_ZERO_PROGRESS_ROUNDS: u32 = 10;
380    const PAUSE_SECS: u64 = 5 * 60;
381
382    fn record(&mut self, made_progress: bool) -> CriticalEvictionSchedule {
383        if made_progress {
384            self.consecutive_zero_progress = 0;
385            return CriticalEvictionSchedule::RetryAfter(Self::BASE_POLL_SECS);
386        }
387
388        self.consecutive_zero_progress = self.consecutive_zero_progress.saturating_add(1);
389        if self.consecutive_zero_progress >= Self::PAUSE_AFTER_ZERO_PROGRESS_ROUNDS {
390            return CriticalEvictionSchedule::PauseFor(Self::PAUSE_SECS);
391        }
392
393        let exponent = self.consecutive_zero_progress.saturating_sub(2).min(6);
394        let poll_secs = Self::BASE_POLL_SECS
395            .saturating_mul(1u64 << exponent)
396            .min(Self::MAX_POLL_SECS);
397        CriticalEvictionSchedule::RetryAfter(poll_secs)
398    }
399
400    fn reset(&mut self) {
401        self.consecutive_zero_progress = 0;
402    }
403}
404
405/// Start the background memory guardian task (idempotent).
406/// Polls every 3s (normal), 1s (under pressure), or up to 15s once RSS has been
407/// stably calm (idle backoff). Critical no-progress eviction rounds back off to
408/// 60s, then pause for five minutes. The callback returns whether it reclaimed
409/// memory so the guard can distinguish a real retry from an empty-cache loop.
410pub fn start_guard(eviction_callback: Arc<dyn Fn(PressureLevel) -> bool + Send + Sync>) {
411    // The guardian is a long-lived background monitor for the running
412    // server/daemon. Under `cargo test` a single OS process executes the entire
413    // suite, so its RSS routinely exceeds the per-operation pressure threshold
414    // (default 5% of system RAM). A test that constructs a server (e.g. the
415    // `http_server` tests via `new_shared_with_context`) would start this thread,
416    // which then flips the process-global `CURRENT_PRESSURE` / `ABORT_REQUESTED`
417    // flags. Unrelated later tests in the same binary read those flags and skip
418    // work — notably `graph_index::build_edges_with_cache` aborts edge-building
419    // under pressure, leaving indexed files with no edges. That manifested as an
420    // intermittent, macOS-only flake ("No files depend on Base.gd"). The guardian
421    // has no purpose inside the test harness, so never start it there. Production
422    // and the daemon compile without `cfg!(test)` and are unaffected.
423    if cfg!(test) {
424        return;
425    }
426    if GUARD_RUNNING.swap(true, Ordering::SeqCst) {
427        return;
428    }
429    std::thread::Builder::new()
430        .name("memory-guard".into())
431        .spawn(move || {
432            // Idle backoff: once RSS has stayed below the Soft threshold for
433            // CALM_TICKS_BEFORE_BACKOFF consecutive samples, stretch the poll
434            // interval to IDLE_POLL_SECS. An idle server allocates nothing, so 3s
435            // RSS sampling is just wasted wakeups; any pressure resets the cadence
436            // instantly (below), leaving OOM reaction time during real work
437            // unchanged (#453 idle hygiene).
438            const CALM_TICKS_BEFORE_BACKOFF: u64 = 5;
439            const IDLE_POLL_SECS: u64 = 15;
440            let mut poll_secs = 3u64;
441            let mut calm_ticks = 0u64;
442            let mut critical_backoff = CriticalEvictionBackoff::default();
443
444            // #790: immediate first sample — close the 3s blind window so
445            // builders that start right after start_guard() see real pressure.
446            if let Some(snap) = MemorySnapshot::capture() {
447                publish_pressure(snap.pressure_level);
448                if snap.pressure_level >= PressureLevel::Soft {
449                    let made_progress = eviction_callback(snap.pressure_level);
450                    if snap.pressure_level == PressureLevel::Critical {
451                        poll_secs = critical_backoff.record(made_progress).poll_secs();
452                    }
453                }
454            }
455
456            loop {
457                std::thread::sleep(std::time::Duration::from_secs(poll_secs));
458                let Some(snap) = MemorySnapshot::capture() else {
459                    continue;
460                };
461
462                publish_pressure(snap.pressure_level);
463
464                if snap.pressure_level == PressureLevel::Critical {
465                    tracing::error!(
466                        "[memory_guard] CRITICAL: RSS={:.0}MB ({:.1}% of {:.0}GB) — \
467                         aggressive eviction to prevent OS OOM kill",
468                        snap.rss_bytes as f64 / 1_048_576.0,
469                        snap.rss_percent,
470                        snap.system_ram_bytes as f64 / 1_073_741_824.0,
471                    );
472                    let made_progress = (eviction_callback)(PressureLevel::Critical);
473                    jemalloc_purge();
474
475                    let schedule = critical_backoff.record(made_progress);
476                    poll_secs = schedule.poll_secs();
477                    if let CriticalEvictionSchedule::PauseFor(secs) = schedule {
478                        tracing::warn!(
479                            "[memory_guard] eviction made no progress for {} critical rounds; \
480                             pausing eviction for {secs}s",
481                            critical_backoff.consecutive_zero_progress,
482                        );
483                    }
484                    calm_ticks = 0;
485                    continue;
486                }
487
488                critical_backoff.reset();
489
490                if snap.pressure_level >= PressureLevel::Soft {
491                    poll_secs = 1;
492                    calm_ticks = 0;
493                    tracing::warn!(
494                        "[memory_guard] pressure={:?} RSS={:.0}MB limit={:.0}MB ({:.1}% of {:.0}GB)",
495                        snap.pressure_level,
496                        snap.rss_bytes as f64 / 1_048_576.0,
497                        snap.rss_limit_bytes as f64 / 1_048_576.0,
498                        snap.rss_percent,
499                        snap.system_ram_bytes as f64 / 1_073_741_824.0,
500                    );
501                    (eviction_callback)(snap.pressure_level);
502
503                    if snap.pressure_level >= PressureLevel::Hard {
504                        jemalloc_purge();
505                    }
506                } else {
507                    calm_ticks = calm_ticks.saturating_add(1);
508                    poll_secs = if calm_ticks >= CALM_TICKS_BEFORE_BACKOFF {
509                        IDLE_POLL_SECS
510                    } else {
511                        3
512                    };
513                }
514            }
515        })
516        .ok();
517}
518
519/// Force immediate purge of all caches and jemalloc arenas.
520pub fn force_purge() {
521    jemalloc_purge();
522    tracing::info!("[memory_guard] force_purge completed");
523}
524
525// --- Platform-specific implementations ---
526
527#[cfg(target_os = "linux")]
528fn linux_rss() -> Option<u64> {
529    linux_rss_for_pid(std::process::id())
530}
531
532#[cfg(target_os = "linux")]
533fn linux_rss_for_pid(pid: u32) -> Option<u64> {
534    let path = format!("/proc/{pid}/status");
535    let status = std::fs::read_to_string(path).ok()?;
536    for line in status.lines() {
537        if let Some(val) = line.strip_prefix("VmRSS:") {
538            let kb: u64 = val.trim().trim_end_matches(" kB").trim().parse().ok()?;
539            return Some(kb * 1024);
540        }
541    }
542    None
543}
544
545#[cfg(target_os = "linux")]
546fn linux_memtotal() -> Option<u64> {
547    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
548    for line in info.lines() {
549        if let Some(val) = line.strip_prefix("MemTotal:") {
550            let kb: u64 = val.trim().trim_end_matches(" kB").trim().parse().ok()?;
551            return Some(kb * 1024);
552        }
553    }
554    None
555}
556
557#[cfg(target_os = "macos")]
558#[allow(deprecated, clippy::borrow_as_ptr, clippy::ptr_as_ptr)]
559fn macos_rss() -> Option<u64> {
560    use std::mem;
561    // SAFETY: `mach_task_basic_info_data_t` is a plain C struct for which an
562    // all-zero bit pattern is a valid initial value.
563    let mut info: libc::mach_task_basic_info_data_t = unsafe { mem::zeroed() };
564    let mut count = (mem::size_of::<libc::mach_task_basic_info_data_t>()
565        / mem::size_of::<libc::natural_t>()) as libc::mach_msg_type_number_t;
566    // SAFETY: `mach_task_self()` returns the current task port; `info` and
567    // `count` are live stack locals passed as out-pointers, sized to match the
568    // requested `MACH_TASK_BASIC_INFO` flavour.
569    let kr = unsafe {
570        libc::task_info(
571            libc::mach_task_self(),
572            libc::MACH_TASK_BASIC_INFO,
573            std::ptr::from_mut(&mut info).cast::<i32>(),
574            std::ptr::from_mut(&mut count),
575        )
576    };
577    if kr == libc::KERN_SUCCESS {
578        Some(info.resident_size)
579    } else {
580        None
581    }
582}
583
584#[cfg(target_os = "macos")]
585fn macos_rss_for_pid(pid: u32) -> Option<u64> {
586    // Use `ps -o rss= -p <pid>` as a portable fallback.
587    // `task_for_pid` requires root/entitlements, `proc_pid_rusage` is private API.
588    let output = std::process::Command::new("ps")
589        .args(["-o", "rss=", "-p", &pid.to_string()])
590        .output()
591        .ok()?;
592    if !output.status.success() {
593        return None;
594    }
595    let text = String::from_utf8_lossy(&output.stdout);
596    let kb: u64 = text.trim().parse().ok()?;
597    Some(kb * 1024)
598}
599
600#[cfg(target_os = "macos")]
601#[allow(clippy::borrow_as_ptr, clippy::ptr_as_ptr)]
602fn macos_memsize() -> Option<u64> {
603    use std::mem;
604    let mut memsize: u64 = 0;
605    let mut len = mem::size_of::<u64>();
606    let name = b"hw.memsize\0";
607    // SAFETY: `name` is a static, NUL-terminated sysctl name; `memsize` and
608    // `len` are live stack out-pointers whose sizes match the queried value.
609    let ret = unsafe {
610        libc::sysctlbyname(
611            name.as_ptr().cast(),
612            std::ptr::from_mut(&mut memsize).cast::<libc::c_void>(),
613            std::ptr::from_mut(&mut len),
614            std::ptr::null_mut(),
615            0,
616        )
617    };
618    if ret == 0 { Some(memsize) } else { None }
619}
620
621#[cfg(test)]
622pub mod tests {
623    use super::*;
624
625    #[test]
626    fn rss_returns_some_on_supported_os() {
627        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
628            let rss = get_rss_bytes();
629            assert!(rss.is_some(), "RSS should be readable");
630            assert!(rss.unwrap() > 0, "RSS should be > 0");
631        }
632    }
633
634    #[test]
635    fn system_ram_returns_some_on_supported_os() {
636        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
637            let ram = get_system_ram_bytes();
638            assert!(ram.is_some(), "System RAM should be readable");
639            assert!(ram.unwrap() > 1_000_000, "System RAM should be > 1MB");
640        }
641    }
642
643    #[test]
644    fn snapshot_captures_correctly() {
645        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
646            let snap = MemorySnapshot::capture();
647            assert!(snap.is_some());
648            let s = snap.unwrap();
649            assert!(s.rss_bytes > 0);
650            assert!(s.system_ram_bytes > s.rss_bytes);
651            assert!(s.rss_percent > 0.0 && s.rss_percent < 100.0);
652        }
653    }
654
655    #[test]
656    fn peak_rss_tracks_maximum() {
657        PEAK_RSS.store(0, Ordering::Relaxed);
658        PEAK_RSS.fetch_max(100, Ordering::Relaxed);
659        PEAK_RSS.fetch_max(50, Ordering::Relaxed);
660        assert_eq!(PEAK_RSS.load(Ordering::Relaxed), 100);
661    }
662
663    #[test]
664    fn pressure_level_roundtrip() {
665        for level in [
666            PressureLevel::Normal,
667            PressureLevel::Soft,
668            PressureLevel::Medium,
669            PressureLevel::Hard,
670            PressureLevel::Critical,
671        ] {
672            assert_eq!(PressureLevel::from_u8(level as u8), level);
673        }
674    }
675
676    #[test]
677    fn hard_pressure_requests_abort_immediately() {
678        assert!(!pressure_requests_abort(PressureLevel::Normal));
679        assert!(!pressure_requests_abort(PressureLevel::Soft));
680        assert!(!pressure_requests_abort(PressureLevel::Medium));
681        assert!(pressure_requests_abort(PressureLevel::Hard));
682        assert!(pressure_requests_abort(PressureLevel::Critical));
683    }
684
685    #[test]
686    fn critical_zero_progress_backoff_doubles_then_pauses_and_resets() {
687        let mut backoff = CriticalEvictionBackoff::default();
688
689        assert_eq!(
690            backoff.record(false),
691            CriticalEvictionSchedule::RetryAfter(1)
692        );
693        assert_eq!(
694            backoff.record(false),
695            CriticalEvictionSchedule::RetryAfter(1)
696        );
697        assert_eq!(
698            backoff.record(false),
699            CriticalEvictionSchedule::RetryAfter(2)
700        );
701        assert_eq!(
702            backoff.record(false),
703            CriticalEvictionSchedule::RetryAfter(4)
704        );
705
706        for _ in 0..4 {
707            backoff.record(false);
708        }
709        assert_eq!(
710            backoff.record(false),
711            CriticalEvictionSchedule::RetryAfter(60)
712        );
713        assert_eq!(
714            backoff.record(false),
715            CriticalEvictionSchedule::PauseFor(5 * 60)
716        );
717
718        assert_eq!(
719            backoff.record(true),
720            CriticalEvictionSchedule::RetryAfter(1)
721        );
722        assert_eq!(backoff.consecutive_zero_progress, 0);
723    }
724
725    #[test]
726    fn atomic_pressure_defaults_to_normal() {
727        assert_eq!(current_pressure(), PressureLevel::Normal);
728    }
729
730    #[test]
731    fn start_guard_is_noop_under_test() {
732        // Regression guard: the background guardian must never run inside the
733        // test harness. If it did, its 3s poll would observe the suite's large
734        // RSS, flip the global pressure/abort flags, and silently make unrelated
735        // tests (e.g. graph edge-building) skip work — an order/timing-dependent
736        // flake. `start_guard` must be a no-op under `cfg!(test)`.
737        let fired = Arc::new(AtomicBool::new(false));
738        let fired_cb = fired.clone();
739        start_guard(Arc::new(move |_| {
740            fired_cb.store(true, Ordering::SeqCst);
741            false
742        }));
743
744        assert!(
745            !GUARD_RUNNING.load(Ordering::Relaxed),
746            "guardian thread must not start under cfg!(test)"
747        );
748        assert_eq!(current_pressure(), PressureLevel::Normal);
749        assert!(!abort_requested());
750        assert!(
751            !fired.load(Ordering::Relaxed),
752            "eviction callback must never fire in tests"
753        );
754    }
755
756    #[test]
757    fn rss_for_own_pid_matches_self() {
758        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
759            let self_rss = get_rss_bytes().unwrap();
760            let pid_rss = get_rss_bytes_for_pid(std::process::id()).unwrap();
761            let ratio = self_rss as f64 / pid_rss as f64;
762            assert!(
763                (0.5..2.0).contains(&ratio),
764                "self RSS ({self_rss}) and pid-based RSS ({pid_rss}) should be within 2x"
765            );
766        }
767    }
768
769    #[test]
770    fn rss_for_dead_pid_returns_none() {
771        let dead_pid = 999_999_999u32;
772        assert!(get_rss_bytes_for_pid(dead_pid).is_none());
773    }
774
775    #[test]
776    fn capture_for_pid_falls_back_on_dead_pid() {
777        if cfg!(any(target_os = "linux", target_os = "macos", windows)) {
778            let snap = MemorySnapshot::capture_for_pid(999_999_999);
779            assert!(snap.is_some(), "should fall back to self RSS");
780        }
781    }
782}