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