Skip to content

D3D12.X: preserve rect-list GS when a cached graphics PSO blob is stale - #2044

Merged
raylitebull merged 1 commit into
xcl-dev:mainfrom
RandomGithub12309:d3d12x/preserve-rect-gs-on-stale-pso-blob
Nov 25, 2026
Merged

raylitebull merged 1 commit into
xcl-dev:mainfrom
RandomGithub12309:d3d12x/preserve-rect-gs-on-stale-pso-blob

Conversation

@RandomGithub12309

Copy link
Copy Markdown
Contributor

Part of #1269. Fix two caching/retry bugs in translated_graphics_pso_once (crates/xcl/src/hle/d3d12x/real.rs) introduced with graphics PSO blob caching in #1836:

  1. Stale cached blob stripped rect_gs before retrying uncached: retry_without_rect_gs ran inside the first driver_compile_identified call while copy.CachedPSO was still attached. When a cached blob was stale or rejected, retry_without_rect_gs cleared copy.GS immediately and retried with the stale CachedPSO still set; the subsequent uncached retry then compiled without rect_gs even when the driver accepted rect_gs, and note_rect_list_gs skipped registering the PSO.
  2. Genuine rect_gs fallback poisoned the with-GS blob cache: when the driver rejected rect_gs and retry_without_rect_gs succeeded with copy.GS cleared, the no-GS driver blob was still cached in memory and on disk under gkey (which hashed rect_gs = Some(...)), causing future lookups to feed a no-GS blob into a with-GS pipeline description.

What is in it

  • crates/xcl/src/hle/d3d12x/real.rs:
    • Extract create_graphics_pso_cached + GraphicsPsoBuild and call it from translated_graphics_pso_once:
      • When a cached blob is present, try create(copy) directly without stripping rect_gs; only on failure evict the stale blob, clear copy.CachedPSO, and fall back to retry_without_rect_gs with copy.GS intact.
      • Mark cache_eligible false when rect_gs was dropped during fallback (rect_gs && copy.GS.pShaderBytecode.is_null()), so the with-GS gkey / disk entry is never overwritten with a no-GS blob.
    • Add three unit tests in graphics_blob_tests:
      • stale_cached_graphics_blob_preserves_rect_list_gs_on_retry
      • rect_list_gs_fallback_does_not_cache_under_with_gs_key
      • valid_cached_graphics_blob_reuses_without_retry

Tested

  • Hardware: NVIDIA GeForce RTX 5050 Laptop GPU, Intel Core Ultra 7 255HX, Windows 11 Build 26300, rustc 1.100.0 (0ef1bc386 2026-11-09) stable-x86_64-pc-windows-msvc, Windows SDK DXC 1.8.2502.11 (debug for workspace build/tests, release for smoke.ps1).
  • cargo build --workspace: ok.
  • cargo test -p xcl --lib hle::d3d12x::real::graphics_blob_tests -- --test-threads=1 at 27b54e1: 5 passed, 0 failed, 0 ignored (0 skipped).
  • cargo test --workspace -- --test-threads=4 --skip fuzz_validate_and_gpu at 27b54e1: 1110 passed, 0 failed, 46 ignored across all workspace targets (xcl lib: 1061 passed, 0 failed, 26 ignored; integration + e2e targets: 49 passed, 0 failed, 20 ignored, including e2e: 3/0/0).
    • SKIPPED on this adapter (wave32-only, Developer Mode off, XCL_HEAP_WINDOWS unset): wave64-only GPU tests, per-lane wave32 f16/f32 conversion refusals, shaders::tests::pso_measurement_compiles_an_exact_synthetic_record, and heap_window_out_of_memory_falls_back_to_the_switch_form.
    • Excluded gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_{0..3} due to the pre-existing RTX 50 0x8007000E CreateComputePipelineState failure tracked by DXIL GPU fuzz tests reproducibly fail with E_OUTOFMEMORY on RTX 5060 #1905.
  • Game checked: 60 s scripts/smoke.ps1 release build at 27b54e1 vs main (3da2abb).

Regression run

