From d48874d56d3b4e754944bd25c1b83501f220db59 Mon Sep 17 00:00:00 2001 From: RoachxD <5047869+RoachxD@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:39 +0200 Subject: [PATCH] feat: add opt-in D3D12 pipeline validation diagnostics --- crates/victory-gpu/src/host.rs | 27 ++- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/pipeline/host.rs | 11 +- crates/victory-gpu/src/pso_trace.rs | 238 ++++++++++++++++++++++++ docs/d3d12-pso-diagnostics.md | 9 + 5 files changed, 277 insertions(+), 10 deletions(-) create mode 100644 crates/victory-gpu/src/pso_trace.rs create mode 100644 docs/d3d12-pso-diagnostics.md diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d5066d069b..219faa12a2 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -555,11 +555,16 @@ fn create() -> windows::core::Result { unsafe { // The debug layer only in builds with diagnostics. let debug = - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); + cfg!(feature = "diagnostics") && (std::env::var_os("VICTORY_D3D12_DEBUG").is_some() || crate::pso_trace::enabled()); if debug { let mut layer: Option = None; match D3D12GetDebugInterface(&mut layer) { - Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Ok(()) => { + layer.iter().for_each(|l| l.EnableDebugLayer()); + if crate::pso_trace::enabled() { + tracing::info!(interface = layer.is_some(), "PSOTRACE1 debug layer requested before device creation; EnableDebugLayer called if interface present"); + } + }, Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), } // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range @@ -632,9 +637,13 @@ fn create() -> windows::core::Result { tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); } - let messages = debug - .then(|| device.cast::().ok()) - .flatten(); + let messages = debug.then(|| match device.cast::() { + Ok(q) => Some(q), + Err(e) => { + if crate::pso_trace::enabled() { tracing::warn!(error = %e, "PSOTRACE1 InfoQueue cast failed"); } + None + } + }).flatten(); let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() @@ -658,6 +667,8 @@ fn create() -> windows::core::Result { let adapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) .ok(); + // Register after fallible initialization; the Host singleton lives until process exit. + crate::pso_trace::register(&device, messages.as_ref()); tracing::info!("host D3D12 device ready"); Ok(Host { device, @@ -4945,7 +4956,11 @@ impl Host { let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); let text = String::from_utf8_lossy(text); let text = text.trim_end_matches('\0'); - tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}"); + if crate::pso_trace::enabled() { + crate::pso_trace::queued(m, text); + } else { + tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}"); + } if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { first_error = Some(text.to_owned()); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 45a03a3fa5..a2f08ceedf 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -41,6 +41,8 @@ pub mod list; pub mod object; pub mod pipeline; #[cfg(windows)] +mod pso_trace; +#[cfg(windows)] mod primitive; pub mod query; pub mod queue; diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 499792fb71..75d9a59c59 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -547,7 +547,10 @@ impl HostPipeline { } bound.push(stage); } - let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + let make_root = || root_signature(&host.device, ¶ms, &samplers, compute.is_some()); + let (root, root_blob) = match if let Some(cs) = compute { + crate::pso_trace::call(&cs.hash, "root", make_root) + } else { make_root() } { Ok(root) => root, Err(e) => { tracing::warn!(error = %e, ?shaders, "host root signature refused"); @@ -563,7 +566,7 @@ impl HostPipeline { }, ) }; - if compute.is_some() { + if let Some(cs) = compute { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, @@ -574,9 +577,9 @@ impl HostPipeline { let made = super::library::pipeline( &name, // SAFETY: the description points at live data. - |library, name| unsafe { library.LoadComputePipeline(name, &desc) }, + |library, name| crate::pso_trace::call(&cs.hash, "load", || unsafe { library.LoadComputePipeline(name, &desc) }), // SAFETY: as above. - || unsafe { host.device.CreateComputePipelineState(&desc) }, + || crate::pso_trace::call(&cs.hash, "create", || unsafe { host.device.CreateComputePipelineState(&desc) }), ); let pso = match made { Ok(pso) => pso, diff --git a/crates/victory-gpu/src/pso_trace.rs b/crates/victory-gpu/src/pso_trace.rs new file mode 100644 index 0000000000..c9335e5c91 --- /dev/null +++ b/crates/victory-gpu/src/pso_trace.rs @@ -0,0 +1,238 @@ +//! Opt-in CPU-side D3D12 validation diagnostics. Callback attribution is +//! temporal and thread-local, never proof of causality. +use std::cell::Cell; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::{Interface, PCSTR}; + +static NEXT: AtomicU64 = AtomicU64::new(1); +static CACHE_MESSAGES: AtomicU64 = AtomicU64::new(0); +static CACHE_RESULTS: AtomicU64 = AtomicU64::new(0); +static SUCCESSES: AtomicU64 = AtomicU64::new(0); +static SCOPED: AtomicU64 = AtomicU64::new(0); +static UNSCOPED: AtomicU64 = AtomicU64::new(0); +static FAILURES: AtomicU64 = AtomicU64::new(0); +static QUEUED: AtomicU64 = AtomicU64::new(0); +static REGISTERED: OnceLock = OnceLock::new(); + +pub(crate) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + cfg!(feature = "diagnostics") + && *ON.get_or_init(|| std::env::var_os("VICTORY_D3D12_PSO_TRACE").is_some_and(|v| v == "1")) +} + +#[derive(Clone, Copy)] +struct Attempt { + id: u64, + hash: u64, + phase: &'static str, + selected: bool, +} +thread_local! { static CURRENT: Cell> = const { Cell::new(None) }; } +struct Restore(Option); +impl Drop for Restore { + fn drop(&mut self) { + let _ = CURRENT.try_with(|c| c.set(self.0)); + } +} + +fn selected(hash: &str) -> bool { + static FILTER: OnceLock> = OnceLock::new(); + FILTER + .get_or_init(|| { + std::env::var_os("VICTORY_D3D12_PSO_ONLY").map(|v| v.into_string().unwrap_or_default()) + }) + .as_ref() + .is_none_or(|f| f.split(',').any(|h| h.trim().eq_ignore_ascii_case(hash))) +} + +fn permit(counter: &AtomicU64, limit: u64, group: &str) -> bool { + let n = counter.fetch_add(1, Ordering::Relaxed); + if n == limit { + tracing::warn!(group, limit, "PSOTRACE1 further messages suppressed"); + } + n < limit +} + +pub(crate) fn call( + hash: &str, + phase: &'static str, + f: impl FnOnce() -> windows::core::Result, +) -> windows::core::Result { + if !enabled() { + return f(); + } + let Some(hash_value) = u64::from_str_radix(hash, 16).ok() else { + return f(); + }; + let attempt = Attempt { + id: NEXT.fetch_add(1, Ordering::Relaxed), + hash: hash_value, + phase, + selected: selected(hash), + }; + let _restore = Restore(CURRENT.with(|c| c.replace(Some(attempt)))); + let result = f(); + if attempt.selected { + match &result { + Err(e) if phase == "load" && permit(&CACHE_RESULTS, 128, "cache misses") => { + tracing::debug!(attempt = attempt.id, shader = %format_args!("{:016x}", attempt.hash), phase, hresult = %format_args!("0x{:08x}", e.code().0 as u32), "PSOTRACE1 cache load failed"); + } + Err(e) if phase != "load" && permit(&FAILURES, 128, "root/create failures") => { + tracing::warn!(attempt = attempt.id, shader = %format_args!("{:016x}", attempt.hash), phase, hresult = %format_args!("0x{:08x}", e.code().0 as u32), "PSOTRACE1 call failed"); + } + Ok(_) if permit(&SUCCESSES, 256, "successful calls") => { + tracing::info!(attempt = attempt.id, shader = %format_args!("{:016x}", attempt.hash), phase, "PSOTRACE1 call succeeded"); + } + _ => {} + } + } + result +} + +unsafe extern "system" fn callback( + category: D3D12_MESSAGE_CATEGORY, + severity: D3D12_MESSAGE_SEVERITY, + id: D3D12_MESSAGE_ID, + description: PCSTR, + _: *mut core::ffi::c_void, +) { + // Never call D3D12 from a callback or unwind through the ABI. + let _ = std::panic::catch_unwind(|| { + if severity.0 > D3D12_MESSAGE_SEVERITY_WARNING.0 { + return; + } + let attempt = CURRENT.try_with(Cell::get).ok().flatten(); + if attempt.is_some_and(|a| !a.selected) { + return; + } + let cache_miss = attempt.is_some_and(|a| a.phase == "load") && id.0 == 971; + let allowed = if cache_miss { + permit(&CACHE_MESSAGES, 128, "cache validation") + } else if attempt.is_some() { + permit(&SCOPED, 256, "scoped validation") + } else { + permit(&UNSCOPED, 64, "unscoped validation") + }; + if !allowed { + return; + } + let bytes = if description.is_null() { + &[][..] + } else { + // SAFETY: D3D12 supplies a NUL-terminated string valid in the callback. + unsafe { std::ffi::CStr::from_ptr(description.0.cast()).to_bytes() } + }; + let text = String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]); + if let Some(a) = attempt { + if cache_miss { + tracing::debug!(attempt = a.id, shader = %format_args!("{:016x}", a.hash), phase = a.phase, category = category.0, severity = severity.0, id = id.0, truncated = bytes.len() > 4096, "PSOTRACE1 same-thread cache: {text}"); + return; + } + tracing::warn!(attempt = a.id, shader = %format_args!("{:016x}", a.hash), phase = a.phase, category = category.0, severity = severity.0, id = id.0, truncated = bytes.len() > 4096, "PSOTRACE1 same-thread: {text}"); + } else { + tracing::warn!( + category = category.0, + severity = severity.0, + id = id.0, + truncated = bytes.len() > 4096, + "PSOTRACE1 unassigned: {text}" + ); + } + }); +} + +pub(crate) fn register(device: &ID3D12Device, queue: Option<&ID3D12InfoQueue>) { + if !enabled() { + return; + } + // SAFETY: callback uses process-lifetime statics, no borrowed context. + // Host is a process-lifetime singleton; registration lives with its device. + let registered = unsafe { + if let Some(q) = queue { + tracing::info!( + stored = q.GetNumStoredMessages(), + retrievable = q.GetNumStoredMessagesAllowedByRetrievalFilter(), + denied = q.GetNumMessagesDeniedByStorageFilter(), + discarded = q.GetNumMessagesDiscardedByMessageCountLimit(), + "PSOTRACE1 InfoQueue available" + ); + } else { + tracing::warn!("PSOTRACE1 InfoQueue unavailable"); + } + match device.cast::() { + Ok(q) => { + let mut cookie = 0; + match q.RegisterMessageCallback( + Some(callback), + D3D12_MESSAGE_CALLBACK_IGNORE_FILTERS, + std::ptr::null_mut(), + &mut cookie, + ) { + Ok(()) => { + tracing::info!( + cookie, + "PSOTRACE1 InfoQueue1 callback registered (ignore filters)" + ); + true + } + Err(e) => { + tracing::warn!(error = %e, "PSOTRACE1 callback registration failed"); + false + } + } + } + Err(e) => { + tracing::warn!(error = %e, "PSOTRACE1 InfoQueue1 unavailable"); + false + } + } + }; + let _ = REGISTERED.set(registered); +} + +pub(crate) fn queued(m: &D3D12_MESSAGE, text: &str) { + // Legacy queue remains drained for device-removed reporting. Callback + // and queue entries may duplicate each other; queue attribution is unknown. + if !REGISTERED.get().copied().unwrap_or(false) && permit(&QUEUED, 256, "shared queue") { + let end = text.floor_char_boundary(text.len().min(4096)); + tracing::warn!( + id = m.ID.0, + severity = m.Severity.0, + category = m.Category.0, + truncated = end < text.len(), + "PSOTRACE1 shared queue (ambiguous): {}", + &text[..end] + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn bounded_counter_and_nested_scope() { + let n = AtomicU64::new(0); + assert!(permit(&n, 1, "test")); + assert!(!permit(&n, 1, "test")); + let outer = Attempt { + id: 1, + hash: 2, + phase: "outer", + selected: true, + }; + let inner = Attempt { id: 2, ..outer }; + let _outer = Restore(CURRENT.with(|c| c.replace(Some(outer)))); + { + let _inner = Restore(CURRENT.with(|c| c.replace(Some(inner)))); + assert_eq!(CURRENT.with(Cell::get).unwrap().id, 2); + } + assert_eq!(CURRENT.with(Cell::get).unwrap().id, 1); + assert!( + std::thread::spawn(|| CURRENT.with(Cell::get).is_none()) + .join() + .unwrap() + ); + } +} diff --git a/docs/d3d12-pso-diagnostics.md b/docs/d3d12-pso-diagnostics.md new file mode 100644 index 0000000000..cd9eb721e8 --- /dev/null +++ b/docs/d3d12-pso-diagnostics.md @@ -0,0 +1,9 @@ +# D3D12 pipeline validation diagnostics + +Build with `--features diagnostics`. Set `VICTORY_D3D12_PSO_TRACE=1` before launching to request the CPU D3D12 debug layer and log pipeline validation. Install Windows Graphics Tools if the debug interface is unavailable. GPU-based validation is separately controlled by the existing `VICTORY_D3D12_GBV` option and is not required. + +Optionally set `VICTORY_D3D12_PSO_ONLY` to a comma-separated list of compute shader hashes to restrict scoped output. The callback still reports a bounded number of unassigned messages. `PSOTRACE1` logs distinguish root, pipeline-library load and new pipeline creation phases. A library miss can be normal. Cache-miss messages use debug level; successful calls use info. The message severity field retains the original D3D12 severity. Quotas bound the number of messages and log when exhausted. + +For example, validation message ID 622 during `phase=create` may report that a shader requires 64 lanes but the device supports at most 32. This diagnoses PSO rejection; successful creation alone does not validate shader output. + +The callback does not call D3D12 and has no borrowed context. It is registered after successful device initialization and remains registered for the lifetime of the process-wide Host singleton. Concurrent callbacks can run on different threads. Same-thread messages are temporally associated with the current call; other messages are unassigned. Queue fallback attribution is ambiguous. Logging may affect debug-run timing; do not use these captures as uninstrumented performance baselines.