Skip to main content

fuel_ir/
probe.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Cross-backend device enumeration — the foundation for Phase 6b's
3//! `probe → judge → dispatch` lifecycle.
4//!
5//! # Why
6//!
7//! Fuel dispatches ops across multiple backends (CPU, reference, CUDA,
8//! Vulkan, later Metal / MKL / AOCL). Each backend may see zero, one,
9//! or many physical devices. A single physical GPU may be reachable
10//! through more than one backend (an NVIDIA card is visible to both
11//! CUDA and Vulkan) and will produce meaningfully different
12//! performance profiles depending on which backend routes it. The
13//! profiling unit — and therefore the dispatch-table key — is not
14//! "backend" but `(backend, device)`.
15//!
16//! This module defines the data types that represent that pair in a
17//! persistence-friendly shape. The actual enumeration logic lives in
18//! each backend crate (a free function `enumerate_devices() ->
19//! Result<Vec<DeviceDescriptor>>`, not a trait method — see "Why a
20//! convention, not a trait" below). A top-level collector in
21//! `fuel-graph-router` (or a future `fuel-judge`) calls every
22//! backend's enumerator and assembles the combined device table.
23//!
24//! # Equivalence classes
25//!
26//! Four identical RTX 4090s through CUDA produce four essentially-
27//! identical performance profiles — the Judge doesn't need to run
28//! four times. Two [`DeviceDescriptor`]s that share an
29//! [`EquivalenceKey`] can share a profile: profile once per key,
30//! apply to every device in the class. Cross-backend equivalence
31//! never holds (CUDA and Vulkan on the same silicon still key
32//! differently because they have different driver paths and
33//! submission overhead).
34//!
35//! # Why a convention, not a trait
36//!
37//! `BackendProbe` *could* be a trait implemented by each backend's
38//! device or storage type. But enumeration is a **static** operation —
39//! it doesn't need a live backend instance, and requiring one creates
40//! a circular bootstrap problem (you can't know which backends exist
41//! until you've enumerated them, but trait impls need types, and the
42//! types may not be loadable if their runtime isn't present). The
43//! cleaner shape is a plain free function per backend crate that can
44//! be called via the crate's public API without constructing any
45//! state. The [`BackendProbe`] trait below is a *documentation anchor*
46//! — a marker trait each backend-crate-level probe function satisfies
47//! in spirit, so the contract is in one place and the collector has
48//! a single import to follow.
49
50use crate::DeviceLocation;
51use crate::error::Result;
52
53#[cfg(feature = "serde")]
54use serde::{Deserialize, Serialize};
55
56/// Identifier for a Fuel backend implementation. Stable across runs
57/// so the Judge's persisted profile tables remain valid when the
58/// process restarts. Adding a new variant is a non-breaking change;
59/// the enum is `#[non_exhaustive]` so downstream pattern matches stay
60/// forward-compatible.
61#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
62#[non_exhaustive]
63#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
64pub enum BackendId {
65    /// `fuel-cpu-backend` — optimized CPU executor (gemm + rayon).
66    /// One descriptor per physical CPU in the current scope; NUMA
67    /// splits are Phase 7b territory.
68    Cpu,
69    /// `fuel-cuda-backend` via baracuda.
70    Cuda,
71    /// `fuel-vulkan-backend` via vulkane.
72    Vulkan,
73    /// `fuel-metal-backend` (future — not yet probe-wired).
74    Metal,
75    // `Aocl` and `Mkl` variants retired 2026-06-08 (backend-extensions
76    // Phase 2). AOCL and oneMKL are now kernel-source extensions of
77    // `BackendId::Cpu` — their kernels register as siblings at the
78    // same binding-table key, distinguished by `BindingEntry::kernel_source`.
79    // See `docs/architecture/05-backend-contract.md` §Trait surface.
80}
81
82impl BackendId {
83    /// A short lowercase identifier suitable for log lines, directory
84    /// paths, and JSON keys. Stable across Fuel versions.
85    pub fn as_str(self) -> &'static str {
86        match self {
87            BackendId::Cpu => "cpu",
88            BackendId::Cuda => "cuda",
89            BackendId::Vulkan => "vulkan",
90            BackendId::Metal => "metal",
91        }
92    }
93}
94
95impl std::fmt::Display for BackendId {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.write_str(self.as_str())
98    }
99}
100
101/// Everything a Judge / dispatch table needs to know about a single
102/// `(backend, device)` pair. Constructed by each backend's
103/// `enumerate_devices()` and consumed by the collector + the Judge.
104///
105/// Field layout is stable: adding fields is non-breaking so long as
106/// they're additive (`#[serde(default)]` on new optional fields keeps
107/// older profile files loading).
108#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
110pub struct DeviceDescriptor {
111    /// Which backend this descriptor belongs to.
112    pub backend: BackendId,
113    /// Zero-based index within the backend. For CPU this is always 0
114    /// until NUMA splits arrive; for CUDA/Vulkan it's the device
115    /// ordinal the backend's own API uses.
116    pub device_index: u32,
117    /// Human-readable device name as reported by the driver.
118    /// Examples: `"NVIDIA GeForce RTX 4070"`, `"AMD Radeon RX 7900 XT"`,
119    /// `"Intel(R) Core(TM) i9-14900K"`. Used primarily for logs.
120    pub hardware_sku: String,
121    /// PCI-SIG vendor ID (NVIDIA=0x10DE, AMD=0x1002, Intel=0x8086).
122    /// `0` for CPU entries that don't map to a PCI vendor.
123    pub vendor_id: u32,
124    /// PCI-SIG device ID for discrete hardware; zero for CPU.
125    pub device_id: u32,
126    /// CUDA compute capability, when applicable. `None` for non-CUDA
127    /// entries. Stored as `(major, minor)` — e.g. `(8, 9)` for sm_89.
128    pub compute_capability: Option<(u32, u32)>,
129    /// The **default** lanes per subgroup / wave / warp — the primary
130    /// kernel-specialization axis on every SIMT backend. 32 on NVIDIA,
131    /// 64 on AMD GCN/CDNA, 32 *or* 64 on RDNA, 8/16/32 on Intel.
132    /// `None` when the backend cannot report it (CPU, or a Vulkan
133    /// instance created below 1.1).
134    ///
135    /// **This is the default width a shader sees, NOT the set the
136    /// device supports.** A device may *admit several*: an AMD 610M
137    /// reports a default of 64 while admitting dynamic, 32 and 64.
138    /// Vulkan exposes the pinnable range through
139    /// `SubgroupProperties::size_control`, which is 1.3 core / the EXT
140    /// — unreachable from Fuel's V1_2 instances today, so only the
141    /// default is captured here.
142    ///
143    /// **Consequence if Fuel ever specializes kernels by wave width:
144    /// `Option<u32>` is then the wrong shape**, not merely
145    /// under-documented — a wave32-pinned kernel and a wave64 one are
146    /// different cells, so the descriptor would need *the admissible
147    /// set plus the default*. Mirror vulkane's split
148    /// (`admissible_subgroups()` alongside `default_subgroup`) rather
149    /// than widening this field in place.
150    ///
151    /// Deliberately **not** part of [`EquivalenceKey`]: it is a
152    /// function of `(vendor_id, device_id)`, which the key already
153    /// carries, so including it would add no discriminating power and
154    /// would churn the Judge's cache for nothing.
155    pub subgroup_width: Option<u32>,
156    /// Driver version string as reported by the backend. Cache
157    /// invalidation key: if the driver rev changes, Judge re-runs.
158    pub driver_version: String,
159    /// Total device-visible memory in bytes. Zero if unknown.
160    pub total_memory_bytes: u64,
161    /// Fuel's placement enum for this descriptor. Populated by the
162    /// backend so the router can build `DeviceLocation` handles
163    /// without re-querying.
164    pub location: DeviceLocation,
165}
166
167impl DeviceDescriptor {
168    /// The key the Judge uses to share a profile across identical
169    /// devices. Two descriptors that compare equal here can share a
170    /// single profile entry; the table's runtime dispatch just looks
171    /// up the equivalence key rather than the full descriptor.
172    pub fn equivalence_key(&self) -> EquivalenceKey {
173        EquivalenceKey {
174            backend: self.backend,
175            vendor_id: self.vendor_id,
176            device_id: self.device_id,
177            compute_capability: self.compute_capability,
178            driver_version: self.driver_version.clone(),
179        }
180    }
181}
182
183/// Hash key that groups [`DeviceDescriptor`]s likely to profile
184/// identically. Explicitly **scoped by backend** — a CUDA RTX 4090
185/// and a Vulkan RTX 4090 are the same silicon but different
186/// submission paths, so they never share an equivalence class.
187///
188/// The driver version is part of the key because the same
189/// `(vendor, device, capability)` can perform measurably
190/// differently across driver releases; invalidating on driver
191/// upgrade is cheap insurance.
192#[derive(Debug, Clone, PartialEq, Eq, Hash)]
193#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
194pub struct EquivalenceKey {
195    pub backend: BackendId,
196    pub vendor_id: u32,
197    pub device_id: u32,
198    pub compute_capability: Option<(u32, u32)>,
199    pub driver_version: String,
200}
201
202/// Marker trait documenting the enumeration contract each backend
203/// crate satisfies. **Not dispatch-through** — each backend provides
204/// a plain `pub fn enumerate_devices()` at crate root, and the
205/// collector calls them by name. This trait is a single place to
206/// reference the expected signature.
207///
208/// See the module docs for why this is a convention rather than a
209/// dispatch trait.
210pub trait BackendProbe {
211    /// Enumerate every `(backend, device)` pair this backend can
212    /// currently reach. Empty vec = backend loaded but no usable
213    /// hardware visible (e.g. CUDA runtime present but zero GPUs).
214    /// `Err` = backend could not be probed at all (e.g. driver
215    /// dynamic-load failed).
216    fn enumerate_devices() -> Result<Vec<DeviceDescriptor>>;
217}
218
219impl DeviceLocation {
220    /// The kind of backend that drives this place: the one definition of the mapping
221    /// (`Cpu` to [`BackendId::Cpu`], each GPU variant to its backend, whatever the ordinal).
222    pub fn backend(self) -> BackendId {
223        match self {
224            DeviceLocation::Cpu => BackendId::Cpu,
225            DeviceLocation::Cuda { .. } => BackendId::Cuda,
226            DeviceLocation::Vulkan { .. } => BackendId::Vulkan,
227            DeviceLocation::Metal { .. } => BackendId::Metal,
228        }
229    }
230}
231
232impl BackendId {
233    /// The place a backend's work goes when nothing names a device: GPU ordinal 0, or the CPU.
234    /// The match is exhaustive inside this crate, so adding a `BackendId` variant fails to compile
235    /// here until it is given a default place. The ordinal is a within-process enumeration index,
236    /// not an identity (ROADMAP row 125); this is the one place that default lives.
237    pub fn default_location(self) -> DeviceLocation {
238        match self {
239            BackendId::Cpu => DeviceLocation::Cpu,
240            BackendId::Cuda => DeviceLocation::Cuda { gpu_id: 0 },
241            BackendId::Vulkan => DeviceLocation::Vulkan { gpu_id: 0 },
242            BackendId::Metal => DeviceLocation::Metal { gpu_id: 0 },
243        }
244    }
245}
246
247/// A PCI bus address as the OS and the GPU APIs report it. `function` is `None` when the source
248/// does not say (CUDA reports domain, bus and device number only).
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
250#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
251pub struct PciAddress {
252    pub domain: u32,
253    pub bus: u32,
254    pub device: u32,
255    pub function: Option<u32>,
256}
257
258/// What identifies ONE physical GPU across processes and across APIs (ROADMAP row 125). The
259/// enumeration index (`DeviceLocation::{Cuda,Vulkan}.gpu_id`) is only a within-process handle: on
260/// this box the Vulkan order flipped between two runs. Key placement on this, not on the index.
261///
262/// `uuid` is the 16-byte device UUID that Vulkan (`VkPhysicalDeviceIDProperties`), CUDA
263/// (`cuDeviceGetUuid`), NVML and OpenGL agree on. It is `None` when the source could not report one
264/// (and an all-zero value is treated as absent by [`Self::same_physical_device`]: a zeroed join key
265/// reads as a valid UUID that every device shares). `pci` is the bus address, the fallback join key.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
267#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
268pub struct DeviceIdentity {
269    pub uuid: Option<[u8; 16]>,
270    pub pci: Option<PciAddress>,
271}
272
273impl DeviceIdentity {
274    /// The UUID, if present and not all zero.
275    pub fn usable_uuid(&self) -> Option<[u8; 16]> {
276        self.uuid.filter(|u| u.iter().any(|b| *b != 0))
277    }
278
279    /// Do these two identities name the same physical GPU? UUIDs decide when both sides have a
280    /// usable one (equal means same, different means different). Otherwise the PCI address decides
281    /// (domain, bus and device, plus function when both sides report it). With neither, the answer
282    /// is `false`: unknown is not "same".
283    pub fn same_physical_device(&self, other: &DeviceIdentity) -> bool {
284        if let (Some(a), Some(b)) = (self.usable_uuid(), other.usable_uuid()) {
285            return a == b;
286        }
287        match (self.pci, other.pci) {
288            (Some(a), Some(b)) => {
289                a.domain == b.domain
290                    && a.bus == b.bus
291                    && a.device == b.device
292                    && match (a.function, b.function) {
293                        (Some(x), Some(y)) => x == y,
294                        _ => true,
295                    }
296            }
297            _ => false,
298        }
299    }
300}
301
302/// Why [`resolve_identity_ordinal`] found no single device.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub enum IdentityResolveError {
305    /// No enumerated device is the wanted physical GPU (including: the wanted identity carries
306    /// neither a usable UUID nor a PCI address, since unknown is never "same").
307    NoMatch,
308    /// More than one enumerated device claims to be the wanted GPU (their ordinals, ascending).
309    /// Guessing the first would reintroduce the order dependence this exists to remove.
310    Ambiguous(Vec<usize>),
311}
312
313/// Resolve a [`DeviceIdentity`] to the enumeration ordinal of THIS process (ROADMAP row 137,
314/// step 4a). `enumerated[i]` is the identity of the device the process enumerates at ordinal `i`.
315/// The answer is a within-process handle and must not be stored: the next process or build may
316/// enumerate in a different order, which is the reason to ask by identity at all.
317pub fn resolve_identity_ordinal(
318    wanted: &DeviceIdentity,
319    enumerated: &[DeviceIdentity],
320) -> std::result::Result<usize, IdentityResolveError> {
321    let hits: Vec<usize> = enumerated
322        .iter()
323        .enumerate()
324        .filter(|(_, id)| wanted.same_physical_device(id))
325        .map(|(i, _)| i)
326        .collect();
327    match hits.as_slice() {
328        [] => Err(IdentityResolveError::NoMatch),
329        [one] => Ok(*one),
330        _ => Err(IdentityResolveError::Ambiguous(hits)),
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    fn res_ident(uuid_byte: u8, bus: u32) -> DeviceIdentity {
339        DeviceIdentity {
340            uuid: Some([uuid_byte; 16]),
341            pci: Some(PciAddress {
342                domain: 0,
343                bus,
344                device: 0,
345                function: None,
346            }),
347        }
348    }
349
350    #[test]
351    fn resolver_follows_the_device_across_both_enumeration_orders() {
352        let nv = res_ident(0x11, 1);
353        let amd = res_ident(0x22, 6);
354        // Vulkan-only build order vs CUDA-plus-Vulkan build order (row 125 measurement).
355        let amd_first = [amd, nv];
356        let nv_first = [nv, amd];
357        assert_eq!(resolve_identity_ordinal(&nv, &amd_first), Ok(1));
358        assert_eq!(resolve_identity_ordinal(&nv, &nv_first), Ok(0));
359        assert_eq!(resolve_identity_ordinal(&amd, &amd_first), Ok(0));
360        assert_eq!(resolve_identity_ordinal(&amd, &nv_first), Ok(1));
361    }
362
363    #[test]
364    fn resolver_declines_unknown_absent_and_ambiguous() {
365        let nv = res_ident(0x11, 1);
366        let amd = res_ident(0x22, 6);
367        assert_eq!(
368            resolve_identity_ordinal(&nv, &[amd]),
369            Err(IdentityResolveError::NoMatch)
370        );
371        assert_eq!(
372            resolve_identity_ordinal(&nv, &[]),
373            Err(IdentityResolveError::NoMatch)
374        );
375        // Neither UUID nor PCI: unknown is never "same", even against another unknown.
376        let none = DeviceIdentity {
377            uuid: None,
378            pci: None,
379        };
380        assert_eq!(
381            resolve_identity_ordinal(&none, &[none]),
382            Err(IdentityResolveError::NoMatch)
383        );
384        // An all-zero UUID is absent, so two zeroed devices on different buses stay distinct.
385        let z = |bus| DeviceIdentity {
386            uuid: Some([0; 16]),
387            pci: Some(PciAddress {
388                domain: 0,
389                bus,
390                device: 0,
391                function: None,
392            }),
393        };
394        assert_eq!(resolve_identity_ordinal(&z(1), &[z(6), z(1)]), Ok(1));
395        // Two enumerated entries for the same GPU: refuse rather than take the first.
396        assert_eq!(
397            resolve_identity_ordinal(&nv, &[nv, amd, nv]),
398            Err(IdentityResolveError::Ambiguous(vec![0, 2]))
399        );
400    }
401
402    #[test]
403    fn backend_id_as_str_is_stable() {
404        assert_eq!(BackendId::Cpu.as_str(), "cpu");
405        assert_eq!(BackendId::Cuda.as_str(), "cuda");
406        assert_eq!(BackendId::Vulkan.as_str(), "vulkan");
407        assert_eq!(BackendId::Metal.as_str(), "metal");
408    }
409
410    #[test]
411    fn equivalence_key_collapses_identical_cuda_devices() {
412        let make = |idx: u32| DeviceDescriptor {
413            backend: BackendId::Cuda,
414            device_index: idx,
415            hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
416            vendor_id: 0x10DE,
417            device_id: 0x2684,
418            compute_capability: Some((8, 9)),
419            subgroup_width: Some(32), // NVIDIA warp
420            driver_version: "550.54.14".to_string(),
421            total_memory_bytes: 25_769_803_776,
422            location: DeviceLocation::Cuda {
423                gpu_id: idx as usize,
424            },
425        };
426        let a = make(0);
427        let b = make(1);
428        // Same silicon, different ordinals → same equivalence class.
429        assert_eq!(a.equivalence_key(), b.equivalence_key());
430        // Different device_index → descriptors still distinct overall.
431        assert_ne!(a, b);
432    }
433
434    #[test]
435    fn equivalence_key_splits_same_silicon_across_backends() {
436        let cuda = DeviceDescriptor {
437            backend: BackendId::Cuda,
438            device_index: 0,
439            hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
440            vendor_id: 0x10DE,
441            device_id: 0x2684,
442            compute_capability: Some((8, 9)),
443            subgroup_width: Some(32),
444            driver_version: "550.54.14".to_string(),
445            total_memory_bytes: 25_769_803_776,
446            location: DeviceLocation::Cuda { gpu_id: 0 },
447        };
448        let vulkan = DeviceDescriptor {
449            backend: BackendId::Vulkan,
450            device_index: 0,
451            hardware_sku: "NVIDIA GeForce RTX 4090".to_string(),
452            vendor_id: 0x10DE,
453            device_id: 0x2684,
454            compute_capability: None, // Vulkan doesn't expose CUDA CC.
455            subgroup_width: Some(32),
456            driver_version: "550.54.14".to_string(),
457            total_memory_bytes: 25_769_803_776,
458            location: DeviceLocation::Cpu, // placeholder; vulkane uses a different variant
459        };
460        // Same chip, different submission paths → different classes.
461        assert_ne!(cuda.equivalence_key(), vulkan.equivalence_key());
462    }
463
464    #[test]
465    fn equivalence_key_splits_on_driver_version() {
466        let base = DeviceDescriptor {
467            backend: BackendId::Cuda,
468            device_index: 0,
469            hardware_sku: "X".to_string(),
470            vendor_id: 1,
471            device_id: 2,
472            compute_capability: Some((8, 9)),
473            subgroup_width: Some(32),
474            driver_version: "550".to_string(),
475            total_memory_bytes: 0,
476            location: DeviceLocation::Cuda { gpu_id: 0 },
477        };
478        let newer = DeviceDescriptor {
479            driver_version: "560".to_string(),
480            ..base.clone()
481        };
482        assert_ne!(base.equivalence_key(), newer.equivalence_key());
483    }
484
485    /// `subgroup_width` is a function of `(vendor_id, device_id)`, which the
486    /// key already carries, so it must NOT participate in the equivalence
487    /// key — otherwise a backend that learns to report it (or stops) would
488    /// churn every cached Judge profile for no discriminating gain.
489    /// Pins the documented invariant on `DeviceDescriptor::subgroup_width`.
490    #[test]
491    fn equivalence_key_ignores_subgroup_width() {
492        let base = DeviceDescriptor {
493            backend: BackendId::Vulkan,
494            device_index: 0,
495            hardware_sku: "X".to_string(),
496            vendor_id: 1,
497            device_id: 2,
498            compute_capability: None,
499            subgroup_width: None,
500            driver_version: "550".to_string(),
501            total_memory_bytes: 0,
502            location: DeviceLocation::Vulkan { gpu_id: 0 },
503        };
504        let with_width = DeviceDescriptor {
505            subgroup_width: Some(64),
506            ..base.clone()
507        };
508        // Descriptors differ...
509        assert_ne!(base, with_width);
510        // ...but they profile identically, so the key must collapse them.
511        assert_eq!(base.equivalence_key(), with_width.equivalence_key());
512    }
513
514    /// Every GPU ordinal maps to the same backend, and the CPU to the CPU.
515    #[test]
516    fn location_to_backend_ignores_the_ordinal() {
517        assert_eq!(DeviceLocation::Cpu.backend(), BackendId::Cpu);
518        for gpu_id in [0usize, 1, 7] {
519            assert_eq!(DeviceLocation::Cuda { gpu_id }.backend(), BackendId::Cuda);
520            assert_eq!(
521                DeviceLocation::Vulkan { gpu_id }.backend(),
522                BackendId::Vulkan
523            );
524            assert_eq!(DeviceLocation::Metal { gpu_id }.backend(), BackendId::Metal);
525        }
526    }
527
528    /// The default location is ordinal 0 (or the CPU), and mapping it back gives the same backend,
529    /// for every backend this crate knows.
530    #[test]
531    fn default_location_round_trips_for_every_backend() {
532        for b in [
533            BackendId::Cpu,
534            BackendId::Cuda,
535            BackendId::Vulkan,
536            BackendId::Metal,
537        ] {
538            assert_eq!(b.default_location().backend(), b, "{b:?}");
539        }
540        assert_eq!(
541            BackendId::Cuda.default_location(),
542            DeviceLocation::Cuda { gpu_id: 0 }
543        );
544        assert_eq!(BackendId::Cpu.default_location(), DeviceLocation::Cpu);
545    }
546
547    fn ident(uuid: Option<u8>, pci: Option<(u32, u32, u32, Option<u32>)>) -> DeviceIdentity {
548        DeviceIdentity {
549            uuid: uuid.map(|b| [b; 16]),
550            pci: pci.map(|(domain, bus, device, function)| PciAddress {
551                domain,
552                bus,
553                device,
554                function,
555            }),
556        }
557    }
558
559    /// UUIDs decide when both sides have one; the PCI address cannot overrule them.
560    #[test]
561    fn identity_uuid_decides_when_both_sides_have_one() {
562        let a = ident(Some(1), Some((0, 1, 0, None)));
563        assert!(a.same_physical_device(&ident(Some(1), Some((0, 9, 9, None)))));
564        assert!(!a.same_physical_device(&ident(Some(2), Some((0, 1, 0, None)))));
565    }
566
567    /// An all-zero UUID is absent, not a value two devices share (the vulkane V1_0 trap).
568    #[test]
569    fn identity_zero_uuid_is_absent_so_pci_decides() {
570        let zero = DeviceIdentity {
571            uuid: Some([0; 16]),
572            pci: Some(PciAddress {
573                domain: 0,
574                bus: 3,
575                device: 0,
576                function: Some(0),
577            }),
578        };
579        let other_zero_other_bus = DeviceIdentity {
580            uuid: Some([0; 16]),
581            pci: Some(PciAddress {
582                domain: 0,
583                bus: 4,
584                device: 0,
585                function: Some(0),
586            }),
587        };
588        assert!(!zero.same_physical_device(&other_zero_other_bus));
589        assert!(zero.same_physical_device(&zero));
590    }
591
592    /// PCI fallback: a missing function on one side matches (CUDA does not report it); a present,
593    /// different function does not. Neither source having anything is "unknown", not "same".
594    #[test]
595    fn identity_pci_fallback_and_unknown() {
596        let cuda = ident(None, Some((0, 1, 0, None)));
597        assert!(cuda.same_physical_device(&ident(None, Some((0, 1, 0, Some(0))))));
598        assert!(!cuda.same_physical_device(&ident(None, Some((0, 2, 0, Some(0))))));
599        assert!(
600            !ident(Some(1), Some((0, 1, 0, Some(1))))
601                .same_physical_device(&ident(None, Some((0, 1, 0, Some(0)))))
602        );
603        assert!(!ident(None, None).same_physical_device(&ident(None, None)));
604    }
605}