xcl-smoke v1
commit: 3da2abb81606df622610e009f0430de99aa9881c
gpu: NVIDIA GeForce RTX 5050 Laptop GPU
title: e61570a3
seconds: 60
exit: 0x0
frames shown: 1610 (PresentX 1610)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14471 MB
xcl-smoke v1
commit: 27b54e172db07fb76233ef8408127a293b092912
gpu: NVIDIA GeForce RTX 5050 Laptop GPU
title: e61570a3
seconds: 60
exit: 0x0
frames shown: 1583 (PresentX 1583)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 14561 MB

Not tested

  • Real driver-triggered stale-blob rejection on a rect-list pipeline (exercised via unit tests), AMD / Intel / native wave64 GPUs, Wine / Linux, and gameplay beyond the 60 s smoke window.

AI use

  • Antigravity (Gemini 4 Neon) wrote the fix, regression unit tests, and PR description; all builds, workspace tests, and scripts/smoke.ps1 regression runs were executed on the hardware listed above.

Do not invoke retry_without_rect_gs while copy.CachedPSO is still attached: previously a stale cached graphics blob caused retry_without_rect_gs to wipe copy.GS before clearing CachedPSO, so the uncached retry dropped the rect-list GS even when the driver accepted it. Also skip caching the resulting blob under the with-GS key when a genuine rect-list GS fallback clears copy.GS.

Part of xcl-dev#1269

Assisted-by: Antigravity (Gemini 4 Neon)
@RandomGithub12309
RandomGithub12309 marked this pull request as ready for review November 25, 2026 01:53
@raylitebull

Copy link
Copy Markdown
Member

Code review on 27b54e1:

  • Extracting create_graphics_pso_cached cleanly separates cached-blob eviction (on_stale_cache + clearing copy.CachedPSO) from retry_without_rect_gs, ensuring a stale CachedPSO does not strip copy.GS on retry and that a no-GS fallback PSO is never cached under the with-GS key (cache_eligible = retried >= 0 && !dropped_rect_gs).
  • All three unit tests (stale_cached_graphics_blob_preserves_rect_list_gs_on_retry, rect_list_gs_fallback_does_not_cache_under_with_gs_key, valid_cached_graphics_blob_reuses_without_retry) cleanly pin every branch.
  • PR description is green; awaiting Build and test + AMD & NVIDIA verification on 27b54e1.

@WebIdentity1

WebIdentity1 commented Nov 25, 2026 •

Copy link
Copy Markdown

Independent RTX 3090 and AMD iGPU driver/pixel verification of exact 27b54e172db07fb76233ef8408127a293b092912. The stale-cache retry keeps the rectangle GS and renders all 256 pixels; a local replay of the previous retry order drops it and renders only 120.

Tested

Windows 10 Home 19045, Ryzen 7 7800X3D, Rust/Cargo 1.98.1 x64 MSVC, DXC/DXIL 1.8.2502.11, debug. GPUs selected explicitly by XCL_ADAPTER and printed from the device's adapter: RTX 3090 driver591.74 (32.0.15.9174), AMD Radeon(TM) Graphics iGPU 32.0.21030.2001.

The local 99-line test-only overlay below calls the unchanged create_graphics_pso_cached with real ID3D12Device::CreateGraphicsPipelineState, then draws using that returned PSO via runner::draw_on. The VS/PS are synthetic; GS comes from the project's actual emit::rect_list_gs. Three corners must fill a 16×16 target with the exact expected color in every pixel.

Identical results on both GPUs:

Case Actual driver calls (cached blob present, GS present, HRESULT) Result
Fresh (false,true,S_OK) 256/256 correct pixels; cache eligible
Malformed synthetic blob (true,true,E_INVALIDARG), (false,true,S_OK) 256/256 correct pixels; eviction callback once; cache eligible
Valid blob from fresh PSO's GetCachedBlob (true,true,S_OK) 256/256 correct pixels; reused=true; no eviction callback
Previous retry-order replay (true,true,E_INVALIDARG), (true,false,E_INVALIDARG), (false,false,S_OK) GS dropped; only120/256 pixels drawn

