Shader cache: a cache that cannot write still translates #389

Closed
github-bot wants to merge 1 commit from gh-pr/389/head into gh-pr/389/base
Owner

@⁠Kaairim on GitHub · 2026-11-24 02:52 UTC · original
Kaairim:shader-cache-write-failure → main · +75 −7 · 1 files · 1 commits · closed without merging

What

When the shader cache cannot store an entry, host_shader now returns the translation it just made instead of the cache's error. A warning is logged once. A translation that itself fails still fails, once, with the same message as before.

Why

Cache::get_or_convert translates, then creates the entry's folder, writes a temporary file and renames it. If any of those three fail (a full disk, a cache folder we may not write, a file held by a scanner), it returns an error and cached passed it on with ?: the translation had been made and was dropped, so the shader – and the pipeline and draws using it – were lost for the whole run, every time.

The converter now keeps its last output (and whether the translation itself failed), so cached can tell the two errors apart and use the output when only the cache failed.

Tested

Windows 11 (build 26300), Rust 1.98.1 (pinned toolchain), x86_64-pc-windows-msvc:

  • New test shader_cache::tests::a_cache_that_cannot_write_still_translates: a file where the cache folder was, so no entry can be written. Without the fix the first assert fails (Err); with it the shader comes back from the one translation made, and a failing translation is still an error, run once.
  • cargo test --workspace --no-fail-fast: 265 passed, 0 failed, 4 ignored (main: 264 / 0 / 4).
  • cargo clippy --workspace --all-targets: the same two warnings as main, none in this file.
  • rustfmt --check --edition 2024 crates/victory-gpu/src/shader_cache.rs: clean.
  • cargo xtask policy: ok.

Not run: the title (I have no copy of it). The changed path only runs when the cache cannot write.

Improvements by William "kaairim" Deivid (wdcore). AI-assisted: Claude Code with Claude Opus 5.5 wrote the change, the test and this description; a second Claude Opus 5.5 agent reviewed the diff.

🤖 Generated with Claude Code

**@⁠Kaairim** on GitHub · 2026-11-24 02:52 UTC · [original](https://github.com/Marvisak/VIctory/pull/389) `Kaairim:shader-cache-write-failure` → `main` · +75 −7 · 1 files · 1 commits · closed without merging ## What When the shader cache cannot store an entry, `host_shader` now returns the translation it just made instead of the cache's error. A warning is logged once. A translation that itself fails still fails, once, with the same message as before. ## Why `Cache::get_or_convert` translates, then creates the entry's folder, writes a temporary file and renames it. If any of those three fail (a full disk, a cache folder we may not write, a file held by a scanner), it returns an error and `cached` passed it on with `?`: the translation had been made and was dropped, so the shader – and the pipeline and draws using it – were lost for the whole run, every time. The converter now keeps its last output (and whether the translation itself failed), so `cached` can tell the two errors apart and use the output when only the cache failed. ## Tested Windows 11 (build 26300), Rust 1.98.1 (pinned toolchain), x86_64-pc-windows-msvc: - New test `shader_cache::tests::a_cache_that_cannot_write_still_translates`: a file where the cache folder was, so no entry can be written. Without the fix the first assert fails (`Err`); with it the shader comes back from the one translation made, and a failing translation is still an error, run once. - `cargo test --workspace --no-fail-fast`: 265 passed, 0 failed, 4 ignored (main: 264 / 0 / 4). - `cargo clippy --workspace --all-targets`: the same two warnings as main, none in this file. - `rustfmt --check --edition 2024 crates/victory-gpu/src/shader_cache.rs`: clean. - `cargo xtask policy`: ok. Not run: the title (I have no copy of it). The changed path only runs when the cache cannot write. Improvements by William "kaairim" Deivid (wdcore). AI-assisted: Claude Code with Claude Opus 5.5 wrote the change, the test and this description; a second Claude Opus 5.5 agent reviewed the diff. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
When the cache could not store an entry (a full disk, a folder we may not
write, a file held by a scanner), get_or_convert returned an error and
host_shader failed with it: the translation had been made, but was
dropped, and the pipeline using it was lost. Now the translation made is
used, a warning is logged once, and only the shader's own translation
errors fail the shader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:02:13 +00:00
github-bot closed this pull request 2026-11-26 04:02:13 +00:00
Author
Owner

@⁠jeremygold02 on GitHub · 2026-11-24 04:25 UTC · original

Thanks @⁠Kaairim for preserving translation when cache writes fail. I tested head c84e0e60bfc13de5e603c445ebaaf827690ae6cd with:

cargo test --locked -p victory-gpu --lib a_cache_that_cannot_write_still_translates -- --test-threads=1

Result: 1 passed, 0 failed (44 filtered out). The test exercises shader translation with a cache configured so writes are unavailable, checking that the cache failure does not prevent translation. It does not exercise a game launch or persistent cache across processes.

**@⁠jeremygold02** on GitHub · 2026-11-24 04:25 UTC · [original](https://github.com/Marvisak/VIctory/pull/389#issuecomment-7122010053) Thanks @⁠Kaairim for preserving translation when cache writes fail. I tested head `c84e0e60bfc13de5e603c445ebaaf827690ae6cd` with: ``` cargo test --locked -p victory-gpu --lib a_cache_that_cannot_write_still_translates -- --test-threads=1 ``` Result: 1 passed, 0 failed (44 filtered out). The test exercises shader translation with a cache configured so writes are unavailable, checking that the cache failure does not prevent translation. It does not exercise a game launch or persistent cache across processes.
Author
Owner

@⁠andrewpozdnakov7-jpg on GitHub · 2026-11-24 11:54 UTC · original

I checked the shader-cache pair from #813 at a later failure point than the existing shard-folder tests. In a temporary cache, the entry path was a directory. The shader translated, the temporary file could be written, and renaming it into place failed.

Local merge on ffe310e Returned the shader Translator calls
Main No 1
#358 at 369dc32 Yes 2
#389 at c84e0e6 Yes 1

All three cleaned up the temporary entry. After removing the obstruction, the next call wrote a valid entry and the following call hit it.

The incremental change below keeps the original HostShader in #389's converter. That removes the encoded-buffer clone and returns the original on a fresh miss, whether publication succeeded or failed. A cache hit still decodes the stored entry. The tests confirmed the original translator output was retained in both miss cases and that a subsequent hit did not invoke the translator.

AI-assisted. Verified on Windows with synthetic cache entries.

Incremental patch on c84e0e6
diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs
--- a/crates/victory-gpu/src/shader_cache.rs
+++ b/crates/victory-gpu/src/shader_cache.rs
@@ -78,14 +78,12 @@ pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
 }
 
 /// The cache entry's converter: the build and the container in, the
-/// encoded translation out. `ran` tells a miss from a hit; `output` keeps
-/// the last translation so that one the cache could not write still serves,
-/// and `failed` tells the translation's own error from the cache's.
+/// encoded translation out. A miss also keeps the original host shader.
+/// `failed` tells the translation's own error from a cache write error.
 struct Translate<F> {
     translate: F,
-    ran: AtomicBool,
     failed: AtomicBool,
-    output: Mutex<Option<Vec<u8>>>,
+    output: Mutex<Option<HostShader>>,
 }
 
 impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> {
@@ -97,13 +95,12 @@ impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Tra
         1
     }
     fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> {
-        self.ran.store(true, Ordering::Relaxed);
         let shader = (self.translate)(&input[32..]).map_err(|e| {
             self.failed.store(true, Ordering::Relaxed);
             anyhow::Error::msg(e)
         })?;
         let bytes = encode(&shader);
-        *self.output.lock().unwrap_or_else(|e| e.into_inner()) = Some(bytes.clone());
+        *self.output.lock().unwrap_or_else(|e| e.into_inner()) = Some(shader);
         Ok(bytes)
     }
 }
