torsh-backend 0.1.2

Backend abstraction layer for ToRSh
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
//! Enhanced NUMA-aware memory allocation with optional libnuma integration
//!
//! This module provides advanced NUMA memory allocation capabilities that can optionally
//! use libnuma when available for better performance on NUMA systems.

use crate::cpu::memory::{NumaAllocationStrategy, NumaTopology, AccessPatternType};
use crate::error::BackendResult;
use torsh_core::error::TorshError;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::ffi::CString;

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, string::String, vec::Vec};

/// Enhanced NUMA allocator with optional libnuma support
#[derive(Debug)]
pub struct EnhancedNumaAllocator {
    /// Whether libnuma is available and loaded
    numa_available: bool,
    /// NUMA topology information
    topology: Arc<Mutex<NumaTopology>>,
    /// Allocation tracking
    allocations: Arc<Mutex<HashMap<usize, AllocationInfo>>>,
    /// Performance statistics per NUMA node
    node_stats: Arc<Mutex<HashMap<u32, NodeStats>>>,
    /// Memory migration hints
    migration_hints: Arc<Mutex<Vec<MigrationHint>>>,
}

/// Information about a NUMA allocation
#[derive(Debug, Clone)]
struct AllocationInfo {
    ptr: *mut u8,
    size: usize,
    node: u32,
    access_pattern: AccessPatternType,
    allocation_time: std::time::Instant,
    access_count: u64,
    last_access: std::time::Instant,
}

/// Performance statistics for a NUMA node
#[derive(Debug, Clone, Default)]
struct NodeStats {
    allocations: u64,
    total_allocated: u64,
    average_latency: f64,
    bandwidth_utilization: f64,
    migration_count: u64,
}

/// Memory migration hint
#[derive(Debug, Clone)]
struct MigrationHint {
    ptr: *mut u8,
    current_node: u32,
    target_node: u32,
    priority: MigrationPriority,
    reason: MigrationReason,
}

/// Migration priority levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum MigrationPriority {
    Low = 1,
    Medium = 2,
    High = 3,
    Critical = 4,
}

/// Reasons for memory migration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MigrationReason {
    HighLatency,
    BandwidthBottleneck,
    AccessPattern,
    LoadBalancing,
    UserHint,
}

impl EnhancedNumaAllocator {
    /// Create a new enhanced NUMA allocator
    pub fn new(topology: NumaTopology) -> Self {
        let numa_available = Self::detect_libnuma();
        
        Self {
            numa_available,
            topology: Arc::new(Mutex::new(topology)),
            allocations: Arc::new(Mutex::new(HashMap::new())),
            node_stats: Arc::new(Mutex::new(HashMap::new())),
            migration_hints: Arc::new(Mutex::new(Vec::new())),
        }
    }
    
    /// Detect if libnuma is available on the system
    fn detect_libnuma() -> bool {
        #[cfg(target_os = "linux")]
        {
            // Check if libnuma.so is available
            use std::process::Command;
            
            let output = Command::new("ldconfig")
                .arg("-p")
                .output();
                
            if let Ok(output) = output {
                let stdout = String::from_utf8_lossy(&output.stdout);
                return stdout.contains("libnuma.so");
            }
        }
        
        false
    }
    
    /// Allocate memory on a specific NUMA node with enhanced features
    pub fn allocate_on_node(
        &self,
        size: usize,
        alignment: usize,
        numa_node: u32,
        access_pattern: AccessPatternType,
    ) -> BackendResult<*mut u8> {
        let ptr = if self.numa_available {
            self.allocate_with_libnuma(size, alignment, numa_node)?
        } else {
            self.allocate_fallback(size, alignment)?
        };
        
        // Track the allocation
        self.track_allocation(ptr, size, numa_node, access_pattern)?;
        
        // Update node statistics
        self.update_node_stats(numa_node, size)?;
        
        // Apply memory prefetching based on access pattern
        self.apply_prefetch_strategy(ptr, size, access_pattern)?;
        
        Ok(ptr)
    }
    
