diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index baabf424..f7fd6395 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -122,6 +122,11 @@ enum Command { /// (runs with `VICTORY_PIPELINE_BOOK=1` write them down), so that the /// driver's cache on disk has them before a run needs one: once per change /// of the translator or the driver. Goes on where it was stopped. + /// + /// Pipelines that crash or hang the compiler are listed in `warm-bad.txt` + /// with the current fingerprint and retried automatically after a driver + /// or translator change. Set `VICTORY_WARM_BAD=0` to ignore `warm-bad.txt` + /// for this invocation. #[cfg(windows)] Warm { /// Processes at once (default: two thirds of the logical cores). @@ -130,7 +135,7 @@ enum Command { /// At most this many pipelines. #[arg(long)] limit: Option, - /// Those made before too. + /// Retry pipelines already made or listed in `warm-bad.txt` too. #[arg(long)] again: bool, /// Only the pipelines earlier runs drew with. diff --git a/apps/victory/src/warm.rs b/apps/victory/src/warm.rs index 3efee631..e85fe76f 100644 --- a/apps/victory/src/warm.rs +++ b/apps/victory/src/warm.rs @@ -26,6 +26,29 @@ fn folder() -> Result { Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines")) } +fn select_pipelines( + keys: &[String], + done: &HashSet<&str>, + bad: &HashSet, + early: &HashSet<&str>, + again: bool, + used: bool, + limit: Option, +) -> Vec { + // Those earlier runs drew with first, the others in no order (by key). + let mut all: Vec = (0..keys.len()) + .filter(|&n| { + let key = keys[n].as_str(); + (again || !done.contains(key)) + && (again || !bad.contains(key)) + && (!used || early.contains(key)) + }) + .collect(); + all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n])); + all.truncate(limit.unwrap_or(usize::MAX)); + all +} + pub fn run(jobs: Option, limit: Option, again: bool, used: bool, these: Option) -> Result<()> { let dir = folder()?; if let Some(these) = these { @@ -35,7 +58,7 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t victory_hle::known_pipelines::use_translations(dir.with_file_name("shaders")); let fingerprint = known::fingerprint(); let done_file = dir.join("warm-done.txt"); - let bad_file = dir.join("warm-bad.txt"); + let bad_file = dir.join(known::WARM_BAD_FILE); let keys = known::keys(&dir); let listed = std::fs::read_to_string(&done_file).unwrap_or_default(); let mut done: HashSet<&str> = HashSet::new(); @@ -46,19 +69,15 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t done.insert(key); } } - let bad = std::fs::read_to_string(&bad_file).unwrap_or_default(); - let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect(); + let bad: HashSet = if known::bad_list_disabled() { + HashSet::new() + } else { + let text = std::fs::read_to_string(&bad_file).unwrap_or_default(); + known::parse_bad_keys(&text, &fingerprint) + }; let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default(); let early: HashSet<&str> = early.lines().collect(); - // Those earlier runs drew with first, the others in no order (by key). - let mut all: Vec = (0..keys.len()) - .filter(|&n| { - let key = keys[n].as_str(); - (again || !done.contains(key)) && !bad.contains(key) && (!used || early.contains(key)) - }) - .collect(); - all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n])); - all.truncate(limit.unwrap_or(usize::MAX)); + let all = select_pipelines(&keys, &done, &bad, &early, again, used, limit); let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); let jobs = jobs.unwrap_or(cores * 2 / 3).max(1); println!( @@ -93,7 +112,7 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t }, |n, why| { println!("pipeline {n} {}: {why}", keys[n]); - let _ = writeln!(lock(&bad_out), "{} {why}", keys[n]); + let _ = writeln!(lock(&bad_out), "{}", known::format_bad_entry(&keys[n], &fingerprint, &why)); lock(&state).2 += 1; }, )?; @@ -346,4 +365,47 @@ mod tests { .unwrap_err(); assert!(format!("{error:#}").contains("worker unavailable")); } + + #[test] + fn select_pipelines_skips_current_bad_and_retries_on_again_or_new_fingerprint() { + let hex_key = |c: char| c.to_string().repeat(32); + let (k_done, k_bad_current, k_bad_old, k_legacy_bad, k_fresh) = ( + hex_key('0'), + hex_key('1'), + hex_key('2'), + hex_key('3'), + hex_key('4'), + ); + let keys = vec![ + k_done.clone(), + k_bad_current.clone(), + k_bad_old.clone(), + k_legacy_bad.clone(), + k_fresh.clone(), + ]; + let done = HashSet::from([k_done.as_str()]); + let early = HashSet::from([k_bad_current.as_str(), k_fresh.as_str()]); + let current_entry = known::format_bad_entry(&k_bad_current, "1111111111111111", "exit code: 0xc0000005"); + assert_eq!(current_entry.split(' ').next(), Some(k_bad_current.as_str())); + let old_entry = known::format_bad_entry(&k_bad_old, "0000000000000000", "hung for 180 s"); + let bad_text = format!( + "# comment\n\ + {current_entry}\n\ + {old_entry}\n\ + {k_legacy_bad} legacy crash\n" + ); + let bad = known::parse_bad_keys(&bad_text, "1111111111111111"); + assert_eq!(bad, HashSet::from([k_bad_current.clone(), k_legacy_bad])); + + // Early non-done/non-bad first (k_fresh = 4), then stale-fingerprint k_bad_old (2). + assert_eq!(select_pipelines(&keys, &done, &bad, &early, false, false, None), vec![4, 2]); + // --again retries done and bad pipelines (early indices 1, 4 first, then 0, 2, 3). + assert_eq!(select_pipelines(&keys, &done, &bad, &early, true, false, None), vec![1, 4, 0, 2, 3]); + assert_eq!(select_pipelines(&keys, &done, &bad, &early, true, true, None), vec![1, 4]); + // Simulating VICTORY_WARM_BAD=0 clears bad while still honoring done. + assert_eq!( + select_pipelines(&keys, &done, &HashSet::new(), &early, false, false, None), + vec![1, 4, 2, 3] + ); + } } diff --git a/apps/victory/tests/warm_bad.rs b/apps/victory/tests/warm_bad.rs new file mode 100644 index 00000000..5b9c1558 --- /dev/null +++ b/apps/victory/tests/warm_bad.rs @@ -0,0 +1,127 @@ +#![cfg(windows)] + +use std::fs; +use std::path::Path; +use std::process::Command; + +fn run_warm(root: &Path, cache: &Path, extra_env: &[(&str, &str)], args: &[&str]) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_victory")); + command + .current_dir(root) + .env_remove("VICTORY_CONFIG") + .env_remove("VICTORY_WARM_BAD") + .env_remove("VICTORY_WAVE_WIDE") + .env("VICTORY_CACHE_DIR", cache) + .env("VICTORY_DATA_DIR", root.join("data")) + // Keep fingerprint computation deterministic without probing a host GPU. + .env("VICTORY_D3D12_ADAPTER", u32::MAX.to_string()) + .env("VICTORY_D3D12_WARP", "0") + .args(["warm", "--jobs", "1"]) + .args(args); + for (key, value) in extra_env { + command.env(key, value); + } + let output = command.output().unwrap(); + assert!(output.status.success(), "{output:?}"); + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn parse_fingerprint(stdout: &str) -> String { + let (_, after) = stdout + .split_once("made before (") + .unwrap_or_else(|| panic!("missing fingerprint prefix in:\n{stdout}")); + let (fp, _) = after + .split_once(')') + .unwrap_or_else(|| panic!("missing fingerprint suffix in:\n{stdout}")); + assert_eq!(fp.len(), 16, "unexpected fingerprint {fp:?} in:\n{stdout}"); + assert!( + fp.bytes().all(|b| b.is_ascii_hexdigit()), + "non-hex fingerprint {fp:?}" + ); + fp.to_owned() +} + +#[test] +fn warm_bad_fingerprint_override_again_and_help() { + let help = Command::new(env!("CARGO_BIN_EXE_victory")) + .args(["warm", "--help"]) + .output() + .unwrap(); + assert!(help.status.success(), "{help:?}"); + let help_stdout = String::from_utf8_lossy(&help.stdout); + assert!(help_stdout.contains("VICTORY_WARM_BAD=0"), "{help_stdout}"); + assert!(help_stdout.contains("warm-bad.txt"), "{help_stdout}"); + + let root = tempfile::tempdir().unwrap(); + let cache = root.path().join("cache"); + let pipelines = cache.join("pipelines"); + fs::create_dir_all(&pipelines).unwrap(); + + let ids = [0x11u8, 0x22, 0x33, 0x44]; + let [k_fp_bad, k_legacy_bad, k_fresh, k_other] = ids.map(|id| format!("{id:02x}").repeat(16)); + let mut book = Vec::new(); + for id in ids { + // Minimal 16-byte record so known::keys reads the key while workers safely skip compilation. + book.extend(16u32.to_le_bytes()); + book.extend([id; 16]); + } + fs::write(pipelines.join("known-pipelines.bin"), book).unwrap(); + fs::write(pipelines.join("known-shaders.bin"), b"").unwrap(); + fs::write(pipelines.join("early-pipelines.txt"), format!("{k_fp_bad}\n{k_fresh}\n")).unwrap(); + + let probe = run_warm(root.path(), &cache, &[], &["--limit", "0"]); + let fp_base = parse_fingerprint(&probe); + + let fp_entry = format!("{k_fp_bad} fp={fp_base} exit code: 0xc0000005"); + assert_eq!(fp_entry.split(' ').next(), Some(k_fp_bad.as_str())); + fs::write( + pipelines.join("warm-bad.txt"), + format!("\n# comment line\n # indented comment\n{fp_entry}\n\t{k_legacy_bad}\tlegacy crash\n"), + ) + .unwrap(); + + let out_default = run_warm(root.path(), &cache, &[], &[]); + assert!( + out_default.contains(&format!("4 pipelines known, 0 made before ({fp_base}), 2 bad; 2 to make")), + "{out_default}" + ); + + let out_repeat = run_warm(root.path(), &cache, &[], &[]); + assert!( + out_repeat.contains(&format!("4 pipelines known, 2 made before ({fp_base}), 2 bad; 0 to make")), + "{out_repeat}" + ); + + let out_override = run_warm(root.path(), &cache, &[("VICTORY_WARM_BAD", "0")], &[]); + assert!( + out_override.contains(&format!("4 pipelines known, 2 made before ({fp_base}), 0 bad; 2 to make")), + "{out_override}" + ); + + let out_again = run_warm(root.path(), &cache, &[], &["--again", "--used"]); + assert!( + out_again.contains(&format!("4 pipelines known, 4 made before ({fp_base}), 2 bad; 2 to make")), + "{out_again}" + ); + + // Changing a translator switch rotates the fingerprint, expiring fp-tagged entries automatically. + let out_new_fp = run_warm(root.path(), &cache, &[("VICTORY_WAVE_WIDE", "0")], &[]); + let fp_new = parse_fingerprint(&out_new_fp); + assert_ne!(fp_new, fp_base); + assert!( + out_new_fp.contains(&format!("4 pipelines known, 0 made before ({fp_new}), 1 bad; 3 to make")), + "{out_new_fp}" + ); + + let done = fs::read_to_string(pipelines.join("warm-done.txt")).unwrap(); + let new_fp_keys: Vec<_> = done + .lines() + .filter_map(|line| line.split_once(' ')) + .filter(|(fp, _)| *fp == fp_new) + .map(|(_, key)| key) + .collect(); + assert_eq!( + new_fp_keys, + [k_fp_bad.as_str(), k_fresh.as_str(), k_other.as_str()] + ); +} diff --git a/crates/victory-gpu/src/pipeline/known.rs b/crates/victory-gpu/src/pipeline/known.rs index 52642a73..4c49933f 100644 --- a/crates/victory-gpu/src/pipeline/known.rs +++ b/crates/victory-gpu/src/pipeline/known.rs @@ -35,6 +35,8 @@ mod writer; const SHADERS: &str = "known-shaders.bin"; const PIPELINES: &str = "known-pipelines.bin"; +/// Compiler crashes and hangs recorded by `victory warm` and the runtime guard. +pub const WARM_BAD_FILE: &str = "warm-bad.txt"; /// Stages by their number in the files. const STAGES: [&str; 8] = ["vertex", "pixel", "domain", "hull", "geometry", "compute", "amplification", "mesh"]; @@ -257,6 +259,66 @@ pub fn fingerprint() -> String { h.finalize().to_hex()[..16].to_owned() } +/// Whether `warm-bad.txt` is ignored (`VICTORY_WARM_BAD=0`). +pub fn bad_list_disabled() -> bool { + std::env::var_os("VICTORY_WARM_BAD").is_some_and(|v| v == "0") +} + +fn is_hex(s: &str, len: usize) -> bool { + s.len() == len && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Formats a `warm-bad.txt` entry with the pipeline key in column one (so +/// older binaries still quarantine the key) and a tagged fingerprint so +/// driver or translator updates retry it automatically. +pub fn format_bad_entry(key: &str, fingerprint: &str, reason: &str) -> String { + if reason.is_empty() { + format!("{key} fp={fingerprint}") + } else { + format!("{key} fp={fingerprint} {reason}") + } +} + +/// Pipeline keys from `warm-bad.txt` that apply to `fingerprint`. +/// +/// Blank lines and `#` comments are ignored. Entries tagged with a +/// fingerprint (` fp=<16-hex-fingerprint> ...`, or +/// `<16-hex-fingerprint> <32-hex-key> ...`) apply only when their +/// fingerprint matches `fingerprint`, so a driver or translator update +/// automatically retries them. Legacy or manually added bare-key lines +/// (` ...`) continue to apply regardless of fingerprint. +pub fn parse_bad_keys(text: &str, fingerprint: &str) -> HashSet { + let mut keys = HashSet::new(); + for line in text.lines() { + let line = line.trim_start(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let mut parts = line.split_whitespace(); + let Some(first) = parts.next() else { + continue; + }; + if let Some(second) = parts.next() { + if let Some(fp) = second.strip_prefix("fp=") + && is_hex(fp, 16) + { + if fp == fingerprint { + keys.insert(first.to_owned()); + } + continue; + } + if is_hex(first, 16) && is_hex(second, 32) { + if first == fingerprint { + keys.insert(second.to_owned()); + } + continue; + } + } + keys.insert(first.to_owned()); + } + keys +} + /// The translations of earlier runs are in `dir` (the pipeline library is /// not used: what is made here is the driver's to keep). pub fn use_translations(dir: PathBuf) { @@ -571,4 +633,68 @@ mod tests { assert_eq!(seen, [(5, 9, 37, 4)]); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn bad_keys_expire_with_fingerprint_and_skip_comments() { + let k_stale = "a".repeat(32); + let k_warm = "b".repeat(32); + let k_no_reason = "c".repeat(32); + let k_tab = "d".repeat(32); + let k_fp_first = "e".repeat(32); + let k_legacy = "f".repeat(32); + let k_bare = "1".repeat(32); + let k_bad_tag = "2".repeat(32); + + let warm_line = format_bad_entry(&k_warm, "8899aabbccddeeff", "hung for 180 s"); + assert_eq!(warm_line.split(' ').next(), Some(k_warm.as_str())); + let stale_line = format_bad_entry(&k_stale, "0011223344556677", "exit code: 0xc0000005"); + let no_reason_line = format_bad_entry(&k_no_reason, "8899aabbccddeeff", ""); + assert_eq!(no_reason_line, format!("{k_no_reason} fp=8899aabbccddeeff")); + + let text = format!( + "\n \n# comment\n # indented comment\n\ + {stale_line}\n\ + {warm_line}\n\ + {no_reason_line}\n\ + \t{k_tab}\tfp=8899aabbccddeeff\tended the compiler\n\ + 8899aabbccddeeff {k_fp_first} legacy fp-first\n\ + {k_legacy} legacy crash\n\ + {k_bare}\n\ + manual-skip-key reason\n\ + {k_bad_tag} fp=nothex reason\n" + ); + + assert_eq!( + parse_bad_keys(&text, "8899aabbccddeeff"), + HashSet::from([ + k_warm, + k_no_reason, + k_tab, + k_fp_first, + k_legacy.clone(), + k_bare.clone(), + "manual-skip-key".to_owned(), + k_bad_tag.clone(), + ]) + ); + assert_eq!( + parse_bad_keys(&text, "0011223344556677"), + HashSet::from([ + k_stale, + k_legacy.clone(), + k_bare.clone(), + "manual-skip-key".to_owned(), + k_bad_tag.clone(), + ]) + ); + assert_eq!( + parse_bad_keys(&text, "ffffffffffffffff"), + HashSet::from([ + k_legacy, + k_bare, + "manual-skip-key".to_owned(), + k_bad_tag, + ]) + ); + } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 360cca53..7bd2ca7e 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -103,27 +103,27 @@ impl Pending { /// crashes on. static SKIPPED_BAD: AtomicU64 = AtomicU64::new(0); -/// The keys of the pipelines the driver's compiler crashed on -/// (`warm-bad.txt` beside the pipeline library, one key to a line, then -/// anything; `#` begins a comment), loaded on first use. `VICTORY_WARM_BAD=0` -/// leaves the file unread. +/// The keys of the pipelines the driver's compiler crashed or hung on +/// (`warm-bad.txt` beside the pipeline library). Recorded entries use +/// ` fp= ...` so older binaries still see the key in +/// column one while driver or translator changes retry them automatically; +/// bare ` ...` lines remain compatible and `#` begins a comment. +/// Loaded on first use; `VICTORY_WARM_BAD=0` leaves the file unread. static BAD_KEYS: Mutex>> = Mutex::new(None); fn bad_keys(f: impl FnOnce(&mut std::collections::HashSet) -> R) -> R { let mut keys = BAD_KEYS.lock().unwrap_or_else(|e| e.into_inner()); let keys = keys.get_or_insert_with(|| { - if std::env::var_os("VICTORY_WARM_BAD").is_some_and(|v| v == "0") { + if super::known::bad_list_disabled() { return Default::default(); } let listed = super::library::folder() - .and_then(|d| std::fs::read_to_string(d.join("warm-bad.txt")).ok()) + .and_then(|d| std::fs::read_to_string(d.join(super::known::WARM_BAD_FILE)).ok()) .unwrap_or_default(); - listed - .lines() - .filter(|l| !l.trim_start().starts_with('#')) - .filter_map(|l| l.split_whitespace().next()) - .map(str::to_owned) - .collect() + if listed.is_empty() { + return Default::default(); + } + super::known::parse_bad_keys(&listed, &super::known::fingerprint()) }); f(keys) } @@ -296,9 +296,14 @@ fn lost(slot: usize) { let known = bad_keys(|keys| !keys.insert(p.key.clone())); if !known && let Some(dir) = super::library::folder() { use std::io::Write; - let file = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("warm-bad.txt")); + let file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join(super::known::WARM_BAD_FILE)); if let Ok(mut f) = file { - let _ = writeln!(f, "{} ended the compiler in a run: {:?}", p.key, p.shaders); + let fingerprint = super::known::fingerprint(); + let reason = format!("ended the compiler in a run: {:?}", p.shaders); + let _ = writeln!(f, "{}", super::known::format_bad_entry(&p.key, &fingerprint, &reason)); } } let _ = p.made.set(None);