torsh-core 0.1.2

Core types and traits for ToRSh deep learning framework
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
874
875
876
877
878
879
880
//! Registry for backend allocators and storage systems
//!
//! This module provides a centralized registry for managing different allocator
//! implementations and their capabilities across the storage system.

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

/// Registry for backend allocators
///
/// The AllocatorRegistry provides centralized management of allocator implementations,
/// allowing runtime discovery and selection of appropriate allocators for different
/// backends and devices.
///
/// Note: This is a simplified version to avoid trait object compatibility issues.
/// In a full implementation, this would use type erasure and dynamic dispatch.
///
/// # Examples
///
/// ```ignore
/// use torsh_core::storage::AllocatorRegistry;
///
/// let mut registry = AllocatorRegistry::new();
/// registry.register("cpu".to_string());
/// registry.register("cuda".to_string());
///
/// assert!(registry.is_registered("cpu"));
/// assert_eq!(registry.list().len(), 2);
/// ```
#[derive(Debug)]
pub struct AllocatorRegistry {
    /// Set of registered allocator names
    allocator_names: HashSet<String>,
    /// Metadata about each allocator
    allocator_metadata: HashMap<String, AllocatorMetadata>,
    /// Default allocator for each backend type
    default_allocators: HashMap<String, String>,
}

impl Default for AllocatorRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl AllocatorRegistry {
    /// Create a new allocator registry
    pub fn new() -> Self {
        Self {
            allocator_names: HashSet::new(),
            allocator_metadata: HashMap::new(),
            default_allocators: HashMap::new(),
        }
    }

    /// Register an allocator for a backend
    ///
    /// # Arguments
    /// * `name` - Unique name for the allocator
    pub fn register(&mut self, name: String) {
        self.allocator_names.insert(name.clone());
        self.allocator_metadata.insert(
            name.clone(),
            AllocatorMetadata {
                name: name.clone(),
                backend_type: "unknown".to_string(),
                supports_async: false,
                supports_numa: false,
                supports_cross_device: false,
                memory_alignment: 1,
                max_allocation_size: None,
                description: format!("Allocator: {name}"),
            },
        );
    }

    /// Register an allocator with metadata
    ///
    /// # Arguments
    /// * `name` - Unique name for the allocator
    /// * `metadata` - Metadata describing the allocator capabilities
    pub fn register_with_metadata(&mut self, name: String, metadata: AllocatorMetadata) {
        self.allocator_names.insert(name.clone());
        self.allocator_metadata.insert(name, metadata);
    }

    /// Check if an allocator is registered
    ///
    /// # Arguments
    /// * `name` - Name of the allocator to check
    ///
    /// # Returns
    /// True if the allocator is registered
    pub fn is_registered(&self, name: &str) -> bool {
        self.allocator_names.contains(name)
    }

    /// List all registered allocators
    ///
    /// # Returns
    /// Vector of allocator names
    pub fn list(&self) -> Vec<&String> {
        self.allocator_names.iter().collect()
    }

    /// Get metadata for an allocator
    ///
    /// # Arguments
    /// * `name` - Name of the allocator
    ///
    /// # Returns
    /// Metadata if the allocator exists
    pub fn get_metadata(&self, name: &str) -> Option<&AllocatorMetadata> {
        self.allocator_metadata.get(name)
    }

    /// Unregister an allocator
    ///
    /// # Arguments
    /// * `name` - Name of the allocator to remove
    ///
    /// # Returns
    /// True if the allocator was found and removed
    pub fn unregister(&mut self, name: &str) -> bool {
        let removed = self.allocator_names.remove(name);
        if removed {
            self.allocator_metadata.remove(name);
            // Remove as default allocator if it was set
            self.default_allocators.retain(|_, v| v != name);
        }
        removed
    }

    /// Set the default allocator for a backend type
    ///
    /// # Arguments
    /// * `backend_type` - Type of backend (e.g., "cpu", "cuda", "metal")
    /// * `allocator_name` - Name of the allocator to use as default
    ///
    /// # Returns
    /// True if the allocator exists and was set as default
    pub fn set_default(&mut self, backend_type: String, allocator_name: String) -> bool {
        if self.is_registered(&allocator_name) {
            self.default_allocators.insert(backend_type, allocator_name);
            true
        } else {
            false
        }
    }

