optirs-gpu 0.3.2

OptiRS GPU acceleration and multi-GPU optimization
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
// GPU memory allocation strategies and algorithms
//
// This module provides various memory allocation strategies optimized for
// different GPU workload patterns and memory usage scenarios.

pub mod arena_allocator;
pub mod buddy_allocator;
pub mod slab_allocator;
pub mod strategies;

// Re-export main types for convenience
pub use strategies::{
    AdaptiveConfig, AllocationEvent, AllocationPattern, AllocationStats, AllocationStrategy,
    AllocationStrategyManager, HybridConfig, MLConfig, MLFeatures, MLPrediction, MemoryBlock,
};

pub use buddy_allocator::{
    AllocationInfo, BuddyAllocator, BuddyBlock, BuddyConfig, BuddyError, BuddyStats,
    FreeBlockStats, MemoryUsage, ThreadSafeBuddyAllocator,
};

pub use slab_allocator::{
    CacheConfig, CacheInfo, MemoryPool, MemoryPoolUsage, Slab, SlabAllocator, SlabAllocatorStats,
    SlabCache, SlabConfig, SlabError, ThreadSafeSlabAllocator,
};

pub use arena_allocator::{
    ArenaAllocator, ArenaConfig, ArenaError, ArenaStats, ArenaUsage, CheckpointHandle,
    ExternalAllocator, GrowingArena, MemoryLayout, MemoryRegion, RingArena, RingConfig, RingUsage,
    ThreadSafeArena,
};

use std::collections::HashMap;
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::time::Instant;

/// Unified allocator interface that can use different allocation strategies
pub struct UnifiedAllocator {
    /// Strategy manager for general allocations
    strategy_manager: AllocationStrategyManager,
    /// Buddy allocator for power-of-2 allocations
    buddy_allocator: Option<BuddyAllocator>,
    /// Slab allocator for fixed-size objects
    slab_allocator: Option<SlabAllocator>,
    /// Arena allocator for temporary allocations
    arena_allocator: Option<ArenaAllocator>,
    /// Configuration
    config: UnifiedConfig,
    /// Statistics
    stats: UnifiedStats,
    /// Allocation routing table
    routing_table: AllocationRouter,
}

/// Configuration for unified allocator
#[derive(Debug, Clone)]
pub struct UnifiedConfig {
    /// Default allocation strategy
    pub default_strategy: AllocationStrategy,
    /// Enable buddy allocator
    pub enable_buddy: bool,
    /// Enable slab allocator
    pub enable_slab: bool,
    /// Enable arena allocator
    pub enable_arena: bool,
    /// Size threshold for buddy allocator
    pub buddy_threshold: usize,
    /// Size threshold for slab allocator
    pub slab_threshold: usize,
    /// Size threshold for arena allocator
    pub arena_threshold: usize,
    /// Enable automatic routing optimization
    pub enable_auto_routing: bool,
    /// Statistics collection interval
    pub stats_interval: std::time::Duration,
}

impl Default for UnifiedConfig {
    fn default() -> Self {
        Self {
            default_strategy: AllocationStrategy::Adaptive,
            enable_buddy: true,
            enable_slab: true,
            enable_arena: true,
            buddy_threshold: 1024,
            slab_threshold: 4096,
            arena_threshold: 64 * 1024,
            enable_auto_routing: true,
            stats_interval: std::time::Duration::from_secs(1),
        }
    }
}

/// Unified allocator statistics
#[derive(Debug, Clone, Default)]
pub struct UnifiedStats {
    pub total_allocations: u64,
    pub total_deallocations: u64,
    pub bytes_allocated: u64,
    pub bytes_deallocated: u64,
    pub strategy_allocations: HashMap<AllocationStrategy, u64>,
    pub buddy_allocations: u64,
    pub slab_allocations: u64,
    pub arena_allocations: u64,
    pub routing_decisions: u64,
    pub routing_cache_hits: u64,
    pub average_allocation_time_ns: f64,
    pub peak_memory_usage: usize,
    pub current_memory_usage: usize,
}

/// Allocation routing logic
pub struct AllocationRouter {
    /// Size-based routing rules
    size_routes: Vec<SizeRoute>,
    /// Pattern-based routing cache
    pattern_cache: HashMap<AllocationPattern, AllocatorType>,
    /// Performance history for routing decisions
    performance_history: HashMap<AllocatorType, PerformanceMetrics>,
    /// Configuration
    config: RouterConfig,
}

/// Size-based routing rule
#[derive(Debug, Clone)]
pub struct SizeRoute {
    pub min_size: usize,
    pub max_size: Option<usize>,
    pub preferred_allocator: AllocatorType,
    pub fallback_allocator: Option<AllocatorType>,
}

/// Allocator type identification
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AllocatorType {
    Strategy(AllocationStrategy),
    Buddy,
    Slab,
    Arena,
}

/// Performance metrics for routing decisions
#[derive(Debug, Clone, Default)]
pub struct PerformanceMetrics {
    pub average_latency_ns: f64,
    pub success_rate: f64,
    pub fragmentation_ratio: f64,
    pub cache_hit_rate: f64,
    pub memory_efficiency: f64,
}

/// Router configuration
#[derive(Debug, Clone)]
pub struct RouterConfig {
    pub enable_performance_tracking: bool,
    pub cache_size: usize,
    pub adaptation_threshold: f64,
    pub performance_window: usize,
}

impl Default for RouterConfig {
    fn default() -> Self {
        Self {
            enable_performance_tracking: true,
            cache_size: 1000,
            adaptation_threshold: 0.1,
            performance_window: 100,
        }
    }
}

impl AllocationRouter {
    pub fn new(config: RouterConfig) -> Self {
        let size_routes = vec![
            SizeRoute {
                min_size: 0,
                max_size: Some(256),
                preferred_allocator: AllocatorType::Slab,
                fallback_allocator: Some(AllocatorType::Strategy(AllocationStrategy::FirstFit)),
            },
            SizeRoute {
                min_size: 257,
                max_size: Some(4096),
                preferred_allocator: AllocatorType::Strategy(AllocationStrategy::BestFit),
                fallback_allocator: Some(AllocatorType::Buddy),
            },
            SizeRoute {
                min_size: 4097,
                max_size: Some(64 * 1024),
                preferred_allocator: AllocatorType::Buddy,
                fallback_allocator: Some(AllocatorType::Strategy(AllocationStrategy::BestFit)),
            },
            SizeRoute {
                min_size: 64 * 1024 + 1,
                max_size: None,
                preferred_allocator: AllocatorType::Arena,
                fallback_allocator: Some(AllocatorType::Strategy(AllocationStrategy::WorstFit)),
            },
        ];

        Self {
            size_routes,
            pattern_cache: HashMap::new(),
            performance_history: HashMap::new(),
            config,
        }
    }

    /// Route allocation request to appropriate allocator
    pub fn route_allocation(
        &mut self,
        size: usize,
        pattern: Option<AllocationPattern>,
    ) -> AllocatorType {
        // Check pattern cache first
        if let Some(pattern) = pattern {
            if let Some(allocator_type) = self.pattern_cache.get(&pattern) {
                return allocator_type.clone();
            }
        }

        // Use size-based routing
        for route in &self.size_routes {
            if size >= route.min_size && route.max_size.is_none_or(|max| size <= max) {
                // Check performance if tracking is enabled
                if self.config.enable_performance_tracking {
                    let preferred_perf = self
                        .performance_history
                        .get(&route.preferred_allocator)
                        .cloned()
                        .unwrap_or_default();

                    if let Some(fallback) = &route.fallback_allocator {
                        let fallback_perf = self
                            .performance_history
                            .get(fallback)
                            .cloned()
                            .unwrap_or_default();

                        // Choose based on performance
                        if fallback_perf.average_latency_ns > 0.0
                            && preferred_perf.average_latency_ns > 0.0
                        {
                            let perf_ratio = fallback_perf.average_latency_ns
                                / preferred_perf.average_latency_ns;
                            if perf_ratio < 1.0 - self.config.adaptation_threshold {
                                return fallback.clone();
                            }
                        }
                    }
                }

                return route.preferred_allocator.clone();
            }
        }

        // Default fallback
        AllocatorType::Strategy(AllocationStrategy::BestFit)
    }

