ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2024 NervoSys

//! Unified GPU abstraction layer
//!
//! This module provides a vendor-agnostic interface for GPU monitoring across NVIDIA, AMD, and
//! Intel GPUs through a common trait-based system. The [`Device`] trait defines the core API
//! that all GPU backends must implement, while [`GpuCollection`] provides convenient
//! multi-vendor GPU management.
//!
//! # Examples
//!
//! ## Auto-detect all GPUs
//!
//! ```no_run
//! use ironmonitor::gpu::GpuCollection;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Automatically detect and initialize all available GPUs
//! let gpus = GpuCollection::auto_detect()?;
//!
//! println!("Detected {} GPUs:", gpus.device_count());
//!
//! // Get snapshot of all GPUs
//! for (idx, info) in gpus.snapshot_all()?.iter().enumerate() {
//!     println!("GPU {}: {} ({})",
//!         idx,
//!         info.static_info.name,
//!         info.static_info.vendor
//!     );
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Access individual GPU devices
//!
//! ```no_run
//! use ironmonitor::gpu::GpuCollection;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let gpus = GpuCollection::auto_detect()?;
//!
//! // Iterate through devices and query properties
//! for device in gpus.gpus() {
//!     let info = device.info()?;
//!     println!("{} ({})", info.static_info.name, info.static_info.vendor);
//!     
//!     // Temperature
//!     if let Some(temp) = info.dynamic_info.thermal.temperature {
//!         println!("  Temperature: {}°C", temp);
//!     }
//!     
//!     // Utilization
//!     if let Some(util) = info.dynamic_info.utilization {
//!         println!("  Utilization: {}%", util);
//!     }
//!     
//!     // Memory
//!     // `None` where the device reported no figure, which is why these are
//!     // `Option` -- an adapter with no readable memory is not one with none.
//!     if let (Some(used), Some(total)) =
//!         (info.dynamic_info.memory.used, info.dynamic_info.memory.total)
//!     {
//!         println!("  Memory: {} / {} MB", used / 1024 / 1024, total / 1024 / 1024);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Vendor-specific initialization
//!
//! ```no_run,ignore
//! // Note: Vendor-specific initialization requires feature flags
//! // and uses internal types. Use GpuCollection::auto_detect() instead.
//! use ironmonitor::gpu::GpuCollection;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let gpus = GpuCollection::auto_detect()?;
//!
//! // Filter to NVIDIA GPUs only
//! for device in gpus.nvidia_gpus() {
//!     let info = device.info()?;
//!     println!("{} - Power: {:.1}W",
//!         info.static_info.name,
//!         info.dynamic_info.power.draw.unwrap_or(0) as f32 / 1000.0
//!     );
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Feature Flags
//!
//! - `nvidia` - NVIDIA GPU support via NVML (requires CUDA toolkit or NVIDIA driver)
//! - `amd` - AMD GPU support via sysfs/DRM (Linux only, requires amdgpu driver)
//! - `intel` - Intel GPU support via i915/xe drivers (Linux only)
//!
//! # Platform Support
//!
//! | Backend | Linux | Windows | macOS | Requirements |
//! |---------|-------|---------|-------|--------------|
//! | NVIDIA  | ✅    | ✅      | ❌    | libnvidia-ml.so / nvml.dll |
//! | AMD     | ✅    | 🚧      | ❌    | amdgpu driver, /sys/class/drm |
//! | Intel   | ✅    | 🚧      | ❌    | i915 or xe driver, /sys/class/drm |

use serde::{Deserialize, Serialize};
use std::fmt;

// New unified traits module
pub mod traits;

// Re-export key types from traits (with GpuProcess renamed to avoid conflict with legacy)
pub use traits::{
    Clocks, ComputeMode, Device, EccErrors, Error as GpuError, FanSpeed,
    GpuProcess as GpuProcessTrait, LinkState, Memory, MigMode, NvLinkStatus, PciInfo, Power,
    ProcessType, Temperature, TemperatureStatus, TemperatureThresholds, Utilization, Vendor,
};

// New vendor implementations
#[cfg(feature = "nvidia")]
pub mod nvidia_new;

#[cfg(feature = "amd")]
pub mod amd_rocm;

#[cfg(feature = "intel")]
pub mod intel_levelzero;

// Legacy implementations (backward compatibility)
#[cfg(feature = "nvidia")]
pub mod nvidia;

#[cfg(feature = "amd")]
pub mod amd;

#[cfg(feature = "intel")]
pub mod intel;