@@ -117,10 +114,16 @@ fn cached(
     let input = [&build[..], container].concat();
     let converter = Translate {
         translate,
-        ran: AtomicBool::new(false),
         failed: AtomicBool::new(false),
         output: Mutex::new(None),
     };
+    let take_output = || {
+        converter
+            .output
+            .lock()
+            .unwrap_or_else(|e| e.into_inner())
+            .take()
+    };
     for _ in 0..2 {
         let path = match cache.get_or_convert(&converter, &input) {
             Ok(path) => path,
@@ -133,29 +136,24 @@ fn cached(
                 if !WARNED.swap(true, Ordering::Relaxed) {
                     tracing::warn!(
                         error = %format_args!("{e:#}"),
-                        "shader cache not written; translating without it"
+                        "shader cache entry not written"
                     );
                 }
                 MISSES.fetch_add(1, Ordering::Relaxed);
-                let kept = converter
-                    .output
-                    .lock()
-                    .unwrap_or_else(|e| e.into_inner())
-                    .take();
-                return match kept.and_then(|b| decode(&b)) {
+                return match take_output() {
                     Some(shader) => Ok(shader),
                     None => (converter.translate)(container),
                 };
             }
         };
+        if let Some(shader) = take_output() {
+            MISSES.fetch_add(1, Ordering::Relaxed);
+            tracing::debug!(path = %path.display(), "shader translated and cached");
+            return Ok(shader);
+        }
         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");
**@⁠andrewpozdnakov7-jpg** on GitHub · 2026-11-24 11:54 UTC · [original](https://github.com/Marvisak/VIctory/pull/389#issuecomment-7130711180) I checked the shader-cache pair from #813 at a later failure point than the existing shard-folder tests. In a temporary cache, the entry path was a directory. The shader translated, the temporary file could be written, and renaming it into place failed. | Local merge on `ffe310e` | Returned the shader | Translator calls | | --- | --- | ---: | | Main | No | 1 | | #358 at `369dc32` | Yes | 2 | | #389 at `c84e0e6` | Yes | 1 | All three cleaned up the temporary entry. After removing the obstruction, the next call wrote a valid entry and the following call hit it. The incremental change below keeps the original `HostShader` in #389's converter. That removes the encoded-buffer clone and returns the original on a fresh miss, whether publication succeeded or failed. A cache hit still decodes the stored entry. The tests confirmed the original translator output was retained in both miss cases and that a subsequent hit did not invoke the translator. AI-assisted. Verified on Windows with synthetic cache entries. <details> <summary>Incremental patch on c84e0e6</summary> ```diff diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -78,14 +78,12 @@ pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { } /// The cache entry's converter: the build and the container in, the -/// encoded translation out. `ran` tells a miss from a hit; `output` keeps -/// the last translation so that one the cache could not write still serves, -/// and `failed` tells the translation's own error from the cache's. +/// encoded translation out. A miss also keeps the original host shader. +/// `failed` tells the translation's own error from a cache write error. struct Translate<F> { translate: F, - ran: AtomicBool, failed: AtomicBool, - output: Mutex<Option<Vec<u8>>>, + output: Mutex<Option<HostShader>>, } impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> { @@ -97,13 +95,12 @@ impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Tra 1 } fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> { - self.ran.store(true, Ordering::Relaxed); let shader = (self.translate)(&input[32..]).map_err(|e| { self.failed.store(true, Ordering::Relaxed); anyhow::Error::msg(e) })?; let bytes = encode(&shader); - *self.output.lock().unwrap_or_else(|e| e.into_inner()) = Some(bytes.clone()); + *self.output.lock().unwrap_or_else(|e| e.into_inner()) = Some(shader); Ok(bytes) } } @@ -117,10 +114,16 @@ fn cached( let input = [&build[..], container].concat(); let converter = Translate { translate, - ran: AtomicBool::new(false), failed: AtomicBool::new(false), output: Mutex::new(None), }; + let take_output = || { + converter + .output + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + }; for _ in 0..2 { let path = match cache.get_or_convert(&converter, &input) { Ok(path) => path, @@ -133,29 +136,24 @@ fn cached( if !WARNED.swap(true, Ordering::Relaxed) { tracing::warn!( error = %format_args!("{e:#}"), - "shader cache not written; translating without it" + "shader cache entry not written" ); } MISSES.fetch_add(1, Ordering::Relaxed); - let kept = converter - .output - .lock() - .unwrap_or_else(|e| e.into_inner()) - .take(); - return match kept.and_then(|b| decode(&b)) { + return match take_output() { Some(shader) => Ok(shader), None => (converter.translate)(container), }; } }; + if let Some(shader) = take_output() { + MISSES.fetch_add(1, Ordering::Relaxed); + tracing::debug!(path = %path.display(), "shader translated and cached"); + return Ok(shader); + } 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"); ``` </details>

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No reviewers
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/Marvisak--VIctory!389
No description provided.