selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Memory resource management

use crate::config::MemoryConfig;
use crate::errors::ResourceError;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::mpsc;
use tracing::{debug, error, info, warn};

/// Memory manager for system RAM
pub struct MemoryManager {
    config: MemoryConfig,
    action_tx: mpsc::Sender<MemoryAction>,
    allocated: AtomicU64,
}

/// Memory usage statistics
#[derive(Debug, Clone, Default)]
pub struct MemoryUsage {
    pub used: u64,
    pub total: u64,
    pub available: u64,
    pub percent: f32,
}

/// Memory actions for handling pressure
#[derive(Debug, Clone)]
pub enum MemoryAction {
    /// Run garbage collection hints
    RunGC,
    /// Flush caches
    FlushCaches,
    /// Reduce context window
    ReduceContext { target_tokens: usize },
    /// Pause non-critical tasks
    PauseTasks { priority_threshold: u8 },
    /// Offload models to CPU
    OffloadModels,
    /// Emergency: restart component
    EmergencyRestart,
}

impl MemoryManager {
    /// Create a new memory manager
    pub async fn new(config: &MemoryConfig) -> Result<Self, ResourceError> {
        let (action_tx, mut action_rx) = mpsc::channel(10);

        // Start action handler
        tokio::spawn(async move {
            while let Some(action) = action_rx.recv().await {
                match action {
                    MemoryAction::RunGC => {
                        debug!("Running garbage collection hints");
                        // In Rust, we can't force GC, but we can drop references
                    }
                    MemoryAction::FlushCaches => {
                        info!("Flushing caches");
                        // Would flush internal caches
                    }
                    MemoryAction::ReduceContext { target_tokens } => {
                        warn!(target_tokens = target_tokens, "Reducing context window");
                        // Would trigger context compression
                    }
                    MemoryAction::PauseTasks { priority_threshold } => {
                        warn!(priority = ?priority_threshold, "Pausing tasks below priority");
                        // Would pause low-priority tasks
                    }
                    MemoryAction::OffloadModels => {
                        warn!("Offloading models to CPU");
                        // Would offload non-critical models
                    }
                    MemoryAction::EmergencyRestart => {
                        error!("Emergency restart triggered");
                        // Would trigger component restart
                    }
                }
            }
        });

        Ok(Self {
            config: config.clone(),
            action_tx,
            allocated: AtomicU64::new(0),
        })
    }

    /// Get current memory usage
    pub async fn get_usage(&self) -> Result<MemoryUsage, ResourceError> {
        use sysinfo::System;

        let mut system = System::new_all();
        system.refresh_all();

        let total = system.total_memory();
        let used = system.used_memory();
        let available = system.available_memory();

        Ok(MemoryUsage {
            used,
            total,
            available,
            percent: if total > 0 {
                used as f32 / total as f32
            } else {
                0.0
            },
        })
    }

    /// Monitor memory continuously
    pub async fn monitor(&self) {
        let mut interval = tokio::time::interval(std::time::Duration::from_secs(
            self.config.monitor_interval_seconds,
        ));

        loop {
            interval.tick().await;

            if let Ok(usage) = self.get_usage().await {
                // metrics::gauge!("memory.used_bytes", usage.used as f64);
                // metrics::gauge!("memory.available_bytes", usage.available as f64);
                // metrics::gauge!("memory.percent", usage.percent as f64);

                // Check thresholds
                if usage.percent > self.config.emergency_threshold {
                    warn!(
                        percent = usage.percent,
                        "Memory emergency threshold reached"
                    );
                    self.trigger_emergency_cleanup().await;
                } else if usage.percent > self.config.critical_threshold {
                    warn!(percent = usage.percent, "Memory critical threshold reached");
                    self.trigger_critical_cleanup().await;
                } else if usage.percent > self.config.warning_threshold {
                    debug!(percent = usage.percent, "Memory warning threshold reached");
                    self.trigger_warning_cleanup().await;
                }
            }
        }
    }

    /// Trigger warning-level cleanup
    pub async fn trigger_warning_cleanup(&self) {
        let _ = self.action_tx.send(MemoryAction::FlushCaches).await;
    }