#[cfg(feature = "apple")]
pub mod apple;

/// Shared Windows GPU helpers (DXGI, WMI perf counters, OHM/LHM temperature)
#[cfg(windows)]
pub mod windows_helpers;

/// GPU vendor identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GpuVendor {
    /// NVIDIA GPUs (NVML-based, Jetson and desktop)
    Nvidia,
    /// AMD GPUs (amdgpu driver via libdrm)
    Amd,
    /// Intel GPUs (i915/xe driver via DRM)
    Intel,
    /// Apple GPUs (Metal-based, M1/M2/M3/M4)
    Apple,
}

impl fmt::Display for GpuVendor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GpuVendor::Nvidia => write!(f, "NVIDIA"),
            GpuVendor::Amd => write!(f, "AMD"),
            GpuVendor::Intel => write!(f, "Intel"),
            GpuVendor::Apple => write!(f, "Apple"),
        }
    }
}

/// GPU process type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum GpuProcessType {
    /// Graphics/rendering workload
    Graphics,
    /// Compute workload
    Compute,
    /// Mixed graphics and compute
    GraphicsAndCompute,
    /// Unknown/unclassified
    Unknown,
}

/// GPU process information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuProcess {
    /// Process ID
    pub pid: u32,
    /// Process name/command
    pub name: String,
    /// User running the process
    pub user: String,
    /// Process type
    pub process_type: GpuProcessType,
    /// GPU utilization percentage (0-100)
    pub gpu_usage: Option<u8>,
    /// Memory usage in bytes
    pub memory_usage: Option<u64>,
    /// Memory usage percentage (0-100)
    pub memory_usage_percent: Option<u8>,
    /// Encoder utilization percentage (0-100)
    pub encoder_usage: Option<u8>,
    /// Decoder utilization percentage (0-100)
    pub decoder_usage: Option<u8>,
    /// CPU usage percentage (0-100)
    pub cpu_usage: Option<u8>,
    /// CPU memory usage in bytes
    pub cpu_memory: Option<u64>,
}

/// GPU memory information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GpuMemory {
    /// Total memory in bytes, or `None` where the driver reports none.
    ///
    /// Every field here was a bare number, and four backends independently
    /// wrote zeros into them because there was no way to say otherwise. Two
    /// said so in a comment while doing it -- `used: 0, // Not available from
    /// powermetrics` in the Apple reader, and the Intel Linux reader writing a
    /// zero total for an integrated part that has no separate VRAM at all. A
    /// GPU reporting 0 bytes of memory is not a plausible reading; it is the
    /// absence of one, and it reached the TUI, the GUI, the Prometheus
    /// exporter, the ontology and the recorded database as a measurement.
    pub total: Option<u64>,
    /// Used memory in bytes, or `None` where unreported. See [`Self::total`].
    pub used: Option<u64>,
    /// Free memory in bytes, or `None` where unreported. See [`Self::total`].
    pub free: Option<u64>,
    /// Memory utilization percentage (0-100), or `None`.
    ///
    /// Derived from `used / total`, so it is absent whenever either is.
    pub utilization: Option<u8>,
}

impl GpuMemory {
    /// Nothing about this device's memory was readable.
    ///
    /// Distinct from a device reporting zeros, which no real adapter does.
    pub fn unreported() -> Self {
        Self {
            total: None,
            used: None,
            free: None,
            utilization: None,
        }
    }

    /// Build from a total and a used figure, deriving free and utilization.
    ///
    /// The derivation is the reason this exists: four backends computed the
    /// percentage by hand and three of them divided by a total that could be
    /// zero.
    pub fn from_total_used(total: u64, used: u64) -> Self {
        Self {
            total: Some(total),
            used: Some(used),
            free: Some(total.saturating_sub(used)),
            utilization: (total > 0).then(|| ((used as f64 / total as f64) * 100.0) as u8),
        }
    }
}

/// GPU clock information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GpuClocks {
    /// Current graphics/shader clock in MHz
    pub graphics: Option<u32>,
    /// Maximum graphics/shader clock in MHz
    pub graphics_max: Option<u32>,
    /// Current memory clock in MHz
    pub memory: Option<u32>,
    /// Maximum memory clock in MHz
    pub memory_max: Option<u32>,
    /// Current SM/compute clock in MHz
    pub sm: Option<u32>,
    /// Current video clock in MHz
    pub video: Option<u32>,
}