E_INVALIDARG is 0x80070057. The 32-byte malformed blob is deliberately synthetic, not a driver-version-mismatched retail cache. The last row copies the previous two-stage retry ordering into the local test; it is not a run of a parent checkout. Each GPU performed four draws. The fixed path also avoids the old order's extra failed creation request; no timing claim.

Commands:

  • XCL_ADAPTER=3090: cargo test --locked -p xcl --lib -- hle::d3d12x::real::graphics_blob_tests --test-threads=1 --show-output — 6 passed / 0 failed / 0 ignored / 0 skipped, including the existing five unit tests and new GPU probe.
  • XCL_ADAPTER=AMD: cargo test --locked -p xcl --lib -- gpu_stale_rect_blob_preserves_full_rectangle --test-threads=1 --show-output — 1 / 0 / 0 / 0.

All 317 source hashes matched before/after and the local worktree; XCL recompiled. Runtime source is unchanged; no competing implementation.

Not tested

Full workspace, retail smoke/gameplay, actual disk eviction/write wiring, the outer translated-console-PSO path and rectangle-PSO registration, genuine hardware rejection of a valid rectangle GS, debug-layer validation, or compile time/memory. The helper's scheduling/timing wrapper is a trivial test callback and eviction is counted, not performed against disk. The no-GS cache-eligibility fallback remains covered by the author's mock unit test, not a deliberately invalid GS on hardware. Existing full-suite/retail gates remain separate. The local diagnostic requires its GPU; it is not proposed unchanged for GPU-less CI.

AI use — Codex (GPT-6) inspected the source, wrote this test-only driver/pixel probe using existing project helpers, ran both GPUs, verified traces/pixels/source hashes, and drafted this report. The runtime fix remains the PR author's work.