    /// Trigger critical-level cleanup
    pub async fn trigger_critical_cleanup(&self) {
        let _ = self.action_tx.send(MemoryAction::FlushCaches).await;
        let _ = self
            .action_tx
            .send(MemoryAction::ReduceContext {
                target_tokens: 32768,
            })
            .await;
        let _ = self
            .action_tx
            .send(MemoryAction::PauseTasks {
                priority_threshold: 1,
            })
            .await;
    }

    /// Trigger emergency-level cleanup
    pub async fn trigger_emergency_cleanup(&self) {
        let _ = self.action_tx.send(MemoryAction::FlushCaches).await;
        let _ = self
            .action_tx
            .send(MemoryAction::ReduceContext {
                target_tokens: 8192,
            })
            .await;
        let _ = self.action_tx.send(MemoryAction::OffloadModels).await;
        let _ = self
            .action_tx
            .send(MemoryAction::PauseTasks {
                priority_threshold: 2,
            })
            .await;
    }

    /// Allocate memory
    pub fn allocate(&self, bytes: u64) -> Result<(), ResourceError> {
        let current = self.allocated.fetch_add(bytes, Ordering::SeqCst);
        debug!(
            allocated_bytes = bytes,
            total_allocated = current + bytes,
            "Memory allocated"
        );
        Ok(())
    }

    /// Free allocated memory
    pub fn free(&self, bytes: u64) {
        let _ = self.allocated.fetch_sub(bytes, Ordering::SeqCst);
        debug!(freed_bytes = bytes, "Memory freed");
    }

    /// Get allocated memory
    pub fn get_allocated(&self) -> u64 {
        self.allocated.load(Ordering::Relaxed)
    }

    /// Check if enough memory is available
    pub async fn check_available(&self, required_bytes: u64) -> Result<bool, ResourceError> {
        let usage = self.get_usage().await?;
        Ok(usage.available >= required_bytes)
    }

