aphelion-core 1.2.10

Core library for Aphelion AI framework - unified frontend for AI model development
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! Backend abstraction for hardware-specific model execution.
//!
//! This module provides a trait-based abstraction for different computational backends
//! (CPU, GPU, TPU, etc.), enabling hardware-agnostic model definitions that can run
//! on various platforms. It includes device capability reporting and a registry for
//! managing multiple backends.

use crate::diagnostics::TraceSink;
use crate::error::AphelionResult;
use std::collections::BTreeMap;

/// Device capabilities and features.
///
/// `DeviceCapabilities` describes the hardware features and limits of a computational device,
/// enabling models to make informed decisions about data types and execution strategies.
///
/// # Fields
///
/// * `supports_f16` - Support for 16-bit floating point (half precision)
/// * `supports_bf16` - Support for bfloat16 (brain float)
/// * `supports_tf32` - Support for TensorFlow 32-bit format
/// * `max_memory_bytes` - Maximum available memory in bytes
/// * `compute_units` - Number of parallel compute units (cores, etc.)
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::DeviceCapabilities;
///
/// let caps = DeviceCapabilities {
///     supports_f16: true,
///     supports_bf16: true,
///     supports_tf32: false,
///     max_memory_bytes: Some(8 * 1024 * 1024 * 1024), // 8 GB
///     compute_units: Some(1024),
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct DeviceCapabilities {
    /// Device supports 16-bit floating point (FP16)
    pub supports_f16: bool,
    /// Device supports bfloat16 format
    pub supports_bf16: bool,
    /// Device supports TensorFlow 32-bit format
    pub supports_tf32: bool,
    /// Maximum memory available on this device
    pub max_memory_bytes: Option<u64>,
    /// Number of compute units (cores, streaming multiprocessors, etc.)
    pub compute_units: Option<u32>,
}

/// Memory information for a device.
///
/// `MemoryInfo` provides memory usage statistics for a device, useful for monitoring
/// and resource allocation decisions.
///
/// # Fields
///
/// * `total_bytes` - Total memory available
/// * `used_bytes` - Currently used memory
/// * `free_bytes` - Currently available/free memory
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::MemoryInfo;
///
/// let mem = MemoryInfo {
///     total_bytes: 8 * 1024 * 1024 * 1024,
///     used_bytes: 2 * 1024 * 1024 * 1024,
///     free_bytes: 6 * 1024 * 1024 * 1024,
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct MemoryInfo {
    /// Total memory in bytes
    pub total_bytes: u64,
    /// Used memory in bytes
    pub used_bytes: u64,
    /// Free/available memory in bytes
    pub free_bytes: u64,
}

/// Backend abstraction for model builds and execution.
///
/// The `Backend` trait defines the interface for hardware-specific implementations.
/// Backends provide information about device capabilities and handle initialization/shutdown.
/// Implementing this trait enables support for different computational targets (CPU, NVIDIA GPU,
/// AMD GPU, TPU, etc.).
///
/// # Implementing Backend
///
/// Types implementing `Backend` must be thread-safe (`Send + Sync`). The trait provides
/// default implementations for `initialize` and `shutdown` that do nothing, suitable for
/// simple backends.
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::{Backend, DeviceCapabilities};
/// use aphelion_core::error::AphelionResult;
///
/// struct CpuBackend;
///
/// impl Backend for CpuBackend {
///     fn name(&self) -> &str { "cpu" }
///     fn device(&self) -> &str { "cpu" }
///     fn capabilities(&self) -> DeviceCapabilities {
///         DeviceCapabilities::default()
///     }
///     fn is_available(&self) -> bool { true }
/// }
/// ```
pub trait Backend: Send + Sync {
    /// Returns the name of this backend (e.g., "cuda", "cpu", "metal")
    fn name(&self) -> &str;

    /// Returns the device identifier (e.g., "cuda:0", "cpu", "gpu_0")
    fn device(&self) -> &str;

    /// Returns the capabilities of the device
    fn capabilities(&self) -> DeviceCapabilities;

    /// Returns whether this backend is currently available for use
    fn is_available(&self) -> bool;

