Offline shader commands count failed cache writes as cached #185

Open
opened 2026-11-27 06:58:13 +00:00 by github-bot · 0 comments
Owner

@⁠NotADonky43 on GitHub · 2026-11-27 06:57 UTC · original

Reproduced on Windows at 6594538b

victory shaders and victory translate --warm all can exit successfully and count a shader as cached even though the cache entry could not be written. A subsequent game launch therefore still has to translate it. #29 deliberately keeps the translation in memory when runtime caching fails; that behavior should stay. What differs is the success contract of an offline command.

Title-free repro: Run victory shaders --jobs 1 on a directory with the synthetic compute fixture in the diff below, using a disposable cache. Replace the one published shader entry with a directory at the same path and rerun. With stock main, shaders still says 1 shaders in the cache and exits 0; translate --warm all also counts it as successful and exits 0. The warning is not propagated to those commands.

Proposed fix: Carry a per-call cache hit/write/failure outcome rather than inferring it from a process-global miss counter. Both offline commands count only on-disk entries and return nonzero for cache I/O failures, separately from normal unsupported shaders. A matching entry published by a different writer still counts; a different or unreadable entry does not. Gameplay keeps its in-memory fallback. No cache format or translator version change.

Validation: Same optimized profile and inputs on stock and patched 6594538b: normal writes exit 0 on both. Blocking the entry gives the false success on stock; patched commands exit 1 and report one cache I/O failure, with the separate unsupported input still reported as unsupported. Five shader cache tests, seven pipeline cache tests, and the title-free CLI integration test passed on Windows. This is a correctness fix for prewarm, not an FPS claim.

Applicable source-only diff against 6594538b

Save the contents of the block as a patch and apply with git apply. No executable or title assets required for the regression.

diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs
index e14b458f..b265f85c 100644
--- a/apps/victory/src/translate.rs
+++ b/apps/victory/src/translate.rs
@@ -18,6 +18,7 @@ use victory_shader::{
 use victory_shader::{io, resource};
 
 use crate::shader::{MAX_FILE, Source, scan::FileScan, sources};
+use victory_hle::modules::d3d12x::{self, OfflineShaderError};
 
 #[derive(Default)]
 struct Tally {
@@ -177,12 +178,14 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>, wave: Option<
     // (what is done stays in the cache; the next warm-up goes on from there).
     let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::<u64>().ok());
     let cfg = victory_core::Config::load()?;
-    victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
+    d3d12x::prepare_shader_cache(cfg.cache_subdir("shaders")?)
+        .map_err(|why| anyhow::anyhow!("opening offline shader cache: {why}"))?;
     let paths = crate::default_paths(paths)?;
     let threads = jobs.unwrap_or(4).max(1);
     let began = std::time::Instant::now();
     let done = Mutex::new(HashSet::new());
     let counts = [const { AtomicUsize::new(0) }; 5];
+    let cache_errors = CacheErrors::default();
     for root in &paths {
         for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) {
             if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
@@ -212,10 +215,14 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>, wave: Option<
                             if n.is_multiple_of(1000) {
                                 println!("warm-up      {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64());
                             }
-                            let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) {
-                                Ok(true) => 0,
-                                Ok(false) => 1,
-                                Err(_) => 2,
+                            let which = match d3d12x::precompile(&bytes) {
+                                Ok(false) => 0,
+                                Ok(true) => 1,
+                                Err(OfflineShaderError::Translate(_)) => 2,
+                                Err(OfflineShaderError::Cache(why)) => {
+                                    cache_errors.record(why);
+                                    continue;
+                                }
                             };
                             counts[which].fetch_add(1, Ordering::Relaxed);
                         }
@@ -229,10 +236,37 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>, wave: Option<
     let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" };
     println!(
         "warm-up      {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}",
-        translated + there + failed,
+        translated + there + failed + cache_errors.count(),
         began.elapsed().as_secs_f64()
     );
-    Ok(())
+    cache_errors.finish()
+}
+
+/// A partial translation batch is useful, but a cache I/O failure must not
+/// turn a precompile into a reported success. Keep only the first I/O error.
+#[derive(Default)]
+struct CacheErrors {
+    count: AtomicUsize,
+    first: std::sync::OnceLock<String>,
+}
+
+impl CacheErrors {
+    fn record(&self, why: String) {
+        self.count.fetch_add(1, Ordering::Relaxed);
+        let _ = self.first.set(why);
+    }
+
+    fn count(&self) -> usize {
+        self.count.load(Ordering::Relaxed)
+    }
+
+    fn finish(self) -> Result<()> {
+        let count = self.count();
+        if let Some(why) = self.first.into_inner() {
+            anyhow::bail!("could not cache {count} shaders: {why}");
+        }
+        Ok(())
+    }
 }
 
 pub fn run(
@@ -410,13 +444,15 @@ pub fn run(
 /// Every shader found into the cache runs translate from.
 pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>, list: Option<PathBuf>) -> Result<()> {
     let cfg = victory_core::Config::load()?;
-    victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
+    d3d12x::prepare_shader_cache(cfg.cache_subdir("shaders")?)
+        .map_err(|why| anyhow::anyhow!("opening offline shader cache: {why}"))?;
     let paths = crate::default_paths(paths)?;
     let threads =
         jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
     let started = std::time::Instant::now();
     let seen = Mutex::new(HashSet::new());
     let done = AtomicUsize::new(0);
+    let cache_errors = CacheErrors::default();
     let failed = Mutex::new(BTreeMap::<String, (usize, String)>::new());
     let lines = Mutex::new(Vec::<String>::new());
     let mut scan = FileScan::new(MAX_FILE, false);
@@ -433,14 +469,22 @@ pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>, list: Option<PathBuf
                             if !lock(&seen).insert(hash) {
                                 continue;
                             }
-                            match victory_hle::modules::d3d12x::precompile(&bytes) {
+                            match d3d12x::precompile(&bytes) {
                                 Ok(_) => {
                                     let n = done.fetch_add(1, Ordering::Relaxed) + 1;
                                     if n.is_multiple_of(1000) {
                                         println!("{n} shaders in the cache, {:.0} s", started.elapsed().as_secs_f64());
                                     }
                                 }
-                                Err(why) => {
+                                Err(OfflineShaderError::Cache(why)) => {
+                                    if list.is_some() {
+                                        let hex = hash.to_hex()[..16].to_owned();
+                                        let line = format!("{hex}\t{}{}\tcache: {why}", path.display(), job.label());
+                                        lock(&lines).push(line);
+                                    }
+                                    cache_errors.record(why);
+                                }
+                                Err(OfflineShaderError::Translate(why)) => {
                                     let hex = hash.to_hex()[..16].to_owned();
                                     if list.is_some() {
                                         let line = format!("{hex}	{}{}	{why}", path.display(), job.label());
@@ -485,7 +529,7 @@ pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>, list: Option<PathBuf
         println!("  {n:>5}  {why}  (e.g. {hash})");
     }
     println!("{scan}");
-    Ok(())
+    cache_errors.finish()
 }
 
 fn translate(
diff --git a/apps/victory/tests/shader_cache_persistence.rs b/apps/victory/tests/shader_cache_persistence.rs
new file mode 100644
index 00000000..4464e7b5
--- /dev/null
+++ b/apps/victory/tests/shader_cache_persistence.rs
@@ -0,0 +1,81 @@
+#![cfg(windows)]
+
+use std::fs;
+use std::path::Path;
+use std::process::{Command, Output};
+
+fn container(program: Option<&[u8]>) -> Vec<u8> {
+    let mut bytes = b"DXBC".to_vec();
+    bytes.extend([0; 16]); // digest unused by the parser
+    bytes.extend(1u32.to_le_bytes());
+    let size = program.map_or(32, |part| 44 + part.len() as u32);
+    bytes.extend(size.to_le_bytes());
+    bytes.extend(u32::from(program.is_some()).to_le_bytes());
+    if let Some(part) = program {
+        bytes.extend(36u32.to_le_bytes());
+        bytes.extend(b"ACCC");
+        bytes.extend((part.len() as u32).to_le_bytes());
+        bytes.extend(part);
+    }
+    bytes
+}
+
+/// A native compute shader with one wave32 group and only `s_endpgm`.
+fn empty_compute() -> Vec<u8> {
+    let packet = [0u32, 0, 0, 0x0001_0020, 0x0010_0001, 0, 0];
+    let code = [0xBF81_0000u32];
+    let metadata = [0x403u32, 4, 1, 0, 0, 0x40];
+    let mut words = vec![u32::from_le_bytes(*b"FSPX"), 1, 3, 120];
+    words.extend([0, 64, 28, 0, 6, 92, 4, 0, 7, 96, 24, 0]);
+    words.extend(packet);
+    words.extend(code);
+    words.extend(metadata);
+    let program: Vec<u8> = words.into_iter().flat_map(u32::to_le_bytes).collect();
+    container(Some(&program))
+}
+
+fn run(root: &Path, cache: &Path, args: &[&str]) -> Output {
+    Command::new(env!("CARGO_BIN_EXE_victory"))
+        .args(args)
+        .args(["--jobs", "1"])
+        .arg(root.join("input"))
+        .current_dir(root)
+        .env_remove("VICTORY_CONFIG")
+        .env_remove("VICTORY_WARM_SECONDS")
+        .env("VICTORY_CACHE_DIR", cache)
+        .env("VICTORY_DATA_DIR", root.join("data"))
+        .output()
+        .unwrap()
+}
+
+#[test]
+fn offline_commands_do_not_report_an_unwritten_shader_as_cached() {
+    let tmp = tempfile::tempdir().unwrap();
+    let root = tmp.path();
+    let cache = root.join("cache");
+    fs::create_dir(root.join("input")).unwrap();
+    let shader = empty_compute();
+    fs::write(root.join("input/shader.bin"), &shader).unwrap();
+    fs::write(root.join("input/unsupported.bin"), container(None)).unwrap();
+
+    let saved = run(root, &cache, &["shaders"]);
+    assert!(saved.status.success(), "{saved:?}");
+    assert!(String::from_utf8_lossy(&saved.stdout).contains("1 shaders in the cache, 1 do not translate"), "{saved:?}");
+
+    // Recover the real key, without duplicating host/translator key construction.
+    let shard = fs::read_dir(cache.join("shaders")).unwrap().next().unwrap().unwrap().path();
+    let entry = fs::read_dir(shard).unwrap().next().unwrap().unwrap().path();
+    fs::remove_file(&entry).unwrap();
+    fs::create_dir(&entry).unwrap();
+
+    let failed = run(root, &cache, &["shaders"]);
+    assert!(!failed.status.success(), "{failed:?}");
+    assert!(String::from_utf8_lossy(&failed.stdout).contains("0 shaders in the cache, 1 do not translate"), "{failed:?}");
+    assert!(String::from_utf8_lossy(&failed.stderr).contains("could not cache 1 shaders"), "{failed:?}");
+
+    let warm = run(root, &cache, &["translate", "--warm", "all"]);
+    assert!(!warm.status.success(), "{warm:?}");
+    assert!(String::from_utf8_lossy(&warm.stdout).contains("0 translated now, 0 in the cache already, 1 do not translate"), "{warm:?}");
+    assert!(String::from_utf8_lossy(&warm.stderr).contains("could not cache 1 shaders"), "{warm:?}");
+    assert!(entry.is_dir());
+}
diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index 3504aff6..8aaff66e 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -96,6 +96,14 @@ mod safecopy;
 mod sampler;
 #[cfg(windows)]
 pub mod shader_cache;
+
+/// An offline shader could not be translated or could not be kept on disk.
+#[derive(Debug, PartialEq, Eq)]
+pub enum OfflineShaderError {
+    Translate(String),
+    Cache(String),
+}
+
 #[cfg(windows)]
 mod memory;
 #[cfg(windows)]
diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs
index 52bace1c..024c3803 100644
--- a/crates/victory-gpu/src/shader_cache.rs
+++ b/crates/victory-gpu/src/shader_cache.rs
@@ -26,11 +26,13 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
 /// The encoding of entries ([`encode`]), part of the key.
 const FORMAT: u32 = 2;
 
-use victory_pipeline::{Cache, Converter};
+use victory_pipeline::{Cache, CacheKey, Converter};
 use victory_shader::emit::{HostShader, StaticSampler, UserData};
 use victory_shader::resource::RootIndexedView;
 use victory_shader::{HwStage, RootType};
 
+use crate::OfflineShaderError;
+
 static CACHE: OnceLock<Cache> = OnceLock::new();
 static HITS: AtomicU64 = AtomicU64::new(0);
 static MISSES: AtomicU64 = AtomicU64::new(0);
@@ -59,14 +61,18 @@ fn refresh_in_runs() -> bool {
 
 /// Keeps translated shaders in `dir` from now on.
 pub fn use_shader_cache(dir: PathBuf) {
-    match Cache::open(dir) {
-        Ok(cache) => {
-            let _ = CACHE.set(cache);
-        }
-        Err(e) => tracing::warn!(error = %e, "no shader cache"),
+    if let Err(e) = prepare_shader_cache(dir) {
+        tracing::warn!(error = %e, "no shader cache");
     }
 }
 
+/// Open the cache, propagating setup errors to offline callers.
+pub fn prepare_shader_cache(dir: PathBuf) -> Result<(), String> {
+    let cache = Cache::open(dir).map_err(|e| format!("{e:#}"))?;
+    let _ = CACHE.set(cache);
+    Ok(())
+}
+
 /// Shaders found in the cache and translated since the start.
 pub(crate) fn counts() -> (u64, u64) {
     (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed))
@@ -162,19 +168,29 @@ pub(crate) fn translation() -> [u8; 32] {
 }
 
 /// Puts the translation of `container` into the cache before any title asks
-/// for it (`victory shaders`): whether it was there already, or why it does
-/// not translate. The host is opened first, as a run does: what the card
-/// can do decides the form of some programs.
-pub fn precompile(container: &[u8]) -> Result<bool, String> {
+/// for it (`victory shaders`): whether it was there already or why it could
+/// not be translated or saved. The host is opened first, as a run does:
+/// what the card can do decides the form of some programs.
+pub fn precompile(container: &[u8]) -> Result<bool, OfflineShaderError> {
+    let cache = CACHE.get().ok_or_else(|| OfflineShaderError::Cache("no shader cache".into()))?;
     let _ = crate::host::host();
-    let misses = MISSES.load(Ordering::Relaxed);
     let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
-    match CACHE.get() {
-        Some(cache) => cached(cache, &build(), container, translate, true)?,
-        None => translate(container)?,
-    };
-    // (Counts other threads' misses too: the caller only adds them up.)
-    Ok(MISSES.load(Ordering::Relaxed) == misses)
+    offline_result(cached(cache, &build(), container, translate, true))
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum CacheStatus {
+    Hit,
+    Written,
+    NotStored(String),
+}
+
+fn offline_result(result: Result<(HostShader, CacheStatus), String>) -> Result<bool, OfflineShaderError> {
+    match result.map_err(OfflineShaderError::Translate)?.1 {
+        CacheStatus::Hit => Ok(true),
+        CacheStatus::Written => Ok(false),
+        CacheStatus::NotStored(why) => Err(OfflineShaderError::Cache(why)),
+    }
 }
 
 /// The translation of a console shader container, from the cache when
@@ -182,7 +198,7 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> {
 pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
     let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
     match CACHE.get() {
-        Some(cache) => cached(cache, &build(), container, translate, refresh_in_runs()),
+        Some(cache) => cached(cache, &build(), container, translate, refresh_in_runs()).map(|(shader, _)| shader),
         None => translate(container),
     }
 }
@@ -222,7 +238,7 @@ fn cached(
     container: &[u8],
     translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
     refresh: bool,
-) -> Result<HostShader, String> {
+) -> Result<(HostShader, CacheStatus), String> {
     let per_shader_build = victory_shader::emit::wave_wide_cache_override(container)
         .map_or(*build, |enabled| {
             *blake3::Hasher::new()
@@ -243,7 +259,7 @@ fn cached_by(
     container: &[u8],
     translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
     refresh: bool,
-) -> Result<HostShader, String> {
+) -> Result<(HostShader, CacheStatus), String> {
     let input = [&build[..], container].concat();
     let mut converter = Translate {
         translate,
@@ -255,22 +271,32 @@ fn cached_by(
         let entry = cache.get_or_convert(&converter, &input);
         if let Some(shader) = converter.made.get_mut().unwrap_or_else(|err| err.into_inner()).take() {
             MISSES.fetch_add(1, Ordering::Relaxed);
-            match entry {
-                Ok(path) => tracing::debug!(path = %path.display(), "shader translated and cached"),
+            let status = match entry {
+                Ok(path) => {
+                    tracing::debug!(path = %path.display(), "shader translated and cached");
+                    CacheStatus::Written
+                }
                 Err(error) => {
-                    static WARNED: AtomicBool = AtomicBool::new(false);
-                    if !WARNED.swap(true, Ordering::Relaxed) {
-                        tracing::warn!(%error, "shader cache write failed; using the translation in memory");
+                    let path = cache.path_for(&CacheKey::new(&converter, &input));
+                    if matches_translation(&path, &shader, source) {
+                        // A concurrent writer published the same translation.
+                        CacheStatus::Hit
+                    } else {
+                        static WARNED: AtomicBool = AtomicBool::new(false);
+                        if !WARNED.swap(true, Ordering::Relaxed) {
+                            tracing::warn!(%error, "shader cache write failed; using the translation in memory");
+                        }
+                        CacheStatus::NotStored(format!("{error:#}"))
                     }
                 }
-            }
+            };
             if let Some(old) = old.take() {
                 REFRESHED.fetch_add(1, Ordering::Relaxed);
                 if old != shader {
                     CHANGED.fetch_add(1, Ordering::Relaxed);
                 }
             }
-            return Ok(shader);
+            return Ok((shader, status));
         }
         let path = entry.map_err(|e| format!("{e:#}"))?;
         if let Some((shader, made_by)) = std::fs::read(&path).ok().and_then(|b| decode(&b)) {
@@ -291,13 +317,30 @@ fn cached_by(
             }
             HITS.fetch_add(1, Ordering::Relaxed);
             tracing::debug!(path = %path.display(), "shader from the cache");
-            return Ok(shader);
+            let status = if refresh && made_by != source.as_bytes() {
+                CacheStatus::NotStored("could not replace a shader from an earlier translator".into())
+            } else {
+                CacheStatus::Hit
+            };
+            return Ok((shader, status));
         }
         tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again");
         let _ = std::fs::remove_file(&path);
     }
     MISSES.fetch_add(1, Ordering::Relaxed);
-    (converter.translate)(container)
+    let shader = (converter.translate)(container)?;
+    let path = cache.path_for(&CacheKey::new(&converter, &input));
+    let status = if matches_translation(&path, &shader, source) {
+        CacheStatus::Hit
+    } else {
+        CacheStatus::NotStored("cache entry remained unreadable after retries".into())
+    };
+    Ok((shader, status))
+}
+
+fn matches_translation(path: &std::path::Path, shader: &HostShader, source: &str) -> bool {
+    std::fs::read(path).ok().and_then(|b| decode(&b))
+        .is_some_and(|(found, made_by)| found == *shader && made_by == source.as_bytes())
 }
 
 const MAGIC: &[u8; 4] = b"VSH2";
@@ -525,21 +568,21 @@ mod tests {
             runs.fetch_add(1, Ordering::Relaxed);
             Ok(shader())
         };
-        assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader()));
-        assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader()));
+        assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Written)));
+        assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Hit)));
         assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk");
 
         // Another build translates again.
-        assert_eq!(cached(&cache, &[8; 32], container, translate, false), Ok(shader()));
+        assert_eq!(cached(&cache, &[8; 32], container, translate, false), Ok((shader(), CacheStatus::Written)));
         assert_eq!(runs.load(Ordering::Relaxed), 2);
 
         // A damaged entry is a miss, translated and stored again.
         for e in walk(dir.path()) {
             std::fs::write(e, b"VSH2 broken").unwrap();
         }
-        assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader()));
+        assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Written)));
         assert_eq!(runs.load(Ordering::Relaxed), 3);
-        assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader()));
+        assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Hit)));
         assert_eq!(runs.load(Ordering::Relaxed), 3);
 
         // Failures are not stored.
