GPU: keep host pipeline caches per adapter #2803

Open
github-bot wants to merge 8 commits from github-bot/gh-2803 into main AGit
Owner

@⁠yumaste on GitHub · 2026-11-25 20:59 UTC · original
yumaste:fix/pipeline-cache-by-adapter → main · +353 −40 · 1 files · 8 commits · open

Problem

The host pipeline library and its prebuilt list are currently shared by all adapters. Switching between the integrated and discrete GPUs on a hybrid laptop makes D3D12 reject the other adapter's library. A subsequent save can overwrite the existing cache. #2637 and #2646 describe the related WARP case.

Change

  • Identify the actual D3D12 adapter through DXGI and store the serialized library and its prebuilt list together under an adapter-specific directory.
  • Read a legacy cache when there is no scoped cache yet. D3D12 still checks blob compatibility before the library can be reused.
  • Keep the title's early-pipeline list shared across adapters.
  • Record the cache directory consulted when the pipeline library opens. If DXGI cannot identify the adapter or the adapter's library is present but could not be read, the library stays in memory for that run. This protects an existing cache after the lookup or read becomes possible. The shared early list can still be saved independently.

Verification

  • Windows 11, Intel integrated graphics, NVIDIA GeForce RTX 5080 Laptop GPU and WARP. DXGI returned a distinct cache path for each.
  • Follow-up at 19a1ddd: the diagnostics-enabled pipeline:: suite under WARP passed 30 tests, with the all-adapters test ignored. Regressions cover late adapter lookup and a file sharing violation that clears before save. They check that both existing cache files stay intact. The WARP helper checks the adapter's software flag before creating a device. Both strict Clippy profiles and the asset policy passed.
  • No game files used. Implementation and verification assisted by Codex.
**@⁠yumaste** on GitHub · 2026-11-25 20:59 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803) `yumaste:fix/pipeline-cache-by-adapter` → `main` · +353 −40 · 1 files · 8 commits · open ## Problem The host pipeline library and its prebuilt list are currently shared by all adapters. Switching between the integrated and discrete GPUs on a hybrid laptop makes D3D12 reject the other adapter's library. A subsequent save can overwrite the existing cache. #2637 and #2646 describe the related WARP case. ## Change - Identify the actual D3D12 adapter through DXGI and store the serialized library and its prebuilt list together under an adapter-specific directory. - Read a legacy cache when there is no scoped cache yet. D3D12 still checks blob compatibility before the library can be reused. - Keep the title's early-pipeline list shared across adapters. - Record the cache directory consulted when the pipeline library opens. If DXGI cannot identify the adapter or the adapter's library is present but could not be read, the library stays in memory for that run. This protects an existing cache after the lookup or read becomes possible. The shared early list can still be saved independently. ## Verification - Windows 11, Intel integrated graphics, NVIDIA GeForce RTX 5080 Laptop GPU and WARP. DXGI returned a distinct cache path for each. - Follow-up at `19a1ddd`: the diagnostics-enabled `pipeline::` suite under WARP passed 30 tests, with the all-adapters test ignored. Regressions cover late adapter lookup and a file sharing violation that clears before save. They check that both existing cache files stay intact. The WARP helper checks the adapter's software flag before creating a device. Both strict Clippy profiles and the asset policy passed. - No game files used. Implementation and verification assisted by Codex.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 05:14:37 +00:00
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-25 21:20 UTC · original

Reviewed and verified 4a912966 on Windows 11 (triple-adapter host: RTX 5090 + AMD Radeon + WARP) against main (13f91ca).

Code review

  • Safe persistent key (no LUID on disk): uses transient GetAdapterLuid() only to look up DXGI_ADAPTER_DESC1 via EnumAdapterByLuid, then builds the directory strictly from hex PCI/software fields ({hardware|software}-{VendorId:04x}-{DeviceId:04x}-{SubSysId:08x}-{Revision:02x}), avoiding reboot-volatile LUIDs and adapter-name path injection.
  • Legacy fallback & concurrency: read_cache falls back to root host-pipelines.bin + prebuilt-pipelines.txt on NotFound, save() writes only into adapters/<id>/ via write_atomically without clobbering legacy root files, early-pipelines.txt stays shared across adapters, and ADAPTER/LIBRARY use OnceLock.

Verification (Windows 11, rustc 1.98.1 MSVC)

  • pipeline:: (--features diagnostics --test-threads=1): 18/18 passed on RTX 5090 and 18/18 passed on WARP.
  • each_d3d12_device_uses_its_own_dxgi_adapter verified all 3 adapters on this machine:
    • NVIDIA GeForce RTX 5090 -> adapters/hardware-10de-2b85-89ec1043-a1
    • AMD Radeon(TM) Graphics -> adapters/hardware-1002-13c0-88771043-c1
    • Microsoft Basic Render Driver -> adapters/software-1414-008c-00000000-00
  • cargo clippy --locked -p victory-gpu --features diagnostics --all-targets -- -D warnings: 0 warnings; cargo xtask policy: 184 files ok; clean git merge-tree vs 13f91ca and #2801.
**@⁠fuzeofficlal** on GitHub · 2026-11-25 21:20 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7174945377) Reviewed and verified `4a912966` on Windows 11 (triple-adapter host: RTX 5090 + AMD Radeon + WARP) against `main` (`13f91ca`). ### Code review - **Safe persistent key (no LUID on disk)**: uses transient `GetAdapterLuid()` only to look up `DXGI_ADAPTER_DESC1` via `EnumAdapterByLuid`, then builds the directory strictly from hex PCI/software fields (`{hardware|software}-{VendorId:04x}-{DeviceId:04x}-{SubSysId:08x}-{Revision:02x}`), avoiding reboot-volatile LUIDs and adapter-name path injection. - **Legacy fallback & concurrency**: `read_cache` falls back to root `host-pipelines.bin` + `prebuilt-pipelines.txt` on `NotFound`, `save()` writes only into `adapters/<id>/` via `write_atomically` without clobbering legacy root files, `early-pipelines.txt` stays shared across adapters, and `ADAPTER`/`LIBRARY` use `OnceLock`. ### Verification (Windows 11, `rustc 1.98.1` MSVC) - `pipeline::` (`--features diagnostics --test-threads=1`): **18/18 passed on RTX 5090** and **18/18 passed on WARP**. - `each_d3d12_device_uses_its_own_dxgi_adapter` verified all 3 adapters on this machine: - `NVIDIA GeForce RTX 5090` -> `adapters/hardware-10de-2b85-89ec1043-a1` - `AMD Radeon(TM) Graphics` -> `adapters/hardware-1002-13c0-88771043-c1` - `Microsoft Basic Render Driver` -> `adapters/software-1414-008c-00000000-00` - `cargo clippy --locked -p victory-gpu --features diagnostics --all-targets -- -D warnings`: **0 warnings**; `cargo xtask policy`: **184 files ok**; clean `git merge-tree` vs `13f91ca` and `#2801`.
Author
Owner

@⁠oni-swr on GitHub · 2026-11-25 21:21 UTC · original

Independent WARP/CPU verification of head 4a9129667ca5605f29c59abe44c42aba34e527b8, merged onto origin/main 13f91caee25f2fdf2c062be5f7a27f058e51cbca (clean merge).