    /// Initializes the backend, preparing it for use.
    ///
    /// This method is called before any operations are performed on the backend.
    /// Default implementation does nothing; override for backends requiring initialization.
    ///
    /// # Errors
    ///
    /// Returns `AphelionError::Backend` if initialization fails.
    fn initialize(&mut self) -> AphelionResult<()> {
        Ok(())
    }

    /// Shuts down the backend and releases resources.
    ///
    /// This method should be called when the backend is no longer needed.
    /// Default implementation does nothing; override for backends requiring cleanup.
    ///
    /// # Errors
    ///
    /// Returns `AphelionError::Backend` if shutdown fails.
    fn shutdown(&mut self) -> AphelionResult<()> {
        Ok(())
    }
}

/// A simple no-op backend for testing and default usage.
///
/// `NullBackend` is a minimal `Backend` implementation that does nothing but report availability.
/// It's useful for testing model architectures without actual hardware dependencies.
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::{Backend, NullBackend};
///
/// let backend = NullBackend::cpu();
/// assert_eq!(backend.name(), "null");
/// assert!(backend.is_available());
/// ```
#[derive(Debug, Clone)]
pub struct NullBackend {
    device: String,
}

impl NullBackend {
    /// Creates a new `NullBackend` with the specified device identifier.
    ///
    /// # Arguments
    ///
    /// * `device` - Device identifier (e.g., "cpu", "gpu")
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, NullBackend};
    ///
    /// let backend = NullBackend::new("cpu");
    /// assert_eq!(backend.device(), "cpu");
    /// ```
    pub fn new(device: impl Into<String>) -> Self {
        Self {
            device: device.into(),
        }
    }

    /// Creates a new `NullBackend` configured for CPU execution.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, NullBackend};
    ///
    /// let backend = NullBackend::cpu();
    /// assert_eq!(backend.device(), "cpu");
    /// ```
    pub fn cpu() -> Self {
        Self::new("cpu")
    }
}

impl Backend for NullBackend {
    fn name(&self) -> &str {
        "null"
    }

    fn device(&self) -> &str {
        &self.device
    }

    fn capabilities(&self) -> DeviceCapabilities {
        DeviceCapabilities::default()
    }

    fn is_available(&self) -> bool {
        true
    }
}

/// Registry for managing and discovering multiple backends.
///
/// `BackendRegistry` allows registration and retrieval of different `Backend` implementations.
/// This enables applications to dynamically select the appropriate backend at runtime based on
/// availability and requirements.
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::{BackendRegistry, MockBackend};
///
/// let mut registry = BackendRegistry::new();
/// registry.register(Box::new(MockBackend::new("cpu_backend", "cpu")));
/// registry.register(Box::new(MockBackend::new("gpu_backend", "gpu")));
///
/// assert!(registry.get("cpu_backend").is_some());
/// let available = registry.list_available();
/// assert_eq!(available.len(), 2);
/// ```
pub struct BackendRegistry {
    backends: BTreeMap<String, Box<dyn Backend>>,
}