@@ -558,17 +601,58 @@ mod tests {
             runs.fetch_add(1, Ordering::Relaxed);
             Ok(shader())
         };
-        assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader()));
+        assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Written)));
         let entries = walk(dir.path());
         assert_eq!(entries.len(), 1);
         std::fs::remove_file(&entries[0]).unwrap();
         std::fs::create_dir(&entries[0]).unwrap();
 
-        assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader()));
+        let result = cached(&cache, &build, container, translate, false);
+        assert_eq!(result.as_ref().unwrap().0, shader(), "runtime can still use the translation");
+        assert!(matches!(offline_result(result), Err(OfflineShaderError::Cache(_))));
         assert_eq!(runs.load(Ordering::Relaxed), 2);
         assert!(entries[0].is_dir());
         let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned());
-        assert!(cached(&cache, &build, container, fail, false).unwrap_err().contains("unsupported"));
+        assert!(matches!(offline_result(cached(&cache, &build, container, fail, true)),
+            Err(OfflineShaderError::Translate(why)) if why.contains("unsupported")));
+
+        std::fs::remove_dir(&entries[0]).unwrap();
+        assert_eq!(offline_result(cached(&cache, &build, container, translate, true)), Ok(false));
+        assert_eq!(offline_result(cached(&cache, &build, container, translate, true)), Ok(true));
+    }
+
+    #[test]
+    fn a_competing_writer_only_counts_if_it_published_the_same_shader() {
+        use std::os::windows::fs::OpenOptionsExt;
+        for same in [true, false] {
+            let dir = tempfile::tempdir().unwrap();
+            let cache = Cache::open(dir.path()).unwrap();
+            let build = [7u8; 32];
+            let container = b"container with competing writers";
+            let source = "translator a";
+            let mut winner = shader();
+            if !same {
+                winner.dxil.push(59);
+            }
+            let open = Mutex::new(None);
+            let translate = |_: &[u8]| {
+                // A second conversion publishes after the first has seen a miss.
+                // Hold that entry open without delete sharing so the first
+                // converter cannot replace it on Windows.
+                let inner = cached_by(&cache, &build, source, container, |_| Ok(winner.clone()), true);
+                assert_eq!(offline_result(inner), Ok(false));
+                let path = walk(dir.path()).pop().unwrap();
+                let locked = std::fs::OpenOptions::new().read(true).share_mode(1).open(path).unwrap();
+                *open.lock().unwrap() = Some(locked);
+                Ok(shader())
+            };
+            let result = cached_by(&cache, &build, source, container, translate, true);
+            if same {
+                assert_eq!(offline_result(result), Ok(true));
+            } else {
+                assert!(matches!(offline_result(result), Err(OfflineShaderError::Cache(_))));
+            }
+        }
     }
 
     fn walk(dir: &std::path::Path) -> Vec<PathBuf> {
@@ -615,20 +699,20 @@ mod tests {
             runs.fetch_add(1, Ordering::Relaxed);
             Ok(old())
         };
-        assert_eq!(cached_by(&cache, &build, "build a", container, first, false), Ok(old()));
+        assert_eq!(cached_by(&cache, &build, "build a", container, first, false), Ok((old(), CacheStatus::Written)));
         let now = |_: &[u8]| {
             runs.fetch_add(1, Ordering::Relaxed);
             Ok(shader())
         };
         let (stale, refreshed, changed) = stale_counts();
         // The next build, same version: the old translation, not translated.
-        assert_eq!(cached_by(&cache, &build, "build b", container, now, false), Ok(old()));
+        assert_eq!(cached_by(&cache, &build, "build b", container, now, false), Ok((old(), CacheStatus::Hit)));
         assert_eq!(runs.load(Ordering::Relaxed), 1);
         // Refreshing: translated again and kept.
-        assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok(shader()));
+        assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok((shader(), CacheStatus::Written)));
         assert_eq!(runs.load(Ordering::Relaxed), 2);
         // Now the entry is this build's: served when refreshing too.