    /// Allocate memory using libnuma (when available)
    #[cfg(target_os = "linux")]
    fn allocate_with_libnuma(&self, size: usize, alignment: usize, numa_node: u32) -> BackendResult<*mut u8> {
        // In a real implementation, this would use dlopen to load libnuma dynamically
        // and call numa_alloc_onnode. For now, we'll use a simulated implementation.
        
        // Check if the node exists
        let topology = self.topology.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire topology lock".to_string())
        })?;
        
        if !topology.nodes.contains_key(&numa_node) {
            return Err(TorshError::AllocationError(format!(
                "NUMA node {} does not exist", numa_node
            )));
        }
        drop(topology);
        
        // For demonstration, we'll use mmap with memory policy hints
        let ptr = self.allocate_with_mmap_policy(size, alignment, numa_node)?;
        
        Ok(ptr)
    }
    
    /// Allocate memory using mmap with NUMA policy hints
    #[cfg(target_os = "linux")]
    fn allocate_with_mmap_policy(&self, size: usize, alignment: usize, numa_node: u32) -> BackendResult<*mut u8> {
        use std::ptr;
        
        // Use posix_memalign for aligned allocation
        let mut ptr: *mut std::ffi::c_void = ptr::null_mut();
        let result = unsafe {
            libc::posix_memalign(&mut ptr, alignment, size)
        };
        
        if result != 0 || ptr.is_null() {
            return Err(TorshError::AllocationError(format!(
                "posix_memalign failed with error {}", result
            )));
        }
        
        // Apply NUMA memory policy (simplified - real implementation would use mbind)
        let _ = numa_node; // Acknowledge parameter
        
        // In a real implementation, this would call:
        // mbind(ptr, size, MPOL_BIND, &nodemask, maxnode, 0);
        
        Ok(ptr as *mut u8)
    }
    
    /// Fallback allocation when libnuma is not available
    #[cfg(not(target_os = "linux"))]
    fn allocate_with_libnuma(&self, size: usize, alignment: usize, _numa_node: u32) -> BackendResult<*mut u8> {
        self.allocate_fallback(size, alignment)
    }
    
    /// Fallback allocation using standard allocator
    fn allocate_fallback(&self, size: usize, alignment: usize) -> BackendResult<*mut u8> {
        let layout = std::alloc::Layout::from_size_align(size, alignment)
            .map_err(|e| TorshError::AllocationError(format!("Invalid layout: {}", e)))?;
        
        let ptr = unsafe { std::alloc::alloc(layout) };
        if ptr.is_null() {
            return Err(TorshError::AllocationError(format!(
                "Failed to allocate {} bytes", size
            )));
        }
        
        Ok(ptr)
    }
    
    /// Track an allocation for performance monitoring
    fn track_allocation(
        &self,
        ptr: *mut u8,
        size: usize,
        node: u32,
        access_pattern: AccessPatternType,
    ) -> BackendResult<()> {
        let mut allocations = self.allocations.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire allocations lock".to_string())
        })?;
        
        let info = AllocationInfo {
            ptr,
            size,
            node,
            access_pattern,
            allocation_time: std::time::Instant::now(),
            access_count: 0,
            last_access: std::time::Instant::now(),
        };
        
        allocations.insert(ptr as usize, info);
        Ok(())
    }
    
    /// Update NUMA node performance statistics
    fn update_node_stats(&self, numa_node: u32, size: usize) -> BackendResult<()> {
        let mut stats = self.node_stats.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire node stats lock".to_string())
        })?;
        
        let node_stat = stats.entry(numa_node).or_insert_with(NodeStats::default);
        node_stat.allocations += 1;
        node_stat.total_allocated += size as u64;
        
        Ok(())
    }
    
    /// Apply prefetch strategy based on access pattern
    fn apply_prefetch_strategy(
        &self,
        ptr: *mut u8,
        size: usize,
        pattern: AccessPatternType,
    ) -> BackendResult<()> {
        match pattern {
            AccessPatternType::Sequential => {
                self.prefetch_sequential_optimized(ptr, size)?;
            }
            AccessPatternType::Random => {
                self.prefetch_random_optimized(ptr, size)?;
            }
            AccessPatternType::Strided => {
                self.prefetch_strided_optimized(ptr, size)?;
            }
            AccessPatternType::Temporal => {
                self.prefetch_temporal_optimized(ptr, size)?;
            }
            AccessPatternType::Unknown => {
                self.prefetch_adaptive(ptr, size)?;
            }
        }
        
        Ok(())
    }
    
    /// Optimized sequential prefetching with hardware-specific tuning
    fn prefetch_sequential_optimized(&self, ptr: *mut u8, size: usize) -> BackendResult<()> {
        let cache_line_size = self.get_cache_line_size();
        let prefetch_distance = self.get_optimal_prefetch_distance();
        
        let lines = (size + cache_line_size - 1) / cache_line_size;
        let prefetch_ahead = (prefetch_distance / cache_line_size).min(lines);
        
        for i in 0..prefetch_ahead {
            let prefetch_ptr = unsafe { ptr.add(i * cache_line_size) };
            self.prefetch_cache_line(prefetch_ptr, PrefetchHint::Temporal);
        }
        
        Ok(())
    }
    
    /// Optimized random access prefetching
    fn prefetch_random_optimized(&self, ptr: *mut u8, size: usize) -> BackendResult<()> {
        let cache_line_size = self.get_cache_line_size();
        let num_lines = (size + cache_line_size - 1) / cache_line_size;
        
        // For random access, prefetch strategic cache lines
        let prefetch_positions = [0, num_lines / 4, num_lines / 2, 3 * num_lines / 4, num_lines - 1];
        
        for &pos in &prefetch_positions {
            if pos < num_lines {
                let prefetch_ptr = unsafe { ptr.add(pos * cache_line_size) };
                self.prefetch_cache_line(prefetch_ptr, PrefetchHint::NonTemporal);
            }
        }
        
        Ok(())
    }
    
    /// Optimized strided access prefetching
    fn prefetch_strided_optimized(&self, ptr: *mut u8, size: usize) -> BackendResult<()> {
        let cache_line_size = self.get_cache_line_size();
        let stride = self.detect_optimal_stride(size);
        
        let mut offset = 0;
        while offset < size {
            let prefetch_ptr = unsafe { ptr.add(offset) };
            self.prefetch_cache_line(prefetch_ptr, PrefetchHint::Temporal);
            offset += stride;
        }
        
        Ok(())
    }
    
    /// Optimized temporal locality prefetching
    fn prefetch_temporal_optimized(&self, ptr: *mut u8, size: usize) -> BackendResult<()> {
        // For temporal locality, prefetch more aggressively
        let cache_line_size = self.get_cache_line_size();
        let l1_cache_size = self.get_l1_cache_size();
        
        // Prefetch up to L1 cache size or the whole region, whichever is smaller
        let prefetch_size = size.min(l1_cache_size);
        let lines_to_prefetch = (prefetch_size + cache_line_size - 1) / cache_line_size;
        
        for i in 0..lines_to_prefetch {
            let prefetch_ptr = unsafe { ptr.add(i * cache_line_size) };
            self.prefetch_cache_line(prefetch_ptr, PrefetchHint::Temporal);
        }
        
        Ok(())
    }
    
    /// Adaptive prefetching based on runtime analysis
    fn prefetch_adaptive(&self, ptr: *mut u8, size: usize) -> BackendResult<()> {
        // Analyze historical access patterns for this allocation
        let access_pattern = self.analyze_access_pattern(ptr)?;
        
        match access_pattern {
            AccessPatternType::Sequential => self.prefetch_sequential_optimized(ptr, size),
            AccessPatternType::Random => self.prefetch_random_optimized(ptr, size),
            AccessPatternType::Strided => self.prefetch_strided_optimized(ptr, size),
            AccessPatternType::Temporal => self.prefetch_temporal_optimized(ptr, size),
            AccessPatternType::Unknown => {
                // Use conservative strategy
                self.prefetch_sequential_optimized(ptr, size.min(4096))
            }
        }
    }
    
    /// Analyze access pattern for an allocation
    fn analyze_access_pattern(&self, ptr: *mut u8) -> BackendResult<AccessPatternType> {
        let allocations = self.allocations.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire allocations lock".to_string())
        })?;
        
        if let Some(info) = allocations.get(&(ptr as usize)) {
            Ok(info.access_pattern)
        } else {
            Ok(AccessPatternType::Unknown)
        }
    }
    
    /// Prefetch a cache line with specified hint
    fn prefetch_cache_line(&self, ptr: *mut u8, hint: PrefetchHint) {
        #[cfg(target_arch = "x86_64")]
        {
            unsafe {
                match hint {
                    PrefetchHint::Temporal => {
                        std::arch::x86_64::_mm_prefetch(ptr as *const i8, std::arch::x86_64::_MM_HINT_T0);
                    }
                    PrefetchHint::NonTemporal => {
                        std::arch::x86_64::_mm_prefetch(ptr as *const i8, std::arch::x86_64::_MM_HINT_NTA);
                    }
                    PrefetchHint::L2 => {
                        std::arch::x86_64::_mm_prefetch(ptr as *const i8, std::arch::x86_64::_MM_HINT_T1);
                    }
                    PrefetchHint::L3 => {
                        std::arch::x86_64::_mm_prefetch(ptr as *const i8, std::arch::x86_64::_MM_HINT_T2);
                    }
                }
            }
        }
        
        #[cfg(target_arch = "aarch64")]
        {
            // Prefetch instructions are currently unstable in Rust
            // TODO: Re-enable when stabilized (see issue #117217)
            // unsafe {
            //     match hint {
            //         PrefetchHint::Temporal => {
            //             std::arch::aarch64::_prefetch(
            //                 ptr as *const i8,
            //                 std::arch::aarch64::_PREFETCH_READ,
            //                 std::arch::aarch64::_PREFETCH_LOCALITY3
            //             );
            //         }
            //         PrefetchHint::NonTemporal => {
            //             std::arch::aarch64::_prefetch(
            //                 ptr as *const i8,
            //                 std::arch::aarch64::_PREFETCH_READ,
            //                 std::arch::aarch64::_PREFETCH_LOCALITY0
            //             );
            //         }
            //         PrefetchHint::L2 => {
            //             std::arch::aarch64::_prefetch(
            //                 ptr as *const i8,
            //                 std::arch::aarch64::_PREFETCH_READ,
            //                 std::arch::aarch64::_PREFETCH_LOCALITY2
            //             );
            //         }
            //         PrefetchHint::L3 => {
            //             std::arch::aarch64::_prefetch(
            //                 ptr as *const i8,
            //                 std::arch::aarch64::_PREFETCH_READ,
            //                 std::arch::aarch64::_PREFETCH_LOCALITY1
            //             );
            //         }
            //     }
            // }
            let _ = (ptr, hint); // Silence unused variable warnings
        }
        
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            // No prefetch instruction available
            let _ = (ptr, hint);
        }
    }
    
    /// Get cache line size for the current system
    fn get_cache_line_size(&self) -> usize {
        #[cfg(target_os = "linux")]
        {
            if let Ok(content) = std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size") {
                if let Ok(size) = content.trim().parse::<usize>() {
                    return size;
                }
            }
        }
        
        // Default cache line size
        64
    }
    
    /// Get L1 cache size
    fn get_l1_cache_size(&self) -> usize {
        #[cfg(target_os = "linux")]
        {
            if let Ok(content) = std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cache/index0/size") {
                let content = content.trim();
                if content.ends_with('K') {
                    if let Ok(size) = content[..content.len()-1].parse::<usize>() {
                        return size * 1024;
                    }
                }
            }
        }
        
        // Default L1 cache size
        32 * 1024
    }
    
    /// Get optimal prefetch distance based on CPU characteristics
    fn get_optimal_prefetch_distance(&self) -> usize {
        // This would be determined by CPU microarchitecture
        // For now, use a conservative estimate
        512 // bytes
    }
    
    /// Detect optimal stride for strided access patterns
    fn detect_optimal_stride(&self, size: usize) -> usize {
        let cache_line_size = self.get_cache_line_size();
        
        // Use power-of-2 strides that are multiples of cache line size
        if size > 16 * cache_line_size {
            4 * cache_line_size
        } else if size > 4 * cache_line_size {
            2 * cache_line_size
        } else {
            cache_line_size
        }
    }
    
    /// Deallocate memory and update tracking
    pub fn deallocate(&self, ptr: *mut u8, size: usize) -> BackendResult<()> {
        // Remove from tracking
        {
            let mut allocations = self.allocations.lock().map_err(|_| {
                TorshError::AllocationError("Failed to acquire allocations lock".to_string())
            })?;
            allocations.remove(&(ptr as usize));
        }
        
        // Deallocate memory
        let layout = std::alloc::Layout::from_size_align(size, 1)
            .map_err(|e| TorshError::AllocationError(format!("Invalid layout: {}", e)))?;
        
        unsafe {
            std::alloc::dealloc(ptr, layout);
        }
        
        Ok(())
    }
    
    /// Get NUMA allocation statistics
    pub fn get_numa_stats(&self) -> BackendResult<HashMap<u32, NodeStats>> {
        let stats = self.node_stats.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire node stats lock".to_string())
        })?;
        
        Ok(stats.clone())
    }
    
    /// Suggest memory migrations based on access patterns
    pub fn suggest_migrations(&self) -> BackendResult<Vec<MigrationHint>> {
        let hints = self.migration_hints.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire migration hints lock".to_string())
        })?;
        
        Ok(hints.clone())
    }
    
    /// Record memory access for pattern analysis
    pub fn record_access(&self, ptr: *mut u8) -> BackendResult<()> {
        let mut allocations = self.allocations.lock().map_err(|_| {
            TorshError::AllocationError("Failed to acquire allocations lock".to_string())
        })?;
        
        if let Some(info) = allocations.get_mut(&(ptr as usize)) {
            info.access_count += 1;
            info.last_access = std::time::Instant::now();
        }
        
        Ok(())
    }
}