impl BackendRegistry {
    /// Creates a new, empty backend registry.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::BackendRegistry;
    ///
    /// let registry = BackendRegistry::new();
    /// assert_eq!(registry.list_available().len(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            backends: BTreeMap::new(),
        }
    }

    /// Registers a backend in the registry.
    ///
    /// If a backend with the same name already exists, it will be replaced.
    ///
    /// # Arguments
    ///
    /// * `backend` - The backend implementation to register
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{BackendRegistry, NullBackend};
    ///
    /// let mut registry = BackendRegistry::new();
    /// registry.register(Box::new(NullBackend::cpu()));
    /// assert_eq!(registry.list_available().len(), 1);
    /// ```
    pub fn register(&mut self, backend: Box<dyn Backend>) {
        let name = backend.name().to_string();
        self.backends.insert(name, backend);
    }

    /// Retrieves a reference to a backend by name.
    ///
    /// # Arguments
    ///
    /// * `name` - The backend name to look up
    ///
    /// # Returns
    ///
    /// `Some(&dyn Backend)` if found, `None` otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{BackendRegistry, NullBackend};
    ///
    /// let mut registry = BackendRegistry::new();
    /// registry.register(Box::new(NullBackend::cpu()));
    ///
    /// assert!(registry.get("null").is_some());
    /// assert!(registry.get("nonexistent").is_none());
    /// ```
    pub fn get(&self, name: &str) -> Option<&dyn Backend> {
        self.backends.get(name).map(|b| b.as_ref())
    }

    /// Lists the names of all available backends.
    ///
    /// # Returns
    ///
    /// A vector of backend names
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{BackendRegistry, MockBackend};
    ///
    /// let mut registry = BackendRegistry::new();
    /// registry.register(Box::new(MockBackend::new("cpu", "cpu")));
    /// registry.register(Box::new(MockBackend::new("gpu", "gpu")));
    ///
    /// let available = registry.list_available();
    /// assert_eq!(available.len(), 2);
    /// assert!(available.contains(&"cpu"));
    /// ```
    pub fn list_available(&self) -> Vec<&str> {
        self.backends.keys().map(|k| k.as_str()).collect()
    }

    /// Returns the first available backend, preferring non-null backends.
    ///
    /// This method implements deterministic auto-detection by:
    /// 1. Iterating through backends in alphabetical order (BTreeMap ordering)
    /// 2. Filtering for available backends
    /// 3. Returning the first non-null backend if available
    /// 4. Falling back to any available backend (including null) if no non-null backend exists
    ///
    /// # Returns
    ///
    /// `Some(&dyn Backend)` for the first available non-null backend, or the first
    /// available backend overall; `None` if no backends are available.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{BackendRegistry, NullBackend, MockBackend};
    ///
    /// let mut registry = BackendRegistry::new();
    /// registry.register(Box::new(NullBackend::cpu()));
    /// registry.register(Box::new(MockBackend::new("cpu", "cpu")));
    ///
    /// let backend = registry.auto_detect();
    /// assert!(backend.is_some());
    /// // Prefers "cpu" MockBackend over "null" NullBackend
    /// assert_eq!(backend.unwrap().name(), "cpu");
    /// ```
    pub fn auto_detect(&self) -> Option<&dyn Backend> {
        self.backends
            .values()
            .filter(|b| b.is_available())
            .find(|b| b.name() != "null")
            .or_else(|| self.backends.values().find(|b| b.is_available()))
            .map(|b| b.as_ref())
    }

    /// Returns the first available backend from the preference list.
    ///
    /// This method iterates through the provided list of backend names in order
    /// and returns the first one that is both registered and available.
    /// It does not determine "best" - just returns the first matching preference.
    ///
    /// # Arguments
    ///
    /// * `names` - Slice of backend names to check in order of preference
    ///
    /// # Returns
    ///
    /// `Some(&dyn Backend)` for the first matching available backend in the preference list;
    /// `None` if none of the preferred backends are available.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{BackendRegistry, MockBackend};
    ///
    /// let mut registry = BackendRegistry::new();
    /// registry.register(Box::new(MockBackend::new("cuda", "gpu").with_availability(false)));
    /// registry.register(Box::new(MockBackend::new("cpu", "cpu")));
    ///
    /// let backend = registry.prefer(&["cuda", "cpu"]);
    /// assert!(backend.is_some());
    /// // Returns "cpu" since "cuda" is not available
    /// assert_eq!(backend.unwrap().name(), "cpu");
    /// ```
    pub fn prefer(&self, names: &[&str]) -> Option<&dyn Backend> {
        for name in names {
            if let Some(backend) = self.backends.get(*name) {
                if backend.is_available() {
                    return Some(backend.as_ref());
                }
            }
        }
        None
    }
}

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

/// Returns a default backend suitable for testing and basic usage.
///
/// # Returns
///
/// A `NullBackend` configured for CPU execution.
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::{Backend, default_backend};
///
/// let backend = default_backend();
/// assert_eq!(backend.name(), "null");
/// assert!(backend.is_available());
/// ```
pub fn default_backend() -> NullBackend {
    NullBackend::cpu()
}