/// GPU power information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GpuPower {
    /// Current power draw in milliwatts
    pub draw: Option<u32>,
    /// Maximum power limit in milliwatts
    pub limit: Option<u32>,
    /// Default power limit in milliwatts
    pub default_limit: Option<u32>,
    /// Power usage percentage (0-100)
    pub usage_percent: Option<u8>,
}

/// GPU thermal information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GpuThermal {
    /// Current temperature in Celsius
    pub temperature: Option<i32>,
    /// Maximum temperature threshold in Celsius
    pub max_temperature: Option<i32>,
    /// Critical temperature threshold in Celsius
    pub critical_temperature: Option<i32>,
    /// Fan speed percentage (0-100)
    pub fan_speed: Option<u8>,
    /// Fan speed in RPM
    pub fan_rpm: Option<u32>,
}

/// PCIe link information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PcieLinkInfo {
    /// Current PCIe generation (1-6)
    pub current_gen: Option<u8>,
    /// Maximum PCIe generation (1-6)
    pub max_gen: Option<u8>,
    /// Current link width (lanes)
    pub current_width: Option<u8>,
    /// Maximum link width (lanes)
    pub max_width: Option<u8>,
    /// Current link speed in MT/s (Megatransfers per second)
    pub current_speed: Option<u32>,
    /// Maximum link speed in MT/s
    pub max_speed: Option<u32>,
    /// TX throughput in bytes/sec
    pub tx_throughput: Option<u64>,
    /// RX throughput in bytes/sec
    pub rx_throughput: Option<u64>,
}

/// GPU hardware engine utilization
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GpuEngines {
    /// Graphics/3D engine utilization (0-100)
    pub graphics: Option<u8>,
    /// Compute engine utilization (0-100)
    pub compute: Option<u8>,
    /// Video encoder utilization (0-100)
    pub encoder: Option<u8>,
    /// Video decoder utilization (0-100)
    pub decoder: Option<u8>,
    /// Copy/DMA engine utilization (0-100)
    pub copy: Option<u8>,
    /// Vendor-specific engines (e.g., DLA on Jetson)
    pub vendor_specific: Vec<(String, u8)>,
}

/// Static GPU information (doesn't change during runtime)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuStaticInfo {
    /// GPU index/ID
    pub index: usize,
    /// GPU vendor
    pub vendor: GpuVendor,
    /// GPU name/model. Empty where the driver did not report one, which the
    /// resolver publishes as unavailable.
    pub name: String,
    /// PCI bus ID (e.g., "0000:01:00.0")
    pub pci_bus_id: Option<String>,
    /// GPU UUID (vendor-specific format)
    pub uuid: Option<String>,
    /// VBIOS version
    pub vbios_version: Option<String>,
    /// Driver version
    pub driver_version: Option<String>,
    /// Compute capability (for NVIDIA)
    pub compute_capability: Option<(u32, u32)>,
    /// CUDA cores / Shader units / Execution units
    pub shader_cores: Option<u32>,
    /// L2 cache size in bytes
    pub l2_cache: Option<u64>,
    /// Number of execution engines
    pub num_engines: Option<u32>,
    /// Is integrated GPU (shares system memory). `None` where no reader obtained
    /// it. Readers used to guess from the product name ("vega", "arc") or assume a
    /// value per vendor, and those guesses are not stored here.
    pub integrated: Option<bool>,
}

/// Dynamic GPU information (updated each snapshot)
/// Default contains only unknown fields, never fabricated zero readings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GpuDynamicInfo {
    /// GPU utilization percentage (0-100), or `None` where the device reports
    /// no utilization counter.
    ///
    /// This was a bare `u8`. Two backends returned a literal `0` having read
    /// nothing at all, and the NVIDIA reader wrote `utilization_rates().ok()
    /// .map(..).unwrap_or(0)` -- so an NVML query that failed reported an idle
    /// card. An idle GPU and an unreadable one are the same number and
    /// different facts, and `0%` is the one a capacity planner acts on.
    pub utilization: Option<u8>,
    /// Memory information
    pub memory: GpuMemory,
    /// Clock speeds
    pub clocks: GpuClocks,
    /// Power information
    pub power: GpuPower,
    /// Thermal information
    pub thermal: GpuThermal,
    /// PCIe link information
    pub pcie: PcieLinkInfo,
    /// Hardware engine utilization
    pub engines: GpuEngines,
    /// Running processes on this GPU
    pub processes: Vec<GpuProcess>,
}

/// Complete GPU information (static + dynamic)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuInfo {
    /// Static information
    pub static_info: GpuStaticInfo,
    /// Dynamic information
    pub dynamic_info: GpuDynamicInfo,
}

