From effef6719d431ac360ce9d6f46c55e87b1bd486a Mon Sep 17 00:00:00 2001 From: mokkamokacaffe <329663686+mokkamokacaffe@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:43:07 +0100 Subject: [PATCH 1/6] Shaders: identify direct translation artifacts in dump manifests --- crates/xcl/src/shaders.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..1df7b41984 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2375,6 +2375,28 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> Ok(dxil) => dump("direct.dxil", dxil), Err(e) => dump("direct.err.txt", e.as_bytes()), } + if let Some(dir) = &dump_dir { + let manifest = serde_json::json!({ + "schema_version": 1, + "backend": "direct-dxil", + "record_hash": format!("{blob_hash:016x}"), + "fssm_index": fi, + "program_offset": p.offset, + "stage": coverage::stage_name(&mode), + "wave64": wave64, + "split_wave64": o.split, + "memory_windows": windows, + "validation_requested": validate, + "guest_fnv64": format!("{:016x}", shader::fnv64(code)), + "dxil_fnv64": r.as_ref().ok().map(|bytes| format!("{:016x}", shader::fnv64(bytes))), + "translation_wall_us": time.as_micros() as u64, + "error": r.as_ref().err(), + }); + let path = dir.join(format!("{blob_hash:016x}_f{fi}_{:x}.manifest.json", p.offset)); + if let Err(e) = std::fs::write(&path, manifest.to_string()) { + eprintln!("direct: could not write {}: {e}", path.display()); + } + } let hlsl_size = (compare && r.is_ok()) .then(|| { let profile = match mode { From b6bd0c0a7c0d850bd6a102e72aeb8091c671502a Mon Sep 17 00:00:00 2001 From: mokkamokacaffe <329663686+mokkamokacaffe@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:59:51 +0100 Subject: [PATCH 2/6] Shaders: report incomplete direct dump artifacts --- crates/xcl/src/shaders.rs | 54 ++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 1df7b41984..8856d9f24b 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2104,6 +2104,24 @@ mod tests { } } + #[test] + fn direct_dump_does_not_publish_a_manifest_for_a_missing_artifact() { + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + let root = Temp(std::env::temp_dir().join(format!("xcl-direct-dump-write-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&root.0); + std::fs::create_dir_all(root.0.join("sample.guest.bin")).unwrap(); + let err = write_direct_dump(&root.0, "sample", b"guest", &Ok(vec![1, 2, 3]), &serde_json::json!({ "schema_version": 1 })).unwrap_err(); + assert!(err.contains("sample.guest.bin"), "{err}"); + assert!(!root.0.join("sample.direct.dxil").exists()); + assert!(!root.0.join("sample.manifest.json").exists(), "a manifest must not advertise artifacts that were not saved"); + } + #[test] fn hlsl_export_is_ordered_and_exact_hash_selects_one_record() { struct Temp(std::path::PathBuf); @@ -2255,6 +2273,26 @@ fn name_hash(name: &str) -> u64 { h } +/// Write the required artifacts first and publish their manifest only after every write succeeds. +fn write_direct_dump( + dir: &std::path::Path, + prefix: &str, + guest: &[u8], + result: &Result, String>, + manifest: &serde_json::Value, +) -> Result<(), String> { + let write = |suffix: &str, bytes: &[u8]| { + let path = dir.join(format!("{prefix}.{suffix}")); + std::fs::write(&path, bytes).map_err(|e| format!("could not write {}: {e}", path.display())) + }; + write("guest.bin", guest)?; + match result { + Ok(dxil) => write("direct.dxil", dxil)?, + Err(e) => write("direct.err.txt", e.as_bytes())?, + } + write("manifest.json", manifest.to_string().as_bytes()) +} + /// `--direct [--sample N] [--seed S] [--validate] [--compare] [--split 0|1] [--windows W]`: /// every program of a seeded sample of N records (default 200 programs' worth; `--sample 0` = /// all) through the direct DXIL translator; per-stage outcomes, a ranked histogram of what it @@ -2365,16 +2403,15 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> Err(e) => *lanes_why.lock().unwrap().entry(survey_key(&e)).or_default() += 1, } } + let prefix = format!("{blob_hash:016x}_f{fi}_{:x}", p.offset); let dump = |suffix: &str, bytes: &[u8]| { if let Some(d) = &dump_dir { - let _ = std::fs::write(d.join(format!("{blob_hash:016x}_f{fi}_{:x}.{suffix}", p.offset)), bytes); + let path = d.join(format!("{prefix}.{suffix}")); + if let Err(e) = std::fs::write(&path, bytes) { + eprintln!("direct: could not write {}: {e}", path.display()); + } } }; - dump("guest.bin", code); - match &r { - Ok(dxil) => dump("direct.dxil", dxil), - Err(e) => dump("direct.err.txt", e.as_bytes()), - } if let Some(dir) = &dump_dir { let manifest = serde_json::json!({ "schema_version": 1, @@ -2392,9 +2429,8 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> "translation_wall_us": time.as_micros() as u64, "error": r.as_ref().err(), }); - let path = dir.join(format!("{blob_hash:016x}_f{fi}_{:x}.manifest.json", p.offset)); - if let Err(e) = std::fs::write(&path, manifest.to_string()) { - eprintln!("direct: could not write {}: {e}", path.display()); + if let Err(e) = write_direct_dump(dir, &prefix, code, &r, &manifest) { + eprintln!("direct: {e}"); } } let hlsl_size = (compare && r.is_ok()) From 76e7793dbb5ec337a0b30aa832d25f2fa2d1e5ee Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:13:08 +0800 Subject: [PATCH 3/6] Scripts: verify direct shader dump files against their manifest Check the guest hash and the result selected by the manifest. Compare exact diagnostic bytes for rejected translations so saved artifacts can be verified without the source pack or a GPU. Assisted-by: OpenAI Codex (GPT-6) --- scripts/test_verify_shader_dump.py | 62 ++++++++++++++++++++++++++++ scripts/verify_shader_dump.py | 66 ++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 scripts/test_verify_shader_dump.py create mode 100644 scripts/verify_shader_dump.py diff --git a/scripts/test_verify_shader_dump.py b/scripts/test_verify_shader_dump.py new file mode 100644 index 0000000000..3fc5b7a5d7 --- /dev/null +++ b/scripts/test_verify_shader_dump.py @@ -0,0 +1,62 @@ +import json +from pathlib import Path +import tempfile +import unittest + +from verify_shader_dump import verify + + +class ShaderDumpTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.prefix = Path(tmp.name) / "0000000000000001_f0_24" + self.path = self.prefix.with_suffix(".manifest.json") + self.manifest = dict(schema_version=1, backend="direct-dxil", guest_fnv64="a430d84680aabd0b", + dxil_fnv64="85944171f73967e8", error=None) + self.prefix.with_suffix(".guest.bin").write_bytes(b"hello") + self.prefix.with_suffix(".direct.dxil").write_bytes(b"foobar") + + def check(self): + self.path.write_text(json.dumps(self.manifest), encoding="utf-8") + return verify(self.path) + + def test_translation(self): + self.assertEqual(self.check(), "guest and translated DXIL match") + self.prefix.with_suffix(".direct.dxil").write_bytes(b"foo") + with self.assertRaisesRegex(ValueError, "dxil_fnv64 mismatch"): + self.check() + + def test_hashes_every_binary_chunk(self): + self.prefix.with_suffix(".guest.bin").write_bytes(bytes(range(256)) * 512 + b"\0") + self.manifest["guest_fnv64"] = "9fd6a807c893b7df" + self.assertEqual(self.check(), "guest and translated DXIL match") + + def test_error_uses_exact_bytes_even_when_old_dxil_is_present(self): + error = "first\nsecond: \u0394" + self.manifest.update(dxil_fnv64=None, error=error) + diagnostic = self.prefix.with_suffix(".direct.err.txt") + diagnostic.write_bytes(error.encode("utf-8")) + self.assertEqual(self.check(), "guest and translation error match") + diagnostic.write_bytes(error.replace("\n", "\r\n").encode("utf-8")) + with self.assertRaisesRegex(ValueError, "error text mismatch"): + self.check() + + def test_guest_changed_or_missing(self): + guest = self.prefix.with_suffix(".guest.bin") + guest.write_bytes(b"HELLO") + with self.assertRaisesRegex(ValueError, "guest_fnv64 mismatch"): + self.check() + guest.unlink() + with self.assertRaises(FileNotFoundError): + self.check() + + def test_version_and_ambiguous_result(self): + for change in (dict(schema_version=True), dict(schema_version=2), dict(backend="other"), + dict(error="also an error"), dict(dxil_fnv64=None)): + with self.subTest(change=change): + before = dict(self.manifest) + self.manifest.update(change) + with self.assertRaises(ValueError): + self.check() + self.manifest = before diff --git a/scripts/verify_shader_dump.py b/scripts/verify_shader_dump.py new file mode 100644 index 0000000000..a08813f8b8 --- /dev/null +++ b/scripts/verify_shader_dump.py @@ -0,0 +1,66 @@ +"""Check the files next to a manifest written by xcl shaders --direct --dump. + +Run python scripts/verify_shader_dump.py FILE.manifest.json [FILE.manifest.json ...]. +""" + +import argparse +import json +from pathlib import Path +import sys + + +def fnv64(path): + """Match shader::fnv64 on the bytes of a dump file.""" + value = 0xCBF29CE484222325 + with path.open("rb") as stream: + while chunk := stream.read(65536): + for byte in chunk: + value = ((value ^ byte) * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF + return f"{value:016x}" + + +def verify(path): + suffix = ".manifest.json" + if not path.name.endswith(suffix): + raise ValueError(f"expected a {suffix} file") + manifest = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(manifest, dict): + raise ValueError("expected a manifest object") + if type(manifest.get("schema_version")) is not int or manifest["schema_version"] != 1: + raise ValueError("expected schema_version 1") + if manifest.get("backend") != "direct-dxil": + raise ValueError("expected backend direct-dxil") + prefix = path.name[:-len(suffix)] + guest = path.with_name(prefix + ".guest.bin") + if fnv64(guest) != manifest["guest_fnv64"]: + raise ValueError(f"{guest.name}: guest_fnv64 mismatch") + + dxil_hash, error = manifest["dxil_fnv64"], manifest["error"] + if error is None and isinstance(dxil_hash, str): + dxil = path.with_name(prefix + ".direct.dxil") + if fnv64(dxil) != dxil_hash: + raise ValueError(f"{dxil.name}: dxil_fnv64 mismatch") + return "guest and translated DXIL match" + if dxil_hash is None and isinstance(error, str): + diagnostic = path.with_name(prefix + ".direct.err.txt") + if diagnostic.read_bytes() != error.encode("utf-8"): + raise ValueError(f"{diagnostic.name}: error text mismatch") + return "guest and translation error match" + raise ValueError("expected one translation result (dxil_fnv64 or error)") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("manifest", type=Path, nargs="+") + failed = False + for path in parser.parse_args(argv).manifest: + try: + print(f"{path}: {verify(path)}") + except (OSError, ValueError, KeyError) as exc: + print(f"{path}: {exc}", file=sys.stderr) + failed = True + return int(failed) + + +if __name__ == "__main__": + sys.exit(main()) From b0d2fb814b92148710d0f91e590d6c1f9fe26cd2 Mon Sep 17 00:00:00 2001 From: mokkamokacaffe <329663686+mokkamokacaffe@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:54:11 +0100 Subject: [PATCH 4/6] Shaders: invalidate stale dump manifests before replacement Remove an existing manifest before replacing any of its sibling artifacts. A failed rerun can then leave incomplete files, but cannot make the verifier accept the previous generation as the new result. Add a two-generation regression that forces the replacement error artifact to be unwritable and checks that the old manifest is gone. Assisted-by: OpenAI Codex (GPT-6.2 Astra Ultra) --- crates/xcl/src/shaders.rs | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 8856d9f24b..e885b0b85c 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2122,6 +2122,31 @@ mod tests { assert!(!root.0.join("sample.manifest.json").exists(), "a manifest must not advertise artifacts that were not saved"); } + #[test] + fn direct_dump_invalidates_an_old_manifest_before_replacing_artifacts() { + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + let root = Temp(std::env::temp_dir().join(format!("xcl-direct-dump-replace-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&root.0); + std::fs::create_dir_all(&root.0).unwrap(); + let old_manifest = serde_json::json!({ "schema_version": 1, "generation": "old" }); + write_direct_dump(&root.0, "sample", b"guest", &Ok(vec![1, 2, 3]), &old_manifest).unwrap(); + assert!(root.0.join("sample.manifest.json").is_file()); + + // A directory makes the replacement error artifact unwritable. The previous manifest + // must already be gone, or it would still authenticate the old DXIL after this failure. + std::fs::create_dir(root.0.join("sample.direct.err.txt")).unwrap(); + let new_manifest = serde_json::json!({ "schema_version": 1, "generation": "new" }); + let err = write_direct_dump(&root.0, "sample", b"guest", &Err("new failure".into()), &new_manifest).unwrap_err(); + assert!(err.contains("sample.direct.err.txt"), "{err}"); + assert!(!root.0.join("sample.manifest.json").exists(), "a failed replacement must invalidate the previous manifest"); + } + #[test] fn hlsl_export_is_ordered_and_exact_hash_selects_one_record() { struct Temp(std::path::PathBuf); @@ -2273,7 +2298,7 @@ fn name_hash(name: &str) -> u64 { h } -/// Write the required artifacts first and publish their manifest only after every write succeeds. +/// Invalidate an earlier generation, write the required artifacts, then publish the new manifest. fn write_direct_dump( dir: &std::path::Path, prefix: &str, @@ -2281,8 +2306,15 @@ fn write_direct_dump( result: &Result, String>, manifest: &serde_json::Value, ) -> Result<(), String> { + let path = |suffix: &str| dir.join(format!("{prefix}.{suffix}")); + let manifest_path = path("manifest.json"); + match std::fs::remove_file(&manifest_path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("could not invalidate {}: {e}", manifest_path.display())), + } let write = |suffix: &str, bytes: &[u8]| { - let path = dir.join(format!("{prefix}.{suffix}")); + let path = path(suffix); std::fs::write(&path, bytes).map_err(|e| format!("could not write {}: {e}", path.display())) }; write("guest.bin", guest)?; @@ -2290,7 +2322,7 @@ fn write_direct_dump( Ok(dxil) => write("direct.dxil", dxil)?, Err(e) => write("direct.err.txt", e.as_bytes())?, } - write("manifest.json", manifest.to_string().as_bytes()) + std::fs::write(&manifest_path, manifest.to_string()).map_err(|e| format!("could not write {}: {e}", manifest_path.display())) } /// `--direct [--sample N] [--seed S] [--validate] [--compare] [--split 0|1] [--windows W]`: From ba0df5740eef2dc8d004029762fc114c795a8744 Mon Sep 17 00:00:00 2001 From: IISKII Date: Thu, 26 Nov 2026 21:03:36 +0100 Subject: [PATCH 5/6] Scripts: prepare verified shader diagnostic bundles Snapshot and verify analyzer inputs before external tools consume them. Record source metadata and SHA-256 identities separately from diagnostic results. Assisted-by: Codex (GPT-6) --- README.md | 12 ++++++ scripts/analyze_shader.py | 74 ++++++++++++++++++++++++++++++++++ scripts/test_analyze_shader.py | 63 +++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 scripts/analyze_shader.py create mode 100644 scripts/test_analyze_shader.py diff --git a/README.md b/README.md index e966a88b65..7e43c28462 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,18 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder ## Tests +### Offline shader diagnostic bundles + +With Python 3.11+, `python scripts/analyze_shader.py FILE.manifest.json --out diagnostics` +copies a direct shader dump into a new directory and verifies the copied guest/DXIL hashes +(or the exact translation error). It writes `report.json` with the original manifest, SHA-256 +hashes and local artifact paths. Each invocation has its own directory, so an older result +cannot be mistaken for a new one. An invalid bundle returns exit 1; a verified bundle with no +analyzer requested reports `SKIPPED` and returns 0. This is not DXIL validation or GPU coverage. +Use `--source-commit HASH` to record the producer revision when known; it is caller-supplied, +not inferred from the checkout analyzing the files. Bundles remain local and may contain game +shader data; review them before sharing. + ```powershell .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace ``` diff --git a/scripts/analyze_shader.py b/scripts/analyze_shader.py new file mode 100644 index 0000000000..22a0949a46 --- /dev/null +++ b/scripts/analyze_shader.py @@ -0,0 +1,74 @@ +"""Prepare a verified, isolated shader bundle for optional vendor diagnostics.""" + +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import sys +import tempfile + +from verify_shader_dump import verify + + +def prepare(manifest, output, source_commit=None): + """Copy first, then verify the exact bytes an analyzer will consume.""" + output.mkdir(parents=True, exist_ok=True) + run = Path(tempfile.mkdtemp(prefix="shader-", dir=output)).resolve() + report = dict(schema_version=1, source_commit=source_commit, + manifest_path=str(manifest.resolve()), status="ERROR", + category="invalid_bundle", verification=None, analyzer=None) + try: + if not manifest.name.endswith(".manifest.json"): + raise ValueError("expected a .manifest.json file") + bundle = run / "input" + bundle.mkdir() + copied = bundle / manifest.name + shutil.copyfile(manifest, copied) + data = json.loads(copied.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise ValueError("expected a manifest object") + prefix = manifest.name[:-len(".manifest.json")] + suffixes = [".guest.bin", ".direct.err.txt" if data.get("error") is not None else ".direct.dxil"] + for suffix in suffixes: + shutil.copyfile(manifest.with_name(prefix + suffix), bundle / (prefix + suffix)) + report["verification"] = verify(copied) + report["manifest"] = data + # SHA-256 complements the manifest's FNV identity; neither authenticates its author. + report["artifacts"] = {} + for path in sorted(bundle.iterdir()): + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + report["artifacts"][path.name] = dict(path=str(path), sha256=digest) + report.update(status="SKIPPED", category="analyzer_not_requested") + if data.get("error") is not None: + report["category"] = "translation_rejected" + except (OSError, ValueError, KeyError) as exc: + report["detail"] = str(exc) + return run, report + + +def save_report(run, report): + path = run / "report.json" + path.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + return path + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("manifest", type=Path) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--source-commit", help="producer commit, supplied by the caller; not inferred from this checkout") + args = parser.parse_args(argv) + try: + run, report = prepare(args.manifest, args.out, args.source_commit) + path = save_report(run, report) + except OSError as exc: + print(str(exc), file=sys.stderr) + return 1 + print(f"{report['status']}: {report['category']}; {path}") + return int(report["status"] == "ERROR") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test_analyze_shader.py b/scripts/test_analyze_shader.py new file mode 100644 index 0000000000..f46460a6a1 --- /dev/null +++ b/scripts/test_analyze_shader.py @@ -0,0 +1,63 @@ +"""Synthetic artifact fixtures; these bytes are not executable DXIL.""" +import hashlib +import json +from pathlib import Path +import tempfile +import unittest + +from analyze_shader import prepare, save_report, main + + +class AnalysisTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.path = self.root / "sample.manifest.json" + self.data = dict(schema_version=1, backend="direct-dxil", stage="cs", wave64=False, + guest_fnv64="a430d84680aabd0b", dxil_fnv64="85944171f73967e8", error=None) + self.path.write_text(json.dumps(self.data), encoding="utf-8") + (self.root / "sample.guest.bin").write_bytes(b"hello") + (self.root / "sample.direct.dxil").write_bytes(b"foobar") + self.output = self.root / "reports" + + def test_snapshot_and_hashes(self): + run, report = prepare(self.path, self.output, "a" * 40) + self.assertEqual(report["category"], "analyzer_not_requested") + self.assertEqual(report["source_commit"], "a" * 40) + artifact = report["artifacts"]["sample.direct.dxil"] + self.assertEqual(artifact["sha256"], hashlib.sha256(b"foobar").hexdigest()) + (self.root / "sample.direct.dxil").write_bytes(b"changed") + self.assertEqual(Path(artifact["path"]).read_bytes(), b"foobar") + self.assertEqual(json.loads(save_report(run, report).read_text()), report) + + def test_corruption_and_missing_artifact_fail(self): + artifact = self.root / "sample.direct.dxil" + artifact.write_bytes(b"corrupt") + self.assertEqual(prepare(self.path, self.output)[1]["status"], "ERROR") + artifact.unlink() + self.assertEqual(main([str(self.path), "--out", str(self.output)]), 1) + + def test_rejected_translation_preserves_error(self): + self.data.update(dxil_fnv64=None, error="unsupported\n") + self.path.write_text(json.dumps(self.data), encoding="utf-8") + (self.root / "sample.direct.err.txt").write_bytes(b"unsupported\n") + run, report = prepare(self.path, self.output) + self.assertEqual(report["category"], "translation_rejected") + self.assertFalse((run / "input" / "sample.direct.dxil").exists()) + + def test_invalid_manifest_and_schema(self): + for value in ([], {}, dict(self.data, schema_version=True), dict(self.data, backend="other")): + with self.subTest(value=value): + self.path.write_text(json.dumps(value), encoding="utf-8") + self.assertEqual(prepare(self.path, self.output)[1]["status"], "ERROR") + + def test_runs_never_reuse_outputs(self): + a, _ = prepare(self.path, self.output) + b, _ = prepare(self.path, self.output) + self.assertNotEqual(a, b) + self.assertEqual(main([str(self.path), "--out", str(self.output)]), 0) + + +if __name__ == "__main__": + unittest.main() From 57a80785fa65d11131874e621e96b117df4e246a Mon Sep 17 00:00:00 2001 From: IISKII Date: Thu, 26 Nov 2026 21:04:03 +0100 Subject: [PATCH 6/6] Scripts: analyze verified compute dumps with AMD RGA Run explicitly selected offline compute analysis with isolated outputs, bounded subprocess execution and raw CSV statistics. Keep analyzer outcomes separate from XCL correctness results. Assisted-by: Codex (GPT-6) --- README.md | 12 +++++ scripts/analyze_shader.py | 11 +++++ scripts/shader_rga.py | 90 ++++++++++++++++++++++++++++++++++++++ scripts/test_shader_rga.py | 83 +++++++++++++++++++++++++++++++++++ 4 files changed, 196 insertions(+) create mode 100644 scripts/shader_rga.py create mode 100644 scripts/test_shader_rga.py diff --git a/README.md b/README.md index 7e43c28462..6b4ae013ca 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,18 @@ Use `--source-commit HASH` to record the producer revision when known; it is cal not inferred from the checkout analyzing the files. Bundles remain local and may contain game shader data; review them before sharing. +Add `--rga C:\Tools\RGA\rga.exe --target gfx1101` for optional **AMD offline compute** +analysis (or `--rga` with `XCL_RGA` set). Install RGA separately from +[AMD](https://gpuopen.com/rga/); the script never downloads tools. The target is explicitly +selected, not detected from the host GPU. Only `CS` and `kernel` manifests are supported; +other stages, missing tools and tools without the required mode report `SKIPPED`. +Each invocation records its command, exit code, duration and raw output. Nonempty ISA output +is required for success, even if RGA exits zero. Statistics retain RGA's CSV column names +and units. Missing metrics remain absent. `--timeout 120` limits each tool invocation. +Offline compiler results (including autogenerated pipeline state) are not measurements of +the game's actual pipeline, GPU execution, occupancy or frame rate. NVIDIA integration, +host-adapter discovery and graphics-pipeline analysis are not implemented. + ```powershell .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace ``` diff --git a/scripts/analyze_shader.py b/scripts/analyze_shader.py index 22a0949a46..5eb0d0ddce 100644 --- a/scripts/analyze_shader.py +++ b/scripts/analyze_shader.py @@ -3,6 +3,8 @@ import argparse import hashlib import json +import math +import os from pathlib import Path import shutil import sys @@ -59,9 +61,18 @@ def main(argv=None): parser.add_argument("manifest", type=Path) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--source-commit", help="producer commit, supplied by the caller; not inferred from this checkout") + parser.add_argument("--rga", nargs="?", const=os.environ.get("XCL_RGA", "rga.exe"), + help="opt in to AMD offline compute analysis; optional executable path (or XCL_RGA)") + parser.add_argument("--target", help="explicit AMD offline target, e.g. gfx1101; not a detected host adapter") + parser.add_argument("--timeout", type=float, default=120, help="seconds per analyzer invocation") args = parser.parse_args(argv) + if not math.isfinite(args.timeout) or args.timeout <= 0: + parser.error("--timeout must be finite and positive") try: run, report = prepare(args.manifest, args.out, args.source_commit) + if args.rga is not None: + from shader_rga import analyze + analyze(run, report, args.rga, args.target, args.timeout) path = save_report(run, report) except OSError as exc: print(str(exc), file=sys.stderr) diff --git a/scripts/shader_rga.py b/scripts/shader_rga.py new file mode 100644 index 0000000000..5cb20d6877 --- /dev/null +++ b/scripts/shader_rga.py @@ -0,0 +1,90 @@ +"""Opt-in RGA DX12 offline compute diagnostics, separate from XCL validation.""" +import csv +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import time + + +def execute(command, directory, label, timeout): + stdout, stderr = directory / f"{label}.stdout.txt", directory / f"{label}.stderr.txt" + result = dict(command=command, exit_code=None, timed_out=False, + stdout=str(stdout), stderr=str(stderr)) + start = time.monotonic() + with stdout.open("wb") as out, stderr.open("wb") as err: + with subprocess.Popen(command, cwd=directory, stdout=out, stderr=err, + start_new_session=os.name != "nt") as process: + try: + result["exit_code"] = process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + result["timed_out"] = True + if os.name == "nt": + subprocess.run([str(Path(os.environ["SystemRoot"]) / "System32/taskkill.exe"), + "/PID", str(process.pid), "/T", "/F"], + stdout=err, stderr=err, timeout=15, check=False) + else: + os.killpg(process.pid, signal.SIGKILL) + if process.poll() is None: + process.kill() + result["exit_code"] = process.wait() + result["wall_seconds"] = time.monotonic() - start + return result + + +def analyze(run, report, tool, target, timeout=120): + if report["category"] != "analyzer_not_requested": + return + report["analyzer"] = dict(name="Radeon GPU Analyzer", mode="dx12-offline", target=target, + host_adapter=None, version=None, invocations=[], statistics=[]) + info = report["analyzer"] + if report["manifest"].get("stage") not in ("CS", "kernel"): + report["category"] = "unsupported_stage" + return + if not target or not re.fullmatch(r"gfx[0-9a-f]+", target): + report.update(status="ERROR", category="invalid_target") + return + executable = shutil.which(tool) if tool else None + if not executable: + report["category"] = "tool_missing" + return + executable = str(Path(executable).resolve()) + # Batch files invoke a shell on Windows; only a native executable is supported. + if os.name == "nt" and Path(executable).suffix.lower() != ".exe": + report.update(status="ERROR", category="invalid_tool") + return + directory = run / "rga" + directory.mkdir() + try: + for label, arguments in (("version", ["--version"]), ("help", ["-s", "dx12", "-h"])): + invocation = execute([executable, *arguments], directory, label, timeout) + info["invocations"].append(invocation) + if invocation["timed_out"] or invocation["exit_code"] != 0: + report.update(status="ERROR", category="tool_probe_failed") + return + info["version"] = (directory / "version.stdout.txt").read_text(encoding="utf-8", errors="replace").strip() + help_text = (directory / "help.stdout.txt").read_text(encoding="utf-8", errors="replace") + if not all(flag in help_text for flag in ("--offline", "--cs-blob")): + report["category"] = "unsupported_tool_mode" + return + dxil = next(v["path"] for k, v in report["artifacts"].items() if k.endswith(".direct.dxil")) + command = [executable, "-s", "dx12", "--offline", "-c", target, "--cs-blob", dxil, + "--isa", str(directory / "shader.isa"), "-a", str(directory / "stats.csv")] + invocation = execute(command, directory, "analysis", timeout) + info["invocations"].append(invocation) + outputs = [p for p in directory.glob("*.isa") if p.stat().st_size] + info["isa_files"] = [str(p) for p in outputs] + for path in sorted(directory.glob("*.csv")): + with path.open(encoding="utf-8-sig", newline="", errors="replace") as stream: + info["statistics"].append(dict(path=str(path), rows=list(csv.DictReader(stream)))) + if invocation["timed_out"]: + report.update(status="ERROR", category="analyzer_timeout") + elif invocation["exit_code"] != 0 or not outputs: + # RGA versions can return zero even when pipeline creation fails. + report.update(status="ERROR", category="analyzer_failed") + else: + report.update(status="OK", category="analysis_complete") + except (OSError, ValueError, subprocess.SubprocessError) as exc: + report.update(status="ERROR", category="analyzer_failed", detail=str(exc)) diff --git a/scripts/test_shader_rga.py b/scripts/test_shader_rga.py new file mode 100644 index 0000000000..023e500958 --- /dev/null +++ b/scripts/test_shader_rga.py @@ -0,0 +1,83 @@ +"""Synthetic subprocess results; these tests do not establish AMD compiler coverage.""" +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +from shader_rga import analyze, execute + + +class RgaTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.run = Path(tmp.name) + self.report = dict(category="analyzer_not_requested", status="SKIPPED", + manifest={"stage": "CS"}, artifacts={ + "shader.direct.dxil": {"path": str(self.run / "shader.direct.dxil")}}) + + def fake(self, command, directory, label, timeout): + (directory / f"{label}.stdout.txt").write_text( + "RGA test fixture" if label == "version" else "--offline --cs-blob", encoding="utf-8") + if label == "analysis": + (directory / "gfx1101_shader_cs.isa").write_text("synthetic ISA", encoding="utf-8") + (directory / "gfx1101_stats_cs.csv").write_text("DEVICE,VGPRs\ngfx1101,16\n", encoding="utf-8") + return dict(command=command, exit_code=0, timed_out=False, wall_seconds=0.01) + + def test_success_keeps_exact_argv_and_raw_metrics(self): + with patch("shader_rga.shutil.which", return_value="C:/Tools/RGA/rga.exe"), patch("shader_rga.execute", side_effect=self.fake): + analyze(self.run, self.report, "rga", "gfx1101") + self.assertEqual(self.report["status"], "OK") + info = self.report["analyzer"] + self.assertEqual(info["statistics"][0]["rows"][0]["VGPRs"], "16") + command = info["invocations"][-1]["command"] + self.assertEqual(command[command.index("--cs-blob") + 1], str(self.run / "shader.direct.dxil")) + self.assertIn("--offline", command) + + def test_absent_tool_skips(self): + with patch("shader_rga.shutil.which", return_value=None): + analyze(self.run, self.report, "missing.exe", "gfx1101") + self.assertEqual(self.report["category"], "tool_missing") + + def test_unsupported_stage_never_launches(self): + self.report["manifest"]["stage"] = "GS" + with patch("shader_rga.execute") as launch: + analyze(self.run, self.report, "rga", "gfx1101") + launch.assert_not_called() + self.assertEqual(self.report["category"], "unsupported_stage") + + def test_invalid_bundle_never_launches(self): + self.report.update(category="invalid_bundle", status="ERROR") + with patch("shader_rga.execute") as launch: + analyze(self.run, self.report, "rga", "gfx1101") + launch.assert_not_called() + self.assertEqual(self.report["category"], "invalid_bundle") + + def test_zero_exit_without_output_is_failure(self): + def no_output(command, directory, label, timeout): + result = self.fake(command, directory, label, timeout) + if label == "analysis": + (directory / "gfx1101_shader_cs.isa").unlink() + return result + with patch("shader_rga.shutil.which", return_value="C:/Tools/RGA/rga.exe"), patch("shader_rga.execute", side_effect=no_output): + analyze(self.run, self.report, "rga", "gfx1101") + self.assertEqual(self.report["category"], "analyzer_failed") + + def test_bad_target_is_error(self): + analyze(self.run, self.report, "rga", "--anything") + self.assertEqual(self.report["category"], "invalid_target") + + def test_real_subprocess_exit_and_logs(self): + result = execute([sys.executable, "-c", "import sys; print('output'); sys.exit(7)"], self.run, "child", 5) + self.assertEqual(result["exit_code"], 7) + self.assertIn("output", Path(result["stdout"]).read_text()) + + def test_real_subprocess_timeout(self): + result = execute([sys.executable, "-c", "import time; time.sleep(30)"], self.run, "child", 0.1) + self.assertTrue(result["timed_out"]) + self.assertIsNotNone(result["exit_code"]) + + +if __name__ == "__main__": + unittest.main()