/// Mock backend implementation for testing purposes.
///
/// `MockBackend` simulates a real backend, allowing tests to verify pipeline behavior
/// without actual hardware. It supports failure injection for both initialization and shutdown.
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::{Backend, MockBackend, DeviceCapabilities};
///
/// let mut backend = MockBackend::new("mock", "test_device");
/// assert!(backend.initialize().is_ok());
/// assert!(backend.init_called());
/// ```
#[derive(Debug, Clone)]
pub struct MockBackend {
    name: String,
    device: String,
    capabilities: DeviceCapabilities,
    is_available: bool,
    should_fail_init: bool,
    should_fail_shutdown: bool,
    init_called: std::sync::Arc<std::sync::atomic::AtomicBool>,
    shutdown_called: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl MockBackend {
    /// Creates a new `MockBackend` with sensible defaults.
    ///
    /// # Arguments
    ///
    /// * `name` - Backend name
    /// * `device` - Device identifier
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, MockBackend};
    ///
    /// let backend = MockBackend::new("test", "device");
    /// assert_eq!(backend.name(), "test");
    /// assert_eq!(backend.device(), "device");
    /// assert!(backend.is_available());
    /// ```
    pub fn new(name: impl Into<String>, device: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            device: device.into(),
            capabilities: DeviceCapabilities::default(),
            is_available: true,
            should_fail_init: false,
            should_fail_shutdown: false,
            init_called: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            shutdown_called: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    /// Sets the device capabilities.
    ///
    /// # Arguments
    ///
    /// * `capabilities` - The device capabilities to report
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{MockBackend, DeviceCapabilities};
    ///
    /// let caps = DeviceCapabilities {
    ///     supports_f16: true,
    ///     ..Default::default()
    /// };
    /// let backend = MockBackend::new("test", "gpu")
    ///     .with_capabilities(caps);
    /// ```
    pub fn with_capabilities(mut self, capabilities: DeviceCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Sets whether the backend reports as available.
    ///
    /// # Arguments
    ///
    /// * `available` - Availability status
    pub fn with_availability(mut self, available: bool) -> Self {
        self.is_available = available;
        self
    }

    /// Configures the backend to fail during initialization.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, MockBackend};
    ///
    /// let mut backend = MockBackend::new("test", "device")
    ///     .with_init_failure();
    /// assert!(backend.initialize().is_err());
    /// ```
    pub fn with_init_failure(mut self) -> Self {
        self.should_fail_init = true;
        self
    }

    /// Configures the backend to fail during shutdown.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, MockBackend};
    ///
    /// let mut backend = MockBackend::new("test", "device")
    ///     .with_shutdown_failure();
    /// assert!(backend.shutdown().is_err());
    /// ```
    pub fn with_shutdown_failure(mut self) -> Self {
        self.should_fail_shutdown = true;
        self
    }

    /// Returns whether `initialize` was called on this backend.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, MockBackend};
    ///
    /// let mut backend = MockBackend::new("test", "device");
    /// assert!(!backend.init_called());
    /// let _ = backend.initialize();
    /// assert!(backend.init_called());
    /// ```
    pub fn init_called(&self) -> bool {
        self.init_called.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Returns whether `shutdown` was called on this backend.
    ///
    /// # Examples
    ///
    /// ```
    /// use aphelion_core::backend::{Backend, MockBackend};
    ///
    /// let mut backend = MockBackend::new("test", "device");
    /// assert!(!backend.shutdown_called());
    /// let _ = backend.shutdown();
    /// assert!(backend.shutdown_called());
    /// ```
    pub fn shutdown_called(&self) -> bool {
        self.shutdown_called
            .load(std::sync::atomic::Ordering::SeqCst)
    }
}

impl Backend for MockBackend {
    fn name(&self) -> &str {
        &self.name
    }

    fn device(&self) -> &str {
        &self.device
    }

    fn capabilities(&self) -> DeviceCapabilities {
        self.capabilities.clone()
    }

    fn is_available(&self) -> bool {
        self.is_available
    }

    fn initialize(&mut self) -> AphelionResult<()> {
        self.init_called
            .store(true, std::sync::atomic::Ordering::SeqCst);
        if self.should_fail_init {
            Err(crate::error::AphelionError::backend(
                "MockBackend initialization failed",
            ))
        } else {
            Ok(())
        }
    }

    fn shutdown(&mut self) -> AphelionResult<()> {
        self.shutdown_called
            .store(true, std::sync::atomic::Ordering::SeqCst);
        if self.should_fail_shutdown {
            Err(crate::error::AphelionError::backend(
                "MockBackend shutdown failed",
            ))
        } else {
            Ok(())
        }
    }
}

/// Trait for building models with backend and tracing support.
///
/// `ModelBuilder` defines a common interface for constructing models. Implementations
/// receive both a backend and a trace sink, enabling hardware-specific optimizations
/// and comprehensive logging of the build process.
///
/// # Associated Types
///
/// * `Output` - The type produced by the build operation
///
/// # Examples
///
/// ```
/// use aphelion_core::backend::{ModelBuilder, Backend};
/// use aphelion_core::diagnostics::TraceSink;
/// use aphelion_core::graph::BuildGraph;
///
/// struct SimpleBuilder;
///
/// impl ModelBuilder for SimpleBuilder {
///     type Output = BuildGraph;
///
///     fn build(&self, _backend: &dyn Backend, _trace: &dyn TraceSink) -> BuildGraph {
///         BuildGraph::default()
///     }
/// }
/// ```
pub trait ModelBuilder: Send + Sync {
    /// The type produced by the build operation
    type Output;

    /// Builds a model using the given backend and trace sink.
    ///
    /// # Arguments
    ///
    /// * `backend` - The computational backend to use
    /// * `trace` - The trace sink for recording build events
    fn build(&self, backend: &dyn Backend, trace: &dyn TraceSink) -> Self::Output;
}

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

    #[test]
    fn test_device_capabilities_default() {
        let caps = DeviceCapabilities::default();
        assert!(!caps.supports_f16);
        assert!(!caps.supports_bf16);
        assert!(!caps.supports_tf32);
        assert_eq!(caps.max_memory_bytes, None);
        assert_eq!(caps.compute_units, None);
    }

    #[test]
    fn test_device_capabilities_custom() {
        let caps = DeviceCapabilities {
            supports_f16: true,
            supports_bf16: true,
            supports_tf32: false,
            max_memory_bytes: Some(1024 * 1024 * 1024),
            compute_units: Some(512),
        };
        assert!(caps.supports_f16);
        assert!(caps.supports_bf16);
        assert!(!caps.supports_tf32);
        assert_eq!(caps.max_memory_bytes, Some(1024 * 1024 * 1024));
        assert_eq!(caps.compute_units, Some(512));
    }

    #[test]
    fn test_device_capabilities_clone() {
        let caps1 = DeviceCapabilities {
            supports_f16: true,
            supports_bf16: false,
            supports_tf32: true,
            max_memory_bytes: Some(2048),
            compute_units: Some(256),
        };
        let caps2 = caps1.clone();
        assert_eq!(caps1.supports_f16, caps2.supports_f16);
        assert_eq!(caps1.supports_bf16, caps2.supports_bf16);
        assert_eq!(caps1.max_memory_bytes, caps2.max_memory_bytes);
    }

    #[test]
    fn test_memory_info_default() {
        let mem = MemoryInfo::default();
        assert_eq!(mem.total_bytes, 0);
        assert_eq!(mem.used_bytes, 0);
        assert_eq!(mem.free_bytes, 0);
    }

    #[test]
    fn test_null_backend_name() {
        let backend = NullBackend::cpu();
        assert_eq!(backend.name(), "null");
    }

    #[test]
    fn test_null_backend_device() {
        let backend = NullBackend::cpu();
        assert_eq!(backend.device(), "cpu");
    }

    #[test]
    fn test_null_backend_capabilities() {
        let backend = NullBackend::cpu();
        let caps = backend.capabilities();
        assert!(!caps.supports_f16);
        assert!(!caps.supports_bf16);
        assert!(!caps.supports_tf32);
    }

    #[test]
    fn test_null_backend_is_available() {
        let backend = NullBackend::cpu();
        assert!(backend.is_available());
    }

    #[test]
    fn test_null_backend_initialize() {
        let mut backend = NullBackend::cpu();
        let result = backend.initialize();
        assert!(result.is_ok());
    }

    #[test]
    fn test_null_backend_shutdown() {
        let mut backend = NullBackend::cpu();
        let result = backend.shutdown();
        assert!(result.is_ok());
    }

    #[test]
    fn test_backend_registry_new() {
        let registry = BackendRegistry::new();
        assert_eq!(registry.list_available().len(), 0);
    }

    #[test]
    fn test_backend_registry_register() {
        let mut registry = BackendRegistry::new();
        let backend = Box::new(NullBackend::cpu());
        registry.register(backend);
        assert_eq!(registry.list_available().len(), 1);
    }

    #[test]
    fn test_backend_registry_get() {
        let mut registry = BackendRegistry::new();
        let backend = Box::new(NullBackend::cpu());
        registry.register(backend);
        let retrieved = registry.get("null");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name(), "null");
    }

    #[test]
    fn test_backend_registry_get_missing() {
        let registry = BackendRegistry::new();
        let retrieved = registry.get("nonexistent");
        assert!(retrieved.is_none());
    }

    #[test]
    fn test_backend_registry_list_available() {
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(NullBackend::new("cpu")));
        registry.register(Box::new(MockBackend::new("mock", "gpu")));

        let available = registry.list_available();
        assert_eq!(available.len(), 2);
        assert!(available.contains(&"null"));
        assert!(available.contains(&"mock"));
    }