    /// Update performance metrics for an allocator
    pub fn update_performance(
        &mut self,
        allocator_type: AllocatorType,
        metrics: PerformanceMetrics,
    ) {
        self.performance_history.insert(allocator_type, metrics);
    }

    /// Cache pattern-based routing decision
    pub fn cache_pattern_route(
        &mut self,
        pattern: AllocationPattern,
        allocator_type: AllocatorType,
    ) {
        if self.pattern_cache.len() >= self.config.cache_size {
            // Remove oldest entry (simplified - could use LRU)
            if let Some(key) = self.pattern_cache.keys().next().cloned() {
                self.pattern_cache.remove(&key);
            }
        }
        self.pattern_cache.insert(pattern, allocator_type);
    }
}

impl UnifiedAllocator {
    /// Create a new unified allocator
    pub fn new(
        base_ptr: NonNull<u8>,
        total_size: usize,
        config: UnifiedConfig,
    ) -> Result<Self, AllocationError> {
        let mut strategy_manager = AllocationStrategyManager::new(config.default_strategy.clone());

        let buddy_allocator = if config.enable_buddy {
            let buddy_config = BuddyConfig::default();
            let buddy_size = total_size / 4; // Allocate 1/4 of memory to buddy allocator
            let buddy_ptr = base_ptr;
            Some(BuddyAllocator::new(
                buddy_ptr.as_ptr(),
                buddy_size,
                buddy_config,
            )?)
        } else {
            None
        };

        let slab_allocator = if config.enable_slab {
            let slab_config = SlabConfig::default();
            let slab_size = total_size / 4; // Allocate 1/4 of memory to slab allocator
            let slab_ptr = unsafe { NonNull::new_unchecked(base_ptr.as_ptr().add(total_size / 4)) };
            Some(SlabAllocator::new(slab_ptr, slab_size, slab_config))
        } else {
            None
        };

        let arena_allocator = if config.enable_arena {
            let arena_config = ArenaConfig::default();
            let arena_size = total_size / 4; // Allocate 1/4 of memory to arena allocator
            let arena_ptr =
                unsafe { NonNull::new_unchecked(base_ptr.as_ptr().add(total_size / 2)) };
            Some(ArenaAllocator::new(arena_ptr, arena_size, arena_config)?)
        } else {
            None
        };

        let routing_table = AllocationRouter::new(RouterConfig::default());

        // Initialize strategy manager with remaining memory (1/4 of total)
        let strategy_size = total_size / 4;
        let strategy_ptr = unsafe { base_ptr.as_ptr().add(3 * total_size / 4) };
        strategy_manager.add_free_block(MemoryBlock {
            ptr: strategy_ptr,
            size: strategy_size,
            is_free: true,
            allocated_at: None,
            last_accessed: None,
            access_count: 0,
            fragmentation_score: 0.0,
        });

        Ok(Self {
            strategy_manager,
            buddy_allocator,
            slab_allocator,
            arena_allocator,
            config,
            stats: UnifiedStats::default(),
            routing_table,
        })
    }