/// Prefetch hint types
#[derive(Debug, Clone, Copy)]
enum PrefetchHint {
    /// Temporal locality (T0) - expect multiple accesses
    Temporal,
    /// Non-temporal (NTA) - single access expected
    NonTemporal,
    /// L2 cache (T1) - moderate temporal locality
    L2,
    /// L3 cache (T2) - low temporal locality
    L3,
}

unsafe impl Send for EnhancedNumaAllocator {}
unsafe impl Sync for EnhancedNumaAllocator {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cpu::memory::NumaNode;
    
    fn create_test_topology() -> NumaTopology {
        let mut nodes = HashMap::new();
        nodes.insert(0, NumaNode {
            id: 0,
            available_memory: 8 * 1024 * 1024 * 1024,
            memory_bandwidth: 50.0,
            cpu_cores: vec![0, 1, 2, 3],
            distances: HashMap::new(),
        });
        
        NumaTopology {
            nodes,
            current_node: 0,
            numa_available: true,
        }
    }
    
    #[test]
    fn test_enhanced_numa_allocator_creation() {
        let topology = create_test_topology();
        let allocator = EnhancedNumaAllocator::new(topology);
        
        // Should not crash
        assert!(!allocator.numa_available || allocator.numa_available);
    }
    
    #[test]
    fn test_fallback_allocation() {
        let topology = create_test_topology();
        let allocator = EnhancedNumaAllocator::new(topology);
        
        let ptr = allocator.allocate_fallback(1024, 16).expect("fallback allocation should succeed");
        assert!(!ptr.is_null());
        
        allocator.deallocate(ptr, 1024).expect("deallocation should succeed");
    }
    