    #[test]
    fn test_backend_registry_default() {
        let registry = BackendRegistry::default();
        assert_eq!(registry.list_available().len(), 0);
    }

    #[test]
    fn test_mock_backend_creation() {
        let backend = MockBackend::new("mock", "cpu");
        assert_eq!(backend.name(), "mock");
        assert_eq!(backend.device(), "cpu");
        assert!(backend.is_available());
    }

    #[test]
    fn test_mock_backend_with_capabilities() {
        let caps = DeviceCapabilities {
            supports_f16: true,
            supports_bf16: true,
            supports_tf32: false,
            max_memory_bytes: Some(8 * 1024 * 1024 * 1024),
            compute_units: Some(1024),
        };
        let backend = MockBackend::new("mock", "gpu").with_capabilities(caps.clone());
        let retrieved_caps = backend.capabilities();
        assert!(retrieved_caps.supports_f16);
        assert!(retrieved_caps.supports_bf16);
        assert!(!retrieved_caps.supports_tf32);
        assert_eq!(
            retrieved_caps.max_memory_bytes,
            Some(8 * 1024 * 1024 * 1024)
        );
        assert_eq!(retrieved_caps.compute_units, Some(1024));
    }

    #[test]
    fn test_mock_backend_with_availability() {
        let backend = MockBackend::new("mock", "cpu").with_availability(false);
        assert!(!backend.is_available());
    }