    /// Estimate memory for operation
    pub fn estimate_for_tokens(&self, tokens: usize, bytes_per_token: usize) -> u64 {
        (tokens * bytes_per_token) as u64
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MemoryConfig;

    /// Helper to create a MemoryManager for testing without async overhead.
    /// Uses a bounded channel so we can inspect actions sent.
    fn make_test_memory_manager() -> (MemoryManager, mpsc::Receiver<MemoryAction>) {
        let (action_tx, action_rx) = mpsc::channel(100);
        let mm = MemoryManager {
            config: MemoryConfig::default(),
            action_tx,
            allocated: AtomicU64::new(0),
        };
        (mm, action_rx)
    }

    // ---- MemoryUsage tests ----

    #[test]
    fn test_memory_usage_default() {
        let usage = MemoryUsage::default();
        assert_eq!(usage.used, 0);
        assert_eq!(usage.total, 0);
        assert_eq!(usage.available, 0);
        assert_eq!(usage.percent, 0.0);
    }

    #[test]
    fn test_memory_usage_clone() {
        let usage = MemoryUsage {
            used: 8_000_000_000,
            total: 16_000_000_000,
            available: 8_000_000_000,
            percent: 0.5,
        };
        let cloned = usage.clone();
        assert_eq!(cloned.used, 8_000_000_000);
        assert_eq!(cloned.percent, 0.5);
    }

    // ---- MemoryAction tests ----

    #[test]
    fn test_memory_action_debug() {
        let action = MemoryAction::ReduceContext {
            target_tokens: 32768,
        };
        let debug_str = format!("{:?}", action);
        assert!(debug_str.contains("ReduceContext"));
        assert!(debug_str.contains("32768"));
    }

    #[test]
    fn test_memory_action_clone() {
        let action = MemoryAction::PauseTasks {
            priority_threshold: 2,
        };
        let cloned = action.clone();
        match cloned {
            MemoryAction::PauseTasks {
                priority_threshold: p,
            } => assert_eq!(p, 2),
            _ => panic!("Clone produced wrong variant"),
        }
    }

    // ---- MemoryManager allocate/free tests ----

    #[test]
    fn test_allocate_increases_tracked_memory() {
        let (mm, _rx) = make_test_memory_manager();
        assert_eq!(mm.get_allocated(), 0);

        mm.allocate(1_000_000).unwrap();
        assert_eq!(mm.get_allocated(), 1_000_000);

        mm.allocate(2_000_000).unwrap();
        assert_eq!(mm.get_allocated(), 3_000_000);
    }

    #[test]
    fn test_free_decreases_tracked_memory() {
        let (mm, _rx) = make_test_memory_manager();
        mm.allocate(5_000_000).unwrap();
        mm.free(2_000_000);
        assert_eq!(mm.get_allocated(), 3_000_000);
    }

    #[test]
    fn test_free_saturates_at_zero() {
        let (mm, _rx) = make_test_memory_manager();
        mm.allocate(1_000).unwrap();
        // Freeing more than allocated should wrap to a huge number with fetch_sub,
        // but the AtomicU64 wraps; let's verify current behavior
        mm.free(1_000);
        assert_eq!(mm.get_allocated(), 0);
    }

    #[test]
    fn test_allocate_returns_ok() {
        let (mm, _rx) = make_test_memory_manager();
        let result = mm.allocate(42);
        assert!(result.is_ok());
    }

    // ---- estimate_for_tokens tests ----

    #[test]
    fn test_estimate_for_tokens_basic() {
        let (mm, _rx) = make_test_memory_manager();
        let estimate = mm.estimate_for_tokens(1000, 4);
        assert_eq!(estimate, 4000);
    }

    #[test]
    fn test_estimate_for_tokens_zero() {
        let (mm, _rx) = make_test_memory_manager();
        assert_eq!(mm.estimate_for_tokens(0, 100), 0);
        assert_eq!(mm.estimate_for_tokens(100, 0), 0);
    }

    #[test]
    fn test_estimate_for_tokens_large_context() {
        let (mm, _rx) = make_test_memory_manager();
        // 1M tokens * 2 bytes each = 2MB
        let estimate = mm.estimate_for_tokens(1_000_000, 2);
        assert_eq!(estimate, 2_000_000);
    }

    // ---- Cleanup trigger tests ----

    #[tokio::test]
    async fn test_trigger_warning_cleanup_sends_action() {
        let (mm, mut rx) = make_test_memory_manager();
        mm.trigger_warning_cleanup().await;

        let action = rx.recv().await.unwrap();
        match action {
            MemoryAction::FlushCaches => {} // expected
            other => panic!("Expected FlushCaches, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_trigger_critical_cleanup_sends_three_actions() {
        let (mm, mut rx) = make_test_memory_manager();
        mm.trigger_critical_cleanup().await;

        let a1 = rx.recv().await.unwrap();
        assert!(matches!(a1, MemoryAction::FlushCaches));

        let a2 = rx.recv().await.unwrap();
        assert!(matches!(
            a2,
            MemoryAction::ReduceContext {
                target_tokens: 32768
            }
        ));

        let a3 = rx.recv().await.unwrap();
        assert!(matches!(
            a3,
            MemoryAction::PauseTasks {
                priority_threshold: 1
            }
        ));
    }

    #[tokio::test]
    async fn test_trigger_emergency_cleanup_sends_four_actions() {
        let (mm, mut rx) = make_test_memory_manager();
        mm.trigger_emergency_cleanup().await;

        let a1 = rx.recv().await.unwrap();
        assert!(matches!(a1, MemoryAction::FlushCaches));

        let a2 = rx.recv().await.unwrap();
        assert!(matches!(
            a2,
            MemoryAction::ReduceContext {
                target_tokens: 8192
            }
        ));

        let a3 = rx.recv().await.unwrap();
        assert!(matches!(a3, MemoryAction::OffloadModels));

        let a4 = rx.recv().await.unwrap();
        assert!(matches!(
            a4,
            MemoryAction::PauseTasks {
                priority_threshold: 2
            }
        ));
    }

    // ---- MemoryConfig defaults ----

    #[test]
    fn test_memory_config_thresholds_are_ordered() {
        let config = MemoryConfig::default();
        assert!(config.warning_threshold < config.critical_threshold);
        assert!(config.critical_threshold < config.emergency_threshold);
        assert!(config.emergency_threshold <= 1.0);
    }
}