use std::sync::{Arc, OnceLock};
const GPU_TEST_BUDGET_CPU: u32 = 2;
const GPU_TEST_BUDGET_IGPU: u32 = 4;
const GPU_TEST_BUDGET_DGPU: u32 = 8;
const GPU_TEST_BUDGET_ENV: &str = "BARRACUDA_TEST_GPU_BUDGET";
static GPU_GATE: OnceLock<GpuTestGate> = OnceLock::new();
static CORAL_AVAILABLE: OnceLock<bool> = OnceLock::new();
pub struct GpuTestGate {
semaphore: Arc<tokio::sync::Semaphore>,
budget: u32,
}
impl GpuTestGate {
fn new(budget: u32) -> Self {
Self {
semaphore: Arc::new(tokio::sync::Semaphore::new(budget as usize)),
budget,
}
}
pub async fn acquire(&self) -> tokio::sync::SemaphorePermit<'_> {
self.semaphore
.acquire()
.await
.expect("GPU test gate semaphore closed unexpectedly")
}
pub async fn acquire_owned(&self) -> tokio::sync::OwnedSemaphorePermit {
Arc::clone(&self.semaphore)
.acquire_owned()
.await
.expect("GPU test gate semaphore closed unexpectedly")
}
pub fn acquire_owned_blocking(&self) -> tokio::sync::OwnedSemaphorePermit {
Arc::clone(&self.semaphore)
.try_acquire_owned()
.unwrap_or_else(|_| crate::runtime::tokio_block_on(self.acquire_owned()))
}
#[must_use]
pub fn budget(&self) -> u32 {
self.budget
}
}
impl std::fmt::Debug for GpuTestGate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GpuTestGate")
.field("budget", &self.budget)
.field("available", &self.semaphore.available_permits())
.finish()
}
}
fn resolve_budget() -> u32 {
if let Ok(val) = std::env::var(GPU_TEST_BUDGET_ENV)
&& let Ok(n) = val.parse::<u32>()
&& n > 0
{
return n;
}
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
..Default::default()
});
let adapters =
crate::runtime::tokio_block_on(instance.enumerate_adapters(wgpu::Backends::all()));
if let Some(adapter) = adapters.first() {
let info = adapter.get_info();
match info.device_type {
wgpu::DeviceType::DiscreteGpu => GPU_TEST_BUDGET_DGPU,
wgpu::DeviceType::IntegratedGpu => GPU_TEST_BUDGET_IGPU,
wgpu::DeviceType::Cpu => GPU_TEST_BUDGET_CPU,
_ => GPU_TEST_BUDGET_IGPU,
}
} else {
GPU_TEST_BUDGET_CPU
}
}
pub fn global_gate() -> &'static GpuTestGate {
GPU_GATE.get_or_init(|| {
let budget = resolve_budget();
tracing::debug!(budget, "GPU test gate initialized");
GpuTestGate::new(budget)
})
}
pub async fn gpu_section<F, Fut, T>(f: F) -> T
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = T>,
{
let _permit = global_gate().acquire().await;
f().await
}
pub async fn coral_available() -> bool {
if let Some(&cached) = CORAL_AVAILABLE.get() {
return cached;
}
let available = super::coral_compiler::probe_health().await;
*CORAL_AVAILABLE.get_or_init(|| available)
}
pub async fn with_coral<F, Fut, T>(f: F) -> Option<T>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = T>,
{
if coral_available().await {
Some(f().await)
} else {
None
}
}
static CORAL_CPU_AVAILABLE: OnceLock<bool> = OnceLock::new();
static CORAL_VALIDATE_AVAILABLE: OnceLock<bool> = OnceLock::new();
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShaderValidationBackend {
CoralReef,
Llvmpipe,
}
pub async fn shader_validation_backend() -> ShaderValidationBackend {
let coral_cpu = if let Some(&cached) = CORAL_CPU_AVAILABLE.get() {
cached
} else {
let available = coral_available().await
&& super::coral_compiler::global_coral()
.supports_cpu_execution()
.await;
*CORAL_CPU_AVAILABLE.get_or_init(|| available)
};
if coral_cpu {
ShaderValidationBackend::CoralReef
} else {
ShaderValidationBackend::Llvmpipe
}
}
pub async fn coral_validation_available() -> bool {
if let Some(&cached) = CORAL_VALIDATE_AVAILABLE.get() {
return cached;
}
let available = coral_available().await
&& super::coral_compiler::global_coral()
.supports_validation()
.await;
*CORAL_VALIDATE_AVAILABLE.get_or_init(|| available)
}
#[cfg(feature = "gpu")]
pub fn validate_wgsl_shader(wgsl_source: &str) -> crate::error::Result<()> {
use crate::error::BarracudaError;
let module = naga::front::wgsl::parse_str(wgsl_source)
.map_err(|e| BarracudaError::shader_compilation(format!("parse: {e}")))?;
let mut validator = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
);
validator
.validate(&module)
.map_err(|e| BarracudaError::shader_compilation(format!("validate: {e}")))?;
Ok(())
}
#[cfg(feature = "gpu")]
pub fn validate_df64_shader(shader_body: &str) -> crate::error::Result<()> {
let df64_core = include_str!("../shaders/math/df64_core.wgsl");
let df64_trans = include_str!("../shaders/math/df64_transcendentals.wgsl");
let full_source = format!("{df64_core}\n{df64_trans}\n{shader_body}");
validate_wgsl_shader(&full_source)
}
#[cfg(feature = "gpu")]
#[must_use]
pub fn validate_shader_batch<'a>(
shaders: &'a [(&'a str, &'a str)],
) -> Vec<(&'a str, crate::error::Result<()>)> {
shaders
.iter()
.map(|(name, source)| (*name, validate_wgsl_shader(source)))
.collect()
}
#[cfg(feature = "gpu")]
#[must_use]
pub fn fused_ops_healthy(device: &std::sync::Arc<super::WgpuDevice>) -> bool {
let data = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
match crate::ops::variance_f64_wgsl::VarianceF64::new(std::sync::Arc::clone(device)) {
Ok(var_op) => match var_op.variance(&data) {
Ok(v) => v.is_finite() && v > 0.1,
Err(_) => false,
},
Err(_) => false,
}
}
#[cfg(feature = "gpu")]
#[must_use]
pub fn is_software_adapter(device: &super::WgpuDevice) -> bool {
let info = device.adapter_info();
info.device_type == wgpu::DeviceType::Cpu
|| info.driver.to_lowercase().contains("llvmpipe")
|| info.driver.to_lowercase().contains("lavapipe")
|| info.name.to_lowercase().contains("swiftshader")
}
#[must_use]
pub fn baseline_path(relative: &str) -> Option<std::path::PathBuf> {
std::env::var("CARGO_MANIFEST_DIR")
.ok()
.map(|dir| std::path::PathBuf::from(dir).join(relative))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn budget_resolves_positive() {
let budget = resolve_budget();
assert!(budget > 0, "budget should be positive: {budget}");
assert!(budget <= 128, "budget should be bounded: {budget}");
}
#[test]
fn global_gate_is_consistent() {
let gate1 = global_gate();
let gate2 = global_gate();
assert_eq!(gate1.budget(), gate2.budget());
}
#[tokio::test]
async fn gpu_section_executes_closure() {
let result = gpu_section(|| async { 42 }).await;
assert_eq!(result, 42);
}
#[tokio::test]
async fn gpu_section_concurrent_bounded() {
let gate = global_gate();
let budget = gate.budget() as usize;
let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(budget));
let mut handles = Vec::with_capacity(budget);
for _ in 0..budget {
let b = barrier.clone();
handles.push(tokio::spawn(gpu_section(move || async move {
b.wait().await;
true
})));
}
for h in handles {
assert!(h.await.unwrap());
}
}
#[tokio::test]
async fn coral_probe_is_cached() {
let a = coral_available().await;
let b = coral_available().await;
assert_eq!(a, b, "coral probe should return cached result");
}
#[cfg(feature = "gpu")]
#[test]
fn validate_wgsl_shader_accepts_valid() {
let wgsl = "@compute @workgroup_size(64) fn main() {}";
assert!(validate_wgsl_shader(wgsl).is_ok());
}
#[cfg(feature = "gpu")]
#[test]
fn validate_wgsl_shader_rejects_invalid() {
let bad = "fn main() { let x = ; }";
assert!(validate_wgsl_shader(bad).is_err());
}
#[cfg(feature = "gpu")]
#[test]
fn validate_shader_batch_mixed() {
let shaders = vec![
("valid", "@compute @workgroup_size(64) fn main() {}"),
("invalid", "fn main() { let x = ; }"),
];
let results = validate_shader_batch(&shaders);
assert!(results[0].1.is_ok());
assert!(results[1].1.is_err());
}
}