From 1d3b766db198b67732f2e6cc379e57ddaa220cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=91=D1=83=D1=88=D1=83?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Thu, 26 Nov 2026 19:27:59 -0500 Subject: [PATCH 1/6] perf(shaders): accelerate precompilation, warm cache & fix preparation timer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - crates/xcl/src/shaders.rs — add in-memory program/HLSL deduplication, persistent precompile-index-v1 warm-cache record fast-skip with atomic flushing, XCL_DIRECT_DXIL=all VS/PS support in precompile(), and RAII 2 GB memory reserve - crates/xcl/src/gpu/recomp/dxc.rs — add existing_cache_keys single-read_dir scan, cache_key_for, thread-local IDxcUtils reuse, canonicalized cache path caching, zero-syscall cache dir write, and swap-returning set_memory_reserve - crates/xcl/src/hle/d3d12x/present/preparation.rs — show real Elapsed time, throughput (records/s) and ETA on the preparation screen, and only show 'No shader progress for N s' when quiet >= 5s Tests: Windows 11 RTX 5080 cargo test -p xcl --lib dxc (45 pass), preparation (5 pass), shaders (17 pass); 300-record cold XCL_DIRECT_DXIL=all 18.57s -> 12.68s (-31.7%) --- crates/xcl/src/gpu/recomp/dxc.rs | 112 +++++++- .../xcl/src/hle/d3d12x/present/preparation.rs | 48 +++- crates/xcl/src/shaders.rs | 246 +++++++++++++++++- 3 files changed, 384 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..f88bd7f2ae 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -9,7 +9,7 @@ //! kept for `report.json` ([`toolchain`]). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -359,6 +359,7 @@ fn create_fn() -> Result { thread_local! { static COMPILER: RefCell> = const { RefCell::new(None) }; + static UTILS: RefCell> = const { RefCell::new(None) }; } fn compiler() -> Result { @@ -378,6 +379,23 @@ fn compiler() -> Result { }) } +fn utils() -> Result { + UTILS.with(|u| { + if let Some(x) = u.borrow().as_ref() { + return Ok(x.clone()); + } + let create = create_fn()?; + let mut p = std::ptr::null_mut(); + let hr = unsafe { create(&CLSID_DxcUtils, &IDxcUtils::IID, &mut p) }; + if hr.is_err() || p.is_null() { + return Err(format!("DxcCreateInstance: {hr:?}")); + } + let x = unsafe { IDxcUtils::from_raw(p) }; + *u.borrow_mut() = Some(x.clone()); + Ok(x) + }) +} + /// Stack of the thread DXC runs on: its LLVM passes recurse along long dependency chains of /// big translated programs (2 MB overflowed on a 7 000-instruction retail PS); the caller may /// be a game thread with a small stack. Reserved, committed only as used. @@ -419,8 +437,9 @@ pub fn compile_threads() -> usize { static RESERVE_GB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(6); /// The commit `wait_for_memory` keeps free besides the compiles (no title running: less). -pub fn set_memory_reserve(gb: u64) { - RESERVE_GB.store(gb, std::sync::atomic::Ordering::Relaxed); +/// Returns the previous reserve value so callers can restore it cleanly. +pub fn set_memory_reserve(gb: u64) -> u64 { + RESERVE_GB.swap(gb, std::sync::atomic::Ordering::Relaxed) } /// Compiles running on the DXC workers (`wait_for_memory` lets them in). @@ -586,7 +605,7 @@ fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extr }; unsafe { let linker = IDxcLinker::from_raw(instance(&CLSID_DxcLinker, &IDxcLinker::IID)?); - let utils = IDxcUtils::from_raw(instance(&CLSID_DxcUtils, &IDxcUtils::IID)?); + let utils = utils()?; let names = [crate::util::wide("program"), crate::util::wide("accessors")]; for (name, dxil) in names.iter().zip([&program, &*accessors]) { let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, dxil.len() as u32, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; @@ -648,7 +667,7 @@ fn compile_whole(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Resul } } -pub(super) fn toolchain_identity() -> &'static str { +pub fn toolchain_identity() -> &'static str { static IDENTITY: OnceLock = OnceLock::new(); IDENTITY.get_or_init(|| { let Ok(dir) = location() else { @@ -695,6 +714,44 @@ fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } +pub fn cache_key_for(src: &str, entry: &str, profile: &str) -> u64 { + cache_key(src, entry, profile) +} + +/// Scans `dir` once and returns all valid `<16-hex>.dxil` cache keys present on disk. +pub fn existing_cache_keys(dir: &Path) -> HashSet { + let mut keys = HashSet::new(); + let dir = normalized_cache_dir(dir); + let Ok(rd) = std::fs::read_dir(&dir) else { + return keys; + }; + for entry in rd.flatten() { + let Ok(ft) = entry.file_type() else { + continue; + }; + if !ft.is_file() { + continue; + } + let name = entry.file_name(); + let Some(s) = name.to_str() else { + continue; + }; + let Some(hex) = s.strip_suffix(".dxil") else { + continue; + }; + if hex.len() != 16 { + continue; + } + let Ok(key) = u64::from_str_radix(hex, 16) else { + continue; + }; + if entry.metadata().is_ok_and(|m| m.len() >= 36) { + keys.insert(key); + } + } + keys +} + /// Folder of the DXIL cache: `XCL_DXIL_CACHE`, else `%LOCALAPPDATA%\xcl\dxil`. pub fn cache_dir() -> PathBuf { if let Ok(d) = std::env::var("XCL_DXIL_CACHE") { @@ -817,7 +874,16 @@ fn cache_mutex_name(file: &Path) -> String { } fn normalized_cache_dir(dir: &Path) -> PathBuf { + static CANON: OnceLock>> = OnceLock::new(); + let cache = CANON.get_or_init(|| Mutex::new(HashMap::new())); + if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(dir).cloned() { + return hit; + } if let Ok(canonical) = std::fs::canonicalize(dir) { + let mut g = cache.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() < 1024 { + g.insert(dir.to_path_buf(), canonical.clone()); + } return canonical; } let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf()); @@ -1024,12 +1090,12 @@ where if err_file.is_file() { let _ = std::fs::remove_file(&err_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())); - if std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, &file).is_err() { - let _ = std::fs::remove_file(&tmp); - } + // write to a temporary name first: another thread / process may be reading + let tmp = file.with_extension(format!("tmp{}", std::process::id())); + let wrote = std::fs::write(&tmp, &b).is_ok() + || (std::fs::create_dir_all(&dir).is_ok() && std::fs::write(&tmp, &b).is_ok()); + if wrote && std::fs::rename(&tmp, &file).is_err() { + let _ = std::fs::remove_file(&tmp); } Ok((b, false)) } @@ -1516,6 +1582,30 @@ mod cache_tests { let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn existing_cache_keys_and_memory_reserve_swap_behave_cleanly() { + let prev = set_memory_reserve(3); + assert_eq!(set_memory_reserve(prev), 3); + + let dir = std::env::temp_dir().join(format!("xcl-dxil-keys-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let k1 = cache_key("first shader", "main", "cs_6_6"); + let k2 = cache_key("second shader", "main", "ps_6_6"); + std::fs::write(dir.join(format!("{k1:016x}.dxil")), synthetic_dxil(1)).unwrap(); + std::fs::write(dir.join(format!("{k2:016x}.dxil")), b"tiny").unwrap(); + std::fs::write(dir.join("nothex0000000000.dxil"), synthetic_dxil(2)).unwrap(); + std::fs::write(dir.join(format!("{k1:016x}.err")), b"XCLDXCE1").unwrap(); + + let keys = existing_cache_keys(&dir); + assert!(keys.contains(&k1)); + assert!(!keys.contains(&k2)); + assert_eq!(keys.len(), 1); + assert_eq!(normalized_cache_dir(&dir), normalized_cache_dir(&dir)); + + let _ = std::fs::remove_dir_all(&dir); + } } /// `src` compiled whole and linked with its memory accessors, whatever their number, with the diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 1d4e614b8f..c0e463d558 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -159,8 +159,7 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); let count = if total == 0 { "Reading shader records…".into() } else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); - let mut times = format!("No shader progress for {quiet} s"); - if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } + let times = status_line(done, total, s.start.elapsed(), quiet, last); text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); SelectObject(dc, old); @@ -190,6 +189,33 @@ impl StallClock { } } +fn format_duration(secs: u64) -> String { + if secs < 60 { + format!("{secs} s") + } else if secs < 3600 { + format!("{}m {:02}s", secs / 60, secs % 60) + } else { + format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60) + } +} + +fn status_line(done: usize, total: usize, elapsed: Duration, quiet: u64, last_stall: Option) -> String { + let mut parts = vec![format!("Elapsed {}", format_duration(elapsed.as_secs()))]; + if done > 0 && total > done && elapsed.as_secs() >= 2 { + let rate = done as f64 / elapsed.as_secs_f64(); + let rem_secs = ((total - done) as f64 / rate.max(0.001)).round() as u64; + parts.push(format!("{rate:.1}/s")); + parts.push(format!("ETA ~{}", format_duration(rem_secs))); + } + if quiet >= 5 { + parts.push(format!("No shader progress for {quiet} s")); + } + if let Some(ago) = last_stall { + parts.push(format!("Last stall ended {ago} s ago")); + } + parts.join(" · ") +} + fn percent(done: usize, total: usize, ready: bool) -> usize { if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } } @@ -227,4 +253,22 @@ mod tests { assert_eq!(percent(4, 4, false), 99); assert_eq!(percent(4, 4, true), 100); } + + #[test] + fn status_line_shows_elapsed_rate_and_hides_zero_second_stall() { + let s = Duration::from_secs; + let active = status_line(1500, 26500, s(10), 0, None); + assert!(active.contains("Elapsed 10 s"), "{active}"); + assert!(active.contains("150.0/s"), "{active}"); + assert!(active.contains("ETA ~2m 47s"), "{active}"); + assert!(!active.contains("No shader progress"), "{active}"); + + let stalled = status_line(1500, 26500, s(65), 7, None); + assert!(stalled.contains("Elapsed 1m 05s"), "{stalled}"); + assert!(stalled.contains("No shader progress for 7 s"), "{stalled}"); + + let recovered = status_line(1600, 26500, s(70), 0, Some(3)); + assert!(!recovered.contains("No shader progress"), "{recovered}"); + assert!(recovered.contains("Last stall ended 3 s ago"), "{recovered}"); + } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 4c5a014974..f023cdacc4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1652,7 +1652,100 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R Ok(()) } +fn precompile_index_scope(windows: u32, split: bool, graphics_split: bool, direct_gfx: bool) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let tag = format!( + "{}:{}:{windows}:{split}:{graphics_split}:{direct_gfx}", + env!("CARGO_PKG_VERSION"), + recomp::dxc::toolchain_identity() + ); + for b in tag.bytes() { + h ^= b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + h +} + +const PRECOMPILE_INDEX_MAGIC: &[u8; 8] = b"XCLPIDX1"; + +fn load_precompile_index(path: &Path) -> HashMap> { + let mut out = HashMap::new(); + let Ok(bytes) = std::fs::read(path) else { + return out; + }; + let Some(mut rest) = bytes.strip_prefix(PRECOMPILE_INDEX_MAGIC.as_slice()) else { + return out; + }; + while rest.len() >= 12 { + let (rec_bytes, after_rec) = rest.split_first_chunk::<8>().unwrap(); + let (cnt_bytes, after_cnt) = after_rec.split_first_chunk::<4>().unwrap(); + let count = u32::from_le_bytes(*cnt_bytes) as usize; + if count > 256 || after_cnt.len() < count * 8 { + break; + } + let rec_hash = u64::from_le_bytes(*rec_bytes); + let mut keys = Vec::with_capacity(count); + let mut cur = after_cnt; + for _ in 0..count { + let (kb, next) = cur.split_first_chunk::<8>().unwrap(); + keys.push(u64::from_le_bytes(*kb)); + cur = next; + } + out.insert(rec_hash, keys); + rest = cur; + } + out +} + +fn save_precompile_index(path: &Path, map: &HashMap>) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut buf = Vec::with_capacity(8 + map.len() * 20); + buf.extend_from_slice(PRECOMPILE_INDEX_MAGIC); + for (&rec_hash, keys) in map { + if keys.is_empty() || keys.len() > 256 { + continue; + } + buf.extend_from_slice(&rec_hash.to_le_bytes()); + buf.extend_from_slice(&(keys.len() as u32).to_le_bytes()); + for &k in keys { + buf.extend_from_slice(&k.to_le_bytes()); + } + } + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + std::fs::write(&tmp, &buf)?; + if path.exists() { + let _ = std::fs::remove_file(path); + } + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn fnv64_parts(parts: &[&[u8]]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for part in parts { + for &b in *part { + h ^= b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + h ^= 0xff; + h = h.wrapping_mul(0x100_0000_01b3); + } + h +} + fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { + struct RestoreReserve(u64); + impl Drop for RestoreReserve { + fn drop(&mut self) { + recomp::dxc::set_memory_reserve(self.0); + } + } + let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; @@ -1674,16 +1767,38 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; - // no title runs: only a little commit is kept free besides the compiles - if startup.is_none() { recomp::dxc::set_memory_reserve(2); } + // Before guest startup or standalone `--precompile`, no title allocation exists yet: keep 2 GB reserve + // and restore the previous reserve on return via RAII. + let _reserve_guard = RestoreReserve(recomp::dxc::set_memory_reserve(2)); // VS / PS: the 32-lane form wherever the GPU can run 32-lane waves (`pso::graphics_wave32`); // `--split` sets both let startup_device = pipelines.filter(|_| startup.is_some()); let graphics_split = split.unwrap_or_else(|| startup_device.map_or_else(recomp::runner::graphics_wave32, |p| recomp::pso::graphics_wave32_for_device(&p.dev))); let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); + let direct_gfx = crate::gpu::dxil::kernel::enabled_graphics(); + let cache_dir = recomp::dxc::cache_dir(); + let use_record_index = only.is_none(); + let existing_dxil = if use_record_index { + recomp::dxc::existing_cache_keys(&cache_dir) + } else { + HashSet::new() + }; + let index_path = cache_dir.join(format!( + "precompile-index-v1-{:016x}.bin", + precompile_index_scope(windows, split, graphics_split, direct_gfx) + )); + let initial_index = if use_record_index { + load_precompile_index(&index_path) + } else { + HashMap::new() + }; + let index_state: Mutex>> = Mutex::new(initial_index.clone()); + let dirty_index = AtomicUsize::new(0); + let seen_programs: Mutex>> = Mutex::new(HashMap::new()); + let seen_hlsl_jobs: Mutex> = Mutex::new(HashSet::new()); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", - recomp::dxc::cache_dir().display(), + cache_dir.display(), recomp::dxc::compile_threads(), windows & !recomp::HEAP_WINDOWS, if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, @@ -1708,6 +1823,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; }; + let rec_hash = use_record_index.then(|| shader::fnv64(&blob)); + if let Some(keys) = rec_hash.and_then(|h| initial_index.get(&h)) { + if !keys.is_empty() && keys.iter().all(|k| existing_dxil.contains(k)) { + cached.fetch_add(keys.len(), Ordering::Relaxed); + record_done(); + continue; + } + } let Some(sh) = xbox::parse(&blob) else { if startup.is_some() && !matches!(shader::classify(&blob).0, shader::Kind::Dxil | shader::Kind::Dxbc) { failed.fetch_add(1, Ordering::Relaxed); @@ -1748,8 +1871,36 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } + let mut record_keys: Vec = Vec::new(); + let mut record_indexable = use_record_index; for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; + if direct_gfx && matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { + let stage = if matches!(mode, recomp::Mode::Vertex(_)) { + recomp::pso::Stage::Vertex + } else { + recomp::pso::Stage::Pixel + }; + record_indexable = false; + match recomp::pso::console_to_dxil_in(&blob, stage, 0, graphics_split, windows) { + Ok(_) => { + compiled.fetch_add(1, Ordering::Relaxed); + } + Err(e) if e.contains("incomplete translation") => { + if startup.is_some() { + skipped.fetch_add(1, Ordering::Relaxed); + } + } + Err(e) => { + let mut g = errors.lock().unwrap(); + if g.len() < 10 { + g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))); + } + failed.fetch_add(1, Ordering::Relaxed); + } + } + continue; + } let jobs: Vec<(&str, Option)> = match &mode { recomp::Mode::Vertex(_) => vec![("vs_6_6", None)], recomp::Mode::Pixel(_) => vec![("ps_6_6", None)], @@ -1765,14 +1916,26 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // as `pso` translates: with the title's memory windows (`console_translation`, // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let wave64 = recomp::fssm_wave64(f, code); + let mode_tag = format!("{mode:?}"); + let flags = [wave64 as u8, split as u8]; + let win_bytes = windows.to_le_bytes(); + let prog_sig = fnv64_parts(&[mode_tag.as_bytes(), &flags, &win_bytes, code]); + if let Some(hit_keys) = seen_programs.lock().unwrap().get(&prog_sig).cloned() { + cached.fetch_add(hit_keys.len(), Ordering::Relaxed); + record_keys.extend_from_slice(&hit_keys); + continue; + } + let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: split, mem_windows: windows, ..Default::default() }; let t = match recomp::translate(code, &opt) { Ok(t) if t.complete() => t, Ok(_) => { + record_indexable = false; if startup.is_some() { skipped.fetch_add(1, Ordering::Relaxed); } continue; } Err(e) => { + record_indexable = false; if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); let mut logs = errors.lock().unwrap(); @@ -1781,18 +1944,49 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on continue; } }; + let mut prog_keys = Vec::with_capacity(jobs.len()); + let mut prog_ok = true; for (profile, src) in &jobs { - match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { - Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), - Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + let hlsl_src = src.as_deref().unwrap_or(&t.hlsl); + let job_sig = fnv64_parts(&[profile.as_bytes(), hlsl_src.as_bytes()]); + if seen_hlsl_jobs.lock().unwrap().contains(&job_sig) { + cached.fetch_add(1, Ordering::Relaxed); + prog_keys.push(recomp::dxc::cache_key_for(hlsl_src, "main", profile)); + continue; + } + match recomp::dxc::compile_cached(hlsl_src, "main", profile) { + Ok((_, from_cache)) => { + if from_cache { + cached.fetch_add(1, Ordering::Relaxed); + } else { + compiled.fetch_add(1, Ordering::Relaxed); + } + seen_hlsl_jobs.lock().unwrap().insert(job_sig); + prog_keys.push(recomp::dxc::cache_key_for(hlsl_src, "main", profile)); + } Err(e) => { + prog_ok = false; + record_indexable = false; let mut g = errors.lock().unwrap(); if g.len() < 10 { g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(""))); } - failed.fetch_add(1, Ordering::Relaxed) + failed.fetch_add(1, Ordering::Relaxed); } - }; + } + } + if prog_ok && !prog_keys.is_empty() { + record_keys.extend_from_slice(&prog_keys); + seen_programs.lock().unwrap().insert(prog_sig, prog_keys); + } + } + } + if record_indexable && !record_keys.is_empty() { + if let Some(h) = rec_hash { + index_state.lock().unwrap().insert(h, record_keys); + if dirty_index.fetch_add(1, Ordering::Relaxed) % 500 == 499 { + let snap = index_state.lock().unwrap().clone(); + let _ = save_precompile_index(&index_path, &snap); } } } @@ -1800,6 +1994,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }); } }); + if dirty_index.load(Ordering::Relaxed) > 0 { + let snap = index_state.into_inner().unwrap(); + let _ = save_precompile_index(&index_path, &snap); + } let failed = failed.into_inner(); let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; println!( @@ -2329,6 +2527,36 @@ mod tests { assert_eq!(agg.failed_count, 0, "{:?}", agg.failed); assert_eq!(agg.insts.undecoded, 0); } + + #[test] + fn precompile_index_round_trips_and_ignores_corrupt_tail() { + let dir = std::env::temp_dir().join(format!("xcl-precomp-idx-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let idx = dir.join("index.bin"); + + let mut map = HashMap::new(); + map.insert(0x1111_2222_3333_4444u64, vec![0xAAAA_BBBBu64]); + map.insert(0x5555_6666_7777_8888u64, vec![0xCCCCu64, 0xDDDDu64]); + save_precompile_index(&idx, &map).unwrap(); + + let loaded = load_precompile_index(&idx); + assert_eq!(loaded, map); + + // Corrupt trailing bytes stop safely without discarding valid prefix entries + let mut raw = std::fs::read(&idx).unwrap(); + raw.extend_from_slice(&[0xFFu8; 7]); + std::fs::write(&idx, raw).unwrap(); + assert_eq!(load_precompile_index(&idx), map); + + // Scope hash changes cleanly when direct_gfx toggles + assert_ne!( + precompile_index_scope(4, true, true, false), + precompile_index_scope(4, true, true, true) + ); + + let _ = std::fs::remove_dir_all(&dir); + } } /// `XCL_DUMP_HLSL=` (`--recomp`): every `XCL_DUMP_EVERY`-th complete translation (by a From 6c1a9ffb31137dcbd2b09b6f5ae4e0da3cbd635b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=91=D1=83=D1=88=D1=83?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Thu, 26 Nov 2026 20:20:02 -0500 Subject: [PATCH 2/6] fix(shaders): validate warm-index DXIL containers before skipping --- crates/xcl/src/gpu/recomp/dxc.rs | 75 ++++++++++++++------------------ crates/xcl/src/shaders.rs | 11 ++--- crates/xcl/tests/shaders_e2e.rs | 59 +++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 47 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index f88bd7f2ae..faba4b7fd1 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -718,38 +718,18 @@ pub fn cache_key_for(src: &str, entry: &str, profile: &str) -> u64 { cache_key(src, entry, profile) } -/// Scans `dir` once and returns all valid `<16-hex>.dxil` cache keys present on disk. -pub fn existing_cache_keys(dir: &Path) -> HashSet { - let mut keys = HashSet::new(); - let dir = normalized_cache_dir(dir); - let Ok(rd) = std::fs::read_dir(&dir) else { - return keys; - }; - for entry in rd.flatten() { - let Ok(ft) = entry.file_type() else { - continue; - }; - if !ft.is_file() { - continue; - } - let name = entry.file_name(); - let Some(s) = name.to_str() else { - continue; - }; - let Some(hex) = s.strip_suffix(".dxil") else { - continue; - }; - if hex.len() != 16 { - continue; - } - let Ok(key) = u64::from_str_radix(hex, 16) else { - continue; - }; - if entry.metadata().is_ok_and(|m| m.len() >= 36) { - keys.insert(key); - } +/// Validates only the DXIL cache keys referenced by a warm precompile index using the +/// same container check as `cached_file`, leaving unrelated cache entries unread. +pub fn validated_cache_keys(dir: &Path, candidate_keys: &HashSet) -> HashSet { + if candidate_keys.is_empty() { + return HashSet::new(); } - keys + let dir = normalized_cache_dir(dir); + candidate_keys + .iter() + .copied() + .filter(|key| cached_file(&dir.join(format!("{key:016x}.dxil"))).is_some()) + .collect() } /// Folder of the DXIL cache: `XCL_DXIL_CACHE`, else `%LOCALAPPDATA%\xcl\dxil`. @@ -1584,23 +1564,34 @@ mod cache_tests { } #[test] - fn existing_cache_keys_and_memory_reserve_swap_behave_cleanly() { + fn validated_cache_keys_and_memory_reserve_swap_behave_cleanly() { let prev = set_memory_reserve(3); assert_eq!(set_memory_reserve(prev), 3); let dir = std::env::temp_dir().join(format!("xcl-dxil-keys-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - let k1 = cache_key("first shader", "main", "cs_6_6"); - let k2 = cache_key("second shader", "main", "ps_6_6"); - std::fs::write(dir.join(format!("{k1:016x}.dxil")), synthetic_dxil(1)).unwrap(); - std::fs::write(dir.join(format!("{k2:016x}.dxil")), b"tiny").unwrap(); - std::fs::write(dir.join("nothex0000000000.dxil"), synthetic_dxil(2)).unwrap(); - std::fs::write(dir.join(format!("{k1:016x}.err")), b"XCLDXCE1").unwrap(); - - let keys = existing_cache_keys(&dir); - assert!(keys.contains(&k1)); - assert!(!keys.contains(&k2)); + let valid_blob = synthetic_dxil(1); + let k_valid = cache_key("first shader", "main", "cs_6_6"); + let k_zeroed = cache_key("corrupt zeroed shader", "main", "ps_6_6"); + let k_short = cache_key("truncated shader", "main", "ps_6_6"); + let k_missing = cache_key("missing shader", "main", "vs_6_6"); + let k_unrelated = cache_key("unrelated cached shader", "main", "ps_6_6"); + + std::fs::write(dir.join(format!("{k_valid:016x}.dxil")), &valid_blob).unwrap(); + std::fs::write(dir.join(format!("{k_zeroed:016x}.dxil")), vec![0u8; valid_blob.len()]).unwrap(); + std::fs::write(dir.join(format!("{k_short:016x}.dxil")), b"tiny").unwrap(); + std::fs::write(dir.join(format!("{k_unrelated:016x}.dxil")), synthetic_dxil(2)).unwrap(); + std::fs::write(dir.join("nothex0000000000.dxil"), synthetic_dxil(3)).unwrap(); + std::fs::write(dir.join(format!("{k_valid:016x}.err")), b"XCLDXCE1").unwrap(); + + let candidates = HashSet::from([k_valid, k_zeroed, k_short, k_missing]); + let keys = validated_cache_keys(&dir, &candidates); + assert!(keys.contains(&k_valid)); + assert!(!keys.contains(&k_zeroed)); + assert!(!keys.contains(&k_short)); + assert!(!keys.contains(&k_missing)); + assert!(!keys.contains(&k_unrelated)); assert_eq!(keys.len(), 1); assert_eq!(normalized_cache_dir(&dir), normalized_cache_dir(&dir)); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index f023cdacc4..803d72944d 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1778,11 +1778,6 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let direct_gfx = crate::gpu::dxil::kernel::enabled_graphics(); let cache_dir = recomp::dxc::cache_dir(); let use_record_index = only.is_none(); - let existing_dxil = if use_record_index { - recomp::dxc::existing_cache_keys(&cache_dir) - } else { - HashSet::new() - }; let index_path = cache_dir.join(format!( "precompile-index-v1-{:016x}.bin", precompile_index_scope(windows, split, graphics_split, direct_gfx) @@ -1792,6 +1787,12 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } else { HashMap::new() }; + let existing_dxil = if use_record_index && !initial_index.is_empty() { + let referenced: HashSet = initial_index.values().flatten().copied().collect(); + recomp::dxc::validated_cache_keys(&cache_dir, &referenced) + } else { + HashSet::new() + }; let index_state: Mutex>> = Mutex::new(initial_index.clone()); let dirty_index = AtomicUsize::new(0); let seen_programs: Mutex>> = Mutex::new(HashMap::new()); diff --git a/crates/xcl/tests/shaders_e2e.rs b/crates/xcl/tests/shaders_e2e.rs index 337b4fe6b0..7ef346473b 100644 --- a/crates/xcl/tests/shaders_e2e.rs +++ b/crates/xcl/tests/shaders_e2e.rs @@ -62,6 +62,20 @@ fn run_shaders(target: &Path, extra: &[&str]) -> Output { .expect("spawn xcl shaders") } +fn run_shaders_with_cache(target: &Path, extra: &[&str], cache_dir: &Path) -> Output { + Command::new(env!("CARGO_BIN_EXE_xcl")) + .arg("shaders") + .arg(target) + .args(extra) + .env("XCL_DXIL_CACHE", cache_dir) + .env_remove("XCL_DIRECT_DXIL") + .env_remove("XCL_DUMP_HLSL") + .env_remove("XCL_RECOMP_ONLY") + .env_remove("XCL_EXAMPLE_HLSL") + .output() + .expect("spawn xcl shaders") +} + #[test] fn help_lists_shader_precompile_options() { let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("--help").output().unwrap(); @@ -290,3 +304,48 @@ fn shaders_rejects_unknown_options_missing_values_and_mistyped_values() { assert!(out.stdout.is_empty(), "args {args:?}: unexpected stdout {:?}", String::from_utf8_lossy(&out.stdout)); } } + +#[test] +fn shaders_precompile_recovers_corrupt_same_length_cached_dxil() { + let shader_dir = TempDir::new("precompile-corrupt"); + let cache_dir = TempDir::new("precompile-corrupt-cache"); + std::fs::write(shader_dir.path().join("ps.bin"), xbox_shader(0, &[fssm(&CODE, &[(5, 1)])])).unwrap(); + + // 1. Cold precompile writes the cached DXIL container and warm index. + let cold = run_shaders_with_cache(shader_dir.path(), &["--precompile"], cache_dir.path()); + assert!(cold.status.success(), "{cold:?}"); + let cold_stdout = String::from_utf8(cold.stdout).unwrap(); + assert!(cold_stdout.contains("compiled 1, already cached 0, errors 0"), "{cold_stdout}"); + + let mut dxil_files = Vec::new(); + let mut index_files = Vec::new(); + for entry in std::fs::read_dir(cache_dir.path()).unwrap().flatten() { + let name = entry.file_name(); + let s = name.to_string_lossy(); + if s.ends_with(".dxil") { + dxil_files.push(entry.path()); + } else if s.starts_with("precompile-index-v1-") && s.ends_with(".bin") { + index_files.push(entry.path()); + } + } + assert_eq!(dxil_files.len(), 1, "expected 1 .dxil file: {dxil_files:?}"); + assert_eq!(index_files.len(), 1, "expected 1 precompile index file: {index_files:?}"); + let dxil_path = dxil_files.pop().unwrap(); + let orig_bytes = std::fs::read(&dxil_path).unwrap(); + assert!(orig_bytes.starts_with(b"DXBC"), "unexpected DXIL header"); + + // 2. Warm valid run hits the index without recompiling. + let warm = run_shaders_with_cache(shader_dir.path(), &["--precompile"], cache_dir.path()); + assert!(warm.status.success(), "{warm:?}"); + let warm_stdout = String::from_utf8(warm.stdout).unwrap(); + assert!(warm_stdout.contains("compiled 0, already cached 1, errors 0"), "{warm_stdout}"); + assert_eq!(std::fs::read(&dxil_path).unwrap(), orig_bytes); + + // 3. Overwriting the cached DXIL with same-length zeros must be caught and restored. + std::fs::write(&dxil_path, vec![0u8; orig_bytes.len()]).unwrap(); + let recovered = run_shaders_with_cache(shader_dir.path(), &["--precompile"], cache_dir.path()); + assert!(recovered.status.success(), "{recovered:?}"); + let recovered_stdout = String::from_utf8(recovered.stdout).unwrap(); + assert!(recovered_stdout.contains("compiled 1, already cached 0, errors 0"), "{recovered_stdout}"); + assert_eq!(std::fs::read(&dxil_path).unwrap(), orig_bytes); +} From fe16099b195d971ab89a96def5a0ad214fb13401 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=91=D1=83=D1=88=D1=83?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Thu, 26 Nov 2026 20:40:35 -0500 Subject: [PATCH 3/6] fix(shaders): scope warm index by translator ID, safe barrier & cache policy --- crates/xcl/src/gpu/recomp/pso.rs | 8 +++ crates/xcl/src/shaders.rs | 76 ++++++++++++++++++++++--- crates/xcl/tests/shaders_e2e.rs | 95 ++++++++++++++++++++++++++++++-- 3 files changed, 167 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..4deb87d53d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -919,6 +919,14 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { .any(|name| present(name))) } +pub(crate) fn precompile_index_allowed_with(present: impl Fn(&str) -> bool) -> bool { + cache_allowed(Stage::Pixel, present) +} + +pub(crate) fn precompile_index_allowed() -> bool { + precompile_index_allowed_with(|name| std::env::var_os(name).is_some()) +} + /// User SGPRs of a console compute shader (COMPUTE_PGM_RSRC2 in FSPX or FSSM): /// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in /// registers. None: not a console compute shader. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 803d72944d..55e1f69a70 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1652,11 +1652,23 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R Ok(()) } -fn precompile_index_scope(windows: u32, split: bool, graphics_split: bool, direct_gfx: bool) -> u64 { +fn safe_barrier_enabled(raw: Option<&str>) -> bool { + raw.map_or(true, |v| v.trim() != "0") +} + +fn precompile_index_scope_with( + translator_source_id: &str, + windows: u32, + split: bool, + graphics_split: bool, + direct_gfx: bool, + safe_barrier: bool, +) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; let tag = format!( - "{}:{}:{windows}:{split}:{graphics_split}:{direct_gfx}", + "{}:{}:{}:{windows}:{split}:{graphics_split}:{direct_gfx}:{safe_barrier}", env!("CARGO_PKG_VERSION"), + translator_source_id, recomp::dxc::toolchain_identity() ); for b in tag.bytes() { @@ -1666,6 +1678,23 @@ fn precompile_index_scope(windows: u32, split: bool, graphics_split: bool, direc h } +fn precompile_index_scope( + windows: u32, + split: bool, + graphics_split: bool, + direct_gfx: bool, + safe_barrier: bool, +) -> u64 { + precompile_index_scope_with( + env!("XCL_TRANSLATOR_SOURCE_ID"), + windows, + split, + graphics_split, + direct_gfx, + safe_barrier, + ) +} + const PRECOMPILE_INDEX_MAGIC: &[u8; 8] = b"XCLPIDX1"; fn load_precompile_index(path: &Path) -> HashMap> { @@ -1777,10 +1806,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); let direct_gfx = crate::gpu::dxil::kernel::enabled_graphics(); let cache_dir = recomp::dxc::cache_dir(); - let use_record_index = only.is_none(); + let use_record_index = only.is_none() && recomp::pso::precompile_index_allowed(); + let safe_barrier = safe_barrier_enabled(std::env::var("XCL_SAFE_BARRIER").ok().as_deref()); let index_path = cache_dir.join(format!( "precompile-index-v1-{:016x}.bin", - precompile_index_scope(windows, split, graphics_split, direct_gfx) + precompile_index_scope(windows, split, graphics_split, direct_gfx, safe_barrier) )); let initial_index = if use_record_index { load_precompile_index(&index_path) @@ -2550,12 +2580,44 @@ mod tests { std::fs::write(&idx, raw).unwrap(); assert_eq!(load_precompile_index(&idx), map); - // Scope hash changes cleanly when direct_gfx toggles + // Scope hash changes cleanly when translator source, direct_gfx, or safe_barrier toggles + assert_ne!( + precompile_index_scope(4, true, true, false, true), + precompile_index_scope(4, true, true, true, true) + ); + assert_ne!( + precompile_index_scope(4, true, true, false, true), + precompile_index_scope(4, true, true, false, false) + ); assert_ne!( - precompile_index_scope(4, true, true, false), - precompile_index_scope(4, true, true, true) + precompile_index_scope_with("rev-a", 4, true, true, false, true), + precompile_index_scope_with("rev-b", 4, true, true, false, true) ); + assert!(safe_barrier_enabled(None)); + assert!(safe_barrier_enabled(Some("1"))); + assert!(safe_barrier_enabled(Some(" 1 "))); + assert!(!safe_barrier_enabled(Some("0"))); + assert!(!safe_barrier_enabled(Some(" 0 "))); + + assert!(recomp::pso::precompile_index_allowed_with(|_| false)); + for var in [ + "XCL_RECOMP_NO_STRUCTURED", + "XCL_RECOMP_WHY", + "XCL_X64_ALL_MASKS", + "XCL_WAVE64_SPIN", + "XCL_DXIL_NO_OPT", + "XCL_DEBUG_MAGENTA", + "XCL_DEBUG_LOD0", + "XCL_DEBUG_PS_SUB", + "XCL_DEBUG_PS_EXPR", + ] { + assert!( + !recomp::pso::precompile_index_allowed_with(|name| name == var), + "expected {var} to disable warm precompile index" + ); + } + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/xcl/tests/shaders_e2e.rs b/crates/xcl/tests/shaders_e2e.rs index 7ef346473b..390a2b40a5 100644 --- a/crates/xcl/tests/shaders_e2e.rs +++ b/crates/xcl/tests/shaders_e2e.rs @@ -63,17 +63,30 @@ fn run_shaders(target: &Path, extra: &[&str]) -> Output { } fn run_shaders_with_cache(target: &Path, extra: &[&str], cache_dir: &Path) -> Output { - Command::new(env!("CARGO_BIN_EXE_xcl")) - .arg("shaders") + run_shaders_with_cache_and_env(target, extra, cache_dir, &[]) +} + +fn run_shaders_with_cache_and_env( + target: &Path, + extra: &[&str], + cache_dir: &Path, + envs: &[(&str, &str)], +) -> Output { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_xcl")); + cmd.arg("shaders") .arg(target) .args(extra) .env("XCL_DXIL_CACHE", cache_dir) .env_remove("XCL_DIRECT_DXIL") + .env_remove("XCL_SAFE_BARRIER") + .env_remove("XCL_RECOMP_NO_STRUCTURED") .env_remove("XCL_DUMP_HLSL") .env_remove("XCL_RECOMP_ONLY") - .env_remove("XCL_EXAMPLE_HLSL") - .output() - .expect("spawn xcl shaders") + .env_remove("XCL_EXAMPLE_HLSL"); + for (k, v) in envs { + cmd.env(k, v); + } + cmd.output().expect("spawn xcl shaders") } #[test] @@ -349,3 +362,75 @@ fn shaders_precompile_recovers_corrupt_same_length_cached_dxil() { assert!(recovered_stdout.contains("compiled 1, already cached 0, errors 0"), "{recovered_stdout}"); assert_eq!(std::fs::read(&dxil_path).unwrap(), orig_bytes); } + +#[test] +fn shaders_precompile_scopes_safe_barrier_and_bypasses_diagnostic_overrides() { + let shader_dir = TempDir::new("precompile-scope"); + let cache_dir = TempDir::new("precompile-scope-cache"); + std::fs::write(shader_dir.path().join("ps.bin"), xbox_shader(0, &[fssm(&CODE, &[(5, 1)])])).unwrap(); + + let count_indices = |dir: &Path| { + std::fs::read_dir(dir) + .unwrap() + .flatten() + .filter(|e| { + let name = e.file_name(); + let s = name.to_string_lossy(); + s.starts_with("precompile-index-v1-") && s.ends_with(".bin") + }) + .count() + }; + + // 1. Default (XCL_SAFE_BARRIER unset) -> 1 index, then XCL_SAFE_BARRIER=1 / " 1 " hit the same scope. + let cold = run_shaders_with_cache_and_env(shader_dir.path(), &["--precompile"], cache_dir.path(), &[]); + assert!(cold.status.success(), "{cold:?}"); + let cold_stdout = String::from_utf8(cold.stdout).unwrap(); + assert!(cold_stdout.contains("compiled 1, already cached 0, errors 0"), "{cold_stdout}"); + assert_eq!(count_indices(cache_dir.path()), 1); + + for val in ["1", " 1 "] { + let warm = run_shaders_with_cache_and_env( + shader_dir.path(), + &["--precompile"], + cache_dir.path(), + &[("XCL_SAFE_BARRIER", val)], + ); + assert!(warm.status.success(), "{warm:?}"); + let warm_stdout = String::from_utf8(warm.stdout).unwrap(); + assert!(warm_stdout.contains("compiled 0, already cached 1, errors 0"), "{val:?}: {warm_stdout}"); + assert_eq!(count_indices(cache_dir.path()), 1); + } + + // 2. XCL_SAFE_BARRIER=0 uses a separate scope; whitespace-padded " 0 " hits that same scope. + let sb0 = run_shaders_with_cache_and_env( + shader_dir.path(), + &["--precompile"], + cache_dir.path(), + &[("XCL_SAFE_BARRIER", "0")], + ); + assert!(sb0.status.success(), "{sb0:?}"); + assert_eq!(count_indices(cache_dir.path()), 2); + + let sb0_pad = run_shaders_with_cache_and_env( + shader_dir.path(), + &["--precompile"], + cache_dir.path(), + &[("XCL_SAFE_BARRIER", " 0 ")], + ); + assert!(sb0_pad.status.success(), "{sb0_pad:?}"); + let sb0_pad_stdout = String::from_utf8(sb0_pad.stdout).unwrap(); + assert!(sb0_pad_stdout.contains("compiled 0, already cached 1, errors 0"), "{sb0_pad_stdout}"); + assert_eq!(count_indices(cache_dir.path()), 2); + + // 3. Diagnostic recomp overrides disable the warm record index cleanly. + let diag = run_shaders_with_cache_and_env( + shader_dir.path(), + &["--precompile"], + cache_dir.path(), + &[("XCL_RECOMP_NO_STRUCTURED", "1")], + ); + assert!(diag.status.success(), "{diag:?}"); + let diag_stdout = String::from_utf8(diag.stdout).unwrap(); + assert!(diag_stdout.contains("errors 0"), "{diag_stdout}"); + assert_eq!(count_indices(cache_dir.path()), 2); +} From 9b918518e4ca7f6a02e4ffae13a9e5a3c77a2645 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=91=D1=83=D1=88=D1=83?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Thu, 26 Nov 2026 21:17:02 -0500 Subject: [PATCH 4/6] fix(shaders): lock and merge precompile index across concurrent writers --- crates/xcl/src/gpu/recomp/dxc.rs | 18 ++++++++---- crates/xcl/src/shaders.rs | 44 +++++++++++++++++++++------- crates/xcl/tests/shaders_e2e.rs | 49 ++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index faba4b7fd1..0c83b9c906 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -827,7 +827,7 @@ fn cache_flight(key: CacheFlight) -> Arc> { flight } -struct ProcessCacheLock { +pub(crate) struct ProcessCacheLock { handle: windows_sys::Win32::Foundation::HANDLE, } @@ -877,15 +877,19 @@ fn normalized_cache_dir(dir: &Path) -> PathBuf { absolute } -fn process_cache_lock(file: &Path) -> Result { - use windows_sys::Win32::Foundation::{CloseHandle, WAIT_ABANDONED, WAIT_OBJECT_0}; - use windows_sys::Win32::System::Threading::{CreateMutexW, WaitForSingleObject, INFINITE}; +pub(crate) fn lock_cache_file_timeout(file: &Path, timeout_ms: u32) -> Result { + use windows_sys::Win32::Foundation::{CloseHandle, WAIT_ABANDONED, WAIT_OBJECT_0, WAIT_TIMEOUT}; + use windows_sys::Win32::System::Threading::{CreateMutexW, WaitForSingleObject}; let name = crate::util::wide(&cache_mutex_name(file)); let handle = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) }; if handle.is_null() { return Err("DXIL cache: cannot create the cross-process mutex".into()); } - let wait = unsafe { WaitForSingleObject(handle, INFINITE) }; + let wait = unsafe { WaitForSingleObject(handle, timeout_ms) }; + if wait == WAIT_TIMEOUT { + unsafe { CloseHandle(handle) }; + return Err("DXIL cache: cross-process lock timed out".into()); + } if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED { unsafe { CloseHandle(handle) }; return Err(format!("DXIL cache: waiting for the cross-process mutex failed ({wait:#x})")); @@ -893,6 +897,10 @@ fn process_cache_lock(file: &Path) -> Result { Ok(ProcessCacheLock { handle }) } +fn process_cache_lock(file: &Path) -> Result { + lock_cache_file_timeout(file, windows_sys::Win32::System::Threading::INFINITE) +} + fn cached_file(file: &Path) -> Option> { if let Ok(b) = std::fs::read(&file) { if valid_dxil_container(&b) { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 55e1f69a70..931ee35934 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; @@ -1726,13 +1726,24 @@ fn load_precompile_index(path: &Path) -> HashMap> { out } -fn save_precompile_index(path: &Path, map: &HashMap>) -> std::io::Result<()> { +fn save_precompile_index(path: &Path, additions: &HashMap>) -> std::io::Result<()> { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_REPLACE_EXISTING}; + static TMP_SEQ: AtomicU64 = AtomicU64::new(0); + if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } + let _lock = recomp::dxc::lock_cache_file_timeout(path, 250).map_err(std::io::Error::other)?; + let mut map = load_precompile_index(path); + for (&rec_hash, keys) in additions { + if !keys.is_empty() && keys.len() <= 256 { + map.insert(rec_hash, keys.clone()); + } + } let mut buf = Vec::with_capacity(8 + map.len() * 20); buf.extend_from_slice(PRECOMPILE_INDEX_MAGIC); - for (&rec_hash, keys) in map { + for (&rec_hash, keys) in &map { if keys.is_empty() || keys.len() > 256 { continue; } @@ -1742,14 +1753,16 @@ fn save_precompile_index(path: &Path, map: &HashMap>) -> std::io:: buf.extend_from_slice(&k.to_le_bytes()); } } - let tmp = path.with_extension(format!("tmp{}", std::process::id())); + let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); + let tmp = path.with_extension(format!("tmp{}-{seq}", std::process::id())); std::fs::write(&tmp, &buf)?; - if path.exists() { - let _ = std::fs::remove_file(path); - } - if let Err(e) = std::fs::rename(&tmp, path) { + let to_wide = |p: &Path| -> Vec { p.as_os_str().encode_wide().chain([0]).collect() }; + let tmp_w = to_wide(&tmp); + let dst_w = to_wide(path); + if unsafe { MoveFileExW(tmp_w.as_ptr(), dst_w.as_ptr(), MOVEFILE_REPLACE_EXISTING) } == 0 { + let err = std::io::Error::last_os_error(); let _ = std::fs::remove_file(&tmp); - return Err(e); + return Err(err); } Ok(()) } @@ -1823,7 +1836,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } else { HashSet::new() }; - let index_state: Mutex>> = Mutex::new(initial_index.clone()); + let index_state: Mutex>> = Mutex::new(HashMap::new()); let dirty_index = AtomicUsize::new(0); let seen_programs: Mutex>> = Mutex::new(HashMap::new()); let seen_hlsl_jobs: Mutex> = Mutex::new(HashSet::new()); @@ -2574,11 +2587,20 @@ mod tests { let loaded = load_precompile_index(&idx); assert_eq!(loaded, map); + // Saving disjoint additions merges with existing on-disk index entries + let mut extra = HashMap::new(); + extra.insert(0x9999_0000_1111_2222u64, vec![0xEEEEu64]); + save_precompile_index(&idx, &extra).unwrap(); + let merged = load_precompile_index(&idx); + assert_eq!(merged.get(&0x1111_2222_3333_4444u64), map.get(&0x1111_2222_3333_4444u64)); + assert_eq!(merged.get(&0x5555_6666_7777_8888u64), map.get(&0x5555_6666_7777_8888u64)); + assert_eq!(merged.get(&0x9999_0000_1111_2222u64), extra.get(&0x9999_0000_1111_2222u64)); + // Corrupt trailing bytes stop safely without discarding valid prefix entries let mut raw = std::fs::read(&idx).unwrap(); raw.extend_from_slice(&[0xFFu8; 7]); std::fs::write(&idx, raw).unwrap(); - assert_eq!(load_precompile_index(&idx), map); + assert_eq!(load_precompile_index(&idx), merged); // Scope hash changes cleanly when translator source, direct_gfx, or safe_barrier toggles assert_ne!( diff --git a/crates/xcl/tests/shaders_e2e.rs b/crates/xcl/tests/shaders_e2e.rs index 390a2b40a5..a3ed43d29d 100644 --- a/crates/xcl/tests/shaders_e2e.rs +++ b/crates/xcl/tests/shaders_e2e.rs @@ -434,3 +434,52 @@ fn shaders_precompile_scopes_safe_barrier_and_bypasses_diagnostic_overrides() { assert!(diag_stdout.contains("errors 0"), "{diag_stdout}"); assert_eq!(count_indices(cache_dir.path()), 2); } + +#[test] +fn shaders_precompile_concurrent_processes_preserve_both_index_entries() { + /// s_mov_b32 s0, s1 ; v_add_f32 v0, v2, v5 ; s_endpgm + const CODE_B: [u8; 12] = [0x01, 0x03, 0x80, 0xbe, 0x02, 0x0b, 0x00, 0x06, 0x00, 0x00, 0x81, 0xbf]; + let dir_a = TempDir::new("concurrent-a"); + let dir_b = TempDir::new("concurrent-b"); + std::fs::write(dir_a.path().join("ps_a.bin"), xbox_shader(0, &[fssm(&CODE, &[(5, 1)])])).unwrap(); + std::fs::write(dir_b.path().join("ps_b.bin"), xbox_shader(0, &[fssm(&CODE_B, &[(5, 1)])])).unwrap(); + + for trial in 0..3 { + let cache_dir = TempDir::new(&format!("concurrent-cache-{trial}")); + let child_a = Command::new(env!("CARGO_BIN_EXE_xcl")) + .arg("shaders") + .arg(dir_a.path()) + .arg("--precompile") + .env("XCL_DXIL_CACHE", cache_dir.path()) + .env_remove("XCL_DIRECT_DXIL") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn child a"); + let child_b = Command::new(env!("CARGO_BIN_EXE_xcl")) + .arg("shaders") + .arg(dir_b.path()) + .arg("--precompile") + .env("XCL_DXIL_CACHE", cache_dir.path()) + .env_remove("XCL_DIRECT_DXIL") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn child b"); + + let out_a = child_a.wait_with_output().unwrap(); + let out_b = child_b.wait_with_output().unwrap(); + assert!(out_a.status.success(), "trial {trial} A: {out_a:?}"); + assert!(out_b.status.success(), "trial {trial} B: {out_b:?}"); + + let warm_a = run_shaders_with_cache(dir_a.path(), &["--precompile"], cache_dir.path()); + assert!(warm_a.status.success(), "trial {trial} warm_a: {warm_a:?}"); + let stdout_a = String::from_utf8(warm_a.stdout).unwrap(); + assert!(stdout_a.contains("compiled 0, already cached 1, errors 0"), "trial {trial} A: {stdout_a}"); + + let warm_b = run_shaders_with_cache(dir_b.path(), &["--precompile"], cache_dir.path()); + assert!(warm_b.status.success(), "trial {trial} warm_b: {warm_b:?}"); + let stdout_b = String::from_utf8(warm_b.stdout).unwrap(); + assert!(stdout_b.contains("compiled 0, already cached 1, errors 0"), "trial {trial} B: {stdout_b}"); + } +} From 65091a5a7af87d5d0b5bf11f35a34bd17e948661 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=91=D1=83=D1=88=D1=83?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Thu, 26 Nov 2026 21:42:12 -0500 Subject: [PATCH 5/6] fix(shaders): use std::fs::rename for long-path index replace & check index directly in E2E --- crates/xcl/src/shaders.rs | 35 +++++++++++++++++++++++++-------- crates/xcl/tests/shaders_e2e.rs | 24 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 931ee35934..dae9c68482 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1727,8 +1727,6 @@ fn load_precompile_index(path: &Path) -> HashMap> { } fn save_precompile_index(path: &Path, additions: &HashMap>) -> std::io::Result<()> { - use std::os::windows::ffi::OsStrExt; - use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_REPLACE_EXISTING}; static TMP_SEQ: AtomicU64 = AtomicU64::new(0); if let Some(dir) = path.parent() { @@ -1756,13 +1754,9 @@ fn save_precompile_index(path: &Path, additions: &HashMap>) -> std let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); let tmp = path.with_extension(format!("tmp{}-{seq}", std::process::id())); std::fs::write(&tmp, &buf)?; - let to_wide = |p: &Path| -> Vec { p.as_os_str().encode_wide().chain([0]).collect() }; - let tmp_w = to_wide(&tmp); - let dst_w = to_wide(path); - if unsafe { MoveFileExW(tmp_w.as_ptr(), dst_w.as_ptr(), MOVEFILE_REPLACE_EXISTING) } == 0 { - let err = std::io::Error::last_os_error(); + if let Err(e) = std::fs::rename(&tmp, path) { let _ = std::fs::remove_file(&tmp); - return Err(err); + return Err(e); } Ok(()) } @@ -2642,6 +2636,31 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn precompile_index_saves_and_merges_over_long_path() { + let root = std::env::temp_dir().join(format!("xcl-idx-long-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let seg = "a_long_nested_directory_segment_for_path_limit_testing_0123456789"; + let nested = root.join(seg).join(seg).join(seg).join(seg).join(seg); + let idx = nested.join("precompile-index-v1-longpath.bin"); + assert!(idx.as_os_str().len() > 280, "expected path > 280 chars: {}", idx.as_os_str().len()); + + let mut first = HashMap::new(); + first.insert(0x1010_2020_3030_4040u64, vec![0xABCDu64]); + save_precompile_index(&idx, &first).unwrap(); + + let mut second = HashMap::new(); + second.insert(0x5050_6060_7070_8080u64, vec![0xEF01u64]); + save_precompile_index(&idx, &second).unwrap(); + + let loaded = load_precompile_index(&idx); + assert_eq!(loaded.get(&0x1010_2020_3030_4040u64), Some(&vec![0xABCDu64])); + assert_eq!(loaded.get(&0x5050_6060_7070_8080u64), Some(&vec![0xEF01u64])); + assert_eq!(loaded.len(), 2); + + let _ = std::fs::remove_dir_all(&root); + } } /// `XCL_DUMP_HLSL=` (`--recomp`): every `XCL_DUMP_EVERY`-th complete translation (by a diff --git a/crates/xcl/tests/shaders_e2e.rs b/crates/xcl/tests/shaders_e2e.rs index a3ed43d29d..67f24b323c 100644 --- a/crates/xcl/tests/shaders_e2e.rs +++ b/crates/xcl/tests/shaders_e2e.rs @@ -472,6 +472,30 @@ fn shaders_precompile_concurrent_processes_preserve_both_index_entries() { assert!(out_a.status.success(), "trial {trial} A: {out_a:?}"); assert!(out_b.status.success(), "trial {trial} B: {out_b:?}"); + // Verify directly from disk BEFORE any serial revisit that both records survived in the index. + let indices: Vec = std::fs::read_dir(cache_dir.path()) + .unwrap() + .flatten() + .filter_map(|e| { + let s = e.file_name().to_string_lossy().into_owned(); + (s.starts_with("precompile-index-v1-") && s.ends_with(".bin")).then(|| e.path()) + }) + .collect(); + assert_eq!(indices.len(), 1, "trial {trial}: expected 1 shared index, got {indices:?}"); + let raw = std::fs::read(&indices[0]).unwrap(); + let mut rest = raw.strip_prefix(b"XCLPIDX1").expect("valid index magic"); + let mut entry_hashes = Vec::new(); + while rest.len() >= 12 { + let rec_hash = u64::from_le_bytes(rest[..8].try_into().unwrap()); + let count = u32::from_le_bytes(rest[8..12].try_into().unwrap()) as usize; + let need = 12 + count * 8; + assert!(rest.len() >= need, "trial {trial}: truncated index entry"); + entry_hashes.push(rec_hash); + rest = &rest[need..]; + } + assert!(rest.is_empty(), "trial {trial}: trailing bytes {}", rest.len()); + assert_eq!(entry_hashes.len(), 2, "trial {trial}: expected 2 index entries on disk before revisit: {entry_hashes:?}"); + let warm_a = run_shaders_with_cache(dir_a.path(), &["--precompile"], cache_dir.path()); assert!(warm_a.status.success(), "trial {trial} warm_a: {warm_a:?}"); let stdout_a = String::from_utf8(warm_a.stdout).unwrap(); From c110607afb9818b64b5fc5ba32f64e4ae8a23c8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD=20=D0=91=D1=83=D1=88=D1=83?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Fri, 27 Nov 2026 06:17:13 -0500 Subject: [PATCH 6/6] perf(shaders): address review feedback on precompile index and stats - Propagate non-NotFound I/O errors from try_load_precompile_index inside save_precompile_index so unreadable or locked index files are never overwritten as empty - Replace eager upfront validated_cache_keys scan across the entire precompile index with lazy per-key OnceLock validation (recomp::dxc::validate_cached_key) evaluated only when a selected record matches the index - Propagate cache-hit status through console_to_dxil_in_status so warm direct-DXIL and cached compute runs count against already cached instead of compiled Tests (Windows release): precompile_index 3/3, validated_cache_keys 1/1, shader_cache_tests 23/23, shaders_e2e 12/12 PASS --- crates/xcl/src/gpu/recomp/dxc.rs | 6 ++ crates/xcl/src/gpu/recomp/pso.rs | 103 ++++++++++++++++++++++++------- crates/xcl/src/shaders.rs | 103 ++++++++++++++++++++++++++----- crates/xcl/tests/shaders_e2e.rs | 48 ++++++++++++++ 4 files changed, 220 insertions(+), 40 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 0c83b9c906..c38db9549a 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -718,6 +718,12 @@ pub fn cache_key_for(src: &str, entry: &str, profile: &str) -> u64 { cache_key(src, entry, profile) } +/// Validates a single DXIL cache key using the same container check as `cached_file`. +pub fn validate_cached_key(dir: &Path, key: u64) -> bool { + let dir = normalized_cache_dir(dir); + cached_file(&dir.join(format!("{key:016x}.dxil"))).is_some() +} + /// Validates only the DXIL cache keys referenced by a warm precompile index using the /// same container check as `cached_file`, leaving unrelated cache entries unread. pub fn validated_cache_keys(dir: &Path, candidate_keys: &HashSet) -> HashSet { diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 4deb87d53d..3e5c53e97b 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -153,9 +153,21 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// 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); + console_to_dxil_in_status(blob, stage, sampler_base, split_wave64, windows).map(|(c, _)| c) +} + +/// Like [`console_to_dxil_in`], also reporting whether the shader was served from RAM/disk cache +/// rather than freshly translated/compiled. +pub fn console_to_dxil_in_status( + blob: &[u8], + stage: Stage, + sampler_base: u32, + split_wave64: bool, + windows: u32, +) -> Result<(Compiled, bool), String> { + let compile_one = || compile_console_shader_status(blob, stage, sampler_base, windows, split_wave64); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { - return compile_one().map(|(c, _)| c); + return compile_one().map(|(c, _, from_cache)| (c, from_cache)); } let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), @@ -167,8 +179,9 @@ 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); - cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone()) + let from_disk = || translated::cached_status(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); + let (shader, from_cache) = cached_shader_status(shader_cache(), key, blob, from_disk)?; + Ok((shader.as_ref().clone(), from_cache)) } /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run @@ -486,7 +499,22 @@ mod translated { split: bool, translate: impl FnOnce() -> Result<(Compiled, bool), String>, ) -> Result { - cached_rerouted(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, translate) + cached_rerouted_status(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, || { + translate().map(|(c, direct)| (c, direct, false)) + }) + .map(|(c, _)| c) + } + + pub(super) fn cached_status( + dir: &Path, + blob: &[u8], + stage: Stage, + sampler_base: u32, + windows: u32, + split: bool, + translate: impl FnOnce() -> Result<(Compiled, bool, bool), String>, + ) -> Result<(Compiled, bool), String> { + cached_rerouted_status(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, translate) } /// What the direct translator's output depends on besides the HLSL path's identity: its @@ -525,6 +553,7 @@ mod translated { identity_for(&format!("{ident:016x}"), &format!("xcl-enormous-direct-{direct:016x}")) } + #[cfg(test)] pub(super) fn cached_rerouted( dir: &Path, ident: u64, @@ -536,14 +565,31 @@ mod translated { split: bool, translate: impl FnOnce() -> Result<(Compiled, bool), String>, ) -> Result { + cached_rerouted_status(dir, ident, direct, blob, stage, sampler_base, windows, split, || { + translate().map(|(c, d)| (c, d, false)) + }) + .map(|(c, _)| c) + } + + pub(super) fn cached_rerouted_status( + dir: &Path, + ident: u64, + direct: u64, + blob: &[u8], + stage: Stage, + sampler_base: u32, + windows: u32, + split: bool, + translate: impl FnOnce() -> Result<(Compiled, bool, bool), String>, + ) -> Result<(Compiled, bool), String> { if ident == 0 { - return translate().map(|(c, _)| c); + return translate().map(|(c, _, from_cache)| (c, from_cache)); } 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); + return Ok((c, true)); } } let err_path = file(dir, rerouted, blob, stage, sampler_base, windows, split).with_extension("err"); @@ -551,13 +597,13 @@ mod translated { return Err(reason); } match translate() { - Ok((c, direct)) => { + Ok((c, direct, from_cache)) => { if err_path.is_file() { let _ = std::fs::remove_file(&err_path); } let id = if direct { rerouted } else { ident }; store_in(&file(dir, id, blob, stage, sampler_base, windows, split), id, blob, &c); - Ok(c) + Ok((c, from_cache)) } Err(reason) => { if !super::dxc::cached_only_missed() && is_cacheable_error(&reason) { @@ -582,7 +628,7 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool { // `TRANSLATION_GLUE_REVISION` in build.rs; cache serialization changes need not bump it. /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its /// disk cache entry then follows that translator's version: `translated::cached`). -fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { +fn compile_console_shader_status(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool, bool), String> { // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path // for what it cannot translate yet if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() { @@ -592,7 +638,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: match direct_compute(blob, sampler_base, windows, split_wave64) { Ok(c) => { crate::gpu::dxil::coverage::record_translated("CS"); - return Ok((c, false)); + return Ok((c, false, false)); } Err(e) => direct_fallback("CS", &e), } @@ -607,7 +653,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: match direct_graphics(blob, stage, sampler_base, windows) { Ok(c) => { crate::gpu::dxil::coverage::record_translated(if stage == Stage::Vertex { "VS" } else { "PS" }); - return Ok((c, false)); + return Ok((c, false, false)); } Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), } @@ -625,7 +671,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl.len() >> 10, c.dxil.len() >> 10 ); - return Ok((c, true)); + return Ok((c, true, false)); } Err(e) => direct_fallback("CS", &e), } @@ -659,8 +705,8 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: }) { t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } - let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) + let (dxil, from_cache) = dxc::compile_cached(&t.hlsl, "main", profile)?; + Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false, from_cache)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -874,34 +920,45 @@ fn cached_shader( blob: &[u8], compile_one: impl FnOnce() -> Result, ) -> Result, String> { + cached_shader_status(cache, key, blob, || compile_one().map(|c| (c, false))).map(|(shader, _)| shader) +} + +fn cached_shader_status( + cache: &Mutex, + key: ShaderKey, + blob: &[u8], + compile_one: impl FnOnce() -> Result<(Compiled, bool), String>, +) -> Result<(Arc, bool), String> { if let Some(shader) = cache.lock().unwrap().get(&key, blob) { dxc::note_memory_hit(); - return Ok(shader); + return Ok((shader, true)); } // Cached-only probes (non-blocking PSO creation) must never block on an in-flight worker. if dxc::in_cached_only() { - let shader = Arc::new(compile_one()?); + let (compiled, from_cache) = compile_one()?; + let shader = Arc::new(compiled); let mut cache = cache.lock().unwrap(); if let Some(existing) = cache.get(&key, blob) { - return Ok(existing); + return Ok((existing, true)); } cache.insert(key, blob, shader.clone()); - return Ok(shader); + return Ok((shader, from_cache)); } let flight = shader_flight(key.clone()); let _guard = flight.lock().unwrap_or_else(|e| e.into_inner()); if let Some(shader) = cache.lock().unwrap().get(&key, blob) { dxc::note_memory_hit(); - return Ok(shader); + return Ok((shader, true)); } // Keep compilation outside the cache lock. - let shader = Arc::new(compile_one()?); + let (compiled, from_cache) = compile_one()?; + let shader = Arc::new(compiled); let mut cache = cache.lock().unwrap(); if let Some(existing) = cache.get(&key, blob) { - return Ok(existing); + return Ok((existing, true)); } cache.insert(key, blob, shader.clone()); - Ok(shader) + Ok((shader, from_cache)) } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index dae9c68482..98d7588cb7 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1697,11 +1697,8 @@ fn precompile_index_scope( const PRECOMPILE_INDEX_MAGIC: &[u8; 8] = b"XCLPIDX1"; -fn load_precompile_index(path: &Path) -> HashMap> { +fn parse_precompile_index(bytes: &[u8]) -> HashMap> { let mut out = HashMap::new(); - let Ok(bytes) = std::fs::read(path) else { - return out; - }; let Some(mut rest) = bytes.strip_prefix(PRECOMPILE_INDEX_MAGIC.as_slice()) else { return out; }; @@ -1726,6 +1723,19 @@ fn load_precompile_index(path: &Path) -> HashMap> { out } +fn try_load_precompile_index(path: &Path) -> std::io::Result>> { + let bytes = match std::fs::read(path) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()), + Err(e) => return Err(e), + }; + Ok(parse_precompile_index(&bytes)) +} + +fn load_precompile_index(path: &Path) -> HashMap> { + try_load_precompile_index(path).unwrap_or_default() +} + fn save_precompile_index(path: &Path, additions: &HashMap>) -> std::io::Result<()> { static TMP_SEQ: AtomicU64 = AtomicU64::new(0); @@ -1733,7 +1743,7 @@ fn save_precompile_index(path: &Path, additions: &HashMap>) -> std std::fs::create_dir_all(dir)?; } let _lock = recomp::dxc::lock_cache_file_timeout(path, 250).map_err(std::io::Error::other)?; - let mut map = load_precompile_index(path); + let mut map = try_load_precompile_index(path)?; for (&rec_hash, keys) in additions { if !keys.is_empty() && keys.len() <= 256 { map.insert(rec_hash, keys.clone()); @@ -1824,11 +1834,15 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } else { HashMap::new() }; - let existing_dxil = if use_record_index && !initial_index.is_empty() { - let referenced: HashSet = initial_index.values().flatten().copied().collect(); - recomp::dxc::validated_cache_keys(&cache_dir, &referenced) + let dxil_valid: HashMap> = if use_record_index && !initial_index.is_empty() { + initial_index + .values() + .flatten() + .copied() + .map(|k| (k, std::sync::OnceLock::new())) + .collect() } else { - HashSet::new() + HashMap::new() }; let index_state: Mutex>> = Mutex::new(HashMap::new()); let dirty_index = AtomicUsize::new(0); @@ -1863,7 +1877,13 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }; let rec_hash = use_record_index.then(|| shader::fnv64(&blob)); if let Some(keys) = rec_hash.and_then(|h| initial_index.get(&h)) { - if !keys.is_empty() && keys.iter().all(|k| existing_dxil.contains(k)) { + if !keys.is_empty() + && keys.iter().all(|k| { + dxil_valid + .get(k) + .is_some_and(|cell| *cell.get_or_init(|| recomp::dxc::validate_cached_key(&cache_dir, *k))) + }) + { cached.fetch_add(keys.len(), Ordering::Relaxed); record_done(); continue; @@ -1888,22 +1908,26 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } - match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { - Ok(c) => { + match recomp::pso::console_to_dxil_in_status(&blob, recomp::pso::Stage::Compute, 0, split, windows) { + Ok((c, from_cache)) => { if let Some(p) = pipelines { p.make(&c); if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { p.make_one(&c.dxil, &c.samplers, true, None); } } - compiled.fetch_add(1, Ordering::Relaxed) + if from_cache { + cached.fetch_add(1, Ordering::Relaxed); + } else { + compiled.fetch_add(1, Ordering::Relaxed); + } } Err(e) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))); } - failed.fetch_add(1, Ordering::Relaxed) + failed.fetch_add(1, Ordering::Relaxed); } }; record_done(); @@ -1920,9 +1944,13 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on recomp::pso::Stage::Pixel }; record_indexable = false; - match recomp::pso::console_to_dxil_in(&blob, stage, 0, graphics_split, windows) { - Ok(_) => { - compiled.fetch_add(1, Ordering::Relaxed); + match recomp::pso::console_to_dxil_in_status(&blob, stage, 0, graphics_split, windows) { + Ok((_, from_cache)) => { + if from_cache { + cached.fetch_add(1, Ordering::Relaxed); + } else { + compiled.fetch_add(1, Ordering::Relaxed); + } } Err(e) if e.contains("incomplete translation") => { if startup.is_some() { @@ -2661,6 +2689,47 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + + #[test] + fn save_precompile_index_preserves_existing_file_on_read_error() { + let dir = std::env::temp_dir().join(format!("xcl-idx-readerr-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // 1. A path that exists as a directory (NotFound == false) returns Err instead of treating it as empty. + let dir_as_index = dir.join("dir_index.bin"); + std::fs::create_dir_all(&dir_as_index).unwrap(); + let mut add = HashMap::new(); + add.insert(0xDEAD_BEEFu64, vec![0x1234u64]); + let err = save_precompile_index(&dir_as_index, &add).unwrap_err(); + assert_ne!(err.kind(), std::io::ErrorKind::NotFound); + assert!(dir_as_index.is_dir()); + + // 2. An existing readable index later held with share_mode(0) must return Err and remain intact. + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + let idx = dir.join("locked_index.bin"); + let mut initial = HashMap::new(); + initial.insert(0x1111_2222_3333_4444u64, vec![0xAAAAu64]); + save_precompile_index(&idx, &initial).unwrap(); + + let locked = std::fs::OpenOptions::new() + .read(true) + .write(true) + .share_mode(0) + .open(&idx) + .unwrap(); + let err = save_precompile_index(&idx, &add).unwrap_err(); + assert_ne!(err.kind(), std::io::ErrorKind::NotFound); + drop(locked); + + let after = load_precompile_index(&idx); + assert_eq!(after, initial); + } + + let _ = std::fs::remove_dir_all(&dir); + } } /// `XCL_DUMP_HLSL=` (`--recomp`): every `XCL_DUMP_EVERY`-th complete translation (by a diff --git a/crates/xcl/tests/shaders_e2e.rs b/crates/xcl/tests/shaders_e2e.rs index 67f24b323c..d91b0643c1 100644 --- a/crates/xcl/tests/shaders_e2e.rs +++ b/crates/xcl/tests/shaders_e2e.rs @@ -507,3 +507,51 @@ fn shaders_precompile_concurrent_processes_preserve_both_index_entries() { assert!(stdout_b.contains("compiled 0, already cached 1, errors 0"), "trial {trial} B: {stdout_b}"); } } + +#[test] +fn shaders_precompile_direct_dxil_warm_reports_cached_and_limit_skips_unselected_keys() { + /// s_mov_b32 s0, s1 ; v_add_f32 v0, v2, v5 ; s_endpgm + const CODE_B: [u8; 12] = [0x01, 0x03, 0x80, 0xbe, 0x02, 0x0b, 0x00, 0x06, 0x00, 0x00, 0x81, 0xbf]; + + // 1. Direct DXIL graphics warm precompile reports `compiled 0, already cached 1`. + let gfx_dir = TempDir::new("precompile-direct-gfx"); + let gfx_cache = TempDir::new("precompile-direct-gfx-cache"); + std::fs::write(gfx_dir.path().join("ps.bin"), xbox_shader(0, &[fssm(&CODE, &[(5, 1)])])).unwrap(); + + let cold_direct = run_shaders_with_cache_and_env( + gfx_dir.path(), + &["--precompile"], + gfx_cache.path(), + &[("XCL_DIRECT_DXIL", "all")], + ); + assert!(cold_direct.status.success(), "{cold_direct:?}"); + let cold_direct_stdout = String::from_utf8(cold_direct.stdout).unwrap(); + assert!(cold_direct_stdout.contains("compiled 1, already cached 0, errors 0"), "{cold_direct_stdout}"); + + let warm_direct = run_shaders_with_cache_and_env( + gfx_dir.path(), + &["--precompile"], + gfx_cache.path(), + &[("XCL_DIRECT_DXIL", "all")], + ); + assert!(warm_direct.status.success(), "{warm_direct:?}"); + let warm_direct_stdout = String::from_utf8(warm_direct.stdout).unwrap(); + assert!(warm_direct_stdout.contains("compiled 0, already cached 1, errors 0"), "{warm_direct_stdout}"); + + // 2. Lazy per-key validation with --limit only checks selected records. + // Replace an unrelated `.dxil` with unreadable directory/invalid state and confirm --limit 1 hits cache cleanly. + let limit_dir = TempDir::new("precompile-lazy"); + let limit_cache = TempDir::new("precompile-lazy-cache"); + std::fs::write(limit_dir.path().join("00_first.bin"), xbox_shader(0, &[fssm(&CODE, &[(5, 1)])])).unwrap(); + std::fs::write(limit_dir.path().join("01_second.bin"), xbox_shader(0, &[fssm(&CODE_B, &[(5, 1)])])).unwrap(); + + let cold_all = run_shaders_with_cache(limit_dir.path(), &["--precompile"], limit_cache.path()); + assert!(cold_all.status.success(), "{cold_all:?}"); + let cold_all_stdout = String::from_utf8(cold_all.stdout).unwrap(); + assert!(cold_all_stdout.contains("compiled 2, already cached 0, errors 0"), "{cold_all_stdout}"); + + let warm_limit = run_shaders_with_cache(limit_dir.path(), &["--precompile", "--limit", "1"], limit_cache.path()); + assert!(warm_limit.status.success(), "{warm_limit:?}"); + let warm_limit_stdout = String::from_utf8(warm_limit.stdout).unwrap(); + assert!(warm_limit_stdout.contains("compiled 0, already cached 1, errors 0"), "{warm_limit_stdout}"); +}