Skip to main content

vtcode_core/memory/
mod.rs

1//! Memory monitoring and pressure detection system.
2//!
3//! This module provides real-time memory usage tracking for VT Code, including:
4//! - RSS-based memory monitoring
5//! - Memory pressure classification (Normal, Warning, Critical)
6//! - Memory checkpoints for debugging
7//! - Adaptive TTL based on memory pressure
8
9use std::collections::VecDeque;
10use std::sync::{Arc, Mutex};
11use thiserror::Error;
12use tracing::warn;
13use vtcode_commons::utils::current_timestamp;
14
15pub use self::pressure::MemoryPressure;
16
17mod pressure;
18
19/// Errors that can occur during memory monitoring operations.
20#[derive(Debug, Error)]
21pub enum MemoryError {
22    /// Failed to read system memory information.
23    #[error("failed to read memory info: {0}")]
24    Io(#[from] std::io::Error),
25
26    /// Failed to parse memory value from system output.
27    #[error("failed to parse memory value: {0}")]
28    Parse(String),
29
30    /// Memory monitoring is not supported on this platform.
31    #[error("memory monitoring not supported on this platform")]
32    Unsupported,
33}
34
35/// Memory monitor for tracking system memory usage
36#[derive(Clone)]
37pub struct MemoryMonitor {
38    state: Arc<Mutex<MemoryMonitorState>>,
39}
40
41struct MemoryMonitorState {
42    /// Memory checkpoint history for debugging
43    checkpoints: VecDeque<RssCheckpoint>,
44    /// Last recorded RSS in bytes
45    last_rss_bytes: usize,
46    /// Timestamp of last check
47    last_check_timestamp: u64,
48}
49
50/// Memory checkpoint for debugging memory spikes
51#[derive(Debug, Clone)]
52pub struct RssCheckpoint {
53    /// Timestamp when checkpoint was recorded
54    pub timestamp: u64,
55    /// RSS memory at checkpoint (bytes)
56    pub rss_bytes: usize,
57    /// Label/context for this checkpoint
58    pub label: String,
59}
60
61/// Memory report for user visibility
62#[derive(Debug, Clone)]
63pub struct MemoryReport {
64    /// Current RSS in MB
65    pub current_rss_mb: f64,
66    /// Soft limit in MB
67    pub soft_limit_mb: f64,
68    /// Hard limit in MB
69    pub hard_limit_mb: f64,
70    /// Current memory pressure
71    pub pressure: MemoryPressure,
72    /// Usage percentage (0-100)
73    pub usage_percent: f64,
74    /// Recent memory checkpoints
75    pub recent_checkpoints: Vec<RssCheckpoint>,
76}
77
78impl MemoryMonitor {
79    /// Create a new memory monitor
80    pub fn new() -> Self {
81        Self {
82            state: Arc::new(Mutex::new(MemoryMonitorState {
83                checkpoints: VecDeque::with_capacity(vtcode_config::constants::memory::MAX_CHECKPOINT_HISTORY),
84                last_rss_bytes: 0,
85                last_check_timestamp: 0,
86            })),
87        }
88    }
89
90    /// Get current RSS in bytes using the shared platform sampler.
91    ///
92    /// Delegates to [`vtcode_commons::memory::resident_set_size_mb`] (Mach task
93    /// info on macOS, `/proc/self/statm` on Linux) instead of shelling out or
94    /// re-parsing procfs here, so every sample is one cheap syscall.
95    pub fn get_rss_bytes() -> Result<usize, MemoryError> {
96        let mb = vtcode_commons::memory::resident_set_size_mb().ok_or(MemoryError::Unsupported)?;
97        let bytes = (mb * 1024.0 * 1024.0).round();
98        // The sampler only returns finite, non-negative values; reject anything
99        // else rather than casting blindly.
100        if !bytes.is_finite() || bytes < 0.0 || bytes > usize::MAX as f64 {
101            return Err(MemoryError::Unsupported);
102        }
103        #[expect(
104            clippy::cast_possible_truncation,
105            clippy::cast_sign_loss,
106            reason = "Range-checked above: finite, non-negative, and within usize::MAX."
107        )]
108        Ok(bytes as usize)
109    }
110
111    /// Check current memory pressure
112    pub fn check_pressure(&self) -> Result<MemoryPressure, MemoryError> {
113        let rss = Self::get_rss_bytes()?;
114        let pressure = MemoryPressure::from_rss(rss);
115
116        // Update last known RSS
117        if let Ok(mut state) = self.state.lock() {
118            state.last_rss_bytes = rss;
119            state.last_check_timestamp = current_timestamp();
120        }
121
122        Ok(pressure)
123    }
124
125    /// Record a memory checkpoint for debugging
126    pub fn record_checkpoint(&self, label: String) -> Result<(), MemoryError> {
127        let rss = Self::get_rss_bytes()?;
128
129        // Only record if change is significant (> 1 MB).
130        // Hold a single lock for both the threshold check and the push to
131        // avoid acquiring the mutex twice.
132        let min_threshold = vtcode_config::constants::memory::MIN_RSS_CHECKPOINT_BYTES;
133        if let Ok(mut state) = self.state.lock() {
134            let diff = (rss as i64 - state.last_rss_bytes as i64).unsigned_abs() as usize;
135            if diff < min_threshold {
136                return Ok(());
137            }
138
139            state.checkpoints.push_back(RssCheckpoint {
140                timestamp: current_timestamp(),
141                rss_bytes: rss,
142                label,
143            });
144
145            // Enforce max checkpoint history
146            let max_history = vtcode_config::constants::memory::MAX_CHECKPOINT_HISTORY;
147            while state.checkpoints.len() > max_history {
148                state.checkpoints.pop_front();
149            }
150        }
151
152        Ok(())
153    }
154
155    /// Get memory report for user visibility
156    pub fn get_report(&self) -> Result<MemoryReport, MemoryError> {
157        let rss_bytes = Self::get_rss_bytes()?;
158        let pressure = MemoryPressure::from_rss(rss_bytes);
159
160        let soft_limit = vtcode_config::constants::memory::SOFT_LIMIT_BYTES as f64 / (1024.0 * 1024.0);
161        let hard_limit = vtcode_config::constants::memory::HARD_LIMIT_BYTES as f64 / (1024.0 * 1024.0);
162        let current_rss_mb = rss_bytes as f64 / (1024.0 * 1024.0);
163
164        // Use hard limit for percentage calculation (worst case)
165        let usage_percent = (rss_bytes as f64 / vtcode_config::constants::memory::HARD_LIMIT_BYTES as f64) * 100.0;
166
167        let recent_checkpoints = if let Ok(state) = self.state.lock() {
168            state.checkpoints.iter().cloned().collect()
169        } else {
170            Vec::new()
171        };
172
173        Ok(MemoryReport {
174            current_rss_mb,
175            soft_limit_mb: soft_limit,
176            hard_limit_mb: hard_limit,
177            pressure,
178            usage_percent,
179            recent_checkpoints,
180        })
181    }
182
183    /// Get adaptive TTL factor based on current memory pressure
184    pub fn adaptive_ttl_factor(&self) -> f64 {
185        match self.check_pressure() {
186            Ok(MemoryPressure::Normal) => 1.0,
187            Ok(MemoryPressure::Warning) => vtcode_config::constants::memory::WARNING_TTL_REDUCTION_FACTOR,
188            Ok(MemoryPressure::Critical) => vtcode_config::constants::memory::CRITICAL_TTL_REDUCTION_FACTOR,
189            Err(error) => {
190                warn!(error = %error, "memory pressure check failed; assuming normal TTL factor");
191                1.0
192            }
193        }
194    }
195
196    /// Clear checkpoint history (for testing)
197    pub fn clear_checkpoints(&self) {
198        if let Ok(mut state) = self.state.lock() {
199            state.checkpoints.clear();
200        }
201    }
202
203    /// Get number of recorded checkpoints
204    pub fn checkpoint_count(&self) -> usize {
205        self.state.lock().map(|state| state.checkpoints.len()).unwrap_or(0)
206    }
207}
208
209impl Default for MemoryMonitor {
210    fn default() -> Self {
211        Self::new()
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    #[test]
220    fn test_memory_monitor_creation() {
221        let monitor = MemoryMonitor::new();
222        assert_eq!(monitor.checkpoint_count(), 0);
223    }
224
225    #[test]
226    fn test_get_rss_bytes() {
227        match MemoryMonitor::get_rss_bytes() {
228            Ok(rss) => {
229                // RSS should be reasonable (> 1MB and < 10GB)
230                assert!(rss > 1024 * 1024, "RSS should be > 1MB");
231                assert!(rss < 10 * 1024 * 1024 * 1024, "RSS should be < 10GB");
232            }
233            Err(e) => {
234                println!("Warning: Could not get RSS: {e}");
235                // This is acceptable on unsupported platforms
236            }
237        }
238    }
239
240    #[test]
241    fn test_get_rss_bytes_matches_shared_sampler() {
242        // Independent oracle: the shared sampler this delegates to, with the
243        // MiB-to-bytes scale stated here rather than reused from production.
244        // RSS can move between the two samples, so assert closeness in both
245        // directions (plus an absolute floor) instead of exact equality.
246        let sampler_mb = vtcode_commons::memory::resident_set_size_mb();
247        match (MemoryMonitor::get_rss_bytes(), sampler_mb) {
248            (Ok(bytes), Some(mb)) => {
249                let expected = mb * 1024.0 * 1024.0;
250                let actual = bytes as f64;
251                assert!(actual >= expected * 0.95, "delegated RSS {bytes} bytes fell below sampler {mb} MiB");
252                assert!(
253                    actual <= expected * 1.05 + 1024.0 * 1024.0,
254                    "delegated RSS {bytes} bytes rose above sampler {mb} MiB"
255                );
256                assert!(bytes > 1024 * 1024, "RSS should exceed 1 MiB, got {bytes}");
257            }
258            (Err(_), None) => {} // Unsupported platform: both sides agree.
259            (Ok(bytes), None) => {
260                panic!("get_rss_bytes returned {bytes} but the sampler is unavailable")
261            }
262            (Err(e), Some(mb)) => {
263                panic!("get_rss_bytes failed ({e}) but the sampler returned {mb} MiB")
264            }
265        }
266    }
267
268    #[test]
269    fn test_check_pressure() {
270        let monitor = MemoryMonitor::new();
271        match monitor.check_pressure() {
272            Ok(pressure) => {
273                // Should always return a valid pressure level
274                let _ = format!("{pressure:?}");
275            }
276            Err(e) => {
277                println!("Warning: Could not check pressure: {e}");
278                // Acceptable on unsupported platforms
279            }
280        }
281    }
282
283    #[test]
284    fn test_record_checkpoint() {
285        let monitor = MemoryMonitor::new();
286        // Try to record checkpoints (may fail on unsupported platforms)
287        let _result = monitor.record_checkpoint("test_checkpoint".to_string());
288    }
289
290    #[test]
291    fn test_clear_checkpoints() {
292        let monitor = MemoryMonitor::new();
293        monitor.clear_checkpoints();
294        assert_eq!(monitor.checkpoint_count(), 0);
295    }
296
297    #[test]
298    fn test_adaptive_ttl_factor() {
299        let monitor = MemoryMonitor::new();
300        let factor = monitor.adaptive_ttl_factor();
301
302        // TTL factor should be between 0.1 and 1.0
303        assert!(factor > 0.0);
304        assert!(factor <= 1.0);
305    }
306
307    #[test]
308    fn test_memory_report() {
309        let monitor = MemoryMonitor::new();
310        match monitor.get_report() {
311            Ok(report) => {
312                // Report should have reasonable values
313                assert!(report.usage_percent >= 0.0);
314                assert!(report.soft_limit_mb > 0.0);
315                assert!(report.hard_limit_mb > report.soft_limit_mb);
316            }
317            Err(e) => {
318                println!("Warning: Could not generate report: {e}");
319                // Acceptable on unsupported platforms
320            }
321        }
322    }
323}