    #[test]
    fn test_mock_backend_initialize_success() {
        let mut backend = MockBackend::new("mock", "cpu");
        let result = backend.initialize();
        assert!(result.is_ok());
        assert!(backend.init_called());
    }

    #[test]
    fn test_mock_backend_initialize_failure() {
        let mut backend = MockBackend::new("mock", "cpu").with_init_failure();
        let result = backend.initialize();
        assert!(result.is_err());
        assert!(backend.init_called());
    }

    #[test]
    fn test_mock_backend_shutdown_success() {
        let mut backend = MockBackend::new("mock", "cpu");
        let result = backend.shutdown();
        assert!(result.is_ok());
        assert!(backend.shutdown_called());
    }

    #[test]
    fn test_mock_backend_shutdown_failure() {
        let mut backend = MockBackend::new("mock", "cpu").with_shutdown_failure();
        let result = backend.shutdown();
        assert!(result.is_err());
        assert!(backend.shutdown_called());
    }

    #[test]
    fn test_mock_backend_lifecycle() {
        let mut backend = MockBackend::new("mock", "cpu");
        assert!(!backend.init_called());
        assert!(!backend.shutdown_called());

        let init_result = backend.initialize();
        assert!(init_result.is_ok());
        assert!(backend.init_called());
        assert!(!backend.shutdown_called());

        let shutdown_result = backend.shutdown();
        assert!(shutdown_result.is_ok());
        assert!(backend.init_called());
        assert!(backend.shutdown_called());
    }