    /// Get the default allocator for a backend type
    ///
    /// # Arguments
    /// * `backend_type` - Type of backend
    ///
    /// # Returns
    /// Name of the default allocator if set
    pub fn get_default(&self, backend_type: &str) -> Option<&String> {
        self.default_allocators.get(backend_type)
    }

    /// Find allocators by capability
    ///
    /// # Arguments
    /// * `capability` - Capability to search for
    ///
    /// # Returns
    /// Vector of allocator names that support the capability
    pub fn find_by_capability(&self, capability: AllocatorCapability) -> Vec<&String> {
        self.allocator_metadata
            .iter()
            .filter(|(_, metadata)| metadata.supports_capability(capability))
            .map(|(name, _)| name)
            .collect()
    }

    /// Find allocators by backend type
    ///
    /// # Arguments
    /// * `backend_type` - Backend type to search for
    ///
    /// # Returns
    /// Vector of allocator names for the backend type
    pub fn find_by_backend(&self, backend_type: &str) -> Vec<&String> {
        self.allocator_metadata
            .iter()
            .filter(|(_, metadata)| metadata.backend_type == backend_type)
            .map(|(name, _)| name)
            .collect()
    }

    /// Get registry statistics
    pub fn statistics(&self) -> RegistryStatistics {
        let backend_counts =
            self.allocator_metadata
                .values()
                .fold(HashMap::new(), |mut acc, metadata| {
                    *acc.entry(metadata.backend_type.clone()).or_insert(0) += 1;
                    acc
                });

        let capability_counts =
            self.allocator_metadata
                .values()
                .fold(HashMap::new(), |mut acc, metadata| {
                    for capability in AllocatorCapability::all() {
                        if metadata.supports_capability(capability) {
                            *acc.entry(capability).or_insert(0) += 1;
                        }
                    }
                    acc
                });

        RegistryStatistics {
            total_allocators: self.allocator_names.len(),
            backend_counts,
            capability_counts,
            default_allocators: self.default_allocators.len(),
        }
    }

    /// Clear all registered allocators
    pub fn clear(&mut self) {
        self.allocator_names.clear();
        self.allocator_metadata.clear();
        self.default_allocators.clear();
    }

    /// Get all allocators sorted by priority
    ///
    /// # Arguments
    /// * `backend_type` - Optional backend type filter
    ///
    /// # Returns
    /// Vector of allocator names sorted by priority (default first)
    pub fn get_prioritized(&self, backend_type: Option<&str>) -> Vec<&String> {
        let mut allocators: Vec<&String> = if let Some(backend) = backend_type {
            self.find_by_backend(backend)
        } else {
            self.list()
        };

        // Sort with default allocator first
        allocators.sort_by(|a, b| {
            let a_is_default = backend_type.and_then(|bt| self.get_default(bt)) == Some(*a);
            let b_is_default = backend_type.and_then(|bt| self.get_default(bt)) == Some(*b);

            match (a_is_default, b_is_default) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => a.cmp(b),
            }
        });

        allocators
    }
}

/// Metadata describing an allocator's capabilities
#[derive(Debug, Clone)]
pub struct AllocatorMetadata {
    /// Name of the allocator
    pub name: String,
    /// Backend type (e.g., "cpu", "cuda", "metal")
    pub backend_type: String,
    /// Whether the allocator supports async operations
    pub supports_async: bool,
    /// Whether the allocator supports NUMA awareness
    pub supports_numa: bool,
    /// Whether the allocator supports cross-device operations
    pub supports_cross_device: bool,
    /// Required memory alignment in bytes
    pub memory_alignment: usize,
    /// Maximum single allocation size (None for unlimited)
    pub max_allocation_size: Option<usize>,
    /// Human-readable description
    pub description: String,
}

impl AllocatorMetadata {
    /// Create new allocator metadata
    pub fn new(name: String, backend_type: String) -> Self {
        Self {
            name,
            backend_type,
            supports_async: false,
            supports_numa: false,
            supports_cross_device: false,
            memory_alignment: 1,
            max_allocation_size: None,
            description: String::new(),
        }
    }

    /// Set async support
    pub fn with_async(mut self, supports: bool) -> Self {
        self.supports_async = supports;
        self
    }

    /// Set NUMA support
    pub fn with_numa(mut self, supports: bool) -> Self {
        self.supports_numa = supports;
        self
    }

