primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Device creation and adapter selection
//!
//! **Why this file is large (~640 lines)**: Single concern—"how do I obtain a
//! `WgpuDevice`?" Many entry points (new, `new_gpu`, `new_cpu`, `from_env`,
//! `discover_best_adapter`, `from_physical_device`, etc.) reflect different selection
//! strategies, not mixed concerns. All logic serves device creation.

use super::WgpuDevice;
use crate::device::probe;
use crate::error::{BarracudaError, Result};
use std::sync::Arc;

/// Global serialization guard for wgpu device creation.
///
/// Vulkan drivers (especially NVK/nouveau) can segfault when concurrent
/// `request_device` calls race on the kernel DRM file descriptor. This
/// mutex ensures all device creation across the entire process is serial.
static DEVICE_CREATION_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// Environment variable for adapter selection
pub const ADAPTER_ENV_VAR: &str = "BARRACUDA_GPU_ADAPTER";

/// Desired features to negotiate with any adapter.
fn desired_features() -> Vec<wgpu::Features> {
    vec![
        wgpu::Features::SHADER_F64,
        wgpu::Features::SHADER_F16,
        wgpu::Features::SUBGROUP,
    ]
}

/// Extended feature set that also includes `TIMESTAMP_QUERY` (for benchmarks).
fn desired_features_extended() -> Vec<wgpu::Features> {
    vec![
        wgpu::Features::SHADER_F64,
        wgpu::Features::SHADER_F16,
        wgpu::Features::TIMESTAMP_QUERY,
        wgpu::Features::SUBGROUP,
    ]
}

/// Negotiate features: request everything the adapter supports from `wanted`.
fn negotiate_features(adapter: &wgpu::Adapter, wanted: &[wgpu::Features]) -> wgpu::Features {
    let available = adapter.features();
    let mut required = wgpu::Features::empty();
    for &f in wanted {
        if available.contains(f) {
            required |= f;
        }
    }
    required
}

/// Score a physical device for capability-based selection.
fn score_physical_device(device: &super::super::registry::PhysicalDevice) -> u32 {
    let mut score: u32 = match device.device_type {
        wgpu::DeviceType::DiscreteGpu => 100,
        wgpu::DeviceType::IntegratedGpu => 50,
        wgpu::DeviceType::Cpu => 10,
        _ => 5,
    };
    if device.capabilities.f64_shaders {
        score += 30;
    }
    score
}

impl WgpuDevice {
    fn install_error_handler(
        device: &wgpu::Device,
        lost_flag: &Arc<std::sync::atomic::AtomicBool>,
        oom_flag: &Arc<std::sync::atomic::AtomicBool>,
    ) {
        let lost = Arc::clone(lost_flag);
        let oom = Arc::clone(oom_flag);
        device.on_uncaptured_error(Arc::new(move |error: wgpu::Error| {
            let msg = error.to_string();
            if msg.contains("lost") || msg.contains("Lost") || msg.contains("Parent device") {
                lost.store(true, std::sync::atomic::Ordering::Release);
                tracing::warn!("GPU device lost (flagged for pool recovery): {msg}");
                return;
            }
            let lower = msg.to_lowercase();
            if lower.contains("out of memory")
                || lower.contains("allocation failed")
                || lower.contains("not enough memory")
            {
                oom.store(true, std::sync::atomic::Ordering::Release);
                tracing::warn!("GPU OOM detected (flagged for pool migration): {msg}");
                return;
            }
            tracing::warn!("wgpu uncaptured error (non-fatal): {msg}");
        }));
    }

    /// Pipeline caching is deferred until wgpu provides a safe creation API.
    ///
    /// `create_pipeline_cache` is `unsafe` in wgpu 28 even with `data: None`
    /// because the API cannot distinguish fresh-cache from corrupt-blob at the
    /// type level. Rather than carry an `unsafe` block for a performance-only
    /// optimisation, we return `None` and let wgpu compile pipelines without
    /// caching. The field + accessor remain so caching can be re-enabled
    /// when wgpu evolves the API to be safe.
    fn make_pipeline_cache(_device: &wgpu::Device) -> Option<Arc<wgpu::PipelineCache>> {
        None
    }