Environment: Windows 11 Pro 26200, WARP only (VICTORY_D3D12_WARP=1 with --features diagnostics, VICTORY_WARP=1), Windows SDK 10.0.26100.0 x64 dxil.dll 1.8.2502.11.

  • cargo test -j 4 -p victory-gpu --features diagnostics -- --skip each_d3d12_device_uses_its_own_dxgi_adapter: 199 passed, 0 failed, 1 ignored, 1 filtered out. The baseline was 198/0/1, plus adapter_caches_keep_their_own_library_and_prebuilt_list.
  • each_d3d12_device_uses_its_own_dxgi_adapter was not run as written, because it creates a D3D12 device on every EnumAdapters1 adapter. That means the physical GPU, whatever VICTORY_D3D12_WARP says. I ran a local copy limited to EnumWarpAdapter, and it passed: Microsoft Basic Render Driver: cache\adapters\software-1414-008c-00000000-00, with the LUID round trip through EnumAdapterByLuid matching on WARP.
  • Negative controls:
    • When read_cache never falls back to the legacy root, adapter_caches_keep_their_own_library_and_prebuilt_list fails at the legacy assertion, so the test catches it.
    • When DeviceId is dropped from the adapter_cache_dir key, every test still passes. The fixtures differ by vendor (NVIDIA, Intel, WARP), so nothing exercises two adapters from one vendor, such as an Intel iGPU plus an Intel Arc card.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings was clean, with and without --all-features.
  • cargo fmt --all --check: 898 hunks against 891 on the baseline. The 7 new hunks are in new code in pipeline/library.rs: two in save() (the one-line let .. else and the long tracing::warn! arm) and five in the new tests (the DXGI_ADAPTER_DESC1 literals, one assert_eq!, the let Ok(..) else and the eprintln!).

Diff review:

  1. The device-enumerating test should not open devices on hardware adapters by default. The tests here otherwise reach a device through host() or warp_adapter(). Could it use only the software adapter, or be #[ignore]d or gated?
  2. Adding a same-vendor, different-DeviceId pair to adapter_caches_keep_their_own_library_and_prebuilt_list would pin down the key.
  3. Please run rustfmt on the new lines.
  4. Two identical GPUs (same vendor, device, subsystem and revision) share one directory. That seems acceptable, since D3D12 still refuses a library from another driver. The rest of the logic looks right: the legacy fallback only applies when the file is NotFound, other errors give an empty cache, the early list stays shared, and the warning shows when no adapter is known.

Not tested: physical GPU, hybrid-GPU machine, retail title.

AI use: Claude Code (Claude Opus 5.5)

**@⁠oni-swr** on GitHub · 2026-11-25 21:21 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7174975648) Independent WARP/CPU verification of head `4a9129667ca5605f29c59abe44c42aba34e527b8`, merged onto `origin/main` `13f91caee25f2fdf2c062be5f7a27f058e51cbca` (clean merge). Environment: Windows 11 Pro 26200, WARP only (`VICTORY_D3D12_WARP=1` with `--features diagnostics`, `VICTORY_WARP=1`), Windows SDK 10.0.26100.0 x64 `dxil.dll` 1.8.2502.11. - `cargo test -j 4 -p victory-gpu --features diagnostics -- --skip each_d3d12_device_uses_its_own_dxgi_adapter`: 199 passed, 0 failed, 1 ignored, 1 filtered out. The baseline was 198/0/1, plus `adapter_caches_keep_their_own_library_and_prebuilt_list`. - `each_d3d12_device_uses_its_own_dxgi_adapter` was **not run as written**, because it creates a D3D12 device on every `EnumAdapters1` adapter. That means the physical GPU, whatever `VICTORY_D3D12_WARP` says. I ran a local copy limited to `EnumWarpAdapter`, and it passed: `Microsoft Basic Render Driver: cache\adapters\software-1414-008c-00000000-00`, with the LUID round trip through `EnumAdapterByLuid` matching on WARP. - Negative controls: - When `read_cache` never falls back to the legacy root, `adapter_caches_keep_their_own_library_and_prebuilt_list` fails at the legacy assertion, so the test catches it. - When `DeviceId` is dropped from the `adapter_cache_dir` key, **every test still passes**. The fixtures differ by vendor (NVIDIA, Intel, WARP), so nothing exercises two adapters from one vendor, such as an Intel iGPU plus an Intel Arc card. - `cargo clippy -p victory-gpu --all-targets -- -D warnings` was clean, with and without `--all-features`. - `cargo fmt --all --check`: 898 hunks against 891 on the baseline. The 7 new hunks are in new code in `pipeline/library.rs`: two in `save()` (the one-line `let .. else` and the long `tracing::warn!` arm) and five in the new tests (the `DXGI_ADAPTER_DESC1` literals, one `assert_eq!`, the `let Ok(..) else` and the `eprintln!`). Diff review: 1. The device-enumerating test should not open devices on hardware adapters by default. The tests here otherwise reach a device through `host()` or `warp_adapter()`. Could it use only the software adapter, or be `#[ignore]`d or gated? 2. Adding a same-vendor, different-`DeviceId` pair to `adapter_caches_keep_their_own_library_and_prebuilt_list` would pin down the key. 3. Please run `rustfmt` on the new lines. 4. Two identical GPUs (same vendor, device, subsystem and revision) share one directory. That seems acceptable, since D3D12 still refuses a library from another driver. The rest of the logic looks right: the legacy fallback only applies when the file is `NotFound`, other errors give an empty cache, the early list stays shared, and the warning shows when no adapter is known. Not tested: physical GPU, hybrid-GPU machine, retail title. AI use: Claude Code (Claude Opus 5.5)
Author
Owner

@⁠AurumCarlos on GitHub · 2026-11-25 21:23 UTC · original · edited 2026-11-25 21:29 UTC

Review notes: suggested fixes for library.rs

Five issues from a review of this PR, with a patch on top of 4a91296 below.

  1. Library never saved when the adapter lookup fails. cache_dir caches a failed device_adapter result (None) in a static OnceLock, so it is never retried. save then serializes the library and resets added but writes nothing; before this PR the library was always saved under the cache root. Fix: cache only a successful lookup, and when the adapter is unknown, save in the cache root as before (D3D12 still refuses another adapter's library on read).
  2. Wasted serialize and a repeated warning when the adapter is unknown. Every 20 s save serialized the whole library, threw the bytes away and logged the same warning. Fixed by (1): the library is always written somewhere, and the warning branch is removed.
  3. Legacy files never cleaned up. <cache>/pipelines/host-pipelines.bin and prebuilt-pipelines.txt stayed on disk forever. Fix: once a library made from the legacy files (and accepted by D3D12) has been saved under its adapter folder, the legacy files are removed. A legacy library D3D12 rejected is left in place, so the other adapter of a hybrid laptop can still migrate it.
  4. The adapter test never checks that different adapters get different folders. Fix: the test collects every adapter's path and asserts that adapters of different models (vendor, device, software flag) never share one. WARP and the Basic Render Driver may still share. The eprintln! is removed.
  5. Stale doc on use_pipeline_cache. It now describes the dir/adapters/<kind>-<vendor>-<device>-<subsys>-<revision> layout and the root fallback.

Verification (Linux, cross-compiled to x86_64-pc-windows-gnu with Rust 1.98.1 from rust-toolchain.toml, llvm-mingw linker, tests run under Wine 11.22 Staging with D3D12 on a real AMD GPU):

  • cargo clippy -p victory-gpu --lib --tests --locked --target x86_64-pc-windows-gnu -- -D warnings: passed.
  • cargo test -p victory-gpu --lib --locked --target x86_64-pc-windows-gnu pipeline::library::tests -- --test-threads=1: 10 passed, including each_d3d12_device_uses_its_own_dxgi_adapter with real D3D12 devices.
  • Not run on native Windows or with the MSVC target; the legacy-file removal and root fallback in save have no dedicated test.
Patch (applies on top of 4a91296)
diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs
index dc7a7ca..b1ee42e 100644
--- a/crates/victory-gpu/src/pipeline/library.rs
+++ b/crates/victory-gpu/src/pipeline/library.rs
@@ -40,7 +40,10 @@ use windows::core::{HSTRING, Interface, PCWSTR};
 
 static DIR: OnceLock<PathBuf> = OnceLock::new();
 
-/// Keeps the pipeline library and the early list in `dir` from now on.
+/// Keeps the pipeline caches under `dir` from now on: the early list in
+/// `dir`, the library and the pre-build's list in
+/// `dir/adapters/<kind>-<vendor>-<device>-<subsys>-<revision>` (in `dir`
+/// itself when the adapter cannot be told).
 pub fn use_pipeline_cache(dir: PathBuf) {
     let _ = DIR.set(dir);
 }
@@ -61,6 +64,9 @@ struct Library {
     /// key, and whether that list changed since the last save.
     prebuilt: HashSet<String>,
     prebuilt_changed: bool,
+    /// Made from the legacy files in the cache root: removed once the
+    /// library is saved under its adapter.
+    legacy: bool,
 }
 
 // SAFETY: D3D12 objects are free-threaded (a pipeline library with the
@@ -140,10 +146,18 @@ fn adapter_cache_dir(root: &Path, adapter: &DXGI_ADAPTER_DESC1) -> PathBuf {
     ))
 }
 