    /// Allocate memory using the unified interface
    pub fn allocate(
        &mut self,
        size: usize,
        requested_allocator_type: AllocatorType,
        _alignment: Option<usize>,
    ) -> Result<NonNull<u8>, AllocationError> {
        let start_time = Instant::now();
        self.stats.total_allocations += 1;

        // Use requested allocator type if provided, otherwise route automatically
        let allocator_type = requested_allocator_type;

        let result = match &allocator_type {
            AllocatorType::Strategy(strategy) => {
                self.strategy_manager.set_strategy(strategy.clone());
                self.strategy_manager.find_free_block(size).ok_or_else(|| {
                    AllocationError::OutOfMemory("Strategy allocator failed".to_string())
                })
            }
            AllocatorType::Buddy => {
                if let Some(ref mut buddy) = self.buddy_allocator {
                    buddy.allocate(size).map_err(AllocationError::BuddyError)
                } else {
                    Err(AllocationError::AllocatorNotAvailable(
                        "Buddy allocator not enabled".to_string(),
                    ))
                }
            }
            AllocatorType::Slab => {
                if let Some(ref mut slab) = self.slab_allocator {
                    slab.allocate(size)
                        .map(|ptr| ptr.as_ptr())
                        .map_err(AllocationError::SlabError)
                } else {
                    Err(AllocationError::AllocatorNotAvailable(
                        "Slab allocator not enabled".to_string(),
                    ))
                }
            }
            AllocatorType::Arena => {
                if let Some(ref mut arena) = self.arena_allocator {
                    arena
                        .allocate(size)
                        .map(|ptr| ptr.as_ptr())
                        .map_err(AllocationError::ArenaError)
                } else {
                    Err(AllocationError::AllocatorNotAvailable(
                        "Arena allocator not enabled".to_string(),
                    ))
                }
            }
        };

        let allocation_time = start_time.elapsed().as_nanos() as f64;

        match &result {
            Ok(_) => {
                self.stats.bytes_allocated += size as u64;
                self.stats.current_memory_usage += size;
                if self.stats.current_memory_usage > self.stats.peak_memory_usage {
                    self.stats.peak_memory_usage = self.stats.current_memory_usage;
                }

                // Update strategy-specific stats
                match &allocator_type {
                    AllocatorType::Strategy(strategy) => {
                        *self
                            .stats
                            .strategy_allocations
                            .entry(strategy.clone())
                            .or_insert(0) += 1;
                    }
                    AllocatorType::Buddy => self.stats.buddy_allocations += 1,
                    AllocatorType::Slab => self.stats.slab_allocations += 1,
                    AllocatorType::Arena => self.stats.arena_allocations += 1,
                }

                // Update performance metrics
                let metrics = PerformanceMetrics {
                    average_latency_ns: allocation_time,
                    success_rate: 1.0,
                    fragmentation_ratio: 0.0, // Would need to calculate from allocator
                    cache_hit_rate: 0.0,      // Would need to get from allocator
                    memory_efficiency: 1.0,   // Would need to calculate
                };
                self.routing_table
                    .update_performance(allocator_type, metrics);
            }
            Err(_) => {
                // Update failure metrics
                let metrics = PerformanceMetrics {
                    average_latency_ns: allocation_time,
                    success_rate: 0.0,
                    ..Default::default()
                };
                self.routing_table
                    .update_performance(allocator_type, metrics);
            }
        }

        // Update average allocation time
        let total_time = self.stats.average_allocation_time_ns
            * (self.stats.total_allocations - 1) as f64
            + allocation_time;
        self.stats.average_allocation_time_ns = total_time / self.stats.total_allocations as f64;

        result.map(|ptr| unsafe { NonNull::new_unchecked(ptr) })
    }

    /// Deallocate memory
    pub fn deallocate(&mut self, ptr: NonNull<u8>, size: usize) -> Result<(), AllocationError> {
        self.stats.total_deallocations += 1;
        self.stats.bytes_deallocated += size as u64;
        self.stats.current_memory_usage = self.stats.current_memory_usage.saturating_sub(size);

        // Try each allocator to find which one owns this pointer
        if let Some(ref mut buddy) = self.buddy_allocator {
            if let Ok(()) = buddy.deallocate(ptr.as_ptr()) {
                return Ok(());
            }
        }

        if let Some(ref mut slab) = self.slab_allocator {
            if let Ok(()) = slab.deallocate(ptr, size) {
                return Ok(());
            }
        }

        if let Some(ref mut arena) = self.arena_allocator {
            if arena.contains_pointer(ptr) {
                // Arena allocator typically doesn't support individual deallocation
                return Ok(());
            }
        }

        Err(AllocationError::InvalidPointer(
            "Pointer not found in any allocator".to_string(),
        ))
    }

    /// Free memory (alias for deallocate)
    pub fn free(
        &mut self,
        ptr: *mut std::ffi::c_void,
        _allocator_type: AllocatorType,
    ) -> Result<(), AllocationError> {
        // Convert to NonNull<u8> and call deallocate
        let ptr_u8 = NonNull::new(ptr as *mut u8)
            .ok_or_else(|| AllocationError::InvalidPointer("Null pointer".to_string()))?;
        // We don't have the size here, so we'll just try to deallocate with a dummy size
        // This is not ideal, but matches the interface expected by the caller
        self.deallocate(ptr_u8, 0)
    }