    #[test]
    fn test_mock_backend_builder_pattern() {
        let caps = DeviceCapabilities {
            supports_f16: true,
            supports_bf16: false,
            supports_tf32: true,
            max_memory_bytes: Some(1024),
            compute_units: Some(128),
        };
        let backend = MockBackend::new("test_backend", "gpu")
            .with_capabilities(caps)
            .with_availability(true);

        assert_eq!(backend.name(), "test_backend");
        assert_eq!(backend.device(), "gpu");
        assert!(backend.is_available());
        let retrieved_caps = backend.capabilities();
        assert!(retrieved_caps.supports_f16);
        assert!(!retrieved_caps.supports_bf16);
    }

    #[test]
    fn test_mock_backend_clone() {
        let backend1 = MockBackend::new("mock", "cpu").with_availability(false);
        let backend2 = backend1.clone();
        assert_eq!(backend1.name(), backend2.name());
        assert_eq!(backend1.device(), backend2.device());
        assert_eq!(backend1.is_available(), backend2.is_available());
    }

    #[test]
    fn test_backend_auto_detect_prefers_non_null() {
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(NullBackend::cpu()));
        registry.register(Box::new(MockBackend::new("cpu", "cpu")));

        let backend = registry.auto_detect();
        assert!(backend.is_some());
        // Should prefer "cpu" MockBackend over "null" NullBackend
        assert_eq!(backend.unwrap().name(), "cpu");
    }

    #[test]
    fn test_backend_auto_detect_returns_available() {
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(
            MockBackend::new("gpu", "gpu").with_availability(false),
        ));
        registry.register(Box::new(NullBackend::cpu()));

        let backend = registry.auto_detect();
        assert!(backend.is_some());
        // Should return null backend since gpu is unavailable
        assert_eq!(backend.unwrap().name(), "null");
    }

    #[test]
    fn test_backend_auto_detect_none_when_no_available() {
        let registry = BackendRegistry::new();
        let backend = registry.auto_detect();
        assert!(backend.is_none());
    }

    #[test]
    fn test_backend_prefer_respects_order() {
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(MockBackend::new("cuda", "gpu")));
        registry.register(Box::new(MockBackend::new("cpu", "cpu")));

        let backend = registry.prefer(&["cuda", "cpu"]);
        assert!(backend.is_some());
        // Should return "cuda" since it comes first in the preference list
        assert_eq!(backend.unwrap().name(), "cuda");
    }

    #[test]
    fn test_backend_prefer_skips_unavailable() {
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(
            MockBackend::new("cuda", "gpu").with_availability(false),
        ));
        registry.register(Box::new(MockBackend::new("cpu", "cpu")));

        let backend = registry.prefer(&["cuda", "cpu"]);
        assert!(backend.is_some());
        // Should skip unavailable "cuda" and return "cpu"
        assert_eq!(backend.unwrap().name(), "cpu");
    }

    #[test]
    fn test_backend_prefer_none_when_no_match() {
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(MockBackend::new("cuda", "gpu")));

        let backend = registry.prefer(&["metal", "rocm"]);
        assert!(backend.is_none());
    }

    #[test]
    fn test_backend_auto_detect_deterministic_ordering() {
        // BTreeMap should provide deterministic iteration order
        // This test verifies that auto_detect gives consistent results
        let mut registry = BackendRegistry::new();
        registry.register(Box::new(MockBackend::new("zebra", "gpu")));
        registry.register(Box::new(MockBackend::new("apple", "cpu")));
        registry.register(Box::new(MockBackend::new("monkey", "tpu")));

        // Should return "apple" (first alphabetically among non-null backends)
        let backend = registry.auto_detect();
        assert!(backend.is_some());
        assert_eq!(backend.unwrap().name(), "apple");
    }

    #[test]
    fn test_default_backend_function() {
        let backend = default_backend();
        assert_eq!(backend.name(), "null");
        assert_eq!(backend.device(), "cpu");
        assert!(backend.is_available());
    }
}