+/// The adapter's cache folder, if the adapter can be told (a failed lookup
+/// is tried again next time).
 fn cache_dir(root: &Path) -> Option<PathBuf> {
-    static ADAPTER: OnceLock<Option<DXGI_ADAPTER_DESC1>> = OnceLock::new();
-    let adapter = ADAPTER.get_or_init(|| device_adapter(&crate::host::host()?.device));
-    Some(adapter_cache_dir(root, adapter.as_ref()?))
+    static ADAPTER: OnceLock<DXGI_ADAPTER_DESC1> = OnceLock::new();
+    let adapter = match ADAPTER.get() {
+        Some(adapter) => adapter,
+        None => {
+            let found = device_adapter(&crate::host::host()?.device)?;
+            ADAPTER.get_or_init(|| found)
+        }
+    };
+    Some(adapter_cache_dir(root, adapter))
 }
 
 fn read_cache(root: &Path, adapter: Option<&Path>) -> (Vec<u8>, Option<Vec<u8>>) {
@@ -152,7 +166,9 @@ fn read_cache(root: &Path, adapter: Option<&Path>) -> (Vec<u8>, Option<Vec<u8>>)
             .map(|blob| (blob, std::fs::read(dir.join(PREBUILT_FILE)).ok()))
     };
     // A compatible legacy library can be reused when there is no adapter
-    // library yet. The legacy files are never overwritten by the new layout.
+    // library yet; `save` removes the legacy files once it is saved under
+    // the adapter. The root also holds the library when the adapter cannot
+    // be told.
     match adapter.map(read) {
         Some(Ok(cache)) => cache,
         Some(Err(e)) if e.kind() != std::io::ErrorKind::NotFound => Default::default(),
@@ -174,12 +190,22 @@ fn library() -> Option<&'static Mutex<Library>> {
     LIBRARY
         .get_or_init(|| {
             let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?;
-            let (blob, prebuilt) = DIR
-                .get()
-                .map(|d| read_cache(d, cache_dir(d).as_deref()))
+            let root = DIR.get();
+            let adapter = root.map(PathBuf::as_path).and_then(cache_dir);
+            // Read from the legacy root files: no adapter library yet.
+            let legacy = adapter
+                .as_ref()
+                .is_some_and(|a| !a.join(LIBRARY_FILE).exists());
+            let (blob, prebuilt) = root
+                .map(|d| read_cache(d, adapter.as_deref()))
                 .unwrap_or_default();
             let tag = tag(&blob);
             let mut library = open(&device, blob);
+            if let Some(l) = library.as_mut() {
+                // Only a legacy library the host accepted moves to the
+                // adapter: another adapter's stays for that adapter.
+                l.legacy = legacy && !l._blob.is_empty();
+            }
             // The pre-build's list, if it was saved with these bytes.
             if let (Some(l), Some(list)) = (library.as_mut(), prebuilt)
                 && !l._blob.is_empty()
@@ -215,6 +241,7 @@ fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
                     added: 0,
                     prebuilt: HashSet::new(),
                     prebuilt_changed: false,
+                    legacy: false,
                 });
             }
             Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"),
@@ -229,6 +256,7 @@ fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
         added: 0,
         prebuilt: HashSet::new(),
         prebuilt_changed: false,
+        legacy: false,
     })
 }
 
@@ -356,7 +384,7 @@ pub(crate) fn save(now: bool) {
         }
         *last = Some(std::time::Instant::now());
     }