    /// Set cross-device support
    pub fn with_cross_device(mut self, supports: bool) -> Self {
        self.supports_cross_device = supports;
        self
    }

    /// Set memory alignment requirement
    pub fn with_alignment(mut self, alignment: usize) -> Self {
        self.memory_alignment = alignment;
        self
    }

    /// Set maximum allocation size
    pub fn with_max_allocation(mut self, max_size: usize) -> Self {
        self.max_allocation_size = Some(max_size);
        self
    }

    /// Set description
    pub fn with_description(mut self, description: String) -> Self {
        self.description = description;
        self
    }

    /// Check if the allocator supports a specific capability
    pub fn supports_capability(&self, capability: AllocatorCapability) -> bool {
        match capability {
            AllocatorCapability::Async => self.supports_async,
            AllocatorCapability::Numa => self.supports_numa,
            AllocatorCapability::CrossDevice => self.supports_cross_device,
            AllocatorCapability::HighAlignment => self.memory_alignment >= 64,
            AllocatorCapability::LargeAllocations => {
                self.max_allocation_size
                    .is_none_or(|max| max >= 1024 * 1024 * 1024)
                // 1GB threshold
            }
        }
    }

    /// Check compatibility with requirements
    pub fn is_compatible_with(&self, requirements: &AllocatorRequirements) -> bool {
        if let Some(required_backend) = &requirements.backend_type {
            if self.backend_type != *required_backend {
                return false;
            }
        }

        if requirements.requires_async && !self.supports_async {
            return false;
        }

        if requirements.requires_numa && !self.supports_numa {
            return false;
        }

        if requirements.requires_cross_device && !self.supports_cross_device {
            return false;
        }

        if self.memory_alignment < requirements.min_alignment {
            return false;
        }

        if let (Some(max_alloc), Some(required_max)) =
            (self.max_allocation_size, requirements.min_max_allocation)
        {
            if max_alloc < required_max {
                return false;
            }
        }

        true
    }
}

/// Capabilities that an allocator can support
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AllocatorCapability {
    /// Supports asynchronous operations
    Async,
    /// Supports NUMA-aware allocation
    Numa,
    /// Supports cross-device memory operations
    CrossDevice,
    /// Supports high memory alignment (64+ bytes)
    HighAlignment,
    /// Supports large allocations (1GB+)
    LargeAllocations,
}

impl AllocatorCapability {
    /// Get all possible capabilities
    pub fn all() -> Vec<Self> {
        vec![
            Self::Async,
            Self::Numa,
            Self::CrossDevice,
            Self::HighAlignment,
            Self::LargeAllocations,
        ]
    }

    /// Get human-readable name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Async => "Async",
            Self::Numa => "NUMA",
            Self::CrossDevice => "Cross-Device",
            Self::HighAlignment => "High Alignment",
            Self::LargeAllocations => "Large Allocations",
        }
    }
}

/// Requirements for allocator selection
#[derive(Debug, Clone, Default)]
pub struct AllocatorRequirements {
    /// Required backend type
    pub backend_type: Option<String>,
    /// Requires async support
    pub requires_async: bool,
    /// Requires NUMA support
    pub requires_numa: bool,
    /// Requires cross-device support
    pub requires_cross_device: bool,
    /// Minimum memory alignment
    pub min_alignment: usize,
    /// Minimum maximum allocation size
    pub min_max_allocation: Option<usize>,
}

impl AllocatorRequirements {
    /// Create new requirements
    pub fn new() -> Self {
        Self::default()
    }

    /// Set backend type requirement
    pub fn with_backend(mut self, backend_type: String) -> Self {
        self.backend_type = Some(backend_type);
        self
    }

    /// Require async support
    pub fn with_async(mut self) -> Self {
        self.requires_async = true;
        self
    }

    /// Require NUMA support
    pub fn with_numa(mut self) -> Self {
        self.requires_numa = true;
        self
    }

    /// Require cross-device support
    pub fn with_cross_device(mut self) -> Self {
        self.requires_cross_device = true;
        self
    }

    /// Set minimum alignment requirement
    pub fn with_min_alignment(mut self, alignment: usize) -> Self {
        self.min_alignment = alignment;
        self
    }

    /// Set minimum maximum allocation size requirement
    pub fn with_min_max_allocation(mut self, size: usize) -> Self {
        self.min_max_allocation = Some(size);
        self
    }
}

