From 899c5090a714ec477056401c3d653083dca52356 Mon Sep 17 00:00:00 2001 From: KarolKurzyna <187065594+KarolKurzyna@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:35:31 +0100 Subject: [PATCH 1/2] Shaders: cache refused shaders and DXC failures by capability (#1412) Deterministic DXC failures and upstream translator refusals are currently re-run from scratch on every boot, even though `report.json` logs the exact same refusal set across launches. Add capability-keyed negative cache markers across both layers without poisoning caches across recompiler/DXC fixes or debug overrides: - `dxc.rs`: write `.fail` (`XCLFAIL1` + capability digest of version, `XCL_TRANSLATOR_SOURCE_ID`, and DXC toolchain) only on deterministic DXC refusals (`"dxc: ..."`), replay exact error strings via `CacheCounters::cached_failure` (`cached_failures`), and skip DXC and `CACHED_ONLY` deferrals on hit without bumping `compilations`. - `pso.rs`: write `.fail` (`XCLTRNF1` + `ident`, capability digest covering stage/sampler_base/windows/split, blob len + hash2) in `translated` for deterministic upstream translator and DXC refusals, skipping transient errors and `cached_only` deferrals. - Skip and delete stale/mismatched markers whenever capability-changing or debug env overrides are active (`XCL_SAFE_BARRIER`, `XCL_SPLIT_WAVE64`, `XCL_WAVE64_SPIN`, `XCL_NEGATIVE_CACHE`, `XCL_RECOMP_*`, `XCL_DEBUG_*`). Fixes #1412. Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/dxc.rs | 282 +++++++++++++++++++++++- crates/xcl/src/gpu/recomp/pso.rs | 360 ++++++++++++++++++++++++++++++- 2 files changed, 626 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ec63906c58..5ddc3c3613 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -608,6 +608,8 @@ pub struct CacheStats { /// Compilation attempts, including failures. pub compilations: u64, pub compilation_failures: u64, + /// Deterministic failures satisfied from on-disk negative cache markers without compiling. + pub cached_failures: u64, /// First 20 distinct compiler errors. pub compilation_errors: Vec, } @@ -620,6 +622,7 @@ struct CacheCounters { deferred_misses: AtomicU64, compilations: AtomicU64, compilation_failures: AtomicU64, + cached_failures: AtomicU64, compilation_errors: Mutex>, } @@ -632,15 +635,28 @@ impl CacheCounters { deferred_misses: self.deferred_misses.load(Ordering::Relaxed), compilations: self.compilations.load(Ordering::Relaxed), compilation_failures: self.compilation_failures.load(Ordering::Relaxed), + cached_failures: self.cached_failures.load(Ordering::Relaxed), compilation_errors: self.compilation_errors.lock().unwrap().clone(), } } + fn record_error(&self, error: &str) { + let mut errors = self.compilation_errors.lock().unwrap(); + if errors.len() < 20 && !errors.iter().any(|existing| existing == error) { + errors.push(error.to_string()); + } + } + fn failure(&self, error: String) -> String { self.compilation_failures.fetch_add(1, Ordering::Relaxed); - let mut errors = self.compilation_errors.lock().unwrap(); - if errors.len() < 20 && !errors.contains(&error) { - errors.push(error.clone()); + self.record_error(&error); + error + } + + fn cached_failure(&self, error: String, record_error: bool) -> String { + self.cached_failures.fetch_add(1, Ordering::Relaxed); + if record_error { + self.record_error(&error); } error } @@ -659,6 +675,10 @@ pub(super) fn note_memory_hit() { cache_counters().hits.fetch_add(1, Ordering::Relaxed); } +pub(super) fn note_cached_failure(reason: &str) { + cache_counters().cached_failure(reason.to_string(), reason.starts_with("DXIL cache ")); +} + /// `compile` through a disk cache in `dir` (big translated programs take seconds in DXC; /// the same console shader comes back every run). Returns (DXIL, from cache). pub fn compile_cached_in(dir: &Path, src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { @@ -793,6 +813,93 @@ where compile_cached_in_observed(dir, src, entry, profile, cache_counters(), compile_one) } +const FAIL_MAGIC: &[u8; 8] = b"XCLFAIL1"; +const MAX_FAIL_REASON_BYTES: usize = 64 * 1024; + +pub(super) fn negative_cache_allowed_with(present: impl Fn(&str) -> bool) -> bool { + ![ + "XCL_RECOMP_NO_STRUCTURED", + "XCL_RECOMP_WHY", + "XCL_X64_ALL_MASKS", + "XCL_WAVE64_SPIN", + "XCL_SAFE_BARRIER", + "XCL_SPLIT_WAVE64", + "XCL_DEBUG_MAGENTA", + "XCL_DEBUG_LOD0", + "XCL_DEBUG_PS_SUB", + "XCL_DEBUG_PS_EXPR", + "XCL_NEGATIVE_CACHE", + ] + .iter() + .any(|name| present(name)) +} + +fn is_deterministic_dxc_failure(raw_error: &str) -> bool { + raw_error.starts_with("dxc: ") +} + +fn negative_capability_digest(source_id: &str, toolchain: &str, extra: &[&str]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for part in ["xcl-dxc-fail-v1", env!("CARGO_PKG_VERSION"), source_id, toolchain] + .into_iter() + .chain(extra.iter().copied()) + { + for b in part.bytes().chain([0u8]) { + h ^= b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + } + h +} + +enum FailLookup { + Hit(String), + Stale, + Miss, +} + +fn read_fail_marker(path: &Path, expected_digest: u64) -> FailLookup { + let Ok(bytes) = std::fs::read(path) else { + return FailLookup::Miss; + }; + let Some(rest) = bytes.strip_prefix(FAIL_MAGIC) else { + return FailLookup::Stale; + }; + let Some((digest_bytes, rest)) = rest.split_first_chunk::<8>() else { + return FailLookup::Stale; + }; + let Some((len_bytes, rest)) = rest.split_first_chunk::<4>() else { + return FailLookup::Stale; + }; + let digest = u64::from_le_bytes(*digest_bytes); + let len = u32::from_le_bytes(*len_bytes) as usize; + if digest != expected_digest || len > MAX_FAIL_REASON_BYTES || rest.len() != len { + return FailLookup::Stale; + } + match std::str::from_utf8(rest) { + Ok(reason) => FailLookup::Hit(reason.to_string()), + Err(_) => FailLookup::Stale, + } +} + +fn write_fail_marker(dir: &Path, path: &Path, digest: u64, reason: &str) { + if reason.len() > MAX_FAIL_REASON_BYTES || std::fs::create_dir_all(dir).is_err() { + return; + } + let mut buf = Vec::with_capacity(FAIL_MAGIC.len() + 8 + 4 + reason.len()); + buf.extend_from_slice(FAIL_MAGIC); + buf.extend_from_slice(&digest.to_le_bytes()); + buf.extend_from_slice(&(reason.len() as u32).to_le_bytes()); + buf.extend_from_slice(reason.as_bytes()); + let tmp = path.with_extension(format!("fail.tmp.{}.{:?}", std::process::id(), std::thread::current().id())); + if path.is_file() { + let _ = std::fs::remove_file(path); + } + if std::fs::write(&tmp, &buf).is_ok() && std::fs::rename(&tmp, path).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + fn compile_cached_in_observed( dir: &Path, src: &str, @@ -801,16 +908,47 @@ fn compile_cached_in_observed( counters: &CacheCounters, compile_one: F, ) -> Result<(Vec, bool), String> +where + F: FnOnce() -> Result, String>, +{ + let cap_digest = negative_capability_digest(env!("XCL_TRANSLATOR_SOURCE_ID"), toolchain_identity(), &[]); + let allow_negative = negative_cache_allowed_with(|name| std::env::var_os(name).is_some()); + compile_cached_in_observed_with_capability(dir, src, entry, profile, counters, cap_digest, allow_negative, compile_one) +} + +#[allow(clippy::too_many_arguments)] +fn compile_cached_in_observed_with_capability( + dir: &Path, + src: &str, + entry: &str, + profile: &str, + counters: &CacheCounters, + cap_digest: u64, + allow_negative: bool, + compile_one: F, +) -> Result<(Vec, bool), String> where F: FnOnce() -> Result, String>, { let key = cache_key(src, entry, profile); let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); + let fail_file = dir.join(format!("{key:016x}.fail")); if let Some(b) = cached_file(&file) { counters.hits.fetch_add(1, Ordering::Relaxed); return Ok((b, true)); } + if allow_negative { + match read_fail_marker(&fail_file, cap_digest) { + FailLookup::Hit(reason) => return Err(counters.cached_failure(reason, true)), + FailLookup::Stale => { + let _ = std::fs::remove_file(&fail_file); + } + FailLookup::Miss => {} + } + } else if fail_file.is_file() { + let _ = std::fs::remove_file(&fail_file); + } // before the locks: a cached-only attempt (non-blocking pipeline creation) must not wait // for a worker compiling the same shader if CACHED_ONLY.with(|c| c.get()) { @@ -827,13 +965,22 @@ where counters.coalesced_hits.fetch_add(1, Ordering::Relaxed); return Ok((b, true)); } + if allow_negative { + match read_fail_marker(&fail_file, cap_digest) { + FailLookup::Hit(reason) => return Err(counters.cached_failure(reason, true)), + FailLookup::Stale => { + let _ = std::fs::remove_file(&fail_file); + } + FailLookup::Miss => {} + } + } // A corrupt target must be removed before the atomic rename on Windows; // rename does not replace an existing file there. if file.is_file() { let _ = std::fs::remove_file(&file); } counters.compilations.fetch_add(1, Ordering::Relaxed); - let b = { + let compiled = { let _active = Compiling::start(); compile_one() } @@ -845,12 +992,26 @@ where } }) .map_err(|e| { - counters.failure(format!( + let deterministic = is_deterministic_dxc_failure(&e); + let formatted = counters.failure(format!( "DXIL cache {} ({profile}, entry {entry:?}, {} B HLSL): {e}", file.display(), src.len() - )) - })?; + )); + (formatted, deterministic) + }); + let b = match compiled { + Ok(b) => b, + Err((formatted, deterministic)) => { + if allow_negative && deterministic { + write_fail_marker(&dir, &fail_file, cap_digest, &formatted); + } + return Err(formatted); + } + }; + if fail_file.is_file() { + let _ = std::fs::remove_file(&fail_file); + } if std::fs::create_dir_all(&dir).is_ok() { // write to a temporary name first: another thread / process may be reading let tmp = file.with_extension(format!("tmp{}", std::process::id())); @@ -917,6 +1078,11 @@ pub fn in_cached_only() -> bool { CACHED_ONLY.with(|c| c.get()) } +/// Did the current `cached_only` scope observe any deferred miss? +pub(super) fn has_missed() -> bool { + MISSED.with(|m| m.get()) +} + pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { compile_cached_in(&cache_dir(), src, entry, profile) } @@ -1269,4 +1435,106 @@ mod cache_tests { second_rx.recv_timeout(Duration::from_secs(2)).unwrap(); }); } + + #[test] + fn dxc_deterministic_failures_are_cached_and_replayed() { + let dir = std::env::temp_dir().join(format!("xcl-dxil-neg-hit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let src = "broken hlsl shader"; + let cap = negative_capability_digest("rev-1", "tc-1", &[]); + let counters1 = CacheCounters::default(); + let err1 = compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &counters1, cap, true, || { + Err("dxc: error: undeclared identifier".into()) + }) + .unwrap_err(); + assert_eq!(counters1.snapshot().compilations, 1); + assert_eq!(counters1.snapshot().compilation_failures, 1); + assert_eq!(counters1.snapshot().cached_failures, 0); + + let counters2 = CacheCounters::default(); + let err2 = compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &counters2, cap, true, || { + panic!("cached failure marker must avoid DXC re-invocation") + }) + .unwrap_err(); + assert_eq!(err2, err1); + let stats2 = counters2.snapshot(); + assert_eq!((stats2.compilations, stats2.compilation_failures, stats2.cached_failures), (0, 0, 1)); + assert_eq!(stats2.compilation_errors, vec![err1.clone()]); + + let (probe, missed) = cached_only(|| { + compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &counters2, cap, true, || { + panic!("cached_only must hit negative marker without deferring") + }) + }); + assert_eq!(probe.unwrap_err(), err1); + assert!(!missed); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn dxc_negative_marker_invalidates_on_capability_change_and_env_override() { + let dir = std::env::temp_dir().join(format!("xcl-dxil-neg-inv-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let src = "fixable shader"; + let key = cache_key(src, "main", "cs_6_6"); + let fail_path = dir.join(format!("{key:016x}.fail")); + let cap_old = negative_capability_digest("rev-1", "tc-1", &[]); + let cap_new = negative_capability_digest("rev-2", "tc-1", &[]); + let cap_other = negative_capability_digest("rev-1", "tc-1", &["-opt-disable", "gvn"]); + assert_ne!(cap_old, cap_new); + assert_ne!(cap_old, cap_other); + + let c1 = CacheCounters::default(); + assert!(compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &c1, cap_old, true, || { + Err("dxc: unsupported opcode".into()) + }) + .is_err()); + assert!(fail_path.is_file()); + + // Debugging / capability override skips AND deletes existing marker and never writes a new one. + let c_ovr = CacheCounters::default(); + assert!(compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &c_ovr, cap_old, false, || { + Err("dxc: debug session refusal".into()) + }) + .is_err()); + assert!(!fail_path.is_file(), "override session must delete stale marker and write none"); + assert_eq!(c_ovr.snapshot().compilations, 1); + + // Recreate marker under cap_old, then drift capability digest to cap_new -> invalidates & succeeds. + assert!(compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &CacheCounters::default(), cap_old, true, || { + Err("dxc: still failing under rev-1".into()) + }) + .is_err()); + assert!(fail_path.is_file()); + let c2 = CacheCounters::default(); + let (dxil, hit) = compile_cached_in_observed_with_capability(&dir, src, "main", "cs_6_6", &c2, cap_new, true, || { + Ok(synthetic_dxil(42)) + }) + .unwrap(); + assert!(!hit && dxil == synthetic_dxil(42)); + assert!(!fail_path.is_file(), "successful rebuild under new capability must remove old .fail marker"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn dxc_transient_failures_are_not_negative_cached() { + let dir = std::env::temp_dir().join(format!("xcl-dxil-neg-trans-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let cap = negative_capability_digest("rev-1", "tc-1", &[]); + for (i, msg) in [ + "Compile: E_OUTOFMEMORY", + "DXC: no compile threads", + "dxcompiler.dll not found", + ] + .into_iter() + .enumerate() + { + let src = format!("transient {i}"); + let counters = CacheCounters::default(); + assert!(compile_cached_in_observed_with_capability(&dir, &src, "main", "cs_6_6", &counters, cap, true, || Err(msg.into())).is_err()); + let fail_path = dir.join(format!("{:016x}.fail", cache_key(&src, "main", "cs_6_6"))); + assert!(!fail_path.is_file(), "transient error {msg:?} must not leave a .fail marker"); + } + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c9a50b72b4..f39591c909 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -150,7 +150,18 @@ fn shader_cache() -> &'static Mutex { /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); - if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { + let env_present = |name: &str| std::env::var_os(name).is_some(); + let allow_negative = dxc::negative_cache_allowed_with(env_present); + if !cache_allowed(stage, env_present) { + if !allow_negative { + let ident = translated::identity(); + if ident != 0 { + let fail_path = translated::fail_file(&dxc::cache_dir(), ident, blob, stage, sampler_base, windows, split_wave64); + if fail_path.is_file() { + let _ = std::fs::remove_file(&fail_path); + } + } + } return compile_one().map(|(c, _)| c); } let key = ShaderKey { @@ -163,10 +174,24 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa }; // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, // direct translator version, routing mode): never mixed with the HLSL path's entries - let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); + let from_disk = || translated::cached_with_negative(&dxc::cache_dir(), allow_negative, blob, stage, sampler_base, windows, split_wave64, compile_one); cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone()) } +fn is_cacheable_translation_refusal(err: &str) -> bool { + if err == "DXIL not compiled yet" + || err.contains("dxcompiler.dll not found") + || err.contains("DXC: no compile threads") + || err.contains("DXC: the compile thread exited") + { + return false; + } + if err.starts_with("DXIL cache ") { + return err.contains("): dxc: "); + } + true +} + /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run /// does not translate again what an earlier run of the same XCL build translated. The DXIL /// cache is keyed by the generated HLSL, so it needs the translation first: a retail game's @@ -180,6 +205,14 @@ mod translated { use std::sync::OnceLock; const MAGIC: &[u8; 8] = b"XCLTRAN2"; + const FAIL_MAGIC: &[u8; 8] = b"XCLTRNF1"; + const MAX_FAIL_REASON_BYTES: usize = 64 * 1024; + + pub(super) enum FailLookup { + Hit(String), + Stale, + Miss, + } pub(super) fn identity_for(source: &str, toolchain: &str) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; @@ -239,7 +272,7 @@ mod translated { /// Translation semantics and the DXC DLLs, independent of link metadata and build profile. /// Zero means the disk cache is disabled. - fn identity() -> u64 { + pub(super) fn identity() -> u64 { static I: OnceLock = OnceLock::new(); *I.get_or_init(|| { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { @@ -270,6 +303,25 @@ mod translated { }) } + pub(super) fn capability_digest(ident: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let parts: [&[u8]; 6] = [ + b"xcl-translated-fail-v1", + &ident.to_le_bytes(), + &[stage as u8], + &sampler_base.to_le_bytes(), + &windows.to_le_bytes(), + &[split as u8], + ]; + for part in parts { + for &byte in part { + h ^= byte as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + } + h + } + /// a second hash of the bytes, independent of `fnv64`'s fn hash2(b: &[u8]) -> u64 { b.iter().fold(0x9E37_79B9_7F4A_7C15u64, |h, &x| (h ^ x as u64).wrapping_mul(0xFF51_AFD7_ED55_8CCD).rotate_left(29)) @@ -282,6 +334,10 @@ mod translated { .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", crate::gpu::shader::fnv64(blob), split as u8)) } + pub(super) fn fail_file(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf { + file(dir, ident, blob, stage, sampler_base, windows, split).with_extension("fail") + } + fn header(ident: u64, blob: &[u8]) -> Vec { let mut h = MAGIC.to_vec(); for v in [ident, blob.len() as u64, hash2(blob)] { @@ -337,7 +393,53 @@ mod translated { } } - /// `cached_rerouted` for a translation that is never rerouted (the tests') + fn fail_header(ident: u64, cap_digest: u64, blob: &[u8]) -> Vec { + let mut h = FAIL_MAGIC.to_vec(); + for v in [ident, cap_digest, blob.len() as u64, hash2(blob)] { + h.extend_from_slice(&v.to_le_bytes()); + } + h + } + + pub(super) fn load_fail_in(path: &Path, ident: u64, cap_digest: u64, blob: &[u8]) -> FailLookup { + let Ok(b) = std::fs::read(path) else { + return FailLookup::Miss; + }; + let head = fail_header(ident, cap_digest, blob); + let Some(rest) = b.strip_prefix(head.as_slice()) else { + return FailLookup::Stale; + }; + let Some((len_bytes, rest)) = rest.split_first_chunk::<4>() else { + return FailLookup::Stale; + }; + let len = u32::from_le_bytes(*len_bytes) as usize; + if len > MAX_FAIL_REASON_BYTES || rest.len() != len { + return FailLookup::Stale; + } + match std::str::from_utf8(rest) { + Ok(reason) => FailLookup::Hit(reason.to_string()), + Err(_) => FailLookup::Stale, + } + } + + pub(super) fn store_fail_in(path: &Path, ident: u64, cap_digest: u64, blob: &[u8], reason: &str) { + if reason.len() > MAX_FAIL_REASON_BYTES { + return; + } + let Some(dir) = path.parent() else { return }; + let mut b = fail_header(ident, cap_digest, blob); + b.extend_from_slice(&(reason.len() as u32).to_le_bytes()); + b.extend_from_slice(reason.as_bytes()); + let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); + if path.is_file() { + let _ = std::fs::remove_file(path); + } + if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() { + let _ = std::fs::remove_file(&tmp); + } + } + + /// `cached_rerouted` for a translation that is never rerouted (the tests'). #[cfg(test)] pub(super) fn cached_in( dir: &Path, @@ -348,6 +450,24 @@ mod translated { windows: u32, split: bool, translate: impl FnOnce() -> Result, + ) -> Result { + let cap_digest = capability_digest(ident, stage, sampler_base, windows, split); + cached_in_with_negative(dir, ident, cap_digest, true, blob, stage, sampler_base, windows, split, translate) + } + + #[cfg(test)] + #[allow(clippy::too_many_arguments)] + pub(super) fn cached_in_with_negative( + dir: &Path, + ident: u64, + cap_digest: u64, + allow_negative: bool, + blob: &[u8], + stage: Stage, + sampler_base: u32, + windows: u32, + split: bool, + translate: impl FnOnce() -> Result, ) -> Result { if ident == 0 { return translate(); @@ -357,12 +477,39 @@ mod translated { super::dxc::note_memory_hit(); return Ok(c); } - let c = translate()?; - if !super::dxc::valid_dxil_container(&c.dxil) { - return Err("translated cache: translator returned an invalid DXIL container".into()); + let fail_path = fail_file(dir, ident, blob, stage, sampler_base, windows, split); + if allow_negative { + match load_fail_in(&fail_path, ident, cap_digest, blob) { + FailLookup::Hit(reason) => { + super::dxc::note_cached_failure(&reason); + return Err(reason); + } + FailLookup::Stale => { + let _ = std::fs::remove_file(&fail_path); + } + FailLookup::Miss => {} + } + } else if fail_path.is_file() { + let _ = std::fs::remove_file(&fail_path); + } + match translate() { + Ok(c) => { + if !super::dxc::valid_dxil_container(&c.dxil) { + return Err("translated cache: translator returned an invalid DXIL container".into()); + } + store_in(&path, ident, blob, &c); + if fail_path.is_file() { + let _ = std::fs::remove_file(&fail_path); + } + Ok(c) + } + Err(e) => { + if allow_negative && !super::dxc::has_missed() && super::is_cacheable_translation_refusal(&e) { + store_fail_in(&fail_path, ident, cap_digest, blob, &e); + } + Err(e) + } } - store_in(&path, ident, blob, &c); - Ok(c) } /// `translate` through the disk (`identity()` zero: not used). An enormous compute program @@ -380,6 +527,22 @@ mod translated { cached_rerouted(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, translate) } + /// `translate` with capability-aware refusal markers and the direct-DXIL reroute identity. + pub(super) fn cached_with_negative( + dir: &Path, + allow_negative: bool, + blob: &[u8], + stage: Stage, + sampler_base: u32, + windows: u32, + split: bool, + translate: impl FnOnce() -> Result<(Compiled, bool), String>, + ) -> Result { + let ident = identity(); + let direct = direct_output(); + cached_rerouted_with_negative(dir, ident, direct, allow_negative, blob, stage, sampler_base, windows, split, translate) + } + /// What the direct translator's output depends on besides the HLSL path's identity: its /// version and sources, a forced compact form, the per-lane form (`direct_compute`). fn direct_output() -> u64 { @@ -430,6 +593,63 @@ mod translated { store_in(&file(dir, id, blob, stage, sampler_base, windows, split), id, blob, &c); Ok(c) } + + #[allow(clippy::too_many_arguments)] + fn cached_rerouted_with_negative( + dir: &Path, + ident: u64, + direct: u64, + allow_negative: bool, + blob: &[u8], + stage: Stage, + sampler_base: u32, + windows: u32, + split: bool, + translate: impl FnOnce() -> Result<(Compiled, bool), String>, + ) -> Result { + if ident == 0 { + return translate().map(|(c, _)| c); + } + let rerouted = rerouted_identity(ident, direct); + for id in [ident, rerouted] { + if let Some(c) = load_in(&file(dir, id, blob, stage, sampler_base, windows, split), id, blob) { + super::dxc::note_memory_hit(); + return Ok(c); + } + } + let cap_digest = capability_digest(ident, stage, sampler_base, windows, split); + let fail_path = fail_file(dir, ident, blob, stage, sampler_base, windows, split); + if allow_negative { + match load_fail_in(&fail_path, ident, cap_digest, blob) { + FailLookup::Hit(reason) => { + super::dxc::note_cached_failure(&reason); + return Err(reason); + } + FailLookup::Stale => { + let _ = std::fs::remove_file(&fail_path); + } + FailLookup::Miss => {} + } + } else if fail_path.is_file() { + let _ = std::fs::remove_file(&fail_path); + } + match translate() { + Ok((c, is_direct)) => { + let id = if is_direct { rerouted } else { ident }; + store_in(&file(dir, id, blob, stage, sampler_base, windows, split), id, blob, &c); + if fail_path.is_file() { + let _ = std::fs::remove_file(&fail_path); + } + Ok(c) + } + Err(e) => { + if allow_negative && !super::dxc::has_missed() && super::is_cacheable_translation_refusal(&e) { + store_fail_in(&fail_path, ident, cap_digest, blob, &e); + } + Err(e) + } + } + } } /// A compute program whose HLSL DXC would compile unoptimised (`dxc::UNOPTIMISED_ABOVE`) @@ -1798,6 +2018,128 @@ mod shader_cache_tests { } }); } + + #[test] + fn translated_refusals_are_cached_and_invalidated_by_capability_digest() { + let dir = std::env::temp_dir().join(format!("xcl-pso-neg-cap-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let blob_refused = b"shader-unsupported-atomic"; + let blob_other = b"shader-unrelated"; + let ident = translated::identity_for("src-v1", "tc-1"); + let cap_v1 = translated::capability_digest(ident, Stage::Compute, 0, 4, false); + let cap_v2 = translated::capability_digest(ident, Stage::Compute, 0, 4, true); + let cap_spec_changed = translated::capability_digest(translated::identity_for("src-v2", "tc-1"), Stage::Compute, 0, 4, false); + let cap_direct_v1 = translated::capability_digest(translated::identity_with("src-v1", "tc-1", translated::Backend::DirectCompute, 1), Stage::Compute, 0, 4, false); + let cap_direct_v2 = translated::capability_digest(translated::identity_with("src-v1", "tc-1", translated::Backend::DirectCompute, 2), Stage::Compute, 0, 4, false); + assert_ne!(cap_v1, cap_v2); + assert_ne!(cap_v1, cap_spec_changed); + assert_ne!(cap_v1, cap_direct_v1); + assert_ne!(cap_direct_v1, cap_direct_v2); + + let err1 = translated::cached_in_with_negative(&dir, ident, cap_v1, true, blob_refused, Stage::Compute, 0, 4, false, || { + Err("incomplete translation, missing: [\"image_atomic_add\"]".into()) + }) + .err() + .unwrap(); + assert_eq!(err1, "incomplete translation, missing: [\"image_atomic_add\"]"); + + // Second run with unchanged corpus & capabilities must not re-lower. + let err2 = translated::cached_in_with_negative(&dir, ident, cap_v1, true, blob_refused, Stage::Compute, 0, 4, false, || { + panic!("refusal marker must short-circuit before re-lowering") + }) + .err() + .unwrap(); + assert_eq!(err2, err1); + + // Create a marker for an unrelated shader to confirm invalidating blob_refused leaves it alone. + let other_err = translated::cached_in_with_negative(&dir, ident, cap_v1, true, blob_other, Stage::Compute, 0, 4, false, || { + Err("incomplete translation, missing: [\"other_op\"]".into()) + }) + .err() + .unwrap(); + assert_eq!(other_err, "incomplete translation, missing: [\"other_op\"]"); + + // Capability change invalidates only the affected marker while preserving unrelated ones. + let rebuilt = translated::cached_in_with_negative(&dir, ident, cap_v2, true, blob_refused, Stage::Compute, 0, 4, false, || { + Ok(compiled(77)) + }) + .unwrap(); + assert_eq!(rebuilt.dxil[0], 77); + assert!(!translated::fail_file(&dir, ident, blob_refused, Stage::Compute, 0, 4, false).is_file()); + + let still_cached = translated::cached_in_with_negative(&dir, ident, cap_v1, true, blob_other, Stage::Compute, 0, 4, false, || { + panic!("unrelated negative marker must remain intact") + }) + .err() + .unwrap(); + assert_eq!(still_cached, other_err); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn translated_negative_markers_skip_and_delete_under_env_overrides() { + for name in [ + "XCL_DEBUG_PS_SUB", + "XCL_SAFE_BARRIER", + "XCL_SPLIT_WAVE64", + "XCL_WAVE64_SPIN", + "XCL_NEGATIVE_CACHE", + "XCL_RECOMP_NO_STRUCTURED", + ] { + assert!(!dxc::negative_cache_allowed_with(|v| v == name), "{name} must disable negative markers"); + } + assert!(dxc::negative_cache_allowed_with(|_| false)); + + let dir = std::env::temp_dir().join(format!("xcl-pso-neg-ovr-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let blob = b"shader-override-target"; + let ident = translated::identity_for("src-v1", "tc-1"); + let cap = translated::capability_digest(ident, Stage::Pixel, 0, 4, false); + let fail_path = translated::fail_file(&dir, ident, blob, Stage::Pixel, 0, 4, false); + + assert!(translated::cached_in_with_negative(&dir, ident, cap, true, blob, Stage::Pixel, 0, 4, false, || { + Err("incomplete translation, missing: [\"op\"]".into()) + }) + .is_err()); + assert!(fail_path.is_file()); + + // Under an env override (allow_negative = false), the marker is skipped, deleted, and not recreated. + let calls = std::sync::atomic::AtomicUsize::new(0); + assert!(translated::cached_in_with_negative(&dir, ident, cap, false, blob, Stage::Pixel, 0, 4, false, || { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Err("override session refusal".into()) + }) + .is_err()); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); + assert!(!fail_path.is_file(), "override session must delete existing .fail marker and write none"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn translated_deferred_and_transient_errors_are_not_negative_cached() { + assert!(!is_cacheable_translation_refusal("DXIL not compiled yet")); + assert!(!is_cacheable_translation_refusal("DXIL cache x.dxil (cs_6_6, entry \"main\", 10 B HLSL): Compile: E_OUTOFMEMORY")); + assert!(!is_cacheable_translation_refusal("DXIL cache x.dxil (cs_6_6, entry \"main\", 10 B HLSL): dxccompiler: dxcompiler.dll not found")); + assert!(is_cacheable_translation_refusal("DXIL cache x.dxil (cs_6_6, entry \"main\", 10 B HLSL): dxc: error: invalid operand")); + assert!(is_cacheable_translation_refusal("incomplete translation, missing: [\"op\"]")); + + let dir = std::env::temp_dir().join(format!("xcl-pso-neg-trans-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let blob = b"shader-deferred"; + let ident = translated::identity_for("src-v1", "tc-1"); + let cap = translated::capability_digest(ident, Stage::Compute, 0, 4, false); + let fail_path = translated::fail_file(&dir, ident, blob, Stage::Compute, 0, 4, false); + + let (r, missed) = dxc::cached_only(|| { + translated::cached_in_with_negative(&dir, ident, cap, true, blob, Stage::Compute, 0, 4, false, || { + dxc::compile_cached_in(&dir, "missing hlsl", "main", "cs_6_6")?; + Ok(compiled(1)) + }) + }); + assert!(r.is_err() && missed); + assert!(!fail_path.is_file(), "cached_only deferral must not create a .fail marker"); + let _ = std::fs::remove_dir_all(&dir); + } } #[cfg(test)] From 9e1a79e4791597607c1cb9048687c05be8294141 Mon Sep 17 00:00:00 2001 From: KarolKurzyna <187065594+KarolKurzyna@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:10:19 +0100 Subject: [PATCH 2/2] test: check translated DXIL marker byte --- crates/xcl/src/gpu/recomp/pso.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index f39591c909..8c9b01df17 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -2064,7 +2064,7 @@ mod shader_cache_tests { Ok(compiled(77)) }) .unwrap(); - assert_eq!(rebuilt.dxil[0], 77); + assert_eq!(rebuilt.dxil[67], 77); assert!(!translated::fail_file(&dir, ident, blob_refused, Stage::Compute, 0, 4, false).is_file()); let still_cached = translated::cached_in_with_negative(&dir, ident, cap_v1, true, blob_other, Stage::Compute, 0, 4, false, || {