impl GpuInfo {
    /// Get GPU index
    pub fn index(&self) -> usize {
        self.static_info.index
    }

    /// Get GPU vendor
    pub fn vendor(&self) -> GpuVendor {
        self.static_info.vendor
    }

    /// Get GPU name
    pub fn name(&self) -> &str {
        &self.static_info.name
    }

    /// GPU utilization percentage, or `None` where the device reports no
    /// utilization counter.
    pub fn utilization(&self) -> Option<u8> {
        self.dynamic_info.utilization
    }

    /// Get GPU temperature
    pub fn temperature(&self) -> Option<i32> {
        self.dynamic_info.thermal.temperature
    }

    /// Memory usage percentage, or `None` where the device reported no
    /// memory figures to derive it from.
    pub fn memory_utilization(&self) -> Option<u8> {
        self.dynamic_info.memory.utilization
    }

    /// Get power draw in watts
    pub fn power_draw_watts(&self) -> Option<f32> {
        self.dynamic_info.power.draw.map(|mw| mw as f32 / 1000.0)
    }

    /// Get number of running processes
    pub fn num_processes(&self) -> usize {
        self.dynamic_info.processes.len()
    }
}

/// Unified GPU interface trait
///
/// This trait provides a vendor-agnostic interface for GPU monitoring and control.
/// All GPU vendors (NVIDIA, AMD, Intel) implement this trait.
pub trait Gpu: Send + Sync {
    /// Get static GPU information
    fn static_info(&self) -> Result<GpuStaticInfo, crate::Error>;

    /// Get dynamic GPU information (snapshot)
    fn dynamic_info(&self) -> Result<GpuDynamicInfo, crate::Error>;

    /// Get complete GPU information
    fn info(&self) -> Result<GpuInfo, crate::Error> {
        Ok(GpuInfo {
            static_info: self.static_info()?,
            dynamic_info: self.dynamic_info()?,
        })
    }

    /// Get GPU vendor
    fn vendor(&self) -> GpuVendor;

    /// Get GPU index
    fn index(&self) -> usize;

    /// Get GPU name/model
    fn name(&self) -> Result<String, crate::Error>;

    /// Get running processes on this GPU
    fn processes(&self) -> Result<Vec<GpuProcess>, crate::Error>;

    /// Kill a process by PID
    fn kill_process(&self, pid: u32) -> Result<(), crate::Error>;

    /// Set power limit in milliwatts (if supported)
    fn set_power_limit(&mut self, limit_mw: u32) -> Result<(), crate::Error> {
        let _ = limit_mw;
        Err(crate::Error::NotSupported(
            "Power limit control not supported for this GPU".to_string(),
        ))
    }

    /// Set fan speed percentage (if supported)
    fn set_fan_speed(&mut self, speed_percent: u8) -> Result<(), crate::Error> {
        let _ = speed_percent;
        Err(crate::Error::NotSupported(
            "Fan control not supported for this GPU".to_string(),
        ))
    }

    /// Enable/disable auto fan control (if supported)
    fn set_fan_auto(&mut self, enabled: bool) -> Result<(), crate::Error> {
        let _ = enabled;
        Err(crate::Error::NotSupported(
            "Fan control not supported for this GPU".to_string(),
        ))
    }

    /// Get vendor-specific data as JSON (for advanced features)
    fn vendor_specific_data(&self) -> Result<serde_json::Value, crate::Error> {
        Ok(serde_json::Value::Null)
    }
}

/// Adapter to convert new trait-based Device to legacy Gpu trait
#[allow(dead_code)]
struct TraitGpuAdapter {
    device: Box<dyn Device>,
}

impl TraitGpuAdapter {
    #[allow(dead_code)]
    fn new(device: Box<dyn Device>) -> Self {
        Self { device }
    }

    #[allow(dead_code)]
    fn convert_vendor(vendor: Vendor) -> GpuVendor {
        match vendor {
            Vendor::Nvidia => GpuVendor::Nvidia,
            Vendor::Amd => GpuVendor::Amd,
            Vendor::Intel => GpuVendor::Intel,
            Vendor::Apple => GpuVendor::Apple,
        }
    }
}

