1use 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
16pub 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(not(any(target_os = "linux", target_os = "macos")))]
27 {
28 None
29 }
30}
31
32pub fn get_rss_bytes_for_pid(pid: u32) -> Option<u64> {
34 #[cfg(target_os = "linux")]
35 {
36 linux_rss_for_pid(pid)
37 }
38 #[cfg(target_os = "macos")]
39 {
40 macos_rss_for_pid(pid)
41 }
42 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
43 {
44 let _ = pid;
45 None
46 }
47}
48
49pub fn get_system_ram_bytes() -> Option<u64> {
51 #[cfg(target_os = "linux")]
52 {
53 linux_memtotal()
54 }
55 #[cfg(target_os = "macos")]
56 {
57 macos_memsize()
58 }
59 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
60 {
61 None
62 }
63}
64
65pub fn rss_limit_bytes() -> Option<u64> {
67 let sys_ram = get_system_ram_bytes()?;
68 let cfg = super::config::Config::load();
69 let pct = super::config::MemoryGuardConfig::effective(&cfg).max_ram_percent;
70 Some(sys_ram / 100 * u64::from(pct))
71}
72
73pub fn adaptive_batch_size(
78 min_files: usize,
79 max_files: usize,
80 estimated_bytes_per_file: u64,
81) -> usize {
82 let headroom = match (rss_limit_bytes(), get_rss_bytes()) {
83 (Some(limit), Some(rss)) => hard_headroom_bytes(limit, rss),
84 _ => return max_files.max(1),
85 };
86 batch_size_for_headroom(headroom, min_files, max_files, estimated_bytes_per_file)
87}
88
89fn hard_headroom_bytes(base_limit: u64, rss: u64) -> u64 {
90 base_limit
91 .saturating_mul(3)
92 .saturating_div(2)
93 .saturating_sub(rss)
94}
95
96fn batch_size_for_headroom(
97 headroom_bytes: u64,
98 min_files: usize,
99 max_files: usize,
100 estimated_bytes_per_file: u64,
101) -> usize {
102 let min_files = min_files.max(1);
103 let max_files = max_files.max(min_files);
104 let estimate = estimated_bytes_per_file.max(1);
105 let by_headroom = (headroom_bytes / estimate).min(max_files as u64) as usize;
106 by_headroom.clamp(min_files, max_files)
107}
108
109#[cfg(test)]
110pub mod adaptive_batch_tests {
111 use super::{batch_size_for_headroom, hard_headroom_bytes};
112
113 #[test]
114 fn hard_headroom_uses_guardian_hard_threshold() {
115 assert_eq!(hard_headroom_bytes(1_000, 1_100), 400);
116 assert_eq!(hard_headroom_bytes(1_000, 1_500), 0);
117 assert_eq!(hard_headroom_bytes(1_000, 2_000), 0);
118 }
119
120 #[test]
121 fn batch_size_tracks_headroom_and_bounds() {
122 assert_eq!(batch_size_for_headroom(1_000, 1, 500, 100), 10);
123 assert_eq!(batch_size_for_headroom(0, 1, 500, 100), 1);
124 assert_eq!(batch_size_for_headroom(100_000, 1, 500, 100), 500);
125 }
126
127 #[test]
128 fn batch_size_sanitizes_zero_bounds_and_estimate() {
129 assert_eq!(batch_size_for_headroom(0, 0, 0, 0), 1);
130 }
131}
132
133pub fn peak_rss_bytes() -> u64 {
135 PEAK_RSS.load(Ordering::Relaxed)
136}
137
138#[derive(Debug, Clone, serde::Serialize)]
140pub struct MemorySnapshot {
141 pub rss_bytes: u64,
142 pub peak_rss_bytes: u64,
143 pub system_ram_bytes: u64,
144 pub rss_limit_bytes: u64,
145 pub rss_percent: f64,
146 pub pressure_level: PressureLevel,
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
150#[serde(rename_all = "lowercase")]
151#[repr(u8)]
152pub enum PressureLevel {
153 Normal = 0,
154 Soft = 1,
155 Medium = 2,
156 Hard = 3,
157 Critical = 4,
158}
159
160impl PressureLevel {
161 fn from_u8(v: u8) -> Self {
162 match v {
163 1 => Self::Soft,
164 2 => Self::Medium,
165 3 => Self::Hard,
166 4 => Self::Critical,
167 _ => Self::Normal,
168 }
169 }
170}
171
172impl MemorySnapshot {
173 pub fn capture() -> Option<Self> {
175 Self::capture_impl(get_rss_bytes()?)
176 }
177
178 pub fn capture_for_pid(pid: u32) -> Option<Self> {
181 let rss = get_rss_bytes_for_pid(pid).or_else(get_rss_bytes)?;
182 Self::capture_impl(rss)
183 }
184
185 fn capture_impl(rss: u64) -> Option<Self> {
186 let sys = get_system_ram_bytes()?;
187 let limit = rss_limit_bytes()?;
188 let pct = if sys > 0 {
189 (rss as f64 / sys as f64) * 100.0
190 } else {
191 0.0
192 };
193
194 PEAK_RSS.fetch_max(rss, Ordering::Relaxed);
195
196 let cfg = super::config::Config::load();
197 let guard_cfg = super::config::MemoryGuardConfig::effective(&cfg);
198 let base = f64::from(guard_cfg.max_ram_percent);
199
200 let level = if pct > base * 2.0 {
206 PressureLevel::Critical
207 } else if pct > base * 1.5 {
208 PressureLevel::Hard
209 } else if pct > base * 1.2 {
210 PressureLevel::Medium
211 } else if pct > base {
212 PressureLevel::Soft
213 } else {
214 PressureLevel::Normal
215 };
216
217 Some(Self {
218 rss_bytes: rss,
219 peak_rss_bytes: PEAK_RSS.load(Ordering::Relaxed),
220 system_ram_bytes: sys,
221 rss_limit_bytes: limit,
222 rss_percent: pct,
223 pressure_level: level,
224 })
225 }
226}
227
228pub fn jemalloc_purge() {
232 #[cfg(all(feature = "jemalloc", not(windows)))]
233 {
234 use tikv_jemalloc_ctl::raw;
235 let purge_mib = b"arena.4096.purge\0";
236 unsafe {
240 if let Err(e) = raw::write(purge_mib, 0u64) {
241 tracing::debug!("[memory_guard] jemalloc purge failed: {e}");
242 }
243 }
244 }
245}
246
247pub fn abort_requested() -> bool {
249 ABORT_REQUESTED.load(Ordering::Relaxed)
250}
251
252pub fn is_under_pressure() -> bool {
255 current_pressure() >= PressureLevel::Soft
256}
257
258pub fn current_pressure() -> PressureLevel {
260 PressureLevel::from_u8(CURRENT_PRESSURE.load(Ordering::Relaxed))
261}
262
263#[inline]
264const fn pressure_requests_abort(level: PressureLevel) -> bool {
265 level as u8 >= PressureLevel::Hard as u8
266}
267
268#[inline]
269fn publish_pressure(level: PressureLevel) {
270 CURRENT_PRESSURE.store(level as u8, Ordering::Relaxed);
271 ABORT_REQUESTED.store(pressure_requests_abort(level), Ordering::SeqCst);
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275enum CriticalEvictionSchedule {
276 RetryAfter(u64),
277 PauseFor(u64),
278}
279
280impl CriticalEvictionSchedule {
281 fn poll_secs(self) -> u64 {
282 match self {
283 Self::RetryAfter(secs) | Self::PauseFor(secs) => secs,
284 }
285 }
286}
287
288#[derive(Default)]
290struct CriticalEvictionBackoff {
291 consecutive_zero_progress: u32,
292}
293
294impl CriticalEvictionBackoff {
295 const BASE_POLL_SECS: u64 = 1;
296 const MAX_POLL_SECS: u64 = 60;
297 const PAUSE_AFTER_ZERO_PROGRESS_ROUNDS: u32 = 10;
298 const PAUSE_SECS: u64 = 5 * 60;
299
300 fn record(&mut self, made_progress: bool) -> CriticalEvictionSchedule {
301 if made_progress {
302 self.consecutive_zero_progress = 0;
303 return CriticalEvictionSchedule::RetryAfter(Self::BASE_POLL_SECS);
304 }
305
306 self.consecutive_zero_progress = self.consecutive_zero_progress.saturating_add(1);
307 if self.consecutive_zero_progress >= Self::PAUSE_AFTER_ZERO_PROGRESS_ROUNDS {
308 return CriticalEvictionSchedule::PauseFor(Self::PAUSE_SECS);
309 }
310
311 let exponent = self.consecutive_zero_progress.saturating_sub(2).min(6);
312 let poll_secs = Self::BASE_POLL_SECS
313 .saturating_mul(1u64 << exponent)
314 .min(Self::MAX_POLL_SECS);
315 CriticalEvictionSchedule::RetryAfter(poll_secs)
316 }
317
318 fn reset(&mut self) {
319 self.consecutive_zero_progress = 0;
320 }
321}
322
323pub fn start_guard(eviction_callback: Arc<dyn Fn(PressureLevel) -> bool + Send + Sync>) {
329 if cfg!(test) {
342 return;
343 }
344 if GUARD_RUNNING.swap(true, Ordering::SeqCst) {
345 return;
346 }
347 std::thread::Builder::new()
348 .name("memory-guard".into())
349 .spawn(move || {
350 const CALM_TICKS_BEFORE_BACKOFF: u64 = 5;
357 const IDLE_POLL_SECS: u64 = 15;
358 let mut poll_secs = 3u64;
359 let mut calm_ticks = 0u64;
360 let mut critical_backoff = CriticalEvictionBackoff::default();
361
362 if let Some(snap) = MemorySnapshot::capture() {
365 publish_pressure(snap.pressure_level);
366 if snap.pressure_level >= PressureLevel::Soft {
367 let made_progress = eviction_callback(snap.pressure_level);
368 if snap.pressure_level == PressureLevel::Critical {
369 poll_secs = critical_backoff.record(made_progress).poll_secs();
370 }
371 }
372 }
373
374 loop {
375 std::thread::sleep(std::time::Duration::from_secs(poll_secs));
376 let Some(snap) = MemorySnapshot::capture() else {
377 continue;
378 };
379
380 publish_pressure(snap.pressure_level);
381
382 if snap.pressure_level == PressureLevel::Critical {
383 tracing::error!(
384 "[memory_guard] CRITICAL: RSS={:.0}MB ({:.1}% of {:.0}GB) — \
385 aggressive eviction to prevent OS OOM kill",
386 snap.rss_bytes as f64 / 1_048_576.0,
387 snap.rss_percent,
388 snap.system_ram_bytes as f64 / 1_073_741_824.0,
389 );
390 let made_progress = (eviction_callback)(PressureLevel::Critical);
391 jemalloc_purge();
392
393 let schedule = critical_backoff.record(made_progress);
394 poll_secs = schedule.poll_secs();
395 if let CriticalEvictionSchedule::PauseFor(secs) = schedule {
396 tracing::warn!(
397 "[memory_guard] eviction made no progress for {} critical rounds; \
398 pausing eviction for {secs}s",
399 critical_backoff.consecutive_zero_progress,
400 );
401 }
402 calm_ticks = 0;
403 continue;
404 }
405
406 critical_backoff.reset();
407
408 if snap.pressure_level >= PressureLevel::Soft {
409 poll_secs = 1;
410 calm_ticks = 0;
411 tracing::warn!(
412 "[memory_guard] pressure={:?} RSS={:.0}MB limit={:.0}MB ({:.1}% of {:.0}GB)",
413 snap.pressure_level,
414 snap.rss_bytes as f64 / 1_048_576.0,
415 snap.rss_limit_bytes as f64 / 1_048_576.0,
416 snap.rss_percent,
417 snap.system_ram_bytes as f64 / 1_073_741_824.0,
418 );
419 (eviction_callback)(snap.pressure_level);
420
421 if snap.pressure_level >= PressureLevel::Hard {
422 jemalloc_purge();
423 }
424 } else {
425 calm_ticks = calm_ticks.saturating_add(1);
426 poll_secs = if calm_ticks >= CALM_TICKS_BEFORE_BACKOFF {
427 IDLE_POLL_SECS
428 } else {
429 3
430 };
431 }
432 }
433 })
434 .ok();
435}
436
437pub fn force_purge() {
439 jemalloc_purge();
440 tracing::info!("[memory_guard] force_purge completed");
441}
442
443#[cfg(target_os = "linux")]
446fn linux_rss() -> Option<u64> {
447 linux_rss_for_pid(std::process::id())
448}
449
450#[cfg(target_os = "linux")]
451fn linux_rss_for_pid(pid: u32) -> Option<u64> {
452 let path = format!("/proc/{pid}/status");
453 let status = std::fs::read_to_string(path).ok()?;
454 for line in status.lines() {
455 if let Some(val) = line.strip_prefix("VmRSS:") {
456 let kb: u64 = val.trim().trim_end_matches(" kB").trim().parse().ok()?;
457 return Some(kb * 1024);
458 }
459 }
460 None
461}
462
463#[cfg(target_os = "linux")]
464fn linux_memtotal() -> Option<u64> {
465 let info = std::fs::read_to_string("/proc/meminfo").ok()?;
466 for line in info.lines() {
467 if let Some(val) = line.strip_prefix("MemTotal:") {
468 let kb: u64 = val.trim().trim_end_matches(" kB").trim().parse().ok()?;
469 return Some(kb * 1024);
470 }
471 }
472 None
473}
474
475#[cfg(target_os = "macos")]
476#[allow(deprecated, clippy::borrow_as_ptr, clippy::ptr_as_ptr)]
477fn macos_rss() -> Option<u64> {
478 use std::mem;
479 let mut info: libc::mach_task_basic_info_data_t = unsafe { mem::zeroed() };
482 let mut count = (mem::size_of::<libc::mach_task_basic_info_data_t>()
483 / mem::size_of::<libc::natural_t>()) as libc::mach_msg_type_number_t;
484 let kr = unsafe {
488 libc::task_info(
489 libc::mach_task_self(),
490 libc::MACH_TASK_BASIC_INFO,
491 std::ptr::from_mut(&mut info).cast::<i32>(),
492 std::ptr::from_mut(&mut count),
493 )
494 };
495 if kr == libc::KERN_SUCCESS {
496 Some(info.resident_size)
497 } else {
498 None
499 }
500}
501
502#[cfg(target_os = "macos")]
503fn macos_rss_for_pid(pid: u32) -> Option<u64> {
504 let output = std::process::Command::new("ps")
507 .args(["-o", "rss=", "-p", &pid.to_string()])
508 .output()
509 .ok()?;
510 if !output.status.success() {
511 return None;
512 }
513 let text = String::from_utf8_lossy(&output.stdout);
514 let kb: u64 = text.trim().parse().ok()?;
515 Some(kb * 1024)
516}
517
518#[cfg(target_os = "macos")]
519#[allow(clippy::borrow_as_ptr, clippy::ptr_as_ptr)]
520fn macos_memsize() -> Option<u64> {
521 use std::mem;
522 let mut memsize: u64 = 0;
523 let mut len = mem::size_of::<u64>();
524 let name = b"hw.memsize\0";
525 let ret = unsafe {
528 libc::sysctlbyname(
529 name.as_ptr().cast(),
530 std::ptr::from_mut(&mut memsize).cast::<libc::c_void>(),
531 std::ptr::from_mut(&mut len),
532 std::ptr::null_mut(),
533 0,
534 )
535 };
536 if ret == 0 { Some(memsize) } else { None }
537}
538
539#[cfg(test)]
540pub mod tests {
541 use super::*;
542
543 #[test]
544 fn rss_returns_some_on_supported_os() {
545 if cfg!(any(target_os = "linux", target_os = "macos")) {
546 let rss = get_rss_bytes();
547 assert!(rss.is_some(), "RSS should be readable");
548 assert!(rss.unwrap() > 0, "RSS should be > 0");
549 }
550 }
551
552 #[test]
553 fn system_ram_returns_some_on_supported_os() {
554 if cfg!(any(target_os = "linux", target_os = "macos")) {
555 let ram = get_system_ram_bytes();
556 assert!(ram.is_some(), "System RAM should be readable");
557 assert!(ram.unwrap() > 1_000_000, "System RAM should be > 1MB");
558 }
559 }
560
561 #[test]
562 fn snapshot_captures_correctly() {
563 if cfg!(any(target_os = "linux", target_os = "macos")) {
564 let snap = MemorySnapshot::capture();
565 assert!(snap.is_some());
566 let s = snap.unwrap();
567 assert!(s.rss_bytes > 0);
568 assert!(s.system_ram_bytes > s.rss_bytes);
569 assert!(s.rss_percent > 0.0 && s.rss_percent < 100.0);
570 }
571 }
572
573 #[test]
574 fn peak_rss_tracks_maximum() {
575 PEAK_RSS.store(0, Ordering::Relaxed);
576 PEAK_RSS.fetch_max(100, Ordering::Relaxed);
577 PEAK_RSS.fetch_max(50, Ordering::Relaxed);
578 assert_eq!(PEAK_RSS.load(Ordering::Relaxed), 100);
579 }
580
581 #[test]
582 fn pressure_level_roundtrip() {
583 for level in [
584 PressureLevel::Normal,
585 PressureLevel::Soft,
586 PressureLevel::Medium,
587 PressureLevel::Hard,
588 PressureLevel::Critical,
589 ] {
590 assert_eq!(PressureLevel::from_u8(level as u8), level);
591 }
592 }
593
594 #[test]
595 fn hard_pressure_requests_abort_immediately() {
596 assert!(!pressure_requests_abort(PressureLevel::Normal));
597 assert!(!pressure_requests_abort(PressureLevel::Soft));
598 assert!(!pressure_requests_abort(PressureLevel::Medium));
599 assert!(pressure_requests_abort(PressureLevel::Hard));
600 assert!(pressure_requests_abort(PressureLevel::Critical));
601 }
602
603 #[test]
604 fn critical_zero_progress_backoff_doubles_then_pauses_and_resets() {
605 let mut backoff = CriticalEvictionBackoff::default();
606
607 assert_eq!(
608 backoff.record(false),
609 CriticalEvictionSchedule::RetryAfter(1)
610 );
611 assert_eq!(
612 backoff.record(false),
613 CriticalEvictionSchedule::RetryAfter(1)
614 );
615 assert_eq!(
616 backoff.record(false),
617 CriticalEvictionSchedule::RetryAfter(2)
618 );
619 assert_eq!(
620 backoff.record(false),
621 CriticalEvictionSchedule::RetryAfter(4)
622 );
623
624 for _ in 0..4 {
625 backoff.record(false);
626 }
627 assert_eq!(
628 backoff.record(false),
629 CriticalEvictionSchedule::RetryAfter(60)
630 );
631 assert_eq!(
632 backoff.record(false),
633 CriticalEvictionSchedule::PauseFor(5 * 60)
634 );
635
636 assert_eq!(
637 backoff.record(true),
638 CriticalEvictionSchedule::RetryAfter(1)
639 );
640 assert_eq!(backoff.consecutive_zero_progress, 0);
641 }
642
643 #[test]
644 fn atomic_pressure_defaults_to_normal() {
645 assert_eq!(current_pressure(), PressureLevel::Normal);
646 }
647
648 #[test]
649 fn start_guard_is_noop_under_test() {
650 let fired = Arc::new(AtomicBool::new(false));
656 let fired_cb = fired.clone();
657 start_guard(Arc::new(move |_| {
658 fired_cb.store(true, Ordering::SeqCst);
659 false
660 }));
661
662 assert!(
663 !GUARD_RUNNING.load(Ordering::Relaxed),
664 "guardian thread must not start under cfg!(test)"
665 );
666 assert_eq!(current_pressure(), PressureLevel::Normal);
667 assert!(!abort_requested());
668 assert!(
669 !fired.load(Ordering::Relaxed),
670 "eviction callback must never fire in tests"
671 );
672 }
673
674 #[test]
675 fn rss_for_own_pid_matches_self() {
676 if cfg!(any(target_os = "linux", target_os = "macos")) {
677 let self_rss = get_rss_bytes().unwrap();
678 let pid_rss = get_rss_bytes_for_pid(std::process::id()).unwrap();
679 let ratio = self_rss as f64 / pid_rss as f64;
680 assert!(
681 (0.5..2.0).contains(&ratio),
682 "self RSS ({self_rss}) and pid-based RSS ({pid_rss}) should be within 2x"
683 );
684 }
685 }
686
687 #[test]
688 fn rss_for_dead_pid_returns_none() {
689 let dead_pid = 999_999_999u32;
690 assert!(get_rss_bytes_for_pid(dead_pid).is_none());
691 }
692
693 #[test]
694 fn capture_for_pid_falls_back_on_dead_pid() {
695 if cfg!(any(target_os = "linux", target_os = "macos")) {
696 let snap = MemorySnapshot::capture_for_pid(999_999_999);
697 assert!(snap.is_some(), "should fall back to self RSS");
698 }
699 }
700}