    /// Allocate a fresh block for a reallocation request.
    ///
    /// Deliberately does *not* free `_ptr` (its parameter is unused by
    /// design, not by oversight): the sole caller,
    /// [`crate::memory::GpuMemorySystem::reallocate`], already owns the
    /// complete, correct realloc contract one layer up -- it tracks the old
    /// allocation's real size (which this layer does not), copies the live
    /// data with it via `copy_nonoverlapping`, and only then frees the old
    /// pointer. Freeing `_ptr` here as well would race that caller: it
    /// still reads from `_ptr` after this call returns whenever the new
    /// address differs (the overwhelmingly common case, since this always
    /// allocates fresh rather than truly growing in place), which would
    /// make that read a use-after-free and the caller's own free a
    /// double-free.
    pub fn reallocate(
        &mut self,
        _ptr: *mut std::ffi::c_void,
        new_size: usize,
        allocator_type: AllocatorType,
    ) -> Result<*mut std::ffi::c_void, AllocationError> {
        // For simplicity, implement as a fresh allocation; the caller
        // (see the doc comment above) handles copying and freeing the old
        // block. In a production system, this should instead be optimized
        // for true in-place reallocation using `_ptr`.
        let new_ptr = self.allocate(new_size, allocator_type, None)?;
        Ok(new_ptr.as_ptr() as *mut std::ffi::c_void)
    }

    /// Get unified statistics
    pub fn get_stats(&self) -> &UnifiedStats {
        &self.stats
    }

    /// Get the active configuration (thresholds, enabled sub-allocators,
    /// default strategy).
    ///
    /// `allocate` currently always uses the type its caller passes rather
    /// than deriving one from `buddy_threshold`/`slab_threshold`/
    /// `arena_threshold`/`enable_auto_routing` -- centralizing that
    /// decision here would change
    /// `GpuMemorySystem::choose_allocator`'s tested
    /// routing boundaries (its hardcoded 1 KiB / 1 MiB cutovers do not
    /// line up with this config's threshold values), which is a
    /// deliberate behavior decision left to that caller rather than one
    /// this lint pass makes unilaterally. Exposed so callers can inspect
    /// (and eventually route against) the real configuration instead of
    /// duplicating their own hardcoded thresholds.
    pub fn get_config(&self) -> &UnifiedConfig {
        &self.config
    }

    /// Get detailed allocator information
    pub fn get_detailed_info(&self) -> DetailedAllocatorInfo {
        let mut info = DetailedAllocatorInfo {
            strategy_info: Some(self.strategy_manager.get_stats().clone()),
            buddy_info: None,
            slab_info: None,
            arena_info: None,
            unified_stats: self.stats.clone(),
        };

        if let Some(ref buddy) = self.buddy_allocator {
            info.buddy_info = Some(buddy.get_stats().clone());
        }

        if let Some(ref slab) = self.slab_allocator {
            info.slab_info = Some(slab.get_stats());
        }

        if let Some(ref arena) = self.arena_allocator {
            info.arena_info = Some(arena.get_stats().clone());
        }

        info
    }

    /// Reset specific allocator
    pub fn reset_allocator(
        &mut self,
        allocator_type: AllocatorType,
    ) -> Result<(), AllocationError> {
        match allocator_type {
            AllocatorType::Strategy(_) => {
                self.strategy_manager.clear_history();
            }
            AllocatorType::Buddy => {
                if let Some(ref mut buddy) = self.buddy_allocator {
                    buddy.reset();
                } else {
                    return Err(AllocationError::AllocatorNotAvailable(
                        "Buddy allocator not enabled".to_string(),
                    ));
                }
            }
            AllocatorType::Slab => {
                return Err(AllocationError::UnsupportedOperation(
                    "Slab allocator reset not supported".to_string(),
                ));
            }
            AllocatorType::Arena => {
                if let Some(ref mut arena) = self.arena_allocator {
                    arena.reset();
                } else {
                    return Err(AllocationError::AllocatorNotAvailable(
                        "Arena allocator not enabled".to_string(),
                    ));
                }
            }
        }
        Ok(())
    }

