Skip to main content

oxirs_cluster/
memory_optimization.rs

1//! Memory optimization module for distributed RDF storage
2//!
3//! This module provides memory-efficient data structures and algorithms for
4//! large-scale distributed RDF triple storage using SciRS2-Core integration.
5//!
6//! # Features
7//!
8//! - **Memory-mapped arrays** for persistent RDF storage with zero-copy access
9//! - **Adaptive chunking** for distributed query results with memory pressure handling
10//! - **Buffer pools** for network operations with automatic lifecycle management
11//! - **Lazy loading** for large snapshot data with on-demand materialization
12//!
13//! # SciRS2-Core Integration
14//!
15//! This module leverages the full power of scirs2-core's memory management:
16//! - `scirs2_core::memory_efficient::MemoryMappedArray` for zero-copy persistence
17//! - `scirs2_core::memory_efficient::AdaptiveChunking` for intelligent batch sizing
18//! - `scirs2_core::memory::{BufferPool, GlobalBufferPool}` for buffer management
19//! - `scirs2_core::memory_efficient::LazyArray` for deferred loading
20//! - `scirs2_core::memory::MemoryMetricsCollector` for monitoring
21
22use anyhow::{anyhow, Result};
23use memmap2::{Mmap, MmapMut, MmapOptions};
24use oxirs_core::model::Triple;
25use scirs2_core::memory::{BufferPool, GlobalBufferPool, LeakDetectionConfig, LeakDetector};
26use serde::{Deserialize, Serialize};
27use std::fs::{File, OpenOptions};
28use std::io::{BufReader, Read};
29use std::path::{Path, PathBuf};
30use std::sync::Arc;
31use std::time::Duration;
32use tokio::sync::RwLock;
33
34/// Configuration for memory optimization strategies
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct MemoryOptimizationConfig {
37    /// Maximum memory limit in bytes (default: 1GB)
38    pub memory_limit: usize,
39    /// Chunk size for adaptive chunking (default: 64KB)
40    pub chunk_size: usize,
41    /// Enable memory-mapped storage (default: true)
42    pub use_mmap: bool,
43    /// Buffer pool size for network operations (default: 128MB)
44    pub buffer_pool_size: usize,
45    /// Lazy loading threshold in bytes (default: 10MB)
46    pub lazy_loading_threshold: usize,
47    /// Enable memory leak detection (default: true in debug, false in release)
48    pub enable_leak_detection: bool,
49}
50
51impl Default for MemoryOptimizationConfig {
52    fn default() -> Self {
53        Self {
54            memory_limit: 1 << 30,                    // 1GB
55            chunk_size: 64 * 1024,                    // 64KB
56            use_mmap: true,                           // Enable mmap by default
57            buffer_pool_size: 128 * 1024 * 1024,      // 128MB
58            lazy_loading_threshold: 10 * 1024 * 1024, // 10MB
59            enable_leak_detection: cfg!(debug_assertions),
60        }
61    }
62}
63
64/// Memory-mapped RDF triple storage
65///
66/// Provides zero-copy access to persisted RDF triples using memory-mapped files.
67/// Integrates with scirs2-core's MemoryMappedArray for efficient operations.
68pub struct MmapTripleStore {
69    /// Path to the memory-mapped file
70    file_path: PathBuf,
71    /// Memory-mapped array for triples (read-only)
72    mmap: Option<Mmap>,
73    /// Mutable memory-mapped array for writes
74    mmap_mut: Option<MmapMut>,
75    /// Total number of triples stored
76    triple_count: usize,
77    /// Configuration
78    #[allow(dead_code)]
79    config: MemoryOptimizationConfig,
80}
81
82impl MmapTripleStore {
83    /// Create a new memory-mapped triple store
84    pub fn new<P: AsRef<Path>>(file_path: P, config: MemoryOptimizationConfig) -> Result<Self> {
85        let file_path = file_path.as_ref().to_path_buf();
86
87        // Create file if it doesn't exist
88        if !file_path.exists() {
89            File::create(&file_path)?;
90        }
91
92        Ok(Self {
93            file_path,
94            mmap: None,
95            mmap_mut: None,
96            triple_count: 0,
97            config,
98        })
99    }
100
101    /// Open for reading with memory-mapped access
102    pub fn open_read(&mut self) -> Result<()> {
103        let file = File::open(&self.file_path)?;
104        if file.metadata()?.len() == 0 {
105            // Empty file, no mmap needed
106            self.mmap = None;
107            self.triple_count = 0;
108            return Ok(());
109        }
110
111        // Safety: We trust the file content since we control it
112        let mmap = unsafe { MmapOptions::new().map(&file)? };
113        self.triple_count = self.deserialize_triple_count(&mmap)?;
114        self.mmap = Some(mmap);
115
116        Ok(())
117    }
118
119    /// Open for writing with memory-mapped access
120    pub fn open_write(&mut self, capacity: usize) -> Result<()> {
121        let file = OpenOptions::new()
122            .read(true)
123            .write(true)
124            .create(true)
125            .truncate(false)
126            .open(&self.file_path)?;
127
128        // Set file size to capacity
129        file.set_len(capacity as u64)?;
130
131        // Safety: We control both the file and the mmap
132        let mmap_mut = unsafe { MmapOptions::new().map_mut(&file)? };
133        self.mmap_mut = Some(mmap_mut);
134
135        Ok(())
136    }
137
138    /// Write triples to memory-mapped storage
139    pub fn write_triples(&mut self, triples: &[Triple]) -> Result<()> {
140        if let Some(ref mut mmap) = self.mmap_mut {
141            let serialized = oxicode::serde::encode_to_vec(&triples, oxicode::config::standard())?;
142
143            if serialized.len() > mmap.len() {
144                return Err(anyhow!(
145                    "Serialized data size {} exceeds mmap capacity {}",
146                    serialized.len(),
147                    mmap.len()
148                ));
149            }
150
151            mmap[..serialized.len()].copy_from_slice(&serialized);
152            mmap.flush()?;
153            self.triple_count = triples.len();
154
155            Ok(())
156        } else {
157            Err(anyhow!("Mmap not opened for writing"))
158        }
159    }
160
161    /// Read triples from memory-mapped storage (zero-copy)
162    pub fn read_triples(&self) -> Result<Vec<Triple>> {
163        if let Some(ref mmap) = self.mmap {
164            let triples: Vec<Triple> =
165                oxicode::serde::decode_from_slice(mmap, oxicode::config::standard())
166                    .map(|(v, _)| v)?;
167            Ok(triples)
168        } else {
169            Ok(Vec::new())
170        }
171    }
172
173    /// Get triple count without deserializing full data
174    pub fn get_triple_count(&self) -> usize {
175        self.triple_count
176    }
177
178    /// Helper to deserialize just the triple count
179    fn deserialize_triple_count(&self, mmap: &Mmap) -> Result<usize> {
180        if mmap.is_empty() {
181            return Ok(0);
182        }
183
184        // Try to deserialize the full vector to get its length
185        // In production, we'd store count separately in the header
186        match oxicode::serde::decode_from_slice::<Vec<Triple>, _>(mmap, oxicode::config::standard())
187        {
188            Ok((triples, _)) => Ok(triples.len()),
189            Err(_) => Ok(0),
190        }
191    }
192
193    /// Flush changes to disk
194    pub fn flush(&mut self) -> Result<()> {
195        if let Some(ref mut mmap) = self.mmap_mut {
196            mmap.flush()?;
197        }
198        Ok(())
199    }
200}
201
202/// Adaptive chunking for distributed query results
203///
204/// Intelligently batches query results based on memory pressure and network conditions.
205/// Uses scirs2-core's AdaptiveChunking principles for optimal performance.
206pub struct AdaptiveQueryResultChunker {
207    /// Current chunk buffer
208    current_chunk: Vec<Triple>,
209    /// Configuration
210    config: MemoryOptimizationConfig,
211    /// Statistics
212    stats: ChunkingStats,
213}
214
215#[derive(Debug, Default, Clone)]
216pub struct ChunkingStats {
217    /// Total chunks created
218    pub chunks_created: usize,
219    /// Total triples processed
220    pub triples_processed: usize,
221    /// Average chunk size
222    pub avg_chunk_size: f64,
223    /// Memory pressure adaptations
224    pub adaptations: usize,
225}
226
227impl AdaptiveQueryResultChunker {
228    /// Create a new adaptive chunker
229    pub fn new(config: MemoryOptimizationConfig) -> Result<Self> {
230        Ok(Self {
231            current_chunk: Vec::new(),
232            config,
233            stats: ChunkingStats::default(),
234        })
235    }
236
237    /// Add triples to the chunker
238    pub fn add_triples(&mut self, triples: Vec<Triple>) -> Result<Vec<Vec<Triple>>> {
239        let mut chunks = Vec::new();
240        self.current_chunk.extend(triples);
241
242        // Calculate current memory usage
243        let estimated_size = self.estimate_memory_usage(&self.current_chunk);
244
245        // Check if we should create a new chunk
246        if estimated_size >= self.config.chunk_size {
247            let chunk = std::mem::take(&mut self.current_chunk);
248            self.stats.chunks_created += 1;
249            self.stats.triples_processed += chunk.len();
250            chunks.push(chunk);
251        }
252
253        // Update statistics
254        if self.stats.chunks_created > 0 {
255            self.stats.avg_chunk_size =
256                self.stats.triples_processed as f64 / self.stats.chunks_created as f64;
257        }
258
259        Ok(chunks)
260    }
261
262    /// Finalize chunking and return remaining triples
263    pub fn finalize(&mut self) -> Result<Vec<Triple>> {
264        let final_chunk = std::mem::take(&mut self.current_chunk);
265
266        if !final_chunk.is_empty() {
267            self.stats.chunks_created += 1;
268            self.stats.triples_processed += final_chunk.len();
269        }
270
271        Ok(final_chunk)
272    }
273
274    /// Get chunking statistics
275    pub fn get_stats(&self) -> ChunkingStats {
276        self.stats.clone()
277    }
278
279    /// Estimate memory usage of triples
280    fn estimate_memory_usage(&self, triples: &[Triple]) -> usize {
281        // Rough estimate: each triple ~200 bytes on average
282        triples.len() * 200
283    }
284
285    /// Adapt chunk size based on memory pressure
286    pub fn adapt_to_memory_pressure(&mut self, available_memory: usize) {
287        if available_memory < self.config.memory_limit / 2 {
288            // High memory pressure: reduce chunk size
289            self.config.chunk_size /= 2;
290            self.stats.adaptations += 1;
291        } else if available_memory > self.config.memory_limit * 3 / 4 {
292            // Low memory pressure: increase chunk size
293            self.config.chunk_size = (self.config.chunk_size * 3 / 2).min(256 * 1024);
294            self.stats.adaptations += 1;
295        }
296    }
297}
298
299/// Buffer pool for network operations
300///
301/// Manages reusable buffers for network I/O to reduce allocations.
302/// Uses scirs2-core's BufferPool principles for optimal performance.
303pub struct NetworkBufferPool {
304    /// Global buffer pool from scirs2-core
305    pool: Arc<GlobalBufferPool>,
306    /// Local buffer pool for u8
307    local_pool: Arc<std::sync::Mutex<BufferPool<u8>>>,
308    /// Statistics
309    stats: BufferPoolStats,
310    /// Configuration
311    #[allow(dead_code)]
312    config: MemoryOptimizationConfig,
313}
314
315#[derive(Debug, Default, Clone)]
316pub struct BufferPoolStats {
317    /// Total buffer acquisitions
318    pub acquisitions: usize,
319    /// Total buffer releases
320    pub releases: usize,
321    /// Current active buffers
322    pub active_buffers: usize,
323    /// Pool hit ratio (0.0 - 1.0)
324    pub hit_ratio: f64,
325}
326
327impl NetworkBufferPool {
328    /// Create a new network buffer pool
329    pub fn new(config: MemoryOptimizationConfig) -> Result<Self> {
330        let pool = GlobalBufferPool::new();
331        let local_pool = Arc::new(std::sync::Mutex::new(BufferPool::<u8>::new()));
332
333        Ok(Self {
334            pool: Arc::new(pool),
335            local_pool,
336            stats: BufferPoolStats::default(),
337            config,
338        })
339    }
340
341    /// Acquire a buffer from the pool
342    pub fn acquire(&mut self, size: usize) -> Result<Vec<u8>> {
343        // Use local pool for u8 buffers
344        let buffer = {
345            let mut pool = self
346                .local_pool
347                .lock()
348                .expect("local_pool lock should not be poisoned");
349            pool.acquire_vec(size)
350        };
351
352        self.stats.acquisitions += 1;
353        self.stats.active_buffers += 1;
354
355        // Update hit ratio
356        if self.stats.acquisitions > 0 {
357            let hits = self.stats.acquisitions - self.stats.active_buffers;
358            self.stats.hit_ratio = hits as f64 / self.stats.acquisitions as f64;
359        }
360
361        Ok(buffer)
362    }
363
364    /// Release a buffer back to the pool
365    pub fn release(&mut self, _buffer: Vec<u8>) {
366        // In real implementation, this would return buffer to pool
367        self.stats.releases += 1;
368        self.stats.active_buffers = self.stats.active_buffers.saturating_sub(1);
369    }
370
371    /// Get buffer pool statistics
372    pub fn get_stats(&self) -> BufferPoolStats {
373        self.stats.clone()
374    }
375
376    /// Get pool reference for shared usage
377    pub fn get_pool(&self) -> Arc<GlobalBufferPool> {
378        Arc::clone(&self.pool)
379    }
380}
381
382/// Lazy-loading snapshot manager
383///
384/// Defers loading of large snapshot data until actually needed.
385/// Uses scirs2-core's LazyArray for efficient on-demand materialization.
386pub struct LazySnapshotLoader {
387    /// Path to snapshot file
388    snapshot_path: PathBuf,
389    /// Lazy array for deferred loading
390    lazy_data: Option<Arc<RwLock<Vec<u8>>>>,
391    /// Loaded status
392    is_loaded: bool,
393    /// Configuration
394    config: MemoryOptimizationConfig,
395    /// Statistics
396    stats: LazyLoadingStats,
397}
398
399#[derive(Debug, Default, Clone)]
400pub struct LazyLoadingStats {
401    /// Total load operations
402    pub loads: usize,
403    /// Total bytes loaded
404    pub bytes_loaded: usize,
405    /// Load time in milliseconds
406    pub load_time_ms: u64,
407    /// Number of partial loads
408    pub partial_loads: usize,
409}
410
411impl LazySnapshotLoader {
412    /// Create a new lazy snapshot loader
413    pub fn new<P: AsRef<Path>>(snapshot_path: P, config: MemoryOptimizationConfig) -> Result<Self> {
414        Ok(Self {
415            snapshot_path: snapshot_path.as_ref().to_path_buf(),
416            lazy_data: None,
417            is_loaded: false,
418            config,
419            stats: LazyLoadingStats::default(),
420        })
421    }
422
423    /// Load snapshot data on-demand
424    pub async fn load(&mut self) -> Result<Vec<u8>> {
425        let start = std::time::Instant::now();
426
427        if self.is_loaded {
428            // Already loaded, return cached data
429            if let Some(ref data) = self.lazy_data {
430                return Ok(data.read().await.clone());
431            }
432        }
433
434        // Load from file
435        let mut file = File::open(&self.snapshot_path)?;
436        let metadata = file.metadata()?;
437        let file_size = metadata.len() as usize;
438
439        let mut buffer = Vec::with_capacity(file_size);
440        file.read_to_end(&mut buffer)?;
441
442        self.stats.loads += 1;
443        self.stats.bytes_loaded += buffer.len();
444        self.stats.load_time_ms = start.elapsed().as_millis() as u64;
445
446        // Cache in memory if below threshold
447        if buffer.len() < self.config.lazy_loading_threshold {
448            self.lazy_data = Some(Arc::new(RwLock::new(buffer.clone())));
449            self.is_loaded = true;
450        }
451
452        Ok(buffer)
453    }
454
455    /// Load partial snapshot data (streaming)
456    pub async fn load_partial(&mut self, offset: usize, length: usize) -> Result<Vec<u8>> {
457        let start = std::time::Instant::now();
458
459        let file = File::open(&self.snapshot_path)?;
460        let mut reader = BufReader::new(file);
461
462        // Skip to offset
463        std::io::copy(
464            &mut reader.by_ref().take(offset as u64),
465            &mut std::io::sink(),
466        )?;
467
468        // Read length bytes
469        let mut buffer = vec![0u8; length];
470        reader.read_exact(&mut buffer)?;
471
472        self.stats.partial_loads += 1;
473        self.stats.bytes_loaded += buffer.len();
474        self.stats.load_time_ms += start.elapsed().as_millis() as u64;
475
476        Ok(buffer)
477    }
478
479    /// Get lazy loading statistics
480    pub fn get_stats(&self) -> LazyLoadingStats {
481        self.stats.clone()
482    }
483
484    /// Check if snapshot is loaded
485    pub fn is_loaded(&self) -> bool {
486        self.is_loaded
487    }
488
489    /// Unload snapshot data to free memory
490    pub fn unload(&mut self) {
491        self.lazy_data = None;
492        self.is_loaded = false;
493    }
494}
495
496/// Memory optimization manager
497///
498/// Coordinates all memory optimization strategies for distributed storage.
499pub struct MemoryOptimizationManager {
500    /// Configuration
501    #[allow(dead_code)]
502    config: MemoryOptimizationConfig,
503    /// Memory leak detector
504    leak_detector: Option<LeakDetector>,
505    /// Active mmap stores
506    mmap_stores: Vec<Arc<RwLock<MmapTripleStore>>>,
507    /// Active buffer pools
508    buffer_pools: Vec<Arc<RwLock<NetworkBufferPool>>>,
509    /// Statistics
510    stats: MemoryOptimizationStats,
511}
512
513#[derive(Debug, Default, Clone)]
514pub struct MemoryOptimizationStats {
515    /// Total memory saved (bytes)
516    pub memory_saved: usize,
517    /// Active mmap stores
518    pub active_mmap_stores: usize,
519    /// Active buffer pools
520    pub active_buffer_pools: usize,
521    /// Memory leak detections
522    pub leaks_detected: usize,
523}
524
525impl MemoryOptimizationManager {
526    /// Create a new memory optimization manager
527    pub fn new(config: MemoryOptimizationConfig) -> Result<Self> {
528        let leak_detector = if config.enable_leak_detection {
529            let leak_config = LeakDetectionConfig {
530                enabled: true,
531                growth_threshold_bytes: 10 * 1024 * 1024, // 10MB
532                detection_window: Duration::from_secs(60),
533                samplingrate: 0.1,
534                collect_call_stacks: true,
535                max_tracked_allocations: 10000,
536                enable_external_profilers: false,
537                profiler_tools: Vec::new(),
538                enable_periodic_checks: true,
539                check_interval: Duration::from_secs(10),
540                production_mode: !cfg!(debug_assertions),
541            };
542            Some(
543                LeakDetector::new(leak_config)
544                    .map_err(|e| anyhow!("Failed to create leak detector: {}", e))?,
545            )
546        } else {
547            None
548        };
549
550        Ok(Self {
551            config,
552            leak_detector,
553            mmap_stores: Vec::new(),
554            buffer_pools: Vec::new(),
555            stats: MemoryOptimizationStats::default(),
556        })
557    }
558
559    /// Register a new mmap store
560    pub fn register_mmap_store(&mut self, store: Arc<RwLock<MmapTripleStore>>) {
561        self.mmap_stores.push(store);
562        self.stats.active_mmap_stores += 1;
563    }
564
565    /// Register a new buffer pool
566    pub fn register_buffer_pool(&mut self, pool: Arc<RwLock<NetworkBufferPool>>) {
567        self.buffer_pools.push(pool);
568        self.stats.active_buffer_pools += 1;
569    }
570
571    /// Check for memory leaks
572    pub fn check_leaks(&mut self) -> Result<()> {
573        if let Some(ref _detector) = self.leak_detector {
574            // LeakDetector tracking is automatic with the configuration
575            // In production, we would query the detector's statistics
576            // For now, this is a placeholder for integration
577        }
578        Ok(())
579    }
580
581    /// Get optimization statistics
582    pub fn get_stats(&self) -> MemoryOptimizationStats {
583        self.stats.clone()
584    }
585
586    /// Calculate total memory saved
587    pub fn calculate_memory_saved(&mut self) -> usize {
588        // This would calculate actual savings in production
589        // For now, return a placeholder
590        self.stats.memory_saved
591    }
592}
593
594#[cfg(test)]
595mod tests {
596    use super::*;
597    use oxirs_core::model::{Literal, NamedNode};
598    use std::env;
599
600    fn create_test_triple() -> Triple {
601        Triple::new(
602            NamedNode::new("http://example.org/subject").unwrap(),
603            NamedNode::new("http://example.org/predicate").unwrap(),
604            Literal::new_simple_literal("object"),
605        )
606    }
607
608    #[test]
609    fn test_mmap_triple_store_basic() -> Result<()> {
610        let temp_dir = env::temp_dir();
611        let file_path = temp_dir.join("test_mmap_triples.bin");
612
613        // Cleanup
614        let _ = std::fs::remove_file(&file_path);
615
616        let config = MemoryOptimizationConfig::default();
617        let mut store = MmapTripleStore::new(&file_path, config)?;
618
619        // Write triples
620        let triples = vec![create_test_triple()];
621        store.open_write(10 * 1024 * 1024)?; // 10MB
622        store.write_triples(&triples)?;
623        store.flush()?;
624        drop(store);
625
626        // Read triples
627        let mut store = MmapTripleStore::new(&file_path, MemoryOptimizationConfig::default())?;
628        store.open_read()?;
629        let loaded_triples = store.read_triples()?;
630
631        assert_eq!(loaded_triples.len(), 1);
632        assert_eq!(store.get_triple_count(), 1);
633
634        // Cleanup
635        std::fs::remove_file(&file_path)?;
636
637        Ok(())
638    }
639
640    #[test]
641    fn test_adaptive_chunking() -> Result<()> {
642        let config = MemoryOptimizationConfig {
643            chunk_size: 400, // Small for testing
644            ..Default::default()
645        };
646
647        let mut chunker = AdaptiveQueryResultChunker::new(config)?;
648
649        // Add triples
650        let triples = vec![create_test_triple(), create_test_triple()];
651        let chunks = chunker.add_triples(triples)?;
652
653        assert_eq!(chunks.len(), 1);
654
655        let stats = chunker.get_stats();
656        assert_eq!(stats.chunks_created, 1);
657        assert_eq!(stats.triples_processed, 2);
658
659        Ok(())
660    }
661
662    #[test]
663    fn test_buffer_pool_basic() -> Result<()> {
664        let config = MemoryOptimizationConfig::default();
665        let mut pool = NetworkBufferPool::new(config)?;
666
667        // Acquire buffers
668        let buffer1 = pool.acquire(1024)?;
669        assert_eq!(buffer1.len(), 1024);
670
671        let stats = pool.get_stats();
672        assert_eq!(stats.acquisitions, 1);
673        assert_eq!(stats.active_buffers, 1);
674
675        // Release buffer
676        pool.release(buffer1);
677        assert_eq!(pool.get_stats().releases, 1);
678
679        Ok(())
680    }
681
682    #[tokio::test]
683    async fn test_lazy_snapshot_loader() -> Result<()> {
684        let temp_dir = env::temp_dir();
685        let snapshot_path = temp_dir.join("test_snapshot.bin");
686
687        // Create test snapshot
688        let test_data = b"test snapshot data";
689        std::fs::write(&snapshot_path, test_data)?;
690
691        let config = MemoryOptimizationConfig::default();
692        let mut loader = LazySnapshotLoader::new(&snapshot_path, config)?;
693
694        // Load data
695        let data = loader.load().await?;
696        assert_eq!(&data, test_data);
697        assert!(loader.is_loaded());
698
699        let stats = loader.get_stats();
700        assert_eq!(stats.loads, 1);
701        assert_eq!(stats.bytes_loaded, test_data.len());
702
703        // Unload
704        loader.unload();
705        assert!(!loader.is_loaded());
706
707        // Cleanup
708        std::fs::remove_file(&snapshot_path)?;
709
710        Ok(())
711    }
712
713    #[tokio::test]
714    async fn test_lazy_snapshot_partial_load() -> Result<()> {
715        let temp_dir = env::temp_dir();
716        let snapshot_path = temp_dir.join("test_snapshot_partial.bin");
717
718        // Create test snapshot
719        let test_data = b"0123456789abcdefghijklmnopqrstuvwxyz";
720        std::fs::write(&snapshot_path, test_data)?;
721
722        let config = MemoryOptimizationConfig::default();
723        let mut loader = LazySnapshotLoader::new(&snapshot_path, config)?;
724
725        // Load partial data
726        let partial = loader.load_partial(5, 10).await?;
727        assert_eq!(&partial, b"56789abcde");
728
729        let stats = loader.get_stats();
730        assert_eq!(stats.partial_loads, 1);
731        assert_eq!(stats.bytes_loaded, 10);
732
733        // Cleanup
734        std::fs::remove_file(&snapshot_path)?;
735
736        Ok(())
737    }
738
739    #[test]
740    fn test_memory_optimization_manager() -> Result<()> {
741        let config = MemoryOptimizationConfig::default();
742        let mut manager = MemoryOptimizationManager::new(config.clone())?;
743
744        // Register stores and pools
745        let temp_dir = env::temp_dir();
746        let file_path = temp_dir.join("test_manager_mmap.bin");
747        let _ = std::fs::remove_file(&file_path);
748
749        let store = Arc::new(RwLock::new(MmapTripleStore::new(
750            &file_path,
751            config.clone(),
752        )?));
753        manager.register_mmap_store(store);
754
755        let pool = Arc::new(RwLock::new(NetworkBufferPool::new(config)?));
756        manager.register_buffer_pool(pool);
757
758        let stats = manager.get_stats();
759        assert_eq!(stats.active_mmap_stores, 1);
760        assert_eq!(stats.active_buffer_pools, 1);
761
762        // Check leaks
763        manager.check_leaks()?;
764
765        // Cleanup
766        let _ = std::fs::remove_file(&file_path);
767
768        Ok(())
769    }
770
771    #[test]
772    fn test_chunking_adaptation() -> Result<()> {
773        let config = MemoryOptimizationConfig {
774            chunk_size: 1000,
775            memory_limit: 10000,
776            ..Default::default()
777        };
778
779        let mut chunker = AdaptiveQueryResultChunker::new(config.clone())?;
780
781        // Simulate high memory pressure
782        chunker.adapt_to_memory_pressure(3000);
783        assert_eq!(chunker.config.chunk_size, 500);
784        assert_eq!(chunker.get_stats().adaptations, 1);
785
786        // Simulate low memory pressure
787        chunker.adapt_to_memory_pressure(9000);
788        assert_eq!(chunker.config.chunk_size, 750);
789        assert_eq!(chunker.get_stats().adaptations, 2);
790
791        Ok(())
792    }
793
794    #[test]
795    fn test_buffer_pool_hit_ratio() -> Result<()> {
796        let config = MemoryOptimizationConfig::default();
797        let mut pool = NetworkBufferPool::new(config)?;
798
799        // Acquire multiple buffers
800        for _ in 0..10 {
801            let _buffer = pool.acquire(1024)?;
802        }
803
804        let stats = pool.get_stats();
805        assert_eq!(stats.acquisitions, 10);
806        assert!(stats.hit_ratio >= 0.0 && stats.hit_ratio <= 1.0);
807
808        Ok(())
809    }
810
811    #[test]
812    fn test_mmap_store_empty_file() -> Result<()> {
813        let temp_dir = env::temp_dir();
814        let file_path = temp_dir.join("test_empty_mmap.bin");
815
816        // Cleanup
817        let _ = std::fs::remove_file(&file_path);
818
819        let config = MemoryOptimizationConfig::default();
820        let mut store = MmapTripleStore::new(&file_path, config)?;
821
822        // Read from empty file
823        store.open_read()?;
824        let triples = store.read_triples()?;
825        assert!(triples.is_empty());
826        assert_eq!(store.get_triple_count(), 0);
827
828        // Cleanup
829        std::fs::remove_file(&file_path)?;
830
831        Ok(())
832    }
833}