From d0981c1de710299889a9009d03e133864daa0ff9 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:22:05 -0800 Subject: [PATCH 1/4] test(gpu): reproduce shader loss on cache publication failure --- crates/leonida-gpu/src/shader_cache.rs | 61 ++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/crates/leonida-gpu/src/shader_cache.rs b/crates/leonida-gpu/src/shader_cache.rs index 75bf51e01..11ddba4bb 100644 --- a/crates/leonida-gpu/src/shader_cache.rs +++ b/crates/leonida-gpu/src/shader_cache.rs @@ -394,6 +394,67 @@ mod tests { assert!(cached(&cache, &build, b"other", fail).is_err()); } + #[test] + fn a_translation_survives_an_unwritable_cache() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("cache"); + let cache = Cache::open(&root).unwrap(); + std::fs::remove_dir(&root).unwrap(); + std::fs::write(&root, b"not a folder").unwrap(); + let runs = AtomicU64::new(0); + let translate = |_: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + Ok(shader()) + }; + + assert_eq!(cached(&cache, &[7; 32], b"a container", translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 1, "the result was kept"); + assert_eq!(std::fs::read(&root).unwrap(), b"not a folder"); + } + + #[test] + fn a_translation_survives_failed_publication_without_leaving_a_staging_file() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let runs = AtomicU64::new(0); + let translate = |_: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + Ok(shader()) + }; + let build = [7; 32]; + let container = b"a container"; + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + let entries = walk(dir.path()); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + std::fs::remove_file(entry).unwrap(); + // A directory at the destination lets staging succeed but prevents publication. + std::fs::create_dir(entry).unwrap(); + + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 2, "one translation per miss"); + assert!(entry.is_dir(), "the conflicting destination was not removed"); + assert!(walk(dir.path()).is_empty(), "the staging file was removed"); + } + + #[test] + fn translation_errors_are_reported_and_not_cached() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let runs = AtomicU64::new(0); + let translate = |_: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + Err::("synthetic translation refused".to_owned()) + }; + + for expected in 1..=2 { + let error = cached(&cache, &[7; 32], b"a container", translate).unwrap_err(); + assert!(error.contains("synthetic translation refused"), "{error}"); + assert_eq!(runs.load(Ordering::Relaxed), expected); + assert!(walk(dir.path()).is_empty()); + } + } + fn walk(dir: &std::path::Path) -> Vec { let mut files = Vec::new(); for e in std::fs::read_dir(dir).unwrap().flatten() { From 3b4834f2573e4abb8307fb1a1f1c967c83c756d0 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:24:22 -0800 Subject: [PATCH 2/4] fix(gpu): retain translated shaders when populating the cache --- crates/leonida-gpu/src/shader_cache.rs | 59 ++++++++++++++++++-------- docs/fork-notes.md | 20 +++++++++ 2 files changed, 61 insertions(+), 18 deletions(-) diff --git a/crates/leonida-gpu/src/shader_cache.rs b/crates/leonida-gpu/src/shader_cache.rs index 11ddba4bb..0cde652bc 100644 --- a/crates/leonida-gpu/src/shader_cache.rs +++ b/crates/leonida-gpu/src/shader_cache.rs @@ -4,14 +4,16 @@ //! a changed translator never serves an old translation. Entries go through //! `leonida-pipeline`'s content-addressed cache, which writes them //! atomically; an entry that does not read back is translated again. +//! A new translation is returned directly, even if its entry cannot be +//! saved. A cache write failure warns once; it does not discard the shader. //! //! The entry is our own encoding of [`HostShader`]: a field added to it //! must be added to `encode` and `decode` too (entries of older builds //! are ignored anyway). use std::path::PathBuf; -use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; use leonida_pipeline::{Cache, Converter}; use leonida_shader::emit::{HostShader, StaticSampler, UserData}; @@ -79,7 +81,8 @@ fn build() -> [u8; 32] { /// The offline warm-up (`leonida translate --warm`): `container` is /// translated into the cache unless it is there already. `Ok(true)`: it -/// was translated now. Needs [`use_shader_cache`] and the same host facts +/// was translated now, but a cache write failure can leave it unsaved +/// (with a warning). Needs [`use_shader_cache`] and the same host facts /// the run will have (`leonida_shader::emit::translation_fingerprint`). pub fn warm(container: &[u8]) -> Result { let cache = CACHE.get().ok_or("no shader cache")?; @@ -102,10 +105,11 @@ pub(crate) fn host_shader(container: &[u8]) -> Result { } /// The cache entry's converter: the build and the container in, the -/// encoded translation out. `ran` tells a miss from a hit. +/// encoded translation out. `made` keeps the result so a miss need not +/// read and decode the entry it just wrote. struct Translate { translate: F, - ran: AtomicBool, + made: Mutex>, } impl Result + Send + Sync> Converter for Translate { @@ -117,9 +121,10 @@ impl Result + Send + Sync> Converter for Tra 1 } fn convert(&self, input: &[u8]) -> anyhow::Result> { - self.ran.store(true, Ordering::Relaxed); let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; - Ok(encode(&shader)) + let bytes = encode(&shader); + *self.made.lock().unwrap_or_else(|e| e.into_inner()) = Some(shader); + Ok(bytes) } } @@ -130,22 +135,40 @@ fn cached( translate: impl Fn(&[u8]) -> Result + Send + Sync, ) -> Result { let input = [&build[..], container].concat(); - let converter = Translate { + let mut converter = Translate { translate, - ran: AtomicBool::new(false), + made: Mutex::new(None), }; for _ in 0..2 { - let path = cache - .get_or_convert(&converter, &input) - .map_err(|e| format!("{e:#}"))?; + let entry = cache.get_or_convert(&converter, &input); + if let Some(shader) = converter + .made + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + MISSES.fetch_add(1, Ordering::Relaxed); + match entry { + Ok(path) => tracing::debug!(path = %path.display(), "shader translated and cached"), + Err(error) => { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + let key = leonida_pipeline::CacheKey::new(&converter, &input); + let path = cache.path_for(&key); + tracing::warn!( + path = %path.display(), + error = %format_args!("{error:#}"), + "shader not cached; check cache folder permissions and free space" + ); + }); + } + } + return Ok(shader); + } + let path = entry.map_err(|e| format!("{e:#}"))?; if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { - let (counter, what) = if converter.ran.load(Ordering::Relaxed) { - (&MISSES, "translated and cached") - } else { - (&HITS, "from the cache") - }; - counter.fetch_add(1, Ordering::Relaxed); - tracing::debug!(path = %path.display(), "shader {what}"); + HITS.fetch_add(1, Ordering::Relaxed); + tracing::debug!(path = %path.display(), "shader from the cache"); return Ok(shader); } tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again"); diff --git a/docs/fork-notes.md b/docs/fork-notes.md index a5557154b..356ecedfb 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -5,6 +5,26 @@ The status summary is in [README.md](../README.md). ## Newest (2026-11-26) +**UP-1: keep a shader-cache miss's translation.** +Adapted from upstream VIctory +[`bca3ecd`](https://github.com/Marvisak/VIctory/commit/bca3ecd00a3e0cf4814e0061cafc510f0a286ba2). +A cache miss keeps the shader it translated instead of reading and decoding +the entry it just wrote. If publication fails, the usable translation is +returned with one warning per process about the cache problem. Previously, +that I/O failure discarded the shader and could prevent its pipeline from +being created. Translation failures still return errors; cache hits still +decode and validate the stored entry, with damaged entries translated again. +The cache format and its atomic publication are unchanged. The existing build +fingerprint includes this source file, so this update invalidates old entries +once; warm the cache again before comparing gameplay performance. + +Original synthetic regression tests cover a cache folder replaced by a file, +a directory blocking publication at the entry's destination, staging-file +cleanup, translation errors, cache hits and corrupt-entry recovery. Both +publication regressions fail on `a141614` before the fix. No game data is used +and no gameplay or frame-rate improvement is claimed. UP-1 remains open for +other useful upstream changes. + **U-3: graphics profiles are selected by the executable.** Direct `leonida run` and translation warm-up now resolve the same measured base profile that the launch scripts used, before the runtime caches its From e72f2b1a348b9f952a5c942800f37561fc250614 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:28:31 -0800 Subject: [PATCH 3/4] docs(gpu): record shader cache retention measurements --- docs/fork-notes.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/fork-notes.md b/docs/fork-notes.md index 356ecedfb..e000a759d 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -25,6 +25,34 @@ publication regressions fail on `a141614` before the fix. No game data is used and no gameplay or frame-rate improvement is claimed. UP-1 remains open for other useful upstream changes. +Measured `a141614`'s cache implementation (with tests only, `d0981c1`) +against `3b4834f` on an Intel Core i9-14900KS, Pop!_OS 22.04, ext4, +Proton 11's Wine 11.0 in Steam's offline Flatpak runtime, Rust 1.98.1 +Windows release builds. The PC has an RTX 5090, NVIDIA 580.173.02; this +benchmark does no GPU work. An external harness embeds both exact source +files with identical adapters and the real pipeline cache. It times the +whole `cached()` call using a synthetic clone callback, excluding setup, +result checks, destruction and the caller's build-fingerprint calculation. + +Twelve paired rounds alternate implementation order and rotate payload +sizes, after two warm-up passes. Each sample has 128 lookups. Misses use +unique absent entries; the OS filesystem cache is not flushed. Every +returned field, every stored byte and the translation/hit/miss counts are +checked. All 144 samples are retained, including one slower patched 8 KiB +miss sample. Miss times in microseconds per lookup: + +| Synthetic payload | Before, median (range) | After, median (range) | Reduction in median | +|-------------------|------------------------|-----------------------|---------------------| +| 8 KiB | 276.3 (254.6–307.5) | 204.8 (177.6–419.5) | 25.9% | +| 64 KiB | 297.5 (274.6–478.0) | 220.9 (199.0–299.1) | 25.7% | +| 256 KiB | 541.5 (489.8–1394.2) | 330.2 (312.3–378.7) | 39.0% | + +Pre-existing cache-hit controls never translated. Their median paired +changes were -1.0%, -1.7% and +1.1% respectively: no cache-hit improvement +is claimed. These measurements cover synthetic cache overhead on this +host under Wine, not actual translation time, native Windows filesystem +performance, gameplay loading time or FPS. + **U-3: graphics profiles are selected by the executable.** Direct `leonida run` and translation warm-up now resolve the same measured base profile that the launch scripts used, before the runtime caches its From ff305642ecaf2d4d7491fdd8701e72c5ca04b5c3 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:28:56 -0800 Subject: [PATCH 4/4] docs(gpu): clarify the paired cache benchmark outliers --- docs/fork-notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/fork-notes.md b/docs/fork-notes.md index e000a759d..08b4f4873 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -38,8 +38,8 @@ Twelve paired rounds alternate implementation order and rotate payload sizes, after two warm-up passes. Each sample has 128 lookups. Misses use unique absent entries; the OS filesystem cache is not flushed. Every returned field, every stored byte and the translation/hit/miss counts are -checked. All 144 samples are retained, including one slower patched 8 KiB -miss sample. Miss times in microseconds per lookup: +checked. All 144 samples are retained, including two slower patched 8 KiB +miss pairs. Miss times in microseconds per lookup: | Synthetic payload | Before, median (range) | After, median (range) | Reduction in median | |-------------------|------------------------|-----------------------|---------------------|