    #[test]
    fn test_cache_line_size_detection() {
        let topology = create_test_topology();
        let allocator = EnhancedNumaAllocator::new(topology);
        
        let cache_line_size = allocator.get_cache_line_size();
        assert!(cache_line_size > 0);
        assert!(cache_line_size <= 256); // Reasonable upper bound
    }
    
    #[test]
    fn test_prefetch_strategies() {
        let topology = create_test_topology();
        let allocator = EnhancedNumaAllocator::new(topology);
        
        let layout = std::alloc::Layout::from_size_align(4096, 16).expect("Layout should succeed");
        let ptr = unsafe { std::alloc::alloc(layout) };
        assert!(!ptr.is_null());
        
        // Test different prefetch strategies
        assert!(allocator.prefetch_sequential_optimized(ptr, 4096).is_ok());
        assert!(allocator.prefetch_random_optimized(ptr, 4096).is_ok());
        assert!(allocator.prefetch_strided_optimized(ptr, 4096).is_ok());
        assert!(allocator.prefetch_temporal_optimized(ptr, 4096).is_ok());
        
        unsafe { std::alloc::dealloc(ptr, layout); }
    }
    
    #[test]
    fn test_allocation_tracking() {
        let topology = create_test_topology();
        let allocator = EnhancedNumaAllocator::new(topology);
        
        let ptr = allocator.allocate_fallback(1024, 16).expect("fallback allocation should succeed");
        
        allocator.track_allocation(ptr, 1024, 0, AccessPatternType::Sequential).expect("allocation tracking should succeed");
        allocator.record_access(ptr).expect("access recording should succeed");
        
        allocator.deallocate(ptr, 1024).expect("deallocation should succeed");
    }
    
    #[test]
    fn test_numa_stats() {
        let topology = create_test_topology();
        let allocator = EnhancedNumaAllocator::new(topology);
        
        allocator.update_node_stats(0, 1024).expect("node statistics update should succeed");
        let stats = allocator.get_numa_stats().expect("NUMA statistics retrieval should succeed");
        
        assert!(stats.contains_key(&0));
        assert_eq!(stats[&0].allocations, 1);
        assert_eq!(stats[&0].total_allocated, 1024);
    }
}