-        assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok(shader()));
+        assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok((shader(), CacheStatus::Hit)));
         assert_eq!(runs.load(Ordering::Relaxed), 2);
         // (Other tests count too; these at least.)
         let (s, r, c) = stale_counts();
diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs
index d95e4729..cbaa7b72 100644
--- a/crates/victory-hle/src/modules/d3d12x.rs
+++ b/crates/victory-hle/src/modules/d3d12x.rs
@@ -4,6 +4,7 @@
 
 use std::ffi::c_void;
 
+pub use victory_gpu::OfflineShaderError;
 use victory_gpu::device;
 use victory_gpu::object::{HRESULT, Iid, Object};
 
@@ -39,8 +40,8 @@ fn host_gpu_failed(what: &str) -> ! {
 }
 
 /// Translates `container` into the cache ([`use_shader_cache`]) ahead of
-/// any run: whether it was there already, or why it does not translate.
-pub fn precompile(container: &[u8]) -> Result<bool, String> {
+/// any run: whether it was there already, or why it could not be saved or translated.
+pub fn precompile(container: &[u8]) -> Result<bool, OfflineShaderError> {
     #[cfg(windows)]
     {
         victory_gpu::shader_cache::precompile(container)
@@ -48,7 +49,7 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> {
     #[cfg(not(windows))]
     {
         let _ = container;
-        Err("no host".into())
+        Err(OfflineShaderError::Cache("no host shader cache".into()))
     }
 }
 
@@ -66,16 +67,15 @@ pub fn stale_shaders() -> (u64, u64, u64) {
     }
 }
 
-/// The fork's offline warm-up (`victory translate --warm`), by
-/// [`precompile`]: whether it was translated now.
-pub fn warm_shader(container: &[u8]) -> Result<bool, String> {
+/// Open only the shader cache for offline precompile, with no in-memory fallback.
+pub fn prepare_shader_cache(dir: std::path::PathBuf) -> Result<(), String> {
     #[cfg(windows)]
     {
-        victory_gpu::shader_cache::precompile(container).map(|was_there| !was_there)
+        victory_gpu::shader_cache::prepare_shader_cache(dir)
     }
     #[cfg(not(windows))]
     {
-        let _ = container;
+        let _ = dir;
         Err("no shader cache on this host".into())
     }
 }
**@⁠NotADonky43** on GitHub · 2026-11-27 06:57 UTC · [original](https://github.com/TaynanGT/Vice-Tay/issues/185) ### Reproduced on Windows at `6594538b` `victory shaders` and `victory translate --warm all` can exit successfully and count a shader as cached even though the cache entry could not be written. A subsequent game launch therefore still has to translate it. #29 deliberately keeps the translation in memory when runtime caching fails; that behavior should stay. What differs is the success contract of an offline command. **Title-free repro:** Run `victory shaders --jobs 1` on a directory with the synthetic compute fixture in the diff below, using a disposable cache. Replace the one published shader entry with a directory at the same path and rerun. With stock main, `shaders` still says `1 shaders in the cache` and exits 0; `translate --warm all` also counts it as successful and exits 0. The warning is not propagated to those commands. **Proposed fix:** Carry a per-call cache hit/write/failure outcome rather than inferring it from a process-global miss counter. Both offline commands count only on-disk entries and return nonzero for cache I/O failures, separately from normal unsupported shaders. A matching entry published by a different writer still counts; a different or unreadable entry does not. Gameplay keeps its in-memory fallback. No cache format or translator version change. **Validation:** Same optimized profile and inputs on stock and patched `6594538b`: normal writes exit 0 on both. Blocking the entry gives the false success on stock; patched commands exit 1 and report one cache I/O failure, with the separate unsupported input still reported as unsupported. Five shader cache tests, seven pipeline cache tests, and the title-free CLI integration test passed on Windows. This is a correctness fix for prewarm, not an FPS claim. <details> <summary>Applicable source-only diff against <code>6594538b</code></summary> Save the contents of the block as a patch and apply with `git apply`. No executable or title assets required for the regression. ```diff diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index e14b458f..b265f85c 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -18,6 +18,7 @@ use victory_shader::{ use victory_shader::{io, resource}; use crate::shader::{MAX_FILE, Source, scan::FileScan, sources}; +use victory_hle::modules::d3d12x::{self, OfflineShaderError}; #[derive(Default)] struct Tally { @@ -177,12 +178,14 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>, wave: Option< // (what is done stays in the cache; the next warm-up goes on from there). let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::<u64>().ok()); let cfg = victory_core::Config::load()?; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + d3d12x::prepare_shader_cache(cfg.cache_subdir("shaders")?) + .map_err(|why| anyhow::anyhow!("opening offline shader cache: {why}"))?; let paths = crate::default_paths(paths)?; let threads = jobs.unwrap_or(4).max(1); let began = std::time::Instant::now(); let done = Mutex::new(HashSet::new()); let counts = [const { AtomicUsize::new(0) }; 5]; + let cache_errors = CacheErrors::default(); for root in &paths { for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { @@ -212,10 +215,14 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>, wave: Option< if n.is_multiple_of(1000) { println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64()); } - let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) { - Ok(true) => 0, - Ok(false) => 1, - Err(_) => 2, + let which = match d3d12x::precompile(&bytes) { + Ok(false) => 0, + Ok(true) => 1, + Err(OfflineShaderError::Translate(_)) => 2, + Err(OfflineShaderError::Cache(why)) => { + cache_errors.record(why); + continue; + } }; counts[which].fetch_add(1, Ordering::Relaxed); } @@ -229,10 +236,37 @@ pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>, wave: Option< let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" }; println!( "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}", - translated + there + failed, + translated + there + failed + cache_errors.count(), began.elapsed().as_secs_f64() ); - Ok(()) + cache_errors.finish() +} + +/// A partial translation batch is useful, but a cache I/O failure must not +/// turn a precompile into a reported success. Keep only the first I/O error. +#[derive(Default)] +struct CacheErrors { + count: AtomicUsize, + first: std::sync::OnceLock<String>, +} + +impl CacheErrors { + fn record(&self, why: String) { + self.count.fetch_add(1, Ordering::Relaxed); + let _ = self.first.set(why); + } + + fn count(&self) -> usize { + self.count.load(Ordering::Relaxed) + } + + fn finish(self) -> Result<()> { + let count = self.count(); + if let Some(why) = self.first.into_inner() { + anyhow::bail!("could not cache {count} shaders: {why}"); + } + Ok(()) + } } pub fn run( @@ -410,13 +444,15 @@ pub fn run( /// Every shader found into the cache runs translate from. pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>, list: Option<PathBuf>) -> Result<()> { let cfg = victory_core::Config::load()?; - victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + d3d12x::prepare_shader_cache(cfg.cache_subdir("shaders")?) + .map_err(|why| anyhow::anyhow!("opening offline shader cache: {why}"))?; let paths = crate::default_paths(paths)?; let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); let started = std::time::Instant::now(); let seen = Mutex::new(HashSet::new()); let done = AtomicUsize::new(0); + let cache_errors = CacheErrors::default(); let failed = Mutex::new(BTreeMap::<String, (usize, String)>::new()); let lines = Mutex::new(Vec::<String>::new()); let mut scan = FileScan::new(MAX_FILE, false); @@ -433,14 +469,22 @@ pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>, list: Option<PathBuf if !lock(&seen).insert(hash) { continue; } - match victory_hle::modules::d3d12x::precompile(&bytes) { + match d3d12x::precompile(&bytes) { Ok(_) => { let n = done.fetch_add(1, Ordering::Relaxed) + 1; if n.is_multiple_of(1000) { println!("{n} shaders in the cache, {:.0} s", started.elapsed().as_secs_f64()); } } - Err(why) => { + Err(OfflineShaderError::Cache(why)) => { + if list.is_some() { + let hex = hash.to_hex()[..16].to_owned(); + let line = format!("{hex}\t{}{}\tcache: {why}", path.display(), job.label()); + lock(&lines).push(line); + } + cache_errors.record(why); + } + Err(OfflineShaderError::Translate(why)) => { let hex = hash.to_hex()[..16].to_owned(); if list.is_some() { let line = format!("{hex} {}{} {why}", path.display(), job.label()); @@ -485,7 +529,7 @@ pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>, list: Option<PathBuf println!(" {n:>5} {why} (e.g. {hash})"); } println!("{scan}"); - Ok(()) + cache_errors.finish() } fn translate( diff --git a/apps/victory/tests/shader_cache_persistence.rs b/apps/victory/tests/shader_cache_persistence.rs new file mode 100644 index 00000000..4464e7b5 --- /dev/null +++ b/apps/victory/tests/shader_cache_persistence.rs @@ -0,0 +1,81 @@ +#![cfg(windows)] + +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +fn container(program: Option<&[u8]>) -> Vec<u8> { + let mut bytes = b"DXBC".to_vec(); + bytes.extend([0; 16]); // digest unused by the parser + bytes.extend(1u32.to_le_bytes()); + let size = program.map_or(32, |part| 44 + part.len() as u32); + bytes.extend(size.to_le_bytes()); + bytes.extend(u32::from(program.is_some()).to_le_bytes()); + if let Some(part) = program { + bytes.extend(36u32.to_le_bytes()); + bytes.extend(b"ACCC"); + bytes.extend((part.len() as u32).to_le_bytes()); + bytes.extend(part); + } + bytes +} + +/// A native compute shader with one wave32 group and only `s_endpgm`. +fn empty_compute() -> Vec<u8> { + let packet = [0u32, 0, 0, 0x0001_0020, 0x0010_0001, 0, 0]; + let code = [0xBF81_0000u32]; + let metadata = [0x403u32, 4, 1, 0, 0, 0x40]; + let mut words = vec![u32::from_le_bytes(*b"FSPX"), 1, 3, 120]; + words.extend([0, 64, 28, 0, 6, 92, 4, 0, 7, 96, 24, 0]); + words.extend(packet); + words.extend(code); + words.extend(metadata); + let program: Vec<u8> = words.into_iter().flat_map(u32::to_le_bytes).collect(); + container(Some(&program)) +} + +fn run(root: &Path, cache: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_victory")) + .args(args) + .args(["--jobs", "1"]) + .arg(root.join("input")) + .current_dir(root) + .env_remove("VICTORY_CONFIG") + .env_remove("VICTORY_WARM_SECONDS") + .env("VICTORY_CACHE_DIR", cache) + .env("VICTORY_DATA_DIR", root.join("data")) + .output() + .unwrap() +} + +#[test] +fn offline_commands_do_not_report_an_unwritten_shader_as_cached() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let cache = root.join("cache"); + fs::create_dir(root.join("input")).unwrap(); + let shader = empty_compute(); + fs::write(root.join("input/shader.bin"), &shader).unwrap(); + fs::write(root.join("input/unsupported.bin"), container(None)).unwrap(); + + let saved = run(root, &cache, &["shaders"]); + assert!(saved.status.success(), "{saved:?}"); + assert!(String::from_utf8_lossy(&saved.stdout).contains("1 shaders in the cache, 1 do not translate"), "{saved:?}"); + + // Recover the real key, without duplicating host/translator key construction. + let shard = fs::read_dir(cache.join("shaders")).unwrap().next().unwrap().unwrap().path(); + let entry = fs::read_dir(shard).unwrap().next().unwrap().unwrap().path(); + fs::remove_file(&entry).unwrap(); + fs::create_dir(&entry).unwrap(); + + let failed = run(root, &cache, &["shaders"]); + assert!(!failed.status.success(), "{failed:?}"); + assert!(String::from_utf8_lossy(&failed.stdout).contains("0 shaders in the cache, 1 do not translate"), "{failed:?}"); + assert!(String::from_utf8_lossy(&failed.stderr).contains("could not cache 1 shaders"), "{failed:?}"); + + let warm = run(root, &cache, &["translate", "--warm", "all"]); + assert!(!warm.status.success(), "{warm:?}"); + assert!(String::from_utf8_lossy(&warm.stdout).contains("0 translated now, 0 in the cache already, 1 do not translate"), "{warm:?}"); + assert!(String::from_utf8_lossy(&warm.stderr).contains("could not cache 1 shaders"), "{warm:?}"); + assert!(entry.is_dir()); +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 3504aff6..8aaff66e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -96,6 +96,14 @@ mod safecopy; mod sampler; #[cfg(windows)] pub mod shader_cache; + +/// An offline shader could not be translated or could not be kept on disk. +#[derive(Debug, PartialEq, Eq)] +pub enum OfflineShaderError { + Translate(String), + Cache(String), +} + #[cfg(windows)] mod memory; #[cfg(windows)] diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 52bace1c..024c3803 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -26,11 +26,13 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// The encoding of entries ([`encode`]), part of the key. const FORMAT: u32 = 2; -use victory_pipeline::{Cache, Converter}; +use victory_pipeline::{Cache, CacheKey, Converter}; use victory_shader::emit::{HostShader, StaticSampler, UserData}; use victory_shader::resource::RootIndexedView; use victory_shader::{HwStage, RootType}; +use crate::OfflineShaderError; + static CACHE: OnceLock<Cache> = OnceLock::new(); static HITS: AtomicU64 = AtomicU64::new(0); static MISSES: AtomicU64 = AtomicU64::new(0); @@ -59,14 +61,18 @@ fn refresh_in_runs() -> bool { /// Keeps translated shaders in `dir` from now on. pub fn use_shader_cache(dir: PathBuf) { - match Cache::open(dir) { - Ok(cache) => { - let _ = CACHE.set(cache); - } - Err(e) => tracing::warn!(error = %e, "no shader cache"), + if let Err(e) = prepare_shader_cache(dir) { + tracing::warn!(error = %e, "no shader cache"); } } +/// Open the cache, propagating setup errors to offline callers. +pub fn prepare_shader_cache(dir: PathBuf) -> Result<(), String> { + let cache = Cache::open(dir).map_err(|e| format!("{e:#}"))?; + let _ = CACHE.set(cache); + Ok(()) +} + /// Shaders found in the cache and translated since the start. pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) @@ -162,19 +168,29 @@ pub(crate) fn translation() -> [u8; 32] { } /// Puts the translation of `container` into the cache before any title asks -/// for it (`victory shaders`): whether it was there already, or why it does -/// not translate. The host is opened first, as a run does: what the card -/// can do decides the form of some programs. -pub fn precompile(container: &[u8]) -> Result<bool, String> { +/// for it (`victory shaders`): whether it was there already or why it could +/// not be translated or saved. The host is opened first, as a run does: +/// what the card can do decides the form of some programs. +pub fn precompile(container: &[u8]) -> Result<bool, OfflineShaderError> { + let cache = CACHE.get().ok_or_else(|| OfflineShaderError::Cache("no shader cache".into()))?; let _ = crate::host::host(); - let misses = MISSES.load(Ordering::Relaxed); let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); - match CACHE.get() { - Some(cache) => cached(cache, &build(), container, translate, true)?, - None => translate(container)?, - }; - // (Counts other threads' misses too: the caller only adds them up.) - Ok(MISSES.load(Ordering::Relaxed) == misses) + offline_result(cached(cache, &build(), container, translate, true)) +} + +#[derive(Debug, PartialEq, Eq)] +enum CacheStatus { + Hit, + Written, + NotStored(String), +} + +fn offline_result(result: Result<(HostShader, CacheStatus), String>) -> Result<bool, OfflineShaderError> { + match result.map_err(OfflineShaderError::Translate)?.1 { + CacheStatus::Hit => Ok(true), + CacheStatus::Written => Ok(false), + CacheStatus::NotStored(why) => Err(OfflineShaderError::Cache(why)), + } } /// The translation of a console shader container, from the cache when @@ -182,7 +198,7 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> { pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => cached(cache, &build(), container, translate, refresh_in_runs()), + Some(cache) => cached(cache, &build(), container, translate, refresh_in_runs()).map(|(shader, _)| shader), None => translate(container), } } @@ -222,7 +238,7 @@ fn cached( container: &[u8], translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync, refresh: bool, -) -> Result<HostShader, String> { +) -> Result<(HostShader, CacheStatus), String> { let per_shader_build = victory_shader::emit::wave_wide_cache_override(container) .map_or(*build, |enabled| { *blake3::Hasher::new() @@ -243,7 +259,7 @@ fn cached_by( container: &[u8], translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync, refresh: bool, -) -> Result<HostShader, String> { +) -> Result<(HostShader, CacheStatus), String> { let input = [&build[..], container].concat(); let mut converter = Translate { translate, @@ -255,22 +271,32 @@ fn cached_by( let entry = cache.get_or_convert(&converter, &input); if let Some(shader) = converter.made.get_mut().unwrap_or_else(|err| err.into_inner()).take() { MISSES.fetch_add(1, Ordering::Relaxed); - match entry { - Ok(path) => tracing::debug!(path = %path.display(), "shader translated and cached"), + let status = match entry { + Ok(path) => { + tracing::debug!(path = %path.display(), "shader translated and cached"); + CacheStatus::Written + } Err(error) => { - static WARNED: AtomicBool = AtomicBool::new(false); - if !WARNED.swap(true, Ordering::Relaxed) { - tracing::warn!(%error, "shader cache write failed; using the translation in memory"); + let path = cache.path_for(&CacheKey::new(&converter, &input)); + if matches_translation(&path, &shader, source) { + // A concurrent writer published the same translation. + CacheStatus::Hit + } else { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!(%error, "shader cache write failed; using the translation in memory"); + } + CacheStatus::NotStored(format!("{error:#}")) } } - } + }; if let Some(old) = old.take() { REFRESHED.fetch_add(1, Ordering::Relaxed); if old != shader { CHANGED.fetch_add(1, Ordering::Relaxed); } } - return Ok(shader); + return Ok((shader, status)); } let path = entry.map_err(|e| format!("{e:#}"))?; if let Some((shader, made_by)) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { @@ -291,13 +317,30 @@ fn cached_by( } HITS.fetch_add(1, Ordering::Relaxed); tracing::debug!(path = %path.display(), "shader from the cache"); - return Ok(shader); + let status = if refresh && made_by != source.as_bytes() { + CacheStatus::NotStored("could not replace a shader from an earlier translator".into()) + } else { + CacheStatus::Hit + }; + return Ok((shader, status)); } tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again"); let _ = std::fs::remove_file(&path); } MISSES.fetch_add(1, Ordering::Relaxed); - (converter.translate)(container) + let shader = (converter.translate)(container)?; + let path = cache.path_for(&CacheKey::new(&converter, &input)); + let status = if matches_translation(&path, &shader, source) { + CacheStatus::Hit + } else { + CacheStatus::NotStored("cache entry remained unreadable after retries".into()) + }; + Ok((shader, status)) +} + +fn matches_translation(path: &std::path::Path, shader: &HostShader, source: &str) -> bool { + std::fs::read(path).ok().and_then(|b| decode(&b)) + .is_some_and(|(found, made_by)| found == *shader && made_by == source.as_bytes()) } const MAGIC: &[u8; 4] = b"VSH2"; @@ -525,21 +568,21 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader())); - assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Written))); + assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Hit))); assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); // Another build translates again. - assert_eq!(cached(&cache, &[8; 32], container, translate, false), Ok(shader())); + assert_eq!(cached(&cache, &[8; 32], container, translate, false), Ok((shader(), CacheStatus::Written))); assert_eq!(runs.load(Ordering::Relaxed), 2); // A damaged entry is a miss, translated and stored again. for e in walk(dir.path()) { std::fs::write(e, b"VSH2 broken").unwrap(); } - assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Written))); assert_eq!(runs.load(Ordering::Relaxed), 3); - assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Hit))); assert_eq!(runs.load(Ordering::Relaxed), 3); // Failures are not stored. @@ -558,17 +601,58 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate, false), Ok((shader(), CacheStatus::Written))); let entries = walk(dir.path()); assert_eq!(entries.len(), 1); std::fs::remove_file(&entries[0]).unwrap(); std::fs::create_dir(&entries[0]).unwrap(); - assert_eq!(cached(&cache, &build, container, translate, false), Ok(shader())); + let result = cached(&cache, &build, container, translate, false); + assert_eq!(result.as_ref().unwrap().0, shader(), "runtime can still use the translation"); + assert!(matches!(offline_result(result), Err(OfflineShaderError::Cache(_)))); assert_eq!(runs.load(Ordering::Relaxed), 2); assert!(entries[0].is_dir()); let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned()); - assert!(cached(&cache, &build, container, fail, false).unwrap_err().contains("unsupported")); + assert!(matches!(offline_result(cached(&cache, &build, container, fail, true)), + Err(OfflineShaderError::Translate(why)) if why.contains("unsupported"))); + + std::fs::remove_dir(&entries[0]).unwrap(); + assert_eq!(offline_result(cached(&cache, &build, container, translate, true)), Ok(false)); + assert_eq!(offline_result(cached(&cache, &build, container, translate, true)), Ok(true)); + } + + #[test] + fn a_competing_writer_only_counts_if_it_published_the_same_shader() { + use std::os::windows::fs::OpenOptionsExt; + for same in [true, false] { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let build = [7u8; 32]; + let container = b"container with competing writers"; + let source = "translator a"; + let mut winner = shader(); + if !same { + winner.dxil.push(59); + } + let open = Mutex::new(None); + let translate = |_: &[u8]| { + // A second conversion publishes after the first has seen a miss. + // Hold that entry open without delete sharing so the first + // converter cannot replace it on Windows. + let inner = cached_by(&cache, &build, source, container, |_| Ok(winner.clone()), true); + assert_eq!(offline_result(inner), Ok(false)); + let path = walk(dir.path()).pop().unwrap(); + let locked = std::fs::OpenOptions::new().read(true).share_mode(1).open(path).unwrap(); + *open.lock().unwrap() = Some(locked); + Ok(shader()) + }; + let result = cached_by(&cache, &build, source, container, translate, true); + if same { + assert_eq!(offline_result(result), Ok(true)); + } else { + assert!(matches!(offline_result(result), Err(OfflineShaderError::Cache(_)))); + } + } } fn walk(dir: &std::path::Path) -> Vec<PathBuf> { @@ -615,20 +699,20 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(old()) }; - assert_eq!(cached_by(&cache, &build, "build a", container, first, false), Ok(old())); + assert_eq!(cached_by(&cache, &build, "build a", container, first, false), Ok((old(), CacheStatus::Written))); let now = |_: &[u8]| { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; let (stale, refreshed, changed) = stale_counts(); // The next build, same version: the old translation, not translated. - assert_eq!(cached_by(&cache, &build, "build b", container, now, false), Ok(old())); + assert_eq!(cached_by(&cache, &build, "build b", container, now, false), Ok((old(), CacheStatus::Hit))); assert_eq!(runs.load(Ordering::Relaxed), 1); // Refreshing: translated again and kept. - assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok(shader())); + assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok((shader(), CacheStatus::Written))); assert_eq!(runs.load(Ordering::Relaxed), 2); // Now the entry is this build's: served when refreshing too. - assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok(shader())); + assert_eq!(cached_by(&cache, &build, "build b", container, now, true), Ok((shader(), CacheStatus::Hit))); assert_eq!(runs.load(Ordering::Relaxed), 2); // (Other tests count too; these at least.) let (s, r, c) = stale_counts(); diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index d95e4729..cbaa7b72 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -4,6 +4,7 @@ use std::ffi::c_void; +pub use victory_gpu::OfflineShaderError; use victory_gpu::device; use victory_gpu::object::{HRESULT, Iid, Object}; @@ -39,8 +40,8 @@ fn host_gpu_failed(what: &str) -> ! { } /// Translates `container` into the cache ([`use_shader_cache`]) ahead of -/// any run: whether it was there already, or why it does not translate. -pub fn precompile(container: &[u8]) -> Result<bool, String> { +/// any run: whether it was there already, or why it could not be saved or translated. +pub fn precompile(container: &[u8]) -> Result<bool, OfflineShaderError> { #[cfg(windows)] { victory_gpu::shader_cache::precompile(container) @@ -48,7 +49,7 @@ pub fn precompile(container: &[u8]) -> Result<bool, String> { #[cfg(not(windows))] { let _ = container; - Err("no host".into()) + Err(OfflineShaderError::Cache("no host shader cache".into())) } } @@ -66,16 +67,15 @@ pub fn stale_shaders() -> (u64, u64, u64) { } } -/// The fork's offline warm-up (`victory translate --warm`), by -/// [`precompile`]: whether it was translated now. -pub fn warm_shader(container: &[u8]) -> Result<bool, String> { +/// Open only the shader cache for offline precompile, with no in-memory fallback. +pub fn prepare_shader_cache(dir: std::path::PathBuf) -> Result<(), String> { #[cfg(windows)] { - victory_gpu::shader_cache::precompile(container).map(|was_there| !was_there) + victory_gpu::shader_cache::prepare_shader_cache(dir) } #[cfg(not(windows))] { - let _ = container; + let _ = dir; Err("no shader cache on this host".into()) } } ``` </details>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 06:58:14 +00:00
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/TaynanGT--Vice-Tay#185
No description provided.