/// Statistics about the allocator registry
#[derive(Debug, Clone)]
pub struct RegistryStatistics {
    /// Total number of registered allocators
    pub total_allocators: usize,
    /// Count of allocators by backend type
    pub backend_counts: HashMap<String, usize>,
    /// Count of allocators by capability
    pub capability_counts: HashMap<AllocatorCapability, usize>,
    /// Number of backend types with default allocators
    pub default_allocators: usize,
}

impl std::fmt::Display for RegistryStatistics {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Registry(total={}, backends={}, defaults={})",
            self.total_allocators,
            self.backend_counts.len(),
            self.default_allocators
        )
    }
}

/// Global allocator registry instance
static GLOBAL_REGISTRY: RwLock<Option<Arc<RwLock<AllocatorRegistry>>>> = RwLock::new(None);

/// Get the global allocator registry
pub fn global_registry() -> Arc<RwLock<AllocatorRegistry>> {
    let mut global = GLOBAL_REGISTRY
        .write()
        .expect("lock should not be poisoned");
    if global.is_none() {
        *global = Some(Arc::new(RwLock::new(AllocatorRegistry::new())));
    }
    global
        .as_ref()
        .expect("global registry should be Some after initialization")
        .clone()
}

/// Initialize the global registry with default allocators
pub fn initialize_global_registry() {
    let registry = global_registry();
    let mut registry = registry.write().expect("lock should not be poisoned");

    // Register basic allocators
    registry.register_with_metadata(
        "cpu_std".to_string(),
        AllocatorMetadata::new("cpu_std".to_string(), "cpu".to_string())
            .with_description("Standard CPU allocator using system malloc".to_string())
            .with_alignment(16),
    );

    registry.register_with_metadata(
        "cpu_numa".to_string(),
        AllocatorMetadata::new("cpu_numa".to_string(), "cpu".to_string())
            .with_numa(true)
            .with_description("NUMA-aware CPU allocator".to_string())
            .with_alignment(64),
    );

    // Set defaults
    registry.set_default("cpu".to_string(), "cpu_std".to_string());
}

/// Utility functions for registry operations
pub mod utils {
    use super::*;

    /// Find the best allocator for given requirements
    pub fn find_best_allocator(
        registry: &AllocatorRegistry,
        requirements: &AllocatorRequirements,
    ) -> Option<String> {
        // Get compatible allocators
        let compatible: Vec<_> = registry
            .allocator_metadata
            .iter()
            .filter(|(_, metadata)| metadata.is_compatible_with(requirements))
            .collect();

        if compatible.is_empty() {
            return None;
        }

        // Score allocators based on capabilities
        let mut scored: Vec<_> = compatible
            .into_iter()
            .map(|(name, metadata)| {
                let mut score = 0;

                // Prefer allocators with more capabilities
                for capability in AllocatorCapability::all() {
                    if metadata.supports_capability(capability) {
                        score += 1;
                    }
                }

                // Prefer default allocators
                if let Some(backend) = &requirements.backend_type {
                    if registry.get_default(backend) == Some(name) {
                        score += 10;
                    }
                }

                // Prefer exact backend match
                if let Some(required_backend) = &requirements.backend_type {
                    if metadata.backend_type == *required_backend {
                        score += 5;
                    }
                }

                (name.clone(), score)
            })
            .collect();

        // Sort by score (highest first)
        scored.sort_by(|a, b| b.1.cmp(&a.1));

        scored.first().map(|(name, _)| name.clone())
    }

    /// Validate allocator metadata
    pub fn validate_metadata(metadata: &AllocatorMetadata) -> Result<(), String> {
        if metadata.name.is_empty() {
            return Err("Allocator name cannot be empty".to_string());
        }

        if metadata.backend_type.is_empty() {
            return Err("Backend type cannot be empty".to_string());
        }

        if metadata.memory_alignment == 0 || !metadata.memory_alignment.is_power_of_two() {
            return Err("Memory alignment must be a power of two".to_string());
        }

        Ok(())
    }