impl Gpu for TraitGpuAdapter {
    fn static_info(&self) -> Result<GpuStaticInfo, crate::Error> {
        // A failed name read is empty, not the literal "Unknown" that used to stand
        // in for it and render as a model name.
        let name = self.device.name().unwrap_or_default();
        let pci = self.device.pci_info().ok();
        let uuid = self.device.uuid().ok();
        let driver = self.device.driver_version().ok();

        Ok(GpuStaticInfo {
            index: self.device.index() as usize,
            vendor: Self::convert_vendor(self.device.vendor()),
            name,
            pci_bus_id: pci.as_ref().map(|p| p.bus_id.clone()),
            uuid,
            vbios_version: None,
            driver_version: driver,
            compute_capability: None,
            shader_cores: None,
            l2_cache: None,
            num_engines: None,
            // The trait adapter does not read whether the part is integrated. This
            // used to be `false` for every adapter, including iGPUs.
            integrated: None,
        })
    }

    fn dynamic_info(&self) -> Result<GpuDynamicInfo, crate::Error> {
        let util = self.device.utilization().ok();
        let mem = self.device.memory().ok();
        let clocks = self.device.clocks().ok();
        let power = self.device.power().ok();
        let temp = self.device.temperature().ok();
        let fan = self.device.fan_speed().ok().flatten();
        let pci = self.device.pci_info().ok();

        // `.max(1)` in the old percentage was guarding a division by a total
        // that could be zero -- which is to say the total could be absent, and
        // the guard turned that into "0% of one byte" rather than into an
        // absence. A device whose memory query failed now reports nothing.
        // Both operands must be present to build a total/used pair; a partial
        // read is carried through as the absence it is, rather than being
        // completed with a zero.
        let memory = match mem {
            Some(m) => match (m.total, m.used) {
                (Some(total), Some(used)) => GpuMemory::from_total_used(total, used),
                (total, used) => GpuMemory {
                    total,
                    used,
                    free: m.free,
                    // Derivable only from both operands. See `from_total_used`.
                    utilization: None,
                },
            },
            None => GpuMemory::unreported(),
        };

        let clocks_info = if let Some(c) = clocks {
            GpuClocks {
                // Already optional at the source now; wrapping in `Some` here
                // would re-introduce the zero this change removed.
                graphics: c.graphics,
                graphics_max: None,
                memory: c.memory,
                memory_max: None,
                sm: c.sm,
                video: c.video,
            }
        } else {
            GpuClocks {
                graphics: None,
                graphics_max: None,
                memory: None,
                memory_max: None,
                sm: None,
                video: None,
            }
        };

        let power_info = if let Some(p) = power {
            // Watts to milliwatts, preserving absence rather than wrapping a
            // zero in `Some`. The percentage needs both figures and is absent
            // when either is -- it used to guard only against a zero limit,
            // which was the only way absence could reach it.
            let mw = |w: Option<f32>| w.map(|v| (v * 1000.0) as u32);
            GpuPower {
                draw: mw(p.current),
                limit: mw(p.limit),
                default_limit: mw(p.default_limit),
                usage_percent: match (p.current, p.limit) {
                    (Some(cur), Some(lim)) if lim > 0.0 => Some(((cur / lim) * 100.0) as u8),
                    _ => None,
                },
            }
        } else {
            GpuPower {
                draw: None,
                limit: None,
                default_limit: None,
                usage_percent: None,
            }
        };

        let thermal_info = if let Some(t) = temp {
            GpuThermal {
                temperature: t.edge.map(|e| e as i32),
                max_temperature: t
                    .thresholds
                    .as_ref()
                    .and_then(|th| th.critical.map(|c| c as i32)),
                critical_temperature: t
                    .thresholds
                    .as_ref()
                    .and_then(|th| th.shutdown.map(|s| s as i32)),
                fan_speed: fan.as_ref().map(|f| match f {
                    FanSpeed::Percent(p) => *p as u8,
                    FanSpeed::Rpm(_) => 0u8, // RPM doesn't map to percent
                }),
                fan_rpm: fan.as_ref().and_then(|f| match f {
                    FanSpeed::Rpm(r) => Some(*r),
                    _ => None,
                }),
            }
        } else {
            GpuThermal {
                temperature: None,
                max_temperature: None,
                critical_temperature: None,
                fan_speed: None,
                fan_rpm: None,
            }
        };

        let pcie_info = if let Some(p) = pci {
            PcieLinkInfo {
                current_gen: p.pcie_generation.map(|g| g as u8),
                max_gen: p.pcie_generation.map(|g| g as u8),
                current_width: p.pcie_link_width.map(|w| w as u8),
                max_width: p.pcie_link_width.map(|w| w as u8),
                current_speed: None,
                max_speed: None,
                tx_throughput: None,
                rx_throughput: None,
            }
        } else {
            PcieLinkInfo {
                current_gen: None,
                max_gen: None,
                current_width: None,
                max_width: None,
                current_speed: None,
                max_speed: None,
                tx_throughput: None,
                rx_throughput: None,
            }
        };

        Ok(GpuDynamicInfo {
            // A failed utilization query reports nothing, matching the
            // memory beside it rather than claiming an idle device.
            utilization: util.as_ref().and_then(|u| u.gpu).map(|g| g as u8),
            memory,
            clocks: clocks_info,
            power: power_info,
            thermal: thermal_info,
            pcie: pcie_info,
            engines: GpuEngines {
                graphics: util.as_ref().and_then(|u| u.gpu).map(|g| g as u8),
                compute: None,
                encoder: util.as_ref().and_then(|u| u.encoder.map(|e| e as u8)),
                decoder: util.as_ref().and_then(|u| u.decoder.map(|d| d as u8)),
                copy: None,
                vendor_specific: vec![],
            },
            processes: vec![],
        })
    }

