1use 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);
16static PROCESS_RSS_CAP: AtomicU64 = AtomicU64::new(0);
21
22pub fn set_process_rss_cap(bytes: u64) {
25 PROCESS_RSS_CAP.store(bytes, Ordering::Relaxed);
26}
27
28static PINNED_RESIDENT: AtomicU64 = AtomicU64::new(0);
34
35pub fn pin_resident_bytes(bytes: u64) {
39 PINNED_RESIDENT.fetch_add(bytes, Ordering::Relaxed);
40}
41
42pub fn pinned_resident_bytes() -> u64 {
44 PINNED_RESIDENT.load(Ordering::Relaxed)
45}
46
47pub 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
69pub 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
90pub 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 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 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 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 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 let ok = unsafe { GlobalMemoryStatusEx(&raw mut status) };
176
177 if ok == 0 {
178 None
179 } else {
180 Some(status.ullTotalPhys)
181 }
182}
183
184pub 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
198fn 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
218fn 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
238pub 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 #[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 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
325pub fn peak_rss_bytes() -> u64 {
327 PEAK_RSS.load(Ordering::Relaxed)
328}
329
330#[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 pub fn capture() -> Option<Self> {
367 Self::capture_impl(get_rss_bytes()?, rss_limit_bytes()?)
368 }
369
370 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 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
406pub 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
424pub 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#[cfg(all(feature = "jemalloc", not(windows), not(target_env = "musl")))]
439fn purge_all_arenas() -> Result<(), i32> {
440 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#[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
486pub fn abort_requested() -> bool {
488 ABORT_REQUESTED.load(Ordering::Relaxed)
489}
490
491pub fn is_under_pressure() -> bool {
494 current_pressure() >= PressureLevel::Soft
495}
496
497pub 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#[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#[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
595pub fn start_guard(eviction_callback: Arc<dyn Fn(PressureLevel) -> bool + Send + Sync>) {
602 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 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 const LOG_EVERY: std::time::Duration = std::time::Duration::from_mins(1);
639 let mut logged: Option<(PressureLevel, std::time::Instant)> = None;
640
641 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 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 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
723pub fn force_purge() {
725 jemalloc_purge();
726 release_system_heap();
727 tracing::info!("[memory_guard] force_purge completed");
728}
729
730pub 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
745pub 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 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
774pub fn release_system_heap() {
780 #[cfg(all(target_os = "linux", target_env = "gnu"))]
781 unsafe {
784 libc::malloc_trim(0);
785 }
786}
787
788#[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#[cfg(target_os = "macos")]
832fn macos_footprint(pid: u32) -> Option<u64> {
833 let mut info: libc::rusage_info_v2 = unsafe { std::mem::zeroed() };
836 let pid = libc::c_int::try_from(pid).ok()?;
837 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 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 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 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 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 #[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 #[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 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 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 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 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}