1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct MemoryOptimizationConfig {
37 pub memory_limit: usize,
39 pub chunk_size: usize,
41 pub use_mmap: bool,
43 pub buffer_pool_size: usize,
45 pub lazy_loading_threshold: usize,
47 pub enable_leak_detection: bool,
49}
50
51impl Default for MemoryOptimizationConfig {
52 fn default() -> Self {
53 Self {
54 memory_limit: 1 << 30, chunk_size: 64 * 1024, use_mmap: true, buffer_pool_size: 128 * 1024 * 1024, lazy_loading_threshold: 10 * 1024 * 1024, enable_leak_detection: cfg!(debug_assertions),
60 }
61 }
62}
63
64pub struct MmapTripleStore {
69 file_path: PathBuf,
71 mmap: Option<Mmap>,
73 mmap_mut: Option<MmapMut>,
75 triple_count: usize,
77 #[allow(dead_code)]
79 config: MemoryOptimizationConfig,
80}
81
82impl MmapTripleStore {
83 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 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 pub fn open_read(&mut self) -> Result<()> {
103 let file = File::open(&self.file_path)?;
104 if file.metadata()?.len() == 0 {
105 self.mmap = None;
107 self.triple_count = 0;
108 return Ok(());
109 }
110
111 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 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 file.set_len(capacity as u64)?;
130
131 let mmap_mut = unsafe { MmapOptions::new().map_mut(&file)? };
133 self.mmap_mut = Some(mmap_mut);
134
135 Ok(())
136 }
137
138 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 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 pub fn get_triple_count(&self) -> usize {
175 self.triple_count
176 }
177
178 fn deserialize_triple_count(&self, mmap: &Mmap) -> Result<usize> {
180 if mmap.is_empty() {
181 return Ok(0);
182 }
183
184 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 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
202pub struct AdaptiveQueryResultChunker {
207 current_chunk: Vec<Triple>,
209 config: MemoryOptimizationConfig,
211 stats: ChunkingStats,
213}
214
215#[derive(Debug, Default, Clone)]
216pub struct ChunkingStats {
217 pub chunks_created: usize,
219 pub triples_processed: usize,
221 pub avg_chunk_size: f64,
223 pub adaptations: usize,
225}
226
227impl AdaptiveQueryResultChunker {
228 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 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 let estimated_size = self.estimate_memory_usage(&self.current_chunk);
244
245 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 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 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 pub fn get_stats(&self) -> ChunkingStats {
276 self.stats.clone()
277 }
278
279 fn estimate_memory_usage(&self, triples: &[Triple]) -> usize {
281 triples.len() * 200
283 }
284
285 pub fn adapt_to_memory_pressure(&mut self, available_memory: usize) {
287 if available_memory < self.config.memory_limit / 2 {
288 self.config.chunk_size /= 2;
290 self.stats.adaptations += 1;
291 } else if available_memory > self.config.memory_limit * 3 / 4 {
292 self.config.chunk_size = (self.config.chunk_size * 3 / 2).min(256 * 1024);
294 self.stats.adaptations += 1;
295 }
296 }
297}
298
299pub struct NetworkBufferPool {
304 pool: Arc<GlobalBufferPool>,
306 local_pool: Arc<std::sync::Mutex<BufferPool<u8>>>,
308 stats: BufferPoolStats,
310 #[allow(dead_code)]
312 config: MemoryOptimizationConfig,
313}
314
315#[derive(Debug, Default, Clone)]
316pub struct BufferPoolStats {
317 pub acquisitions: usize,
319 pub releases: usize,
321 pub active_buffers: usize,
323 pub hit_ratio: f64,
325}
326
327impl NetworkBufferPool {
328 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 pub fn acquire(&mut self, size: usize) -> Result<Vec<u8>> {
343 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 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 pub fn release(&mut self, _buffer: Vec<u8>) {
366 self.stats.releases += 1;
368 self.stats.active_buffers = self.stats.active_buffers.saturating_sub(1);
369 }
370
371 pub fn get_stats(&self) -> BufferPoolStats {
373 self.stats.clone()
374 }
375
376 pub fn get_pool(&self) -> Arc<GlobalBufferPool> {
378 Arc::clone(&self.pool)
379 }
380}
381
382pub struct LazySnapshotLoader {
387 snapshot_path: PathBuf,
389 lazy_data: Option<Arc<RwLock<Vec<u8>>>>,
391 is_loaded: bool,
393 config: MemoryOptimizationConfig,
395 stats: LazyLoadingStats,
397}
398
399#[derive(Debug, Default, Clone)]
400pub struct LazyLoadingStats {
401 pub loads: usize,
403 pub bytes_loaded: usize,
405 pub load_time_ms: u64,
407 pub partial_loads: usize,
409}
410
411impl LazySnapshotLoader {
412 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 pub async fn load(&mut self) -> Result<Vec<u8>> {
425 let start = std::time::Instant::now();
426
427 if self.is_loaded {
428 if let Some(ref data) = self.lazy_data {
430 return Ok(data.read().await.clone());
431 }
432 }
433
434 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 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 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 std::io::copy(
464 &mut reader.by_ref().take(offset as u64),
465 &mut std::io::sink(),
466 )?;
467
468 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 pub fn get_stats(&self) -> LazyLoadingStats {
481 self.stats.clone()
482 }
483
484 pub fn is_loaded(&self) -> bool {
486 self.is_loaded
487 }
488
489 pub fn unload(&mut self) {
491 self.lazy_data = None;
492 self.is_loaded = false;
493 }
494}
495
496pub struct MemoryOptimizationManager {
500 #[allow(dead_code)]
502 config: MemoryOptimizationConfig,
503 leak_detector: Option<LeakDetector>,
505 mmap_stores: Vec<Arc<RwLock<MmapTripleStore>>>,
507 buffer_pools: Vec<Arc<RwLock<NetworkBufferPool>>>,
509 stats: MemoryOptimizationStats,
511}
512
513#[derive(Debug, Default, Clone)]
514pub struct MemoryOptimizationStats {
515 pub memory_saved: usize,
517 pub active_mmap_stores: usize,
519 pub active_buffer_pools: usize,
521 pub leaks_detected: usize,
523}
524
525impl MemoryOptimizationManager {
526 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, 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 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 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 pub fn check_leaks(&mut self) -> Result<()> {
573 if let Some(ref _detector) = self.leak_detector {
574 }
578 Ok(())
579 }
580
581 pub fn get_stats(&self) -> MemoryOptimizationStats {
583 self.stats.clone()
584 }
585
586 pub fn calculate_memory_saved(&mut self) -> usize {
588 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 let _ = std::fs::remove_file(&file_path);
615
616 let config = MemoryOptimizationConfig::default();
617 let mut store = MmapTripleStore::new(&file_path, config)?;
618
619 let triples = vec![create_test_triple()];
621 store.open_write(10 * 1024 * 1024)?; store.write_triples(&triples)?;
623 store.flush()?;
624 drop(store);
625
626 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 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, ..Default::default()
645 };
646
647 let mut chunker = AdaptiveQueryResultChunker::new(config)?;
648
649 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 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 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 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 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 loader.unload();
705 assert!(!loader.is_loaded());
706
707 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 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 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 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 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 manager.check_leaks()?;
764
765 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 chunker.adapt_to_memory_pressure(3000);
783 assert_eq!(chunker.config.chunk_size, 500);
784 assert_eq!(chunker.get_stats().adaptations, 1);
785
786 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 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 let _ = std::fs::remove_file(&file_path);
818
819 let config = MemoryOptimizationConfig::default();
820 let mut store = MmapTripleStore::new(&file_path, config)?;
821
822 store.open_read()?;
824 let triples = store.read_triples()?;
825 assert!(triples.is_empty());
826 assert_eq!(store.get_triple_count(), 0);
827
828 std::fs::remove_file(&file_path)?;
830
831 Ok(())
832 }
833}