    /// Get allocator compatibility score
    pub fn compatibility_score(
        metadata: &AllocatorMetadata,
        requirements: &AllocatorRequirements,
    ) -> Option<u32> {
        if !metadata.is_compatible_with(requirements) {
            return None;
        }

        let mut score = 100; // Base compatibility score

        // Bonus for exact backend match
        if let Some(required_backend) = &requirements.backend_type {
            if metadata.backend_type == *required_backend {
                score += 50;
            }
        }

        // Bonus for capabilities
        if requirements.requires_async && metadata.supports_async {
            score += 10;
        }
        if requirements.requires_numa && metadata.supports_numa {
            score += 10;
        }
        if requirements.requires_cross_device && metadata.supports_cross_device {
            score += 10;
        }

        // Bonus for high alignment
        if metadata.memory_alignment >= 64 {
            score += 5;
        }

        Some(score)
    }

    /// Create a summary of registry contents
    pub fn registry_summary(registry: &AllocatorRegistry) -> String {
        let stats = registry.statistics();
        let mut summary = "Allocator Registry Summary:\n".to_string();
        summary.push_str(&format!("  Total allocators: {}\n", stats.total_allocators));

        summary.push_str("  By backend:\n");
        for (backend, count) in &stats.backend_counts {
            summary.push_str(&format!("    {}: {}\n", backend, count));
        }

        summary.push_str("  By capability:\n");
        for (capability, count) in &stats.capability_counts {
            summary.push_str(&format!("    {}: {}\n", capability.name(), count));
        }

        summary.push_str(&format!(
            "  Default allocators: {}\n",
            stats.default_allocators
        ));

        summary
    }
}

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

    #[test]
    fn test_allocator_registry_basic() {
        let mut registry = AllocatorRegistry::new();

        // Initially empty
        assert_eq!(registry.list().len(), 0);
        assert!(!registry.is_registered("test"));

        // Register an allocator
        registry.register("test_allocator".to_string());
        assert!(registry.is_registered("test_allocator"));
        assert_eq!(registry.list().len(), 1);

        // Unregister
        assert!(registry.unregister("test_allocator"));
        assert!(!registry.is_registered("test_allocator"));
        assert_eq!(registry.list().len(), 0);
    }

    #[test]
    fn test_allocator_metadata() {
        let metadata = AllocatorMetadata::new("test".to_string(), "cpu".to_string())
            .with_async(true)
            .with_numa(true)
            .with_alignment(64)
            .with_description("Test allocator".to_string());

        assert!(metadata.supports_capability(AllocatorCapability::Async));
        assert!(metadata.supports_capability(AllocatorCapability::Numa));
        assert!(metadata.supports_capability(AllocatorCapability::HighAlignment));
        assert_eq!(metadata.memory_alignment, 64);
    }

    #[test]
    fn test_allocator_requirements() {
        let requirements = AllocatorRequirements::new()
            .with_backend("cpu".to_string())
            .with_async()
            .with_min_alignment(32);

        let compatible_metadata = AllocatorMetadata::new("test".to_string(), "cpu".to_string())
            .with_async(true)
            .with_alignment(32);

        let incompatible_metadata =
            AllocatorMetadata::new("test".to_string(), "gpu".to_string()).with_alignment(16);

        assert!(compatible_metadata.is_compatible_with(&requirements));
        assert!(!incompatible_metadata.is_compatible_with(&requirements));
    }

    #[test]
    fn test_default_allocators() {
        let mut registry = AllocatorRegistry::new();

        registry.register("cpu_allocator".to_string());
        registry.register("gpu_allocator".to_string());

        // Set defaults
        assert!(registry.set_default("cpu".to_string(), "cpu_allocator".to_string()));
        assert!(registry.set_default("gpu".to_string(), "gpu_allocator".to_string()));

        // Cannot set non-existent allocator as default
        assert!(!registry.set_default("cpu".to_string(), "non_existent".to_string()));

        // Check defaults
        assert_eq!(
            registry.get_default("cpu"),
            Some(&"cpu_allocator".to_string())
        );
        assert_eq!(
            registry.get_default("gpu"),
            Some(&"gpu_allocator".to_string())
        );
        assert_eq!(registry.get_default("metal"), None);
    }

    #[test]
    fn test_find_by_capability() {
        let mut registry = AllocatorRegistry::new();

        let async_metadata =
            AllocatorMetadata::new("async".to_string(), "cpu".to_string()).with_async(true);
        let numa_metadata =
            AllocatorMetadata::new("numa".to_string(), "cpu".to_string()).with_numa(true);

        registry.register_with_metadata("async".to_string(), async_metadata);
        registry.register_with_metadata("numa".to_string(), numa_metadata);

        let async_allocators = registry.find_by_capability(AllocatorCapability::Async);
        assert_eq!(async_allocators.len(), 1);
        assert!(async_allocators.contains(&&"async".to_string()));

        let numa_allocators = registry.find_by_capability(AllocatorCapability::Numa);
        assert_eq!(numa_allocators.len(), 1);
        assert!(numa_allocators.contains(&&"numa".to_string()));
    }

    #[test]
    fn test_find_by_backend() {
        let mut registry = AllocatorRegistry::new();

        let cpu_metadata = AllocatorMetadata::new("cpu1".to_string(), "cpu".to_string());
        let gpu_metadata = AllocatorMetadata::new("gpu1".to_string(), "gpu".to_string());

        registry.register_with_metadata("cpu1".to_string(), cpu_metadata);
        registry.register_with_metadata("gpu1".to_string(), gpu_metadata);

        let cpu_allocators = registry.find_by_backend("cpu");
        assert_eq!(cpu_allocators.len(), 1);
        assert!(cpu_allocators.contains(&&"cpu1".to_string()));

        let gpu_allocators = registry.find_by_backend("gpu");
        assert_eq!(gpu_allocators.len(), 1);
        assert!(gpu_allocators.contains(&&"gpu1".to_string()));
    }

    #[test]
    fn test_registry_statistics() {
        let mut registry = AllocatorRegistry::new();

        let cpu_metadata =
            AllocatorMetadata::new("cpu1".to_string(), "cpu".to_string()).with_async(true);
        let gpu_metadata =
            AllocatorMetadata::new("gpu1".to_string(), "gpu".to_string()).with_numa(true);

        registry.register_with_metadata("cpu1".to_string(), cpu_metadata);
        registry.register_with_metadata("gpu1".to_string(), gpu_metadata);
        registry.set_default("cpu".to_string(), "cpu1".to_string());

        let stats = registry.statistics();
        assert_eq!(stats.total_allocators, 2);
        assert_eq!(stats.backend_counts.get("cpu"), Some(&1));
        assert_eq!(stats.backend_counts.get("gpu"), Some(&1));
        assert_eq!(stats.default_allocators, 1);
    }

    #[test]
    fn test_utils_find_best_allocator() {
        use utils::*;

        let mut registry = AllocatorRegistry::new();

        let good_metadata = AllocatorMetadata::new("good".to_string(), "cpu".to_string())
            .with_async(true)
            .with_numa(true)
            .with_alignment(64);

        let basic_metadata =
            AllocatorMetadata::new("basic".to_string(), "cpu".to_string()).with_alignment(16);

        registry.register_with_metadata("good".to_string(), good_metadata);
        registry.register_with_metadata("basic".to_string(), basic_metadata);
        registry.set_default("cpu".to_string(), "basic".to_string());

        let requirements = AllocatorRequirements::new()
            .with_backend("cpu".to_string())
            .with_async();

        let best = find_best_allocator(&registry, &requirements);
        assert_eq!(best, Some("good".to_string())); // Should pick the one with async support
    }

    #[test]
    fn test_utils_validate_metadata() {
        use utils::*;

        let valid_metadata =
            AllocatorMetadata::new("valid".to_string(), "cpu".to_string()).with_alignment(64);

        let invalid_name = AllocatorMetadata::new("".to_string(), "cpu".to_string());
        let invalid_backend = AllocatorMetadata::new("test".to_string(), "".to_string());
        let invalid_alignment =
            AllocatorMetadata::new("test".to_string(), "cpu".to_string()).with_alignment(0);

        assert!(validate_metadata(&valid_metadata).is_ok());
        assert!(validate_metadata(&invalid_name).is_err());
        assert!(validate_metadata(&invalid_backend).is_err());
        assert!(validate_metadata(&invalid_alignment).is_err());
    }

    #[test]
    fn test_global_registry() {
        initialize_global_registry();

        let registry = global_registry();
        let registry = registry.read().expect("lock should not be poisoned");

        assert!(registry.is_registered("cpu_std"));
        assert!(registry.is_registered("cpu_numa"));
        assert_eq!(registry.get_default("cpu"), Some(&"cpu_std".to_string()));
    }
}