Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 102 additions & 18 deletions crates/leonida-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<bool, String> {
let cache = CACHE.get().ok_or("no shader cache")?;
Expand All @@ -102,10 +105,11 @@ 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.
/// encoded translation out. `made` keeps the result so a miss need not
/// read and decode the entry it just wrote.
struct Translate<F> {
translate: F,
ran: AtomicBool,
made: Mutex<Option<HostShader>>,
}

impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> {
Expand All @@ -117,9 +121,10 @@ 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(anyhow::Error::msg)?;
Ok(encode(&shader))
let bytes = encode(&shader);
*self.made.lock().unwrap_or_else(|e| e.into_inner()) = Some(shader);
Ok(bytes)
}
}

Expand All @@ -130,22 +135,40 @@ fn cached(
translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
) -> Result<HostShader, String> {
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");
Expand Down Expand Up @@ -394,6 +417,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::<HostShader, _>("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<PathBuf> {
let mut files = Vec::new();
for e in std::fs::read_dir(dir).unwrap().flatten() {
Expand Down
48 changes: 48 additions & 0 deletions docs/fork-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,54 @@ 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.

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 two slower patched 8 KiB
miss pairs. 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-6: report missing required DLLs before title initialization.**
The startup check previously examined only the executable's direct imports.
It now follows static imports through the mapped title DLLs, names each
Expand Down