vtcode_core/memory/
mod.rs1use 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#[derive(Debug, Error)]
21pub enum MemoryError {
22 #[error("failed to read memory info: {0}")]
24 Io(#[from] std::io::Error),
25
26 #[error("failed to parse memory value: {0}")]
28 Parse(String),
29
30 #[error("memory monitoring not supported on this platform")]
32 Unsupported,
33}
34
35#[derive(Clone)]
37pub struct MemoryMonitor {
38 state: Arc<Mutex<MemoryMonitorState>>,
39}
40
41struct MemoryMonitorState {
42 checkpoints: VecDeque<RssCheckpoint>,
44 last_rss_bytes: usize,
46 last_check_timestamp: u64,
48}
49
50#[derive(Debug, Clone)]
52pub struct RssCheckpoint {
53 pub timestamp: u64,
55 pub rss_bytes: usize,
57 pub label: String,
59}
60
61#[derive(Debug, Clone)]
63pub struct MemoryReport {
64 pub current_rss_mb: f64,
66 pub soft_limit_mb: f64,
68 pub hard_limit_mb: f64,
70 pub pressure: MemoryPressure,
72 pub usage_percent: f64,
74 pub recent_checkpoints: Vec<RssCheckpoint>,
76}
77
78impl MemoryMonitor {
79 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 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 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 pub fn check_pressure(&self) -> Result<MemoryPressure, MemoryError> {
113 let rss = Self::get_rss_bytes()?;
114 let pressure = MemoryPressure::from_rss(rss);
115
116 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 pub fn record_checkpoint(&self, label: String) -> Result<(), MemoryError> {
127 let rss = Self::get_rss_bytes()?;
128
129 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 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 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 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 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 pub fn clear_checkpoints(&self) {
198 if let Ok(mut state) = self.state.lock() {
199 state.checkpoints.clear();
200 }
201 }
202
203 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 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 }
237 }
238 }
239
240 #[test]
241 fn test_get_rss_bytes_matches_shared_sampler() {
242 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) => {} (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 let _ = format!("{pressure:?}");
275 }
276 Err(e) => {
277 println!("Warning: Could not check pressure: {e}");
278 }
280 }
281 }
282
283 #[test]
284 fn test_record_checkpoint() {
285 let monitor = MemoryMonitor::new();
286 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 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 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 }
321 }
322 }
323}