From 2ee94159a72dbfb4a921287a9643e04f4efaecbf Mon Sep 17 00:00:00 2001 From: FermentoCode <346471937+FermentoCode@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:37:50 +0100 Subject: [PATCH] Keep translated shaders across unrelated rebuilds Identify the translator, its effective settings and the cache encoding independently of the executable. Track device wave width and descriptor clamp per lookup. Add source-level regression coverage for unrelated rebuilds and changed translation inputs. --- Cargo.lock | 2 + crates/victory-gpu/src/shader_cache.rs | 101 +++++++----------- crates/victory-shader/Cargo.toml | 7 ++ crates/victory-shader/build.rs | 43 ++++++++ crates/victory-shader/fingerprint_inputs.rs | 67 ++++++++++++ crates/victory-shader/src/emit/mod.rs | 6 +- crates/victory-shader/src/emit/shader.rs | 7 +- .../victory-shader/tests/cache_fingerprint.rs | 67 ++++++++++++ 8 files changed, 233 insertions(+), 67 deletions(-) create mode 100644 crates/victory-shader/build.rs create mode 100644 crates/victory-shader/fingerprint_inputs.rs create mode 100644 crates/victory-shader/tests/cache_fingerprint.rs diff --git a/Cargo.lock b/Cargo.lock index bab4a7e1a6..1e6e36e20e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -754,7 +754,9 @@ dependencies = [ name = "victory-shader" version = "0.1.0" dependencies = [ + "blake3", "miniz_oxide", + "tempfile", "thiserror", "windows", "windows-sys", diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index f8fcaf47e3..53504fb271 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -1,13 +1,6 @@ -//! Translated shaders kept on disk (decision 0003): under the configured -//! cache folder, keyed by the container's content and by the VIctory build -//! that translated it (the BLAKE3 of our executable), so a rebuilt -//! translator never serves an old translation. Entries go through -//! `victory-pipeline`'s content-addressed cache, which writes them -//! atomically; an entry that does not read back is translated again. -//! -//! 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). +//! Persistent DXIL and binding metadata keyed by shader bytes, translator +//! inputs, encoding and effective host settings. The content-addressed +//! cache writes entries atomically and retranslates unreadable entries. use std::path::PathBuf; use std::sync::OnceLock; @@ -37,57 +30,41 @@ pub(crate) fn counts() -> (u64, u64) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) } -/// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop limit, which a -/// diagnostics build can change at run time). -fn build() -> &'static [u8; 32] { - static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); - BUILD.get_or_init(|| { - let exe = std::env::current_exe().and_then(std::fs::read); - let limit = victory_shader::emit::loop_limit(); - if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { - tracing::warn!( - limit, - "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" - ); - } - match exe { - Ok(mut bytes) => { - bytes.extend_from_slice(&limit.to_le_bytes()); - // Which group barriers wait is part of the translation too. - bytes.push(victory_shader::emit::group_sync()); - // So are the switches that pick the form of a wave64 program: - // without them here a run with `VICTORY_WAVE_WIDE=0` was - // served the translations an earlier run of the same - // executable had cached with the switch unset. - for name in [ - "VICTORY_WAVE_WIDE", - "VICTORY_WAVE_LOCAL", - "VICTORY_WAVE_DEEP_SKIPS", - "VICTORY_WAVE_OWN_BITS", - "VICTORY_F16_NEAREST", - ] { - bytes.extend_from_slice(name.as_bytes()); - bytes.push(b'='); - if let Some(value) = std::env::var_os(name) { - bytes.extend_from_slice(value.as_encoded_bytes()); - } - bytes.push(0); +/// Process-wide translator options. Device facts are appended at lookup time, +/// since the host can discover its wave width and heap limit after startup. +fn translation_key() -> [u8; 32] { + use victory_shader::emit; + static BASE: OnceLock = OnceLock::new(); + let mut hash = BASE.get_or_init(|| { + let mut hash = blake3::Hasher::new_derive_key("VIctory persistent translated shader v2"); + hash.update(emit::TRANSLATOR_INPUTS_HASH.as_bytes()); + // encode() and decode() live here. A codec change starts a new namespace. + hash.update(blake3::hash(include_bytes!("shader_cache.rs")).as_bytes()); + for name in emit::TRANSLATOR_SWITCH_NAMES.split(',').filter(|s| !s.is_empty()) { + hash.update(name.as_bytes()); + hash.update(&[0]); + match std::env::var_os(name) { + Some(value) => { + hash.update(&[1]); + let bytes = value.as_encoded_bytes(); + hash.update(&(bytes.len() as u64).to_le_bytes()); + hash.update(bytes); } - // And which clean-up passes ran over the translated code. - bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes()); - *blake3::hash(&bytes).as_bytes() - } - Err(e) => { - // Without it no entry can be trusted: a fresh key per run. - tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default(); - *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() + None => { hash.update(&[0]); } } } - }) + let limit = emit::loop_limit(); + if limit != emit::DEFAULT_LOOP_LIMIT { + tracing::warn!(limit, "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"); + } + hash.update(&limit.to_le_bytes()); + hash.update(&[emit::group_sync()]); + hash.update(&emit::shader_opt().to_le_bytes()); + hash + }).clone(); + hash.update(&emit::host_max_wave().to_le_bytes()); + hash.update(&emit::view_heap_limit().to_le_bytes()); + *hash.finalize().as_bytes() } /// The translation of a console shader container, from the cache when @@ -95,13 +72,7 @@ fn build() -> &'static [u8; 32] { pub(crate) fn host_shader(container: &[u8]) -> Result { let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); match CACHE.get() { - Some(cache) => { - // A translation cached for a wave64 adapter can contain WaveSize(64). - let mut key = blake3::Hasher::new(); - key.update(build()); - key.update(&victory_shader::emit::host_max_wave().to_le_bytes()); - cached(cache, key.finalize().as_bytes(), container, translate) - } + Some(cache) => cached(cache, &translation_key(), container, translate), None => translate(container), } } diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index edfd1b969b..2a103b0d1d 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -11,6 +11,13 @@ publish.workspace = true thiserror.workspace = true miniz_oxide.workspace = true +[build-dependencies] +blake3.workspace = true + +[dev-dependencies] +blake3.workspace = true +tempfile.workspace = true + [features] # Host D3D12 pipeline checks (`emit::host`). host = ["dep:windows"] diff --git a/crates/victory-shader/build.rs b/crates/victory-shader/build.rs new file mode 100644 index 0000000000..625a18d9a8 --- /dev/null +++ b/crates/victory-shader/build.rs @@ -0,0 +1,43 @@ +mod fingerprint_inputs; + +use std::collections::BTreeMap; +use std::env; +use std::path::Path; +use std::process::Command; + +use fingerprint_inputs::{INPUTS, field, source_inputs}; + +fn main() { + for input in INPUTS { + println!("cargo:rerun-if-changed={input}"); + } + let (mut hash, switches) = source_inputs(Path::new(env!("CARGO_MANIFEST_DIR"))) + .expect("cannot fingerprint the shader translator"); + let rustc = Command::new(env::var_os("RUSTC").expect("Cargo sets RUSTC")) + .arg("-vV") + .output() + .expect("query shader compiler version"); + assert!(rustc.status.success(), "rustc -vV failed"); + field(&mut hash, &rustc.stdout); + // These are Cargo's effective settings for victory-shader itself. + let settings: BTreeMap<_, _> = env::vars_os() + .filter(|(name, _)| { + let name = name.to_string_lossy(); + name.starts_with("CARGO_FEATURE_") + || name.starts_with("CARGO_CFG_") + || matches!( + name.as_ref(), + "TARGET" | "PROFILE" | "OPT_LEVEL" | "DEBUG" | "CARGO_ENCODED_RUSTFLAGS" + ) + }) + .collect(); + for (name, value) in settings { + field(&mut hash, name.as_encoded_bytes()); + field(&mut hash, value.as_encoded_bytes()); + } + println!("cargo:rustc-env=TRANSLATOR_INPUTS_HASH={}", hash.finalize()); + println!( + "cargo:rustc-env=TRANSLATOR_SWITCH_NAMES={}", + switches.into_iter().collect::>().join(",") + ); +} diff --git a/crates/victory-shader/fingerprint_inputs.rs b/crates/victory-shader/fingerprint_inputs.rs new file mode 100644 index 0000000000..271eae2560 --- /dev/null +++ b/crates/victory-shader/fingerprint_inputs.rs @@ -0,0 +1,67 @@ +//! Inputs shared by the shader build script and its regression test. + +use std::collections::BTreeSet; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +pub const INPUTS: &[&str] = &[ + "src", + "build.rs", + "fingerprint_inputs.rs", + "Cargo.toml", + "../../Cargo.toml", + "../../Cargo.lock", +]; + +pub fn field(hash: &mut blake3::Hasher, bytes: &[u8]) { + hash.update(&(bytes.len() as u64).to_le_bytes()); + hash.update(bytes); +} + +fn collect(path: PathBuf, files: &mut Vec) -> io::Result<()> { + if path.is_dir() { + for entry in fs::read_dir(path)? { + collect(entry?.path(), files)?; + } + } else { + files.push(path); + } + Ok(()) +} + +pub fn source_inputs(dir: &Path) -> io::Result<(blake3::Hasher, BTreeSet)> { + let mut files = Vec::new(); + for input in INPUTS { + collect(dir.join(input), &mut files)?; + } + files.sort(); + let mut hash = blake3::Hasher::new_derive_key("VIctory shader build inputs v1"); + let mut switches = BTreeSet::new(); + for path in files { + let name = path + .strip_prefix(dir) + .expect("collected relative to the shader crate"); + let bytes = fs::read(&path)?; + field( + &mut hash, + name.to_string_lossy().replace('\\', "/").as_bytes(), + ); + field(&mut hash, &bytes); + // Collect literal switch names, including names passed to helper functions. + // Require the closing quote to omit prefixes and prose from the list. + if name.starts_with("src") && path.extension().is_some_and(|s| s == "rs") { + let source = std::str::from_utf8(&bytes).map_err(io::Error::other)?; + for (at, _) in source.match_indices("\"VICTORY_") { + if let Some((name, _)) = source[at + 1..].split_once('"') + && name + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + switches.insert(name.to_owned()); + } + } + } + } + Ok((hash, switches)) +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 8a327669dd..22ca99cfce 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -115,9 +115,13 @@ pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, - set_view_heap_limit, + set_view_heap_limit, view_heap_limit, }; +/// Build identity of the translator, and the names of its runtime switches. +pub const TRANSLATOR_INPUTS_HASH: &str = env!("TRANSLATOR_INPUTS_HASH"); +pub const TRANSLATOR_SWITCH_NAMES: &str = env!("TRANSLATOR_SWITCH_NAMES"); + /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index b49bc6def6..ea4e7101e2 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -124,6 +124,11 @@ pub fn set_view_heap_limit(null_slot: u32) { VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); } +/// The effective clamp encoded into translated descriptor reads. +pub fn view_heap_limit() -> u32 { + VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct Shader { pub m: Module, pub t: Types, @@ -397,7 +402,7 @@ impl Shader { props: (u32, u32), ) -> V { // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead - let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + let limit = view_heap_limit(); // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) let index = if !sampler && limit != 0 { let null = self.m.i32(limit); diff --git a/crates/victory-shader/tests/cache_fingerprint.rs b/crates/victory-shader/tests/cache_fingerprint.rs new file mode 100644 index 0000000000..6831a11ce6 --- /dev/null +++ b/crates/victory-shader/tests/cache_fingerprint.rs @@ -0,0 +1,67 @@ +#[path = "../fingerprint_inputs.rs"] +mod fingerprint_inputs; + +use std::fs; + +#[test] +fn compiler_supplies_a_stable_shader_source_key() { + let key = victory_shader::emit::TRANSLATOR_INPUTS_HASH; + assert_eq!(key.len(), 64); + assert!(key.bytes().all(|c| c.is_ascii_hexdigit())); +} + +#[test] +fn renderer_changes_share_a_key_but_shader_and_dependency_changes_do_not() { + let root = tempfile::tempdir().unwrap(); + let shader = root.path().join("crates/victory-shader"); + fs::create_dir_all(shader.join("src/emit")).unwrap(); + for file in &fingerprint_inputs::INPUTS[1..] { + fs::write(shader.join(file), b"fixture").unwrap(); + } + let lower = shader.join("src/emit/lower.rs"); + fs::write(&lower, r#"env::var_os("VICTORY_F16_NEAREST")"#).unwrap(); + let key = || { + fingerprint_inputs::source_inputs(&shader) + .unwrap() + .0 + .finalize() + }; + let original = key(); + for file in [ + "apps/victory/src/main.rs", + "crates/victory-gpu/src/diagnostics.rs", + ] { + let file = root.path().join(file); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, b"unrelated change").unwrap(); + } + assert_eq!(key(), original); + let switches = fingerprint_inputs::source_inputs(&shader).unwrap().1; + assert!(switches.contains("VICTORY_F16_NEAREST")); + fs::write(lower, "changed floating-point rounding").unwrap(); + let changed = key(); + assert_ne!(changed, original); + fs::write(root.path().join("Cargo.lock"), b"new dependency checksum").unwrap(); + assert_ne!(key(), changed); +} + +#[test] +fn translator_lists_local_behavior_switches_for_runtime_keys() { + let names: Vec<_> = victory_shader::emit::TRANSLATOR_SWITCH_NAMES + .split(',') + .collect(); + for required in [ + "VICTORY_F16_NEAREST", + "VICTORY_GROUP_SYNC", + "VICTORY_SHADER_LOOP_LIMIT", + "VICTORY_SHADER_OPT", + "VICTORY_WAVE_WIDE", + "VICTORY_WAVE_LOCAL", + "VICTORY_WAVE_DEEP_SKIPS", + "VICTORY_WAVE_OWN_BITS", + "VICTORY_MESH_OUTPUT_STRICT", + "VICTORY_STRICT_JOINS", + ] { + assert!(names.contains(&required), "{required} missing from the key"); + } +}