    /// Force garbage collection on applicable allocators
    pub fn garbage_collect(&mut self) -> GarbageCollectionResult {
        let mut result = GarbageCollectionResult::default();

        if let Some(ref mut slab) = self.slab_allocator {
            result.slab_reclaimed = slab.reclaim_memory();
        }

        if let Some(ref mut buddy) = self.buddy_allocator {
            result.buddy_defragmented = buddy.defragment();
        }

        result
    }

    /// Optimize allocation strategies based on performance data
    pub fn optimize_strategies(&mut self) -> Result<(), AllocationError> {
        // Update internal routing table based on performance metrics
        let current_stats = self.get_stats();

        // Analyze allocation patterns and update routing decisions
        // Note: Routing optimization would be implemented here based on performance history
        if current_stats.buddy_allocations > current_stats.slab_allocations {
            // Prefer buddy allocator for current workload - implementation would update routing config
        } else {
            // Prefer slab allocator for current workload - implementation would update routing config
        }

        // Reset counters for next optimization cycle
        self.stats.buddy_allocations = 0;
        self.stats.slab_allocations = 0;
        self.stats.arena_allocations = 0;
        self.stats.strategy_allocations.clear();

        Ok(())
    }
}

// Safety: UnifiedAllocator contains multiple allocators managing GPU memory pointers.
// While the contained allocators use NonNull/raw pointers that aren't Send/Sync by default,
// it's safe to share UnifiedAllocator across threads when protected by Arc<Mutex<>> because:
// 1. All pointers point to GPU memory managed by the GPU driver
// 2. The Mutex provides exclusive access for all mutable operations
// 3. No thread-local state is maintained
unsafe impl Send for UnifiedAllocator {}
unsafe impl Sync for UnifiedAllocator {}

/// Detailed information about all allocators
#[derive(Debug, Clone)]
pub struct DetailedAllocatorInfo {
    pub strategy_info: Option<AllocationStats>,
    pub buddy_info: Option<BuddyStats>,
    pub slab_info: Option<SlabAllocatorStats>,
    pub arena_info: Option<ArenaStats>,
    pub unified_stats: UnifiedStats,
}

/// Result of garbage collection operations
#[derive(Debug, Clone, Default)]
pub struct GarbageCollectionResult {
    pub slab_reclaimed: usize,
    pub buddy_defragmented: usize,
    pub arena_reset: bool,
    pub total_bytes_freed: usize,
}

/// Unified allocation errors
#[derive(Debug, Clone)]
pub enum AllocationError {
    OutOfMemory(String),
    InvalidPointer(String),
    AllocatorNotAvailable(String),
    UnsupportedOperation(String),
    BuddyError(BuddyError),
    SlabError(SlabError),
    ArenaError(ArenaError),
}

impl std::fmt::Display for AllocationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AllocationError::OutOfMemory(msg) => write!(f, "Out of memory: {}", msg),
            AllocationError::InvalidPointer(msg) => write!(f, "Invalid pointer: {}", msg),
            AllocationError::AllocatorNotAvailable(msg) => {
                write!(f, "Allocator not available: {}", msg)
            }
            AllocationError::UnsupportedOperation(msg) => {
                write!(f, "Unsupported operation: {}", msg)
            }
            AllocationError::BuddyError(e) => write!(f, "Buddy allocator error: {}", e),
            AllocationError::SlabError(e) => write!(f, "Slab allocator error: {}", e),
            AllocationError::ArenaError(e) => write!(f, "Arena allocator error: {}", e),
        }
    }
}

impl std::error::Error for AllocationError {}

impl From<BuddyError> for AllocationError {
    fn from(error: BuddyError) -> Self {
        AllocationError::BuddyError(error)
    }
}

impl From<SlabError> for AllocationError {
    fn from(error: SlabError) -> Self {
        AllocationError::SlabError(error)
    }
}