    fn vendor(&self) -> GpuVendor {
        Self::convert_vendor(self.device.vendor())
    }

    fn index(&self) -> usize {
        self.device.index() as usize
    }

    fn name(&self) -> Result<String, crate::Error> {
        self.device
            .name()
            .map_err(|e| crate::Error::GpuError(e.to_string()))
    }

    fn processes(&self) -> Result<Vec<GpuProcess>, crate::Error> {
        // Get processes from the underlying Device trait
        let trait_procs = self
            .device
            .processes()
            .map_err(|e| crate::Error::GpuError(e.to_string()))?;

        // Convert from trait GpuProcess to struct GpuProcess
        let mut processes = Vec::new();
        for proc in trait_procs {
            let name = proc
                .name()
                .unwrap_or_else(|_| format!("pid_{}", proc.pid()));
            let memory_usage = proc.gpu_memory_used().ok();
            let gpu_usage = proc.sm_utilization().ok().flatten().map(|u| u as u8);
            let encoder_usage = proc.encoder_utilization().ok().flatten().map(|u| u as u8);
            let decoder_usage = proc.decoder_utilization().ok().flatten().map(|u| u as u8);

            let process_type = match proc.process_type() {
                crate::gpu::traits::ProcessType::Compute => GpuProcessType::Compute,
                crate::gpu::traits::ProcessType::Graphics => GpuProcessType::Graphics,
                crate::gpu::traits::ProcessType::Mixed => GpuProcessType::GraphicsAndCompute,
            };

            processes.push(GpuProcess {
                pid: proc.pid(),
                name,
                user: String::new(), // Not available from trait
                process_type,
                gpu_usage,
                memory_usage,
                memory_usage_percent: None,
                encoder_usage,
                decoder_usage,
                cpu_usage: proc.cpu_utilization().ok().flatten().map(|u| u as u8),
                cpu_memory: proc.host_memory_used().ok().flatten(),
            });
        }

        Ok(processes)
    }

    fn kill_process(&self, _pid: u32) -> Result<(), crate::Error> {
        Err(crate::Error::NotSupported(
            "Process kill not implemented for this adapter".to_string(),
        ))
    }
}

/// GPU collection representing all detected GPUs
pub struct GpuCollection {
    gpus: Vec<Box<dyn Gpu>>,
    /// Vendors whose detection failed, as (vendor, error). A failed read must not
    /// look like an absent GPU, so `auto_detect` records each failure here rather
    /// than stopping at the first one.
    detection_failures: Vec<(&'static str, String)>,
}

impl GpuCollection {
    /// Create a new GPU collection
    pub fn new() -> Self {
        Self {
            gpus: Vec::new(),
            detection_failures: Vec::new(),
        }
    }

