Skip to content
Draft
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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

101 changes: 36 additions & 65 deletions crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -37,71 +30,49 @@ 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<blake3::Hasher> = 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
/// there is one.
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) => {
// 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),
}
}
Expand Down
7 changes: 7 additions & 0 deletions crates/victory-shader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
43 changes: 43 additions & 0 deletions crates/victory-shader/build.rs
Original file line number Diff line number Diff line change
@@ -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::<Vec<_>>().join(",")
);
}
67 changes: 67 additions & 0 deletions crates/victory-shader/fingerprint_inputs.rs
Original file line number Diff line number Diff line change
@@ -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<PathBuf>) -> 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<String>)> {
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))
}
6 changes: 5 additions & 1 deletion crates/victory-shader/src/emit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
7 changes: 6 additions & 1 deletion crates/victory-shader/src/emit/shader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
67 changes: 67 additions & 0 deletions crates/victory-shader/tests/cache_fingerprint.rs
Original file line number Diff line number Diff line change
@@ -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");
}
}