impl From<ArenaError> for AllocationError {
    fn from(error: ArenaError) -> Self {
        AllocationError::ArenaError(error)
    }
}

/// Thread-safe unified allocator wrapper
pub struct ThreadSafeUnifiedAllocator {
    allocator: Arc<Mutex<UnifiedAllocator>>,
}

impl ThreadSafeUnifiedAllocator {
    pub fn new(
        base_ptr: NonNull<u8>,
        total_size: usize,
        config: UnifiedConfig,
    ) -> Result<Self, AllocationError> {
        let allocator = UnifiedAllocator::new(base_ptr, total_size, config)?;
        Ok(Self {
            allocator: Arc::new(Mutex::new(allocator)),
        })
    }

    pub fn allocate(&self, size: usize) -> Result<NonNull<u8>, AllocationError> {
        let mut allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner());
        allocator.allocate(
            size,
            AllocatorType::Strategy(strategies::AllocationStrategy::FirstFit),
            None,
        )
    }

    pub fn deallocate(&self, ptr: NonNull<u8>, size: usize) -> Result<(), AllocationError> {
        let mut allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner());
        allocator.deallocate(ptr, size)
    }

    pub fn get_stats(&self) -> UnifiedStats {
        let allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner());
        allocator.get_stats().clone()
    }

    pub fn garbage_collect(&self) -> GarbageCollectionResult {
        let mut allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner());
        allocator.garbage_collect()
    }
}

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

    #[test]
    fn test_unified_allocator_creation() {
        let size = 1024 * 1024; // 1MB
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = UnifiedConfig::default();
        let allocator = UnifiedAllocator::new(ptr, size, config);
        assert!(allocator.is_ok());
    }

    #[test]
    fn test_get_config_reflects_construction_config() {
        let size = 1024 * 1024;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = UnifiedConfig {
            buddy_threshold: 2048,
            ..UnifiedConfig::default()
        };
        let allocator = UnifiedAllocator::new(ptr, size, config).expect("unwrap failed");

        assert_eq!(allocator.get_config().buddy_threshold, 2048);
    }

    #[test]
    fn test_unified_allocation() {
        let size = 1024 * 1024;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = UnifiedConfig::default();
        let mut allocator = UnifiedAllocator::new(ptr, size, config).expect("unwrap failed");

        // Test different sizes to trigger different allocators
        let small_alloc = allocator.allocate(100, AllocatorType::Slab, None); // Should use slab
        assert!(small_alloc.is_ok());

        let medium_alloc = allocator.allocate(2048, AllocatorType::Buddy, None); // Should use buddy
        assert!(
            medium_alloc.is_ok(),
            "Medium allocation failed: {:?}",
            medium_alloc.err()
        );

        let large_alloc = allocator.allocate(128 * 1024, AllocatorType::Arena, None); // Should use arena
        assert!(large_alloc.is_ok());

        let stats = allocator.get_stats();
        assert_eq!(stats.total_allocations, 3);
    }

    #[test]
    fn test_allocation_routing() {
        let config = RouterConfig::default();
        let mut router = AllocationRouter::new(config);

        let small_route = router.route_allocation(100, None);
        assert_eq!(small_route, AllocatorType::Slab);

        let medium_route = router.route_allocation(2048, None);
        assert_eq!(
            medium_route,
            AllocatorType::Strategy(AllocationStrategy::BestFit)
        );

        let large_route = router.route_allocation(128 * 1024, None);
        assert_eq!(large_route, AllocatorType::Arena);
    }

    #[test]
    fn test_thread_safe_unified_allocator() {
        let size = 1024 * 1024;
        let memory = vec![0u8; size];
        let ptr = NonNull::new(memory.as_ptr() as *mut u8).expect("unwrap failed");

        let config = UnifiedConfig::default();
        let allocator = ThreadSafeUnifiedAllocator::new(ptr, size, config).expect("unwrap failed");

        let alloc_result = allocator.allocate(1024);
        assert!(
            alloc_result.is_ok(),
            "Allocation failed: {:?}",
            alloc_result.err()
        );

        let stats = allocator.get_stats();
        assert!(stats.total_allocations > 0);
    }
}