    /// Assemble a `WgpuDevice` from already-created wgpu primitives.
    fn assemble(device: wgpu::Device, queue: wgpu::Queue, adapter_info: wgpu::AdapterInfo) -> Self {
        let lost = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let oom = Arc::new(std::sync::atomic::AtomicBool::new(false));
        Self::install_error_handler(&device, &lost, &oom);
        let pipeline_cache = Self::make_pipeline_cache(&device);
        let budget = super::concurrency_budget(adapter_info.device_type);
        let active_encoders = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let wgpu_device = Self {
            device: super::GuardedDeviceHandle::new(device, active_encoders.clone()),
            queue,
            adapter_info,
            calibration: None,
            pipeline_cache,
            lost,
            oom,
            gpu_lock: Arc::new(std::sync::Mutex::new(())),
            active_encoders,
            dispatch_semaphore: Arc::new(super::DispatchSemaphore::new(budget)),
            quota_tracker: None,
        };
        probe::seed_cache_from_heuristics(&wgpu_device);
        wgpu_device
    }

    /// Create new WebGPU device with auto-discovery.
    /// Prefers discrete GPU via `HighPerformance` power preference.
    /// Falls back to integrated GPU, then software rasterizer.
    /// # Errors
    /// Returns [`Err`] if no WGPU adapter is found, or if device creation fails
    /// (e.g., driver initialization, required features/limits not supported).
    pub async fn new() -> Result<Self> {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..Default::default()
        });
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .map_err(|e| BarracudaError::device(format!("No WGPU adapter found: {e}")))?;
        Self::from_adapter(adapter).await
    }

    /// Create device explicitly targeting GPU hardware
    /// # Errors
    /// Returns [`Err`] if no GPU adapter is found (only CPU software rasterizer
    /// available), or if device creation fails.
    pub async fn new_gpu() -> Result<Self> {
        Self::new_with_filter(wgpu::Backends::all(), |info| {
            matches!(
                info.device_type,
                wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu
            )
        })
        .await
        .map_err(|e| BarracudaError::device(format!("No GPU adapter found: {e}")))
    }

    /// Create device explicitly targeting CPU software rasterizer
    /// # Errors
    /// Returns [`Err`] if no CPU software rasterizer adapter is available, or
    /// if device creation fails.
    pub async fn new_cpu() -> Result<Self> {
        Self::new_with_filter(wgpu::Backends::all(), |info| {
            info.device_type == wgpu::DeviceType::Cpu
        })
        .await
        .map_err(|e| BarracudaError::device(format!("No CPU software rasterizer: {e}")))
    }

    /// Create a CPU software-rasterizer device using the adapter's own supported limits.
    /// `new_cpu()` requests `science_limits()` (512 MB storage buffer binding), which
    /// llvmpipe and other software rasterizers cannot satisfy (capped at 128 MB), causing
    /// device creation to fail.  `new_cpu_relaxed()` instead asks for only
    /// `wgpu::Limits::downlevel_defaults()`, which every compliant adapter supports.
    /// Use this constructor in tests and any pipeline that runs on CPU/llvmpipe.
    /// # Errors
    /// Returns [`Err`] if no CPU software rasterizer adapter is available, or
    /// if device creation fails (e.g., required features not supported).
    pub async fn new_cpu_relaxed() -> Result<Self> {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..Default::default()
        });
        let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await;
        let adapter = adapters
            .into_iter()
            .find(|a| a.get_info().device_type == wgpu::DeviceType::Cpu)
            .ok_or_else(|| BarracudaError::device("No CPU software rasterizer available"))?;

        let adapter_info = adapter.get_info();
        tracing::info!(
            "barraCuda (cpu-relaxed): {} ({:?})",
            adapter_info.name,
            adapter_info.device_type
        );

        let required_features = negotiate_features(&adapter, &desired_features());
        let creation_guard = DEVICE_CREATION_LOCK.lock().await;
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("barraCuda cpu-relaxed"),
                required_features,
                required_limits: wgpu::Limits::downlevel_defaults(),
                memory_hints: Default::default(),
                experimental_features: Default::default(),
                trace: Default::default(),
            })
            .await
            .map_err(|e| BarracudaError::device(format!("Failed to create CPU device: {e}")))?;
        drop(creation_guard);

        Ok(Self::assemble(device, queue, adapter_info))
    }

    /// Create device with high-capacity limits (1GB+ buffers)
    /// # Errors
    /// Returns [`Err`] if no adapter is found or if device creation fails with
    /// the requested limits (e.g., adapter cannot satisfy high-capacity limits).
    pub async fn new_high_capacity() -> Result<Self> {
        Self::new_with_limits(super::super::tensor_context::high_capacity_limits()).await
    }

    /// Create device with custom limits
    /// # Errors
    /// Returns [`Err`] if no WGPU adapter is found, or if device creation fails
    /// because the adapter cannot satisfy the requested limits.
    pub async fn new_with_limits(limits: wgpu::Limits) -> Result<Self> {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..Default::default()
        });
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .map_err(|e| BarracudaError::device(format!("No WGPU adapter found: {e}")))?;

        let info = adapter.get_info();
        tracing::info!(
            "BarraCuda (custom-limits): {} ({:?})",
            info.name,
            info.device_type
        );

        let required_features = negotiate_features(&adapter, &desired_features_extended());
        let creation_guard = DEVICE_CREATION_LOCK.lock().await;
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("BarraCuda custom-limits device"),
                required_features,
                required_limits: limits,
                memory_hints: Default::default(),
                experimental_features: Default::default(),
                trace: Default::default(),
            })
            .await
            .map_err(|e| BarracudaError::device(format!("Failed to create device: {e}")))?;
        drop(creation_guard);

        let actual_limits = device.limits();
        tracing::info!(
            "Limits: max_binding={}MB, max_buffer={}MB",
            actual_limits.max_storage_buffer_binding_size / (1 << 20),
            actual_limits.max_buffer_size / (1 << 20),
        );

        Ok(Self::assemble(device, queue, info))
    }

    /// Capability-scored adapter discovery.
    /// Scores all available adapters by hardware capabilities (discrete > integrated,
    /// f64 support, memory limits) and returns the best one. Respects the
    /// `BARRACUDA_GPU_ADAPTER` env var override when set.
    /// # Errors
    /// Returns [`Err`] if adapter selection fails (env override invalid, physical
    /// device index out of bounds), or if device creation fails.
    pub async fn discover_best_adapter() -> Result<Self> {
        if let Ok(selector) = std::env::var(ADAPTER_ENV_VAR)
            && !selector.is_empty()
            && selector.to_lowercase() != "auto"
        {
            tracing::info!("discover_best_adapter: env override → {selector}");
            return Self::with_adapter_selector(&selector).await;
        }

        let registry = super::super::registry::DeviceRegistry::global();
        let best = registry
            .physical_devices()
            .enumerate()
            .map(|(idx, dev)| (idx, score_physical_device(dev)))
            .max_by_key(|&(_, s)| s);

        if let Some((idx, score)) = best {
            tracing::info!("discover_best_adapter: physical device {idx} (score {score})");
            Self::from_physical_device(idx).await
        } else {
            Self::new().await
        }
    }

    /// Discover primary and optional secondary adapters for multi-GPU workloads.
    /// Returns `(primary, Option<secondary>)`. The primary is always the
    /// highest-scoring adapter; the secondary is the next best *different*
    /// physical device (if one exists).
    /// # Errors
    /// Returns [`Err`] if primary device creation fails (no adapters, physical
    /// device index out of bounds, or device creation error).
    pub async fn discover_primary_and_secondary_adapters() -> Result<(Self, Option<Self>)> {
        let registry = super::super::registry::DeviceRegistry::global();
        let mut scored: Vec<(usize, u32)> = registry
            .physical_devices()
            .enumerate()
            .map(|(idx, dev)| (idx, score_physical_device(dev)))
            .collect();
        scored.sort_by_key(|entry| std::cmp::Reverse(entry.1));

        let primary = if let Some((idx, _)) = scored.first() {
            Self::from_physical_device(*idx).await?
        } else {
            Self::new().await?
        };

        let secondary = if scored.len() > 1 {
            match Self::from_physical_device(scored[1].0).await {
                Ok(dev) => Some(dev),
                Err(e) => {
                    tracing::debug!("secondary adapter unavailable: {e}");
                    None
                }
            }
        } else {
            None
        };

        Ok((primary, secondary))
    }

    /// List all available WGPU adapters (raw, may include duplicates)
    pub async fn enumerate_adapters() -> Vec<wgpu::AdapterInfo> {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..Default::default()
        });
        instance
            .enumerate_adapters(wgpu::Backends::all())
            .await
            .iter()
            .map(wgpu::Adapter::get_info)
            .collect()
    }

    /// List unique physical devices (deduplicated by hardware)
    #[must_use]
    pub fn enumerate_physical_devices() -> Vec<super::super::registry::PhysicalDevice> {
        super::super::registry::DeviceRegistry::global()
            .physical_devices()
            .cloned()
            .collect()
    }

    /// Get the global device registry
    #[must_use]
    pub fn registry() -> &'static super::super::registry::DeviceRegistry {
        super::super::registry::DeviceRegistry::global()
    }

    /// Create device from a physical device index (using preferred backend)
    /// # Errors
    /// Returns [`Err`] if the physical device index is out of bounds, or if
    /// device creation fails.
    pub async fn from_physical_device(index: usize) -> Result<Self> {
        let registry = super::super::registry::DeviceRegistry::global();
        let adapter_index = registry.get_preferred_adapter_index(index).ok_or_else(|| {
            BarracudaError::device(format!(
                "Physical device index {} out of bounds (only {} devices available)",
                index,
                registry.device_count()
            ))
        })?;
        Self::from_adapter_index(adapter_index).await
    }

    /// Create device from a physical device with explicit backend
    /// # Errors
    /// Returns [`Err`] if the requested backend is not available for the given
    /// device index, or if device creation fails.
    pub async fn from_physical_device_with_backend(
        device_index: usize,
        backend: wgpu::Backend,
    ) -> Result<Self> {
        let registry = super::super::registry::DeviceRegistry::global();
        let adapter_index = registry
            .get_adapter_for_backend(device_index, backend)
            .ok_or_else(|| {
                let device = registry.get_device(device_index);
                let backends: Vec<_> = device
                    .map(|d| {
                        d.backends
                            .iter()
                            .map(|b| format!("{:?}", b.backend))
                            .collect()
                    })
                    .unwrap_or_default();
                BarracudaError::device(format!(
                    "Backend {backend:?} not available for device {device_index} (available: {backends:?})"
                ))
            })?;
        Self::from_adapter_index(adapter_index).await
    }

    /// Create device for the first f64-capable GPU (using preferred backend)
    /// # Errors
    /// Returns [`Err`] if no f64-capable GPU is found (NVIDIA Pascal+, AMD GCN+,
    /// or Intel required), or if device creation fails for the selected adapter.
    pub async fn new_f64_capable() -> Result<Self> {
        let registry = super::super::registry::DeviceRegistry::global();
        for (idx, device) in registry.physical_devices().enumerate() {
            if device.capabilities.f64_shaders
                && matches!(
                    device.device_type,
                    wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu
                )
            {
                return Self::from_physical_device(idx).await;
            }
        }
        Err(BarracudaError::device(
            "No f64-capable GPU found (NVIDIA Pascal+, AMD GCN+, or Intel required)",
        ))
    }

    /// Create device using `BARRACUDA_GPU_ADAPTER` environment variable
    /// # Errors
    /// Returns [`Err`] if adapter selection fails (no adapters, selector does not
    /// match any adapter), or if device creation fails.
    pub async fn from_env() -> Result<Self> {
        let selector = std::env::var(ADAPTER_ENV_VAR).unwrap_or_else(|_| "auto".to_string());
        Self::with_adapter_selector(&selector).await
    }

    /// Create device with explicit adapter selector
    /// # Errors
    /// Returns [`Err`] if no adapters are available, the selector (index or name
    /// substring) does not match any adapter, or if device creation fails.
    pub async fn with_adapter_selector(selector: &str) -> Result<Self> {
        let selector = selector.trim().to_lowercase();

        if selector == "auto" || selector.is_empty() {
            tracing::info!("Adapter selection: auto (HighPerformance)");
            return Self::new().await;
        }

        let adapters = Self::enumerate_adapters().await;
        if adapters.is_empty() {
            return Err(BarracudaError::device("No adapters available"));
        }

        if let Ok(index) = selector.parse::<usize>() {
            if index < adapters.len() {
                tracing::info!(
                    "Adapter selection: index {} → {}",
                    index,
                    adapters[index].name
                );
                return Self::from_adapter_index(index).await;
            }
            tracing::debug!(
                "Adapter index {} out of bounds ({}), trying name match",
                index,
                adapters.len()
            );
        }

        for (index, info) in adapters.iter().enumerate() {
            if info.name.to_lowercase().contains(&selector) {
                tracing::info!(
                    "Adapter selection: '{}' → {} (index {})",
                    selector,
                    info.name,
                    index
                );
                return Self::from_adapter_index(index).await;
            }
        }

        let available: Vec<_> = adapters.iter().map(|a| a.name.as_str()).collect();
        Err(BarracudaError::device(format!(
            "No adapter matches '{selector}'. Available: {available:?}"
        )))
    }

    /// Create with specific backend (for testing/multi-GPU)
    /// Prefers `HighPerformance` adapter within the specified backends.
    /// # Errors
    /// Returns [`Err`] if no WGPU adapter is found for the requested backend(s),
    /// or if device creation fails.
    pub async fn new_with_backend(backends: wgpu::Backends) -> Result<Self> {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends,
            ..Default::default()
        });

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await
            .map_err(|e| {
                BarracudaError::device(format!("No WGPU adapter found for requested backend: {e}"))
            })?;

        Self::from_adapter(adapter).await
    }

    /// Create device from a specific adapter index
    /// # Errors
    /// Returns [`Err`] if the adapter index is out of bounds, or if device
    /// creation fails (e.g., required features/limits not supported).
    pub async fn from_adapter_index(index: usize) -> Result<Self> {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..Default::default()
        });
        let adapters: Vec<wgpu::Adapter> = instance.enumerate_adapters(wgpu::Backends::all()).await;
        if index >= adapters.len() {
            return Err(BarracudaError::device(format!(
                "Adapter index {index} out of bounds (only {} adapters available)",
                adapters.len()
            )));
        }

        let adapter = &adapters[index];
        let info = adapter.get_info();
        tracing::info!(
            "Selecting adapter {index}: {} ({:?})",
            info.name,
            info.device_type
        );

        let required_features = negotiate_features(adapter, &desired_features_extended());
        let creation_guard = DEVICE_CREATION_LOCK.lock().await;
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("BarraCuda device"),
                required_features,
                required_limits: super::super::tensor_context::science_limits(),
                memory_hints: Default::default(),
                experimental_features: Default::default(),
                trace: Default::default(),
            })
            .await
            .map_err(|e| BarracudaError::device(format!("Failed to create device: {e}")))?;
        drop(creation_guard);

        Ok(Self::assemble(device, queue, info))
    }

    /// Create with custom filter (for specific GPU selection)
    /// # Errors
    /// Returns [`Err`] if no WGPU adapters are found for the given backends, no
    /// adapter matches the filter, or if device creation fails.
    pub async fn new_with_filter<F>(backends: wgpu::Backends, filter: F) -> Result<Self>
    where
        F: Fn(&wgpu::AdapterInfo) -> bool,
    {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends,
            ..Default::default()
        });

        let adapters = instance.enumerate_adapters(backends).await;
        if adapters.is_empty() {
            return Err(BarracudaError::device(
                "No WGPU adapters found (need GPU or CPU software rasterizer)",
            ));
        }

        let adapter = adapters
            .into_iter()
            .find(|a: &wgpu::Adapter| filter(&a.get_info()))
            .ok_or_else(|| BarracudaError::device("No adapter matching requested hardware type"))?;

        Self::from_adapter(adapter).await
    }

    /// Create device from a pre-selected adapter (shared helper).
    async fn from_adapter(adapter: wgpu::Adapter) -> Result<Self> {
        let adapter_info = adapter.get_info();
        tracing::info!(
            "barraCuda initialized: {} ({:?})",
            adapter_info.name,
            adapter_info.device_type
        );

        let required_features = negotiate_features(&adapter, &desired_features_extended());
        if required_features.contains(wgpu::Features::SHADER_F64) {
            tracing::info!("  SHADER_F64: enabled");
        }

        let creation_guard = DEVICE_CREATION_LOCK.lock().await;
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("barraCuda Device"),
                required_features,
                required_limits: super::super::tensor_context::science_limits(),
                memory_hints: Default::default(),
                experimental_features: Default::default(),
                trace: Default::default(),
            })
            .await
            .map_err(|e| BarracudaError::device(format!("Failed to create device: {e}")))?;
        drop(creation_guard);

        let wgpu_device = Self::assemble(device, queue, adapter_info);

        if wgpu_device
            .device
            .features()
            .contains(wgpu::Features::SHADER_F64)
        {
            let caps = probe::probe_f64_builtins(&wgpu_device).await;
            if caps.can_compile_f64() {
                tracing::info!("f64 probe: {}/{} builtins native", caps.native_count(), 9);
            } else {
                tracing::warn!(
                    "SHADER_F64 advertised but basic f64 probe FAILED — all f64 shaders will use DF64 fallback"
                );
            }
        }

        Ok(wgpu_device)
    }

    /// Create `WgpuDevice` from existing wgpu device and queue.
    /// In wgpu 28 `Device` and `Queue` are Clone (internally Arc'd),
    /// so no outer Arc is needed.
    #[must_use]
    pub fn from_existing(
        device: wgpu::Device,
        queue: wgpu::Queue,
        adapter_info: wgpu::AdapterInfo,
    ) -> Self {
        let lost = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let oom = Arc::new(std::sync::atomic::AtomicBool::new(false));
        Self::install_error_handler(&device, &lost, &oom);
        let pipeline_cache = Self::make_pipeline_cache(&device);
        let budget = super::concurrency_budget(adapter_info.device_type);
        let active_encoders = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let wgpu_device = Self {
            device: super::GuardedDeviceHandle::new(device, active_encoders.clone()),
            queue,
            adapter_info,
            calibration: None,
            pipeline_cache,
            lost,
            oom,
            gpu_lock: Arc::new(std::sync::Mutex::new(())),
            active_encoders,
            dispatch_semaphore: Arc::new(super::DispatchSemaphore::new(budget)),
            quota_tracker: None,
        };
        probe::seed_cache_from_heuristics(&wgpu_device);
        wgpu_device
    }
}