-    let (blob, prebuilt) = {
+    let (blob, prebuilt, legacy) = {
         let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
         if l.added == 0 && !l.prebuilt_changed && !USED_CHANGED.swap(false, Ordering::Relaxed) {
             return;
@@ -373,7 +401,7 @@ pub(crate) fn save(now: bool) {
                 // Kept beside the bytes it holds for (also when a run adds
                 // pipelines).
                 let prebuilt = (!l.prebuilt.is_empty()).then(|| list(&tag(&bytes), &l.prebuilt));
-                (bytes, prebuilt)
+                (bytes, prebuilt, l.legacy)
             }
             Err(e) => {
                 tracing::warn!(error = %e, "host pipeline library not serialised");
@@ -382,17 +410,21 @@ pub(crate) fn save(now: bool) {
         }
     };
     let used = USED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(Used::list).unwrap_or_default();
+    // The cache root when the adapter cannot be told, as before the
+    // adapter folders (the host still refuses another adapter's library).
     let adapter = cache_dir(dir);
     let written = std::fs::create_dir_all(dir)
-        .and_then(|()| {
-            let Some(adapter) = &adapter else { return Ok(()) };
-            write_cache(adapter, &blob, prebuilt.as_deref())
-        })
+        .and_then(|()| write_cache(adapter.as_deref().unwrap_or(dir), &blob, prebuilt.as_deref()))
         .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
+    // The legacy library this one was made from is now under the adapter.
+    if written.is_ok() && legacy && adapter.is_some() {
+        let _ = std::fs::remove_file(dir.join(LIBRARY_FILE));
+        let _ = std::fs::remove_file(dir.join(PREBUILT_FILE));
+        library.lock().unwrap_or_else(|e| e.into_inner()).legacy = false;
+    }
     let (created, distinct) = created();
     let (shaders_cached, shaders_translated) = crate::shader_cache::counts();
     match written {
-        Ok(()) if adapter.is_none() => tracing::warn!("host pipeline library not saved: adapter unavailable"),
         Ok(()) => tracing::info!(
             bytes = blob.len(),
             early = used.len(),
@@ -549,6 +581,7 @@ mod tests {
             let Ok(factory): windows::core::Result<IDXGIFactory4> =
                 CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) else { return };
             let hardware = (0..).map_while(|i| factory.EnumAdapters1(i).ok());
+            let mut seen: Vec<(DXGI_ADAPTER_DESC1, PathBuf)> = Vec::new();
             for adapter in hardware.chain(factory.EnumWarpAdapter::<IDXGIAdapter1>()) {
                 let mut device: Option<ID3D12Device> = None;
                 if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_err() {
@@ -558,8 +591,21 @@ mod tests {
                 let actual = device_adapter(&device.unwrap()).expect("device adapter metadata");
                 assert_eq!(actual.AdapterLuid, expected.AdapterLuid);
                 let path = adapter_cache_dir(Path::new("cache"), &actual);
-                eprintln!("{}: {}", String::from_utf16_lossy(&actual.Description).trim_end_matches('\0'), path.display());
                 assert_eq!(path, adapter_cache_dir(Path::new("cache"), &expected));
+                seen.push((actual, path));
+            }
+            // Different adapters (an integrated and a discrete GPU, WARP)
+            // never share a folder; the same model twice (or WARP and the
+            // Basic Render Driver) may.
+            let model = |d: &DXGI_ADAPTER_DESC1| {
+                (d.VendorId, d.DeviceId, d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32)
+            };
+            for (i, (a, path_a)) in seen.iter().enumerate() {
+                for (b, path_b) in &seen[i + 1..] {
+                    if model(a) != model(b) {
+                        assert_ne!(path_a, path_b, "two adapters share a cache folder");
+                    }
+                }
             }
         }
     }
**@⁠AurumCarlos** on GitHub · 2026-11-25 21:23 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7175015487) · edited 2026-11-25 21:29 UTC ## Review notes: suggested fixes for `library.rs` Five issues from a review of this PR, with a patch on top of `4a91296` below. 1. **Library never saved when the adapter lookup fails.** `cache_dir` caches a failed `device_adapter` result (`None`) in a static `OnceLock`, so it is never retried. `save` then serializes the library and resets `added` but writes nothing; before this PR the library was always saved under the cache root. Fix: cache only a successful lookup, and when the adapter is unknown, save in the cache root as before (D3D12 still refuses another adapter's library on read). 2. **Wasted serialize and a repeated warning when the adapter is unknown.** Every 20 s save serialized the whole library, threw the bytes away and logged the same warning. Fixed by (1): the library is always written somewhere, and the warning branch is removed. 3. **Legacy files never cleaned up.** `<cache>/pipelines/host-pipelines.bin` and `prebuilt-pipelines.txt` stayed on disk forever. Fix: once a library made from the legacy files (and accepted by D3D12) has been saved under its adapter folder, the legacy files are removed. A legacy library D3D12 rejected is left in place, so the other adapter of a hybrid laptop can still migrate it. 4. **The adapter test never checks that different adapters get different folders.** Fix: the test collects every adapter's path and asserts that adapters of different models (vendor, device, software flag) never share one. WARP and the Basic Render Driver may still share. The `eprintln!` is removed. 5. **Stale doc on `use_pipeline_cache`.** It now describes the `dir/adapters/<kind>-<vendor>-<device>-<subsys>-<revision>` layout and the root fallback. **Verification** (Linux, cross-compiled to `x86_64-pc-windows-gnu` with Rust 1.98.1 from `rust-toolchain.toml`, llvm-mingw linker, tests run under Wine 11.22 Staging with D3D12 on a real AMD GPU): - `cargo clippy -p victory-gpu --lib --tests --locked --target x86_64-pc-windows-gnu -- -D warnings`: passed. - `cargo test -p victory-gpu --lib --locked --target x86_64-pc-windows-gnu pipeline::library::tests -- --test-threads=1`: 10 passed, including `each_d3d12_device_uses_its_own_dxgi_adapter` with real D3D12 devices. - Not run on native Windows or with the MSVC target; the legacy-file removal and root fallback in `save` have no dedicated test. <details> <summary>Patch (applies on top of 4a91296)</summary> ```diff diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index dc7a7ca..b1ee42e 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -40,7 +40,10 @@ use windows::core::{HSTRING, Interface, PCWSTR}; static DIR: OnceLock<PathBuf> = OnceLock::new(); -/// Keeps the pipeline library and the early list in `dir` from now on. +/// Keeps the pipeline caches under `dir` from now on: the early list in +/// `dir`, the library and the pre-build's list in +/// `dir/adapters/<kind>-<vendor>-<device>-<subsys>-<revision>` (in `dir` +/// itself when the adapter cannot be told). pub fn use_pipeline_cache(dir: PathBuf) { let _ = DIR.set(dir); } @@ -61,6 +64,9 @@ struct Library { /// key, and whether that list changed since the last save. prebuilt: HashSet<String>, prebuilt_changed: bool, + /// Made from the legacy files in the cache root: removed once the + /// library is saved under its adapter. + legacy: bool, } // SAFETY: D3D12 objects are free-threaded (a pipeline library with the @@ -140,10 +146,18 @@ fn adapter_cache_dir(root: &Path, adapter: &DXGI_ADAPTER_DESC1) -> PathBuf { )) } +/// The adapter's cache folder, if the adapter can be told (a failed lookup +/// is tried again next time). fn cache_dir(root: &Path) -> Option<PathBuf> { - static ADAPTER: OnceLock<Option<DXGI_ADAPTER_DESC1>> = OnceLock::new(); - let adapter = ADAPTER.get_or_init(|| device_adapter(&crate::host::host()?.device)); - Some(adapter_cache_dir(root, adapter.as_ref()?)) + static ADAPTER: OnceLock<DXGI_ADAPTER_DESC1> = OnceLock::new(); + let adapter = match ADAPTER.get() { + Some(adapter) => adapter, + None => { + let found = device_adapter(&crate::host::host()?.device)?; + ADAPTER.get_or_init(|| found) + } + }; + Some(adapter_cache_dir(root, adapter)) } fn read_cache(root: &Path, adapter: Option<&Path>) -> (Vec<u8>, Option<Vec<u8>>) { @@ -152,7 +166,9 @@ fn read_cache(root: &Path, adapter: Option<&Path>) -> (Vec<u8>, Option<Vec<u8>>) .map(|blob| (blob, std::fs::read(dir.join(PREBUILT_FILE)).ok())) }; // A compatible legacy library can be reused when there is no adapter - // library yet. The legacy files are never overwritten by the new layout. + // library yet; `save` removes the legacy files once it is saved under + // the adapter. The root also holds the library when the adapter cannot + // be told. match adapter.map(read) { Some(Ok(cache)) => cache, Some(Err(e)) if e.kind() != std::io::ErrorKind::NotFound => Default::default(), @@ -174,12 +190,22 @@ fn library() -> Option<&'static Mutex<Library>> { LIBRARY .get_or_init(|| { let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?; - let (blob, prebuilt) = DIR - .get() - .map(|d| read_cache(d, cache_dir(d).as_deref())) + let root = DIR.get(); + let adapter = root.map(PathBuf::as_path).and_then(cache_dir); + // Read from the legacy root files: no adapter library yet. + let legacy = adapter + .as_ref() + .is_some_and(|a| !a.join(LIBRARY_FILE).exists()); + let (blob, prebuilt) = root + .map(|d| read_cache(d, adapter.as_deref())) .unwrap_or_default(); let tag = tag(&blob); let mut library = open(&device, blob); + if let Some(l) = library.as_mut() { + // Only a legacy library the host accepted moves to the + // adapter: another adapter's stays for that adapter. + l.legacy = legacy && !l._blob.is_empty(); + } // The pre-build's list, if it was saved with these bytes. if let (Some(l), Some(list)) = (library.as_mut(), prebuilt) && !l._blob.is_empty() @@ -215,6 +241,7 @@ fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> { added: 0, prebuilt: HashSet::new(), prebuilt_changed: false, + legacy: false, }); } Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), @@ -229,6 +256,7 @@ fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> { added: 0, prebuilt: HashSet::new(), prebuilt_changed: false, + legacy: false, }) } @@ -356,7 +384,7 @@ pub(crate) fn save(now: bool) { } *last = Some(std::time::Instant::now()); } - let (blob, prebuilt) = { + let (blob, prebuilt, legacy) = { let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); if l.added == 0 && !l.prebuilt_changed && !USED_CHANGED.swap(false, Ordering::Relaxed) { return; @@ -373,7 +401,7 @@ pub(crate) fn save(now: bool) { // Kept beside the bytes it holds for (also when a run adds // pipelines). let prebuilt = (!l.prebuilt.is_empty()).then(|| list(&tag(&bytes), &l.prebuilt)); - (bytes, prebuilt) + (bytes, prebuilt, l.legacy) } Err(e) => { tracing::warn!(error = %e, "host pipeline library not serialised"); @@ -382,17 +410,21 @@ pub(crate) fn save(now: bool) { } }; let used = USED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(Used::list).unwrap_or_default(); + // The cache root when the adapter cannot be told, as before the + // adapter folders (the host still refuses another adapter's library). let adapter = cache_dir(dir); let written = std::fs::create_dir_all(dir) - .and_then(|()| { - let Some(adapter) = &adapter else { return Ok(()) }; - write_cache(adapter, &blob, prebuilt.as_deref()) - }) + .and_then(|()| write_cache(adapter.as_deref().unwrap_or(dir), &blob, prebuilt.as_deref())) .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); + // The legacy library this one was made from is now under the adapter. + if written.is_ok() && legacy && adapter.is_some() { + let _ = std::fs::remove_file(dir.join(LIBRARY_FILE)); + let _ = std::fs::remove_file(dir.join(PREBUILT_FILE)); + library.lock().unwrap_or_else(|e| e.into_inner()).legacy = false; + } let (created, distinct) = created(); let (shaders_cached, shaders_translated) = crate::shader_cache::counts(); match written { - Ok(()) if adapter.is_none() => tracing::warn!("host pipeline library not saved: adapter unavailable"), Ok(()) => tracing::info!( bytes = blob.len(), early = used.len(), @@ -549,6 +581,7 @@ mod tests { let Ok(factory): windows::core::Result<IDXGIFactory4> = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) else { return }; let hardware = (0..).map_while(|i| factory.EnumAdapters1(i).ok()); + let mut seen: Vec<(DXGI_ADAPTER_DESC1, PathBuf)> = Vec::new(); for adapter in hardware.chain(factory.EnumWarpAdapter::<IDXGIAdapter1>()) { let mut device: Option<ID3D12Device> = None; if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_err() { @@ -558,8 +591,21 @@ mod tests { let actual = device_adapter(&device.unwrap()).expect("device adapter metadata"); assert_eq!(actual.AdapterLuid, expected.AdapterLuid); let path = adapter_cache_dir(Path::new("cache"), &actual); - eprintln!("{}: {}", String::from_utf16_lossy(&actual.Description).trim_end_matches('\0'), path.display()); assert_eq!(path, adapter_cache_dir(Path::new("cache"), &expected)); + seen.push((actual, path)); + } + // Different adapters (an integrated and a discrete GPU, WARP) + // never share a folder; the same model twice (or WARP and the + // Basic Render Driver) may. + let model = |d: &DXGI_ADAPTER_DESC1| { + (d.VendorId, d.DeviceId, d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) + }; + for (i, (a, path_a)) in seen.iter().enumerate() { + for (b, path_b) in &seen[i + 1..] { + if model(a) != model(b) { + assert_ne!(path_a, path_b, "two adapters share a cache folder"); + } + } } } } ``` </details>
Author
Owner

@⁠AurumCarlos on GitHub · 2026-11-25 21:45 UTC · original

Review of 42cefd0 and cb11009

Thanks for the follow-up: the retried adapter lookup, the dirty state kept on write failures, the serialized saves and the same-vendor test (Intel iGPU vs Arc) cover most of the earlier notes. Three remaining points, with a patch on top of cb11009 below. This supersedes the patch in my previous comment, which no longer applies.

  1. Library still never saved when the adapter lookup keeps failing. save returns as soon as cache_dir(dir) is None, so on a setup where CreateDXGIFactory2 or EnumAdapterByLuid always fails, every run starts with an empty library; main persisted it in <cache>/pipelines. The patch falls back to writing the library in the cache root in that case only (with a one-time warning). D3D12 still refuses another adapter's library on read, and older versions keep reading the root as before. If keeping the root strictly read-only is the intent, it may be worth stating in the PR that losing the cache in this case is the accepted cost.
  2. DXGI lookup under the library mutex. cache_dir(dir) was called inside library.lock(), so while the adapter is unknown each save created a DXGI factory and enumerated adapters while pipeline() and note_prebuilt waited. The patch looks it up before taking the lock.
  3. Stale doc on save. It still said the library and the early list are written together when pipelines were added; since 42cefd0 the early list is written on its own. The comment in read_cache ("legacy files are never overwritten") is updated too, to match (1).

Verification (Linux, cross-compiled to x86_64-pc-windows-gnu with Rust 1.98.1 from rust-toolchain.toml, llvm-mingw linker, tests run under Wine 11.22 Staging with D3D12 on a real AMD GPU):

  • cargo clippy -p victory-gpu --lib --tests --locked --target x86_64-pc-windows-gnu -- -D warnings: passed, on cb11009 and with the patch.
  • cargo test -p victory-gpu --lib --locked --target x86_64-pc-windows-gnu pipeline::library::tests -- --test-threads=1 --include-ignored: 11 passed, on cb11009 and with the patch (including warp_device_uses_its_dxgi_adapter and the ignored all-adapters test).
  • Not run on native Windows or with the MSVC target; the root fallback in save has no dedicated test.
Patch (applies on top of cb11009)
diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs
index 73c58fb..f3bd730 100644
--- a/crates/victory-gpu/src/pipeline/library.rs
+++ b/crates/victory-gpu/src/pipeline/library.rs
@@ -160,7 +160,7 @@ fn read_cache(root: &Path, adapter: Option<&Path>) -> (Vec<u8>, Option<Vec<u8>>)
             .map(|blob| (blob, std::fs::read(dir.join(PREBUILT_FILE)).ok()))
     };
     // A compatible legacy library can be reused when there is no adapter
-    // library yet. The legacy files are never overwritten by the new layout.
+    // library yet. The root is written only when the adapter cannot be told.
     match adapter.map(read) {
         Some(Ok(cache)) => cache,
         Some(Err(e)) if e.kind() != std::io::ErrorKind::NotFound => Default::default(),
@@ -351,8 +351,10 @@ thread_local! {
         const { std::cell::Cell::new(None) };
 }
 
-/// Writes the library and the early list if pipelines were added since the
-/// last save and `SAVE_EVERY` has passed (or `now`).
+/// Once `SAVE_EVERY` has passed (or `now`): writes the early list if it
+/// changed, and, on its own, the library and the pre-build's list if
+/// pipelines were added or that list changed (under the adapter's folder,
+/// or in `dir` when the adapter cannot be told).
 pub(crate) fn save(now: bool) {
     static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None);
     const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20);
@@ -384,18 +386,21 @@ pub(crate) fn save(now: bool) {
     }
 
     let Some(library) = library() else { return };
-    let (adapter, blob, prebuilt, added, prebuilt_changed) = {
+    // Looked up outside the library's lock: the lookup is retried while the
+    // adapter cannot be told. The library then goes in the cache root, as
+    // before adapter folders (the host still refuses another adapter's).
+    let adapter = cache_dir(dir).unwrap_or_else(|| {
+        static WARNED: std::sync::Once = std::sync::Once::new();
+        WARNED.call_once(|| {
+            tracing::warn!("adapter unavailable: host pipeline library saved in the cache root")
+        });
+        dir.clone()
+    });
+    let (blob, prebuilt, added, prebuilt_changed) = {
         let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
         if l.added == 0 && !l.prebuilt_changed {
             return;
         }
-        let Some(adapter) = cache_dir(dir) else {
-            static WARNED: std::sync::Once = std::sync::Once::new();
-            WARNED.call_once(|| {
-                tracing::warn!("host pipeline library not saved: adapter unavailable")
-            });
-            return;
-        };
         // SAFETY: a buffer of the size the library asks for.
         let bytes = unsafe {
             let mut bytes = vec![0u8; l.library.GetSerializedSize()];
@@ -408,7 +413,7 @@ pub(crate) fn save(now: bool) {
                 // Kept beside the bytes it holds for (also when a run adds
                 // pipelines).
                 let prebuilt = (!l.prebuilt.is_empty()).then(|| list(&tag(&bytes), &l.prebuilt));
-                (adapter, bytes, prebuilt, added, prebuilt_changed)
+                (bytes, prebuilt, added, prebuilt_changed)
             }
             Err(e) => {
                 tracing::warn!(error = %e, "host pipeline library not serialised");
**@⁠AurumCarlos** on GitHub · 2026-11-25 21:45 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7175502183) ## Review of 42cefd0 and cb11009 Thanks for the follow-up: the retried adapter lookup, the dirty state kept on write failures, the serialized saves and the same-vendor test (Intel iGPU vs Arc) cover most of the earlier notes. Three remaining points, with a patch on top of `cb11009` below. This supersedes the patch in my previous comment, which no longer applies. 1. **Library still never saved when the adapter lookup keeps failing.** `save` returns as soon as `cache_dir(dir)` is `None`, so on a setup where `CreateDXGIFactory2` or `EnumAdapterByLuid` always fails, every run starts with an empty library; main persisted it in `<cache>/pipelines`. The patch falls back to writing the library in the cache root in that case only (with a one-time warning). D3D12 still refuses another adapter's library on read, and older versions keep reading the root as before. If keeping the root strictly read-only is the intent, it may be worth stating in the PR that losing the cache in this case is the accepted cost. 2. **DXGI lookup under the library mutex.** `cache_dir(dir)` was called inside `library.lock()`, so while the adapter is unknown each save created a DXGI factory and enumerated adapters while `pipeline()` and `note_prebuilt` waited. The patch looks it up before taking the lock. 3. **Stale doc on `save`.** It still said the library and the early list are written together when pipelines were added; since 42cefd0 the early list is written on its own. The comment in `read_cache` ("legacy files are never overwritten") is updated too, to match (1). **Verification** (Linux, cross-compiled to `x86_64-pc-windows-gnu` with Rust 1.98.1 from `rust-toolchain.toml`, llvm-mingw linker, tests run under Wine 11.22 Staging with D3D12 on a real AMD GPU): - `cargo clippy -p victory-gpu --lib --tests --locked --target x86_64-pc-windows-gnu -- -D warnings`: passed, on `cb11009` and with the patch. - `cargo test -p victory-gpu --lib --locked --target x86_64-pc-windows-gnu pipeline::library::tests -- --test-threads=1 --include-ignored`: 11 passed, on `cb11009` and with the patch (including `warp_device_uses_its_dxgi_adapter` and the ignored all-adapters test). - Not run on native Windows or with the MSVC target; the root fallback in `save` has no dedicated test. <details> <summary>Patch (applies on top of cb11009)</summary> ```diff diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 73c58fb..f3bd730 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -160,7 +160,7 @@ fn read_cache(root: &Path, adapter: Option<&Path>) -> (Vec<u8>, Option<Vec<u8>>) .map(|blob| (blob, std::fs::read(dir.join(PREBUILT_FILE)).ok())) }; // A compatible legacy library can be reused when there is no adapter - // library yet. The legacy files are never overwritten by the new layout. + // library yet. The root is written only when the adapter cannot be told. match adapter.map(read) { Some(Ok(cache)) => cache, Some(Err(e)) if e.kind() != std::io::ErrorKind::NotFound => Default::default(), @@ -351,8 +351,10 @@ thread_local! { const { std::cell::Cell::new(None) }; } -/// Writes the library and the early list if pipelines were added since the -/// last save and `SAVE_EVERY` has passed (or `now`). +/// Once `SAVE_EVERY` has passed (or `now`): writes the early list if it +/// changed, and, on its own, the library and the pre-build's list if +/// pipelines were added or that list changed (under the adapter's folder, +/// or in `dir` when the adapter cannot be told). pub(crate) fn save(now: bool) { static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); @@ -384,18 +386,21 @@ pub(crate) fn save(now: bool) { } let Some(library) = library() else { return }; - let (adapter, blob, prebuilt, added, prebuilt_changed) = { + // Looked up outside the library's lock: the lookup is retried while the + // adapter cannot be told. The library then goes in the cache root, as + // before adapter folders (the host still refuses another adapter's). + let adapter = cache_dir(dir).unwrap_or_else(|| { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + tracing::warn!("adapter unavailable: host pipeline library saved in the cache root") + }); + dir.clone() + }); + let (blob, prebuilt, added, prebuilt_changed) = { let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); if l.added == 0 && !l.prebuilt_changed { return; } - let Some(adapter) = cache_dir(dir) else { - static WARNED: std::sync::Once = std::sync::Once::new(); - WARNED.call_once(|| { - tracing::warn!("host pipeline library not saved: adapter unavailable") - }); - return; - }; // SAFETY: a buffer of the size the library asks for. let bytes = unsafe { let mut bytes = vec![0u8; l.library.GetSerializedSize()]; @@ -408,7 +413,7 @@ pub(crate) fn save(now: bool) { // Kept beside the bytes it holds for (also when a run adds // pipelines). let prebuilt = (!l.prebuilt.is_empty()).then(|| list(&tag(&bytes), &l.prebuilt)); - (adapter, bytes, prebuilt, added, prebuilt_changed) + (bytes, prebuilt, added, prebuilt_changed) } Err(e) => { tracing::warn!(error = %e, "host pipeline library not serialised"); ``` </details>
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 23:24 UTC · original

Automated triage for the maintainers.

The host pipeline library and its prebuilt list are now kept per adapter, under adapters/<kind>-<vendor>-<device>-<subsys>-<revision>, found with device_adapter / cache_dir in crates/victory-gpu/src/pipeline/library.rs. When there is no adapter cache yet, the legacy root files are read. The early list stays shared. save is now serialised and puts the counts back when a write fails. I checked the legacy fallback in read_cache (only on NotFound) and the retried adapter lookup, and that the all-adapters device test is now #[ignore]d. One point is still open from the review thread. If the adapter lookup always fails, save writes no library at all, where main saved it in the cache root. That seems unlikely on Windows, but the maintainer may want the root fallback. CI (check) passes.

This is a recommendation for a maintainer to look, not an approval.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 23:24 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7177522429) <!-- victory-triage v1 head=d41fa99c1c97de77651677a20fdc3b53d41bdf79 verdict=merge-candidate at=2026-11-25T23:24:35Z --> Automated triage for the maintainers. The host pipeline library and its prebuilt list are now kept per adapter, under `adapters/<kind>-<vendor>-<device>-<subsys>-<revision>`, found with `device_adapter` / `cache_dir` in `crates/victory-gpu/src/pipeline/library.rs`. When there is no adapter cache yet, the legacy root files are read. The early list stays shared. `save` is now serialised and puts the counts back when a write fails. I checked the legacy fallback in `read_cache` (only on `NotFound`) and the retried adapter lookup, and that the all-adapters device test is now `#[ignore]`d. One point is still open from the review thread. If the adapter lookup always fails, `save` writes no library at all, where `main` saved it in the cache root. That seems unlikely on Windows, but the maintainer may want the root fallback. CI (`check`) passes. This is a recommendation for a maintainer to look, not an approval. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠kotekompotek on GitHub · 2026-11-25 21:16 UTC · original · reviewed

Sound design. Keyed by VendorId/DeviceId/SubSysId/Revision (+software kind) — stable across LUID changes, which is correctly noted as not a disk key. Read precedence is right: adapter dir hit wins, NotFound falls back to the legacy root library (migration path), other IO errors do not. The legacy root files are never overwritten, so an older binary keeps working. The real-hardware test enumerating every adapter incl. WARP and checking LUID roundtrip is the right verification. EARLY_FILE staying in root is consistent — its keys are adapter-independent. LGTM.

**@⁠kotekompotek** on GitHub · 2026-11-25 21:16 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#pullrequestreview-6065093911) · **reviewed** Sound design. Keyed by VendorId/DeviceId/SubSysId/Revision (+software kind) — stable across LUID changes, which is correctly noted as not a disk key. Read precedence is right: adapter dir hit wins, NotFound falls back to the legacy root library (migration path), other IO errors do not. The legacy root files are never overwritten, so an older binary keeps working. The real-hardware test enumerating every adapter incl. WARP and checking LUID roundtrip is the right verification. `EARLY_FILE` staying in root is consistent — its keys are adapter-independent. LGTM.
Author
Owner

@⁠Dukestar69 on GitHub · 2026-11-26 02:48 UTC · original · approved these changes

Tested merged onto origin/main (63bcca4) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + WARP):

  • cargo test -p victory-gpu --lib pipeline::library::tests: 13 passed, 0 failed, 1 ignored (including new adapter_caches_keep_their_own_library_and_prebuilt_list and warp_device_uses_its_dxgi_adapter).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

**@⁠Dukestar69** on GitHub · 2026-11-26 02:48 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#pullrequestreview-6067886576) · **approved these changes** Tested merged onto `origin/main` (`63bcca4`) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + WARP): - `cargo test -p victory-gpu --lib pipeline::library::tests`: **13 passed, 0 failed, 1 ignored** (including new `adapter_caches_keep_their_own_library_and_prebuilt_list` and `warp_device_uses_its_dxgi_adapter`). - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-26 13:24 UTC · original · requested changes

The LUID lookup is the right way to find the DXGI adapter for the actual D3D12 device, and the adapters/{kind}-{vendor:04x}-{device:04x}-{subsys:08x}-{revision:02x} key with EARLY_FILE kept at the root and PREBUILT_FILE scoped per adapter makes sense.

Two issues to fix before merging:

  1. Overwrite risk on transient adapter-lookup recovery (crates/victory-gpu/src/pipeline/library.rs:161-184, 196-218, 399-440): cache_dir caches the adapter in its own OnceLock, separate from LIBRARY. If device_adapter fails when library() initializes, LIBRARY starts empty (or reads the legacy root), leaving ADAPTER unset. If a later save() succeeds in resolving ADAPTER, it can overwrite an existing adapters/<id>/host-pipelines.bin (and prebuilt-pipelines.txt) that this process never loaded. Please record the resolved target/load state alongside LIBRARY initialization so a recovered lookup cannot clobber an unloaded adapter cache, and add a regression test for that sequence.
  2. WARP test software check order (library.rs:662): Please check DXGI_ADAPTER_FLAG_SOFTWARE on GetDesc1() before calling D3D12CreateDevice in warp_device_uses_its_dxgi_adapter, matching crates/victory-gpu/src/host.rs:286-304 (since EnumWarpAdapter can return a hardware adapter under Proton/Wine).

Local verification on commit a3f22422c7ba: xtask policy (191 files ok) and cargo clippy -p victory-gpu --all-targets (default and --all-features) pass. With --features diagnostics and VICTORY_D3D12_DEBUG=1, pipeline::library::tests passes (13 passed, 0 failed, 1 ignored) on both RTX 5090 and VICTORY_D3D12_WARP=1, and each_d3d12_device_uses_its_own_dxgi_adapter -- --ignored passes (1 passed), distinguishing RTX 5090 (hardware-10de-2b85-89ec1043-a1), AMD Radeon(TM) Graphics (hardware-1002-13c0-88771043-c1), and WARP (software-1414-008c-00000000-00).

**@⁠fuzeofficlal** on GitHub · 2026-11-26 13:24 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#pullrequestreview-6074901578) · **requested changes** The LUID lookup is the right way to find the DXGI adapter for the actual D3D12 device, and the `adapters/{kind}-{vendor:04x}-{device:04x}-{subsys:08x}-{revision:02x}` key with `EARLY_FILE` kept at the root and `PREBUILT_FILE` scoped per adapter makes sense. Two issues to fix before merging: 1. **Overwrite risk on transient adapter-lookup recovery (`crates/victory-gpu/src/pipeline/library.rs:161-184, 196-218, 399-440`):** `cache_dir` caches the adapter in its own `OnceLock`, separate from `LIBRARY`. If `device_adapter` fails when `library()` initializes, `LIBRARY` starts empty (or reads the legacy root), leaving `ADAPTER` unset. If a later `save()` succeeds in resolving `ADAPTER`, it can overwrite an existing `adapters/<id>/host-pipelines.bin` (and `prebuilt-pipelines.txt`) that this process never loaded. Please record the resolved target/load state alongside `LIBRARY` initialization so a recovered lookup cannot clobber an unloaded adapter cache, and add a regression test for that sequence. 2. **WARP test software check order (`library.rs:662`):** Please check `DXGI_ADAPTER_FLAG_SOFTWARE` on `GetDesc1()` before calling `D3D12CreateDevice` in `warp_device_uses_its_dxgi_adapter`, matching `crates/victory-gpu/src/host.rs:286-304` (since `EnumWarpAdapter` can return a hardware adapter under Proton/Wine). Local verification on commit `a3f22422c7ba`: `xtask policy` (`191 files ok`) and `cargo clippy -p victory-gpu --all-targets` (`default` and `--all-features`) pass. With `--features diagnostics` and `VICTORY_D3D12_DEBUG=1`, `pipeline::library::tests` passes (`13 passed, 0 failed, 1 ignored`) on both RTX 5090 and `VICTORY_D3D12_WARP=1`, and `each_d3d12_device_uses_its_own_dxgi_adapter -- --ignored` passes (`1 passed`), distinguishing RTX 5090 (`hardware-10de-2b85-89ec1043-a1`), AMD Radeon(TM) Graphics (`hardware-1002-13c0-88771043-c1`), and WARP (`software-1414-008c-00000000-00`).
Author
Owner

@⁠yumaste on GitHub · 2026-11-26 13:31 UTC · original

Addressed the two requested changes in 1226f29. The library now holds the cache directory selected at load. If the lookup failed then, it cannot persist its in-memory library for that process, even if DXGI can identify the adapter later. The regression creates both cache files, simulates that sequence, and verifies both stay intact. Forcing the save to use the recovered directory makes the regression fail.

The WARP test checks DXGI_ADAPTER_FLAG_SOFTWARE before creating a device. Local WARP pipeline suite: 29 passed, 1 ignored. Strict Clippy and asset policy passed.

**@⁠yumaste** on GitHub · 2026-11-26 13:31 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7193460588) Addressed the two requested changes in `1226f29`. The library now holds the cache directory selected at load. If the lookup failed then, it cannot persist its in-memory library for that process, even if DXGI can identify the adapter later. The regression creates both cache files, simulates that sequence, and verifies both stay intact. Forcing the save to use the recovered directory makes the regression fail. The WARP test checks `DXGI_ADAPTER_FLAG_SOFTWARE` before creating a device. Local WARP pipeline suite: 29 passed, 1 ignored. Strict Clippy and asset policy passed.
Author
Owner

@⁠AurumCarlos on GitHub · 2026-11-26 14:08 UTC · original · reviewed

Following up on my earlier notes, now for 1226f29. Pinning the cache directory in Shared when the library opens is a clean answer to the "overwrite a cache that was never consulted" concern. It does reverse my first point from yesterday (a failed lookup now means the library is never saved for that process instead of retried), but with a better reason, since a later lookup could write over an adapter cache this process never read. I'm fine with that trade-off.

A small follow-on: cache is also None when DIR isn't set yet at the first library() call (root.and_then(|_| device_adapter(device))). On main, save recomputed the directory from DIR at save time, so a library opened before use_pipeline_cache would still be saved later. Now it won't be, and the warning says "adapter unavailable at load", which would send someone looking in the wrong place. If d3d12x always sets the directory before the first pipeline, that's moot, but either a debug_assert! on that order or a warning that names which of the two was missing would make it clear.

**@⁠AurumCarlos** on GitHub · 2026-11-26 14:08 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#pullrequestreview-6075519104) · **reviewed** Following up on my earlier notes, now for `1226f29`. Pinning the cache directory in `Shared` when the library opens is a clean answer to the "overwrite a cache that was never consulted" concern. It does reverse my first point from yesterday (a failed lookup now means the library is never saved for that process instead of retried), but with a better reason, since a later lookup could write over an adapter cache this process never read. I'm fine with that trade-off. A small follow-on: `cache` is also `None` when `DIR` isn't set yet at the first `library()` call (`root.and_then(|_| device_adapter(device))`). On `main`, `save` recomputed the directory from `DIR` at save time, so a library opened before `use_pipeline_cache` would still be saved later. Now it won't be, and the warning says "adapter unavailable at load", which would send someone looking in the wrong place. If `d3d12x` always sets the directory before the first pipeline, that's moot, but either a `debug_assert!` on that order or a warning that names which of the two was missing would make it clear.
Author
Owner

@⁠fuzeofficlal on GitHub · 2026-11-26 14:15 UTC · original · approved these changes

Both items from the previous review are cleanly resolved:

  • Shared.cache (pipeline/library.rs:80, 190-243) locks in the adapter directory chosen at open time, save_library (:413-422) only writes to that fixed destination, and a_later_adapter_lookup_cannot_replace_an_unloaded_cache directly verifies that recovering DXGI adapter lookup later cannot overwrite an unloaded cache.
  • warp_device() (:672-699) now checks DXGI_ADAPTER_FLAG_SOFTWARE before calling D3D12CreateDevice.

Two minor non-blocking notes:

  • If an existing adapter cache file fails to read with an error other than NotFound (e.g., a transient sharing violation), read_cache opens an empty blob while open_cache retains Some(cache), so a later save could overwrite the unread file; worth keeping in mind if combined with #2129.
  • The new line at pipeline/library.rs:204 (root.zip(adapter).map(...)) exceeds rustfmt's 100-column wrap.

Local verification at 1226f292 (clean merge onto origin/main 63bcca43): xtask policy (191 files ok), cargo clippy -p victory-gpu -p victory --all-targets (default and --all-features, 0 warnings), cargo test -p victory (18/18), and pipeline::library tests under VICTORY_D3D12_DEBUG=1 passed on RTX 5090 (14/14, 1 ignored), WARP (14/14, 1 ignored), and all enumerated adapters via each_d3d12_device_uses_its_own_dxgi_adapter (RTX 5090, AMD Radeon Graphics, and Microsoft Basic Render Driver). Approving.

**@⁠fuzeofficlal** on GitHub · 2026-11-26 14:15 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#pullrequestreview-6075628976) · **approved these changes** Both items from the previous review are cleanly resolved: - `Shared.cache` (`pipeline/library.rs:80, 190-243`) locks in the adapter directory chosen at open time, `save_library` (`:413-422`) only writes to that fixed destination, and `a_later_adapter_lookup_cannot_replace_an_unloaded_cache` directly verifies that recovering DXGI adapter lookup later cannot overwrite an unloaded cache. - `warp_device()` (`:672-699`) now checks `DXGI_ADAPTER_FLAG_SOFTWARE` before calling `D3D12CreateDevice`. Two minor non-blocking notes: - If an existing adapter cache file fails to read with an error other than `NotFound` (e.g., a transient sharing violation), `read_cache` opens an empty blob while `open_cache` retains `Some(cache)`, so a later save could overwrite the unread file; worth keeping in mind if combined with #2129. - The new line at `pipeline/library.rs:204` (`root.zip(adapter).map(...)`) exceeds `rustfmt`'s 100-column wrap. Local verification at `1226f292` (clean merge onto `origin/main` `63bcca43`): `xtask policy` (`191 files ok`), `cargo clippy -p victory-gpu -p victory --all-targets` (`default` and `--all-features`, 0 warnings), `cargo test -p victory` (`18/18`), and `pipeline::library` tests under `VICTORY_D3D12_DEBUG=1` passed on RTX 5090 (`14/14`, 1 ignored), WARP (`14/14`, 1 ignored), and all enumerated adapters via `each_d3d12_device_uses_its_own_dxgi_adapter` (RTX 5090, AMD Radeon Graphics, and Microsoft Basic Render Driver). Approving.
Author
Owner

@⁠yumaste on GitHub · 2026-11-26 14:22 UTC · original

3a3295a now records the reason when no adapter directory was consulted. A later save reports either cache directory not configured at load or adapter unavailable at load. The normal app run and prebuild paths configure the directory before starting pipeline work. The regression also checks both reasons. The WARP pipeline suite passed (29 passed, 1 ignored), along with all-targets/all-features Clippy.

**@⁠yumaste** on GitHub · 2026-11-26 14:22 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7194736274) `3a3295a` now records the reason when no adapter directory was consulted. A later save reports either `cache directory not configured at load` or `adapter unavailable at load`. The normal app run and prebuild paths configure the directory before starting pipeline work. The regression also checks both reasons. The WARP pipeline suite passed (29 passed, 1 ignored), along with all-targets/all-features Clippy.
Author
Owner

@⁠yumaste on GitHub · 2026-11-26 14:28 UTC · original

Thanks for flagging the read-error case. 19a1ddd keeps the library in memory for the run when Windows reports a scoped library read error other than NotFound. The regression opens an existing cache file with sharing disabled, loads while it is locked, unlocks it, then checks that a dirty in-memory library cannot overwrite either existing cache file. I also wrapped the cache path lookup. Under WARP, 30 pipeline tests passed and one was ignored. Both strict Clippy profiles passed.

**@⁠yumaste** on GitHub · 2026-11-26 14:28 UTC · [original](https://github.com/Marvisak/VIctory/pull/2803#issuecomment-7194871041) Thanks for flagging the read-error case. `19a1ddd` keeps the library in memory for the run when Windows reports a scoped library read error other than `NotFound`. The regression opens an existing cache file with sharing disabled, loads while it is locked, unlocks it, then checks that a dirty in-memory library cannot overwrite either existing cache file. I also wrapped the cache path lookup. Under WARP, 30 pipeline tests passed and one was ignored. Both strict Clippy profiles passed.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2803/head:github-bot/gh-2803'
git switch 'github-bot/gh-2803'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2803'
git switch 'github-bot/gh-2803'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2803'
git switch 'github-bot/gh-2803'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2803'
git switch 'main'
git merge --squash 'github-bot/gh-2803'
git switch 'main'
git merge --ff-only 'github-bot/gh-2803'
git switch 'main'
git merge 'github-bot/gh-2803'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!2803
No description provided.