    /// Per-vendor detection failures recorded by [`GpuCollection::auto_detect`].
    ///
    /// Empty means each enabled vendor either found its GPUs or reported that none
    /// are present. Non-empty means that vendor could not be read, so its missing
    /// GPUs are not a fact about the machine.
    pub fn detection_failures(&self) -> &[(&'static str, String)] {
        &self.detection_failures
    }

    /// Auto-detect and add all available GPUs
    pub fn auto_detect() -> Result<Self, crate::Error> {
        #[allow(unused_mut)]
        let mut collection = Self::new();

        // Every vendor runs even when an earlier one fails, so one broken driver
        // does not discard the GPUs another vendor found.
        #[cfg(feature = "nvidia")]
        {
            if let Err(e) = collection.detect_nvidia() {
                collection
                    .detection_failures
                    .push(("nvidia", e.to_string()));
            }
        }

        #[cfg(feature = "amd")]
        {
            if let Err(e) = collection.detect_amd() {
                collection.detection_failures.push(("amd", e.to_string()));
            }
        }

        #[cfg(feature = "intel")]
        {
            if let Err(e) = collection.detect_intel() {
                collection.detection_failures.push(("intel", e.to_string()));
            }
        }

        #[cfg(feature = "apple")]
        {
            if let Err(e) = collection.detect_apple() {
                collection.detection_failures.push(("apple", e.to_string()));
            }
        }

        // An empty collection with failures would read as "this machine has no
        // GPUs", so that case is an error. With any GPU found, the failures stay on
        // the collection for callers to report.
        // The failures go out as data, not folded into the message, so a caller
        // can report each backend on its own.
        if collection.is_empty() && !collection.detection_failures.is_empty() {
            return Err(crate::Error::GpuDetectionFailed(
                collection.detection_failures,
            ));
        }

        Ok(collection)
    }

    /// Detect NVIDIA GPUs
    #[cfg(feature = "nvidia")]
    pub fn detect_nvidia(&mut self) -> Result<(), crate::Error> {
        nvidia::detect_gpus(self)?;
        Ok(())
    }

    /// Detect AMD GPUs
    #[cfg(feature = "amd")]
    pub fn detect_amd(&mut self) -> Result<(), crate::Error> {
        // Trait-based sysfs reader first. NoDevicesFound means no AMD adapter is
        // present; any other error is kept and reported if the legacy reader also
        // finds nothing, so a failed read is never reported as absence.
        #[cfg(target_os = "linux")]
        let sysfs_error = {
            // A card whose reader could not be built is recorded, not dropped.
            let mut failures = Vec::new();
            let result = amd_rocm::enumerate(&mut failures);
            self.detection_failures
                .extend(failures.into_iter().map(|f| ("amd", f)));
            match result {
                Ok(gpus) => {
                    for gpu in gpus {
                        self.add_gpu(Box::new(TraitGpuAdapter::new(gpu)));
                    }
                    return Ok(());
                }
                Err(GpuError::NoDevicesFound) => None,
                Err(e) => Some(e),
            }
        };
        #[cfg(not(target_os = "linux"))]
        let sysfs_error: Option<GpuError> = None;

        // Legacy implementation: an independent reader, not a retry of sysfs
        let before = self.len();
        amd::detect_gpus(self)?;
        if let Some(e) = sysfs_error {
            if self.len() == before {
                let msg = format!("AMD sysfs enumeration failed: {e}");
                return Err(crate::Error::GpuError(msg));
            }
            log::debug!("AMD sysfs enumeration failed, legacy reader used: {e}");
        }
        Ok(())
    }

    /// Detect Intel GPUs
    #[cfg(feature = "intel")]
    pub fn detect_intel(&mut self) -> Result<(), crate::Error> {
        // Trait-based sysfs reader first. NoDevicesFound means no Intel adapter is
        // present; any other error is kept and reported if the legacy reader also
        // finds nothing, so a failed read is never reported as absence.
        #[cfg(target_os = "linux")]
        let sysfs_error = {
            // A card whose reader could not be built is recorded, not dropped.
            let mut failures = Vec::new();
            let result = intel_levelzero::enumerate(&mut failures);
            self.detection_failures
                .extend(failures.into_iter().map(|f| ("intel", f)));
            match result {
                Ok(gpus) => {
                    for gpu in gpus {
                        self.add_gpu(Box::new(TraitGpuAdapter::new(gpu)));
                    }
                    return Ok(());
                }
                Err(GpuError::NoDevicesFound) => None,
                Err(e) => Some(e),
            }
        };
        #[cfg(not(target_os = "linux"))]
        let sysfs_error: Option<GpuError> = None;

        // Legacy implementation: an independent reader, not a retry of sysfs
        let before = self.len();
        intel::detect_gpus(self)?;
        if let Some(e) = sysfs_error {
            if self.len() == before {
                let msg = format!("Intel sysfs enumeration failed: {e}");
                return Err(crate::Error::GpuError(msg));
            }
            log::debug!("Intel sysfs enumeration failed, legacy reader used: {e}");
        }
        Ok(())
    }

    /// Detect Apple Silicon GPUs
    #[cfg(feature = "apple")]
    pub fn detect_apple(&mut self) -> Result<(), crate::Error> {
        #[cfg(target_os = "macos")]
        {
            // Enumeration failure is an error, not an absent GPU: propagate it
            // as detect_nvidia does rather than reporting an empty machine.
            for gpu in apple::AppleGpu::detect_gpus()? {
                self.add_gpu(Box::new(gpu));
            }
        }
        Ok(())
    }

    /// Add a GPU to the collection
    pub fn add_gpu(&mut self, gpu: Box<dyn Gpu>) {
        self.gpus.push(gpu);
    }

    /// Get all GPUs
    pub fn gpus(&self) -> &[Box<dyn Gpu>] {
        &self.gpus
    }

    /// Get mutable reference to all GPUs
    pub fn gpus_mut(&mut self) -> &mut [Box<dyn Gpu>] {
        &mut self.gpus
    }

    /// Get number of GPUs
    pub fn len(&self) -> usize {
        self.gpus.len()
    }

    /// Get number of GPUs (alias for len())
    pub fn device_count(&self) -> usize {
        self.gpus.len()
    }

    /// Check if collection is empty
    pub fn is_empty(&self) -> bool {
        self.gpus.is_empty()
    }

    /// Get GPU by index
    pub fn get(&self, index: usize) -> Option<&dyn Gpu> {
        self.gpus.get(index).map(|gpu| gpu.as_ref())
    }

    /// Get mutable GPU by index
    pub fn get_mut(&mut self, index: usize) -> Option<&mut (dyn Gpu + 'static)> {
        self.gpus.get_mut(index).map(|gpu| gpu.as_mut())
    }

    /// Get all NVIDIA GPUs
    pub fn nvidia_gpus(&self) -> Vec<&dyn Gpu> {
        self.gpus
            .iter()
            .filter(|gpu| gpu.vendor() == GpuVendor::Nvidia)
            .map(|gpu| gpu.as_ref())
            .collect()
    }

    /// Get all AMD GPUs
    pub fn amd_gpus(&self) -> Vec<&dyn Gpu> {
        self.gpus
            .iter()
            .filter(|gpu| gpu.vendor() == GpuVendor::Amd)
            .map(|gpu| gpu.as_ref())
            .collect()
    }

    /// Get all Intel GPUs
    pub fn intel_gpus(&self) -> Vec<&dyn Gpu> {
        self.gpus
            .iter()
            .filter(|gpu| gpu.vendor() == GpuVendor::Intel)
            .map(|gpu| gpu.as_ref())
            .collect()
    }

    /// Get all GPU info snapshots.
    ///
    /// Queries run concurrently across devices. Vendor queries are dominated by
    /// driver round-trips (NVML, DXGI, sysfs) rather than CPU, so on a multi-GPU
    /// host this turns an N-device serial walk into roughly the cost of the
    /// slowest single device.
    ///
    /// Short-circuits on the first error, matching the original semantics. Use
    /// [`GpuCollection::snapshot_all_partial`] when one failing device should not
    /// blank the rest.
    pub fn snapshot_all(&self) -> Result<Vec<GpuInfo>, crate::Error> {
        self.snapshot_all_partial().into_iter().collect()
    }

    /// Get all GPU info snapshots, preserving per-device results.
    ///
    /// The returned vector is always the same length as [`GpuCollection::len`] and
    /// is index-aligned with [`GpuCollection::gpus`], so a failing device does not
    /// shift the indices of its neighbours. This matters for callers that pair
    /// dynamic samples against static descriptors captured earlier.
    pub fn snapshot_all_partial(&self) -> Vec<Result<GpuInfo, crate::Error>> {
        // Spawning is only worth it past one device.
        if self.gpus.len() <= 1 {
            return self.gpus.iter().map(|gpu| gpu.info()).collect();
        }

        std::thread::scope(|scope| {
            let handles: Vec<_> = self
                .gpus
                .iter()
                .map(|gpu| {
                    scope.spawn(move || {
                        // Some Windows GPU paths reach DXGI/WMI, which require COM
                        // to be initialized on the calling thread.
                        #[cfg(target_os = "windows")]
                        let _com = wmi::COMLibrary::new().ok();

                        gpu.info()
                    })
                })
                .collect();

            handles
                .into_iter()
                .map(|handle| {
                    handle.join().unwrap_or_else(|_| {
                        Err(crate::error::Error::GpuError(
                            "GPU query panicked".to_string(),
                        ))
                    })
                })
                .collect()
        })
    }
}

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