Local reproduction patch, 99 test-only lines
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index 07bbaa1..1f7a374 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -4364,6 +4364,105 @@ unsafe fn graphics_blob_key(
 mod graphics_blob_tests {
     use super::*;
 
+    #[test]
+    fn gpu_stale_rect_blob_preserves_full_rectangle() {
+        use crate::gpu::recomp::{dxc, emit, pso, runner};
+        use windows::Win32::Graphics::Dxgi::Common::*;
+        unsafe {
+            // Local diagnostic: require the selected real adapter rather than silently skip.
+            let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+            let selector = crate::gpu::adapter::Selector::from_env_or("auto");
+            let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next().unwrap();
+            println!("RECT_CACHE adapter={}", crate::gpu::adapter::name(&desc));
+            let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+            let rs = pso::abi_root_signature(&dev, true).unwrap();
+            let vs = dxc::compile("float4 main(float4 p : POSITION) : SV_Position { return p; }", "main", "vs_6_6", &[]).unwrap();
+            let ps = dxc::compile("float4 main() : SV_Target { return float4(1, 0.25, 0.5, 1); }", "main", "ps_6_6", &[]).unwrap();
+            let outputs = [crate::gpu::dxbc::SigElement {
+                name: "SV_Position".into(), index: 0, system_value: 1, component_type: 3,
+                register: 0, mask: 15, rw_mask: 15, stream: 0,
+            }];
+            let gs = dxc::compile(&emit::rect_list_gs(&outputs), "main", "gs_6_6", &[]).unwrap();
+            let input = [D3D12_INPUT_ELEMENT_DESC {
+                SemanticName: PCSTR(b"POSITION\0".as_ptr()), Format: DXGI_FORMAT_R32G32B32A32_FLOAT,
+                InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, ..Default::default()
+            }];
+            let make_desc = || {
+                let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
+                    pRootSignature: std::mem::transmute_copy(&rs), VS: bytecode(&vs), PS: bytecode(&ps), GS: bytecode(&gs),
+                    SampleMask: u32::MAX,
+                    InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: input.as_ptr(), NumElements: 1 },
+                    PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1,
+                    SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default()
+                };
+                d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8;
+                d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
+                d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
+                d.RasterizerState.DepthClipEnable = true.into();
+                d.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
+                d
+            };
+            let vertices = [-1.0f32, 1.0, 0.0, 1.0, -1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 0.0, 1.0];
+            let clear = [0.0f32; 4];
+            let draw = |pipeline: &ID3D12PipelineState| runner::draw_on(&dev, pipeline, &rs, &vertices, 16, &[], &[], 16, clear).unwrap();
+            let stale = [0xABu8; 32];
+            let mut cached = Vec::new();
+            for label in ["fresh", "stale", "valid"] {
+                let blob = match label { "fresh" => None, "stale" => Some(stale.as_slice()), _ => Some(cached.as_slice()) };
+                let mut d = make_desc();
+                let mut pipeline = None;
+                let mut attempts = Vec::new();
+                let mut evictions = 0;
+                let build = create_graphics_pso_cached(&mut d, blob, true, || evictions += 1,
+                    |_, _, f| (f(), std::time::Duration::ZERO),
+                    |c| {
+                        let hr = match dev.CreateGraphicsPipelineState::<ID3D12PipelineState>(c) {
+                            Ok(p) => { pipeline = Some(p); 0 }, Err(e) => e.code().0,
+                        };
+                        attempts.push((!c.CachedPSO.pCachedBlob.is_null(), !c.GS.pShaderBytecode.is_null(), hr));
+                        hr
+                    });
+                println!("RECT_CACHE {label} attempts={attempts:?} evictions={evictions} reused={} eligible={}", build.reused, build.cache_eligible);
+                assert!(build.hr >= 0);
+                assert!(!d.GS.pShaderBytecode.is_null());
+                assert_eq!(evictions, usize::from(label == "stale"));
+                assert_eq!(build.reused, label == "valid");
+                assert_eq!(build.cache_eligible, label != "valid");
+                assert_eq!(attempts.len(), if label == "stale" { 2 } else { 1 });
+                if label == "stale" { assert!(attempts[0].2 < 0); assert_eq!(attempts[1], (false, true, 0)); }
+                let pipeline = pipeline.unwrap();
+                let pixels = draw(&pipeline);
+                assert!(pixels.iter().all(|p| *p == [1.0, 0.25, 0.5, 1.0]), "{label}: incomplete rectangle");
+                println!("RECT_CACHE {label} correct_pixels={}", pixels.len());
+                if label == "fresh" {
+                    let b = pipeline.GetCachedBlob().unwrap();
+                    cached = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec();
+                    assert!(!cached.is_empty());
+                }
+            }
+            // Replay the old retry ordering; this is a local negative control, not a parent checkout.
+            let mut old = make_desc();
+            old.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: stale.as_ptr() as _, CachedBlobSizeInBytes: stale.len() };
+            let mut old_pipeline = None;
+            let mut calls = Vec::new();
+            let mut create = |c: &D3D12_GRAPHICS_PIPELINE_STATE_DESC| {
+                let hr = match dev.CreateGraphicsPipelineState::<ID3D12PipelineState>(c) {
+                    Ok(p) => { old_pipeline = Some(p); 0 }, Err(e) => e.code().0,
+                };
+                calls.push((!c.CachedPSO.pCachedBlob.is_null(), !c.GS.pShaderBytecode.is_null(), hr));
+                hr
+            };
+            assert!(retry_without_rect_gs(&mut old, true, &mut create) < 0);
+            old.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
+            assert!(retry_without_rect_gs(&mut old, true, &mut create) >= 0);
+            assert!(old.GS.pShaderBytecode.is_null());
+            let drawn = draw(&old_pipeline.unwrap()).iter().filter(|p| **p != clear).count();
+            println!("RECT_CACHE old_order attempts={calls:?} drawn_pixels={drawn}/256");
+            assert!(drawn > 256 / 3 && drawn < 256 * 2 / 3);
+        }
+    }
+
+
     #[test]
     fn graphics_blob_key_tracks_shaders_samplers_and_state() {
         unsafe {

@raylitebull
raylitebull merged commit 092d49a into xcl-dev:main Nov 25, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants