GPU: the host pipeline library never loads a mesh pipeline (D3D12 refuses the description it stored), so 723 are recompiled every run; repro without the title, fix on a fork #1683

Open
opened 2026-11-26 04:41:27 +00:00 by github-bot · 4 comments
Owner

@⁠Pablo-Barros on GitHub · 2026-11-24 20:43 UTC · original

What happens. ID3D12PipelineLibrary1::LoadPipeline refuses every mesh pipeline with E_INVALIDARG. With the D3D12 debug layer on it is message 972, "The pipeline state desc provided does not match the one used to create the PSO stored with name …". It does so with the description that created the PSO, passed right after StorePipeline succeeded. Graphics and compute pipelines load back. So the library has never served a mesh pipeline: each is compiled in every run, stored again (refused, message 970 "already exists"), and its entry stays in a library that only grows.

In the game. RTX 3070, Windows 11 build 26300, system D3D12 runtime 10.0.26100.10068, main at ffe310e, debug layer on. A run over the library the previous run wrote (early start of 1,800 pipelines):

kind loaded compiled again 970 "already exists" 972 "does not match"
graphics 551 0 0 0
compute 506 0 (105 were new) 0 0
mesh 0 723 723 723

The 1,000 graphics and compute pipelines load in about 7 s; the 723 mesh pipelines are compiled over the next 55 s as the title creates them. An unmodified main logs them too (567 of 970 and 568 of 972 by the end of the early start). host-pipelines.bin is 231 MB here.

Without the title. The program below: trivial mesh (ms_6_5) and pixel shaders compiled with dxc, an empty root signature, a stream of root signature, MS, PS, render target formats, depth format and sample description. CreatePipelineState, StorePipeline("m"), then LoadPipeline("m", <the same stream>): refused, before and after Serialize, in the same process. The graphics (VS + PS) and compute pipelines in the same program load. Output on the RTX 3070:

store:
  graphics: Ok(())
  compute:  Ok(())
  mesh:     Ok(())
load, same library, the descriptions that created them:
  graphics: loaded
  compute: loaded
  mesh: REFUSED El parámetro no es correcto. (0x80070057)
      D3D12: id=972 ID3D12PipelineLibrary::Load*Pipeline: The pipeline state desc provided does not match the one used to create the PSO stored with name "m".
after Serialize, from a library made of the blob:
  graphics: loaded
  compute: loaded
  mesh: REFUSED (0x80070057)

The same on:

  • the system runtime on WARP (Microsoft Basic Render Driver), so it is not the NVIDIA driver;
  • the Agility SDK runtime 1.618.1 (ID3D12SDKConfiguration1::CreateDeviceFactory, D3D12Core.dll 1.618.1 loaded, checked) on the RTX 3070.

Also tried with a longer program, all refused: an explicit empty AS subobject; no PS; the ten subobjects VIctory hands over (blend, sample mask, rasterizer, depth-stencil, RT formats, DSV format, sample desc).

Found on the way: padding. The library compares descriptions byte for byte, and two of ours carried bytes that are not fields. The depth-stencil description is copied from the title's stream as it stands, and the two bytes between StencilWriteMask and FrontFace hold the title's stack: in one run 192 mesh pipelines differed from a copy of themselves only there, under one name. A mesh pipeline's stream has four unwritten bytes between the type and each eight-byte subobject. This is masked today by the problem above (mesh pipelines do not load either way), but it would bite as soon as they do.

A fix on my fork (pull requests are collaborators-only, so a branch): https://github.com/Pablo-Barros/VIctory/tree/gpu/pipeline-library, two commits on ffe310e. CI's two clippy commands and the workspace tests pass.

  1. 0707260 zeroes that padding where the descriptions are read and built, and in the stream before it is handed over. Two tests: descriptions read from 0xff bytes keep their fields and lose their padding; a stream with set values likewise.
  2. cae3f32 The first pipeline of a kind that is stored is loaded back at once. Refused, the library gets no more of that kind in the run, and says so once:
    WARN host pipeline library refuses a mesh pipeline it just stored: mesh pipelines are compiled every run, none kept
    Same cold run as above: 1 of message 970, 2 of 972, and the 1,051 graphics and compute pipelines still load.

What this does not solve. The mesh pipelines are still compiled in every run. That needs a runtime that loads them, or another cache. Old libraries keep their dead mesh entries (ID3D12PipelineLibrary cannot remove one); deleting host-pipelines.bin once reclaims the space.

I cannot tell whether it is the same with the AMD driver. On a second run, host pipeline library saved … made=… loaded=… tells: with 1,800 pipelines started early, loaded should be well over 1,000 if mesh pipelines load.

Written with Claude (Anthropic); the runs, the measurements and the program below are from this machine.

The program (Rust, windows 0.62.2) and the four shaders
//! Does D3D12's pipeline library load a mesh pipeline it just stored?
//! Controls: a graphics pipeline and a compute one, treated the same.
//!
//! `DEBUG=1`: the D3D12 debug layer, its messages printed after each step.
//! `WARP=1`: the Microsoft Basic Render Driver instead of the default adapter.
//! The argument is the folder holding mesh.dxil, pixel.dxil, vs.dxil, cs.dxil,
//! made with dxc from the four one-line shaders below the program.
use std::ffi::c_void;
use windows::core::{HSTRING, Interface, PCWSTR};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::CreateDXGIFactory1;

/// A stream subobject: its type, then its description, pointer-aligned.
#[repr(C, align(8))]
struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T);

#[repr(C)]
struct Mesh {
    root: Sub<*mut c_void>,
    ms: Sub<D3D12_SHADER_BYTECODE>,
    ps: Sub<D3D12_SHADER_BYTECODE>,
    targets: Sub<D3D12_RT_FORMAT_ARRAY>,
    dsv: Sub<DXGI_FORMAT>,
    samples: Sub<DXGI_SAMPLE_DESC>,
}

fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
    D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }
}

fn make_root(device: &ID3D12Device, flags: D3D12_ROOT_SIGNATURE_FLAGS) -> ID3D12RootSignature {
    let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
        Version: D3D_ROOT_SIGNATURE_VERSION_1_1,
        Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 {
            Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 {
                NumParameters: 0,
                pParameters: std::ptr::null(),
                NumStaticSamplers: 0,
                pStaticSamplers: std::ptr::null(),
                Flags: flags,
            },
        },
    };
    // SAFETY: a description of live data; the blob is read before it is released.
    unsafe {
        let mut blob = None;
        let mut err = None;
        D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut err)).unwrap();
        let blob = blob.unwrap();
        let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
        device.CreateRootSignature(0, bytes).unwrap()
    }
}

fn drain(device: &ID3D12Device) {
    let Ok(queue) = device.cast::<ID3D12InfoQueue>() else { return };
    for i in 0..unsafe { queue.GetNumStoredMessages() } {
        let mut size = 0;
        if unsafe { queue.GetMessage(i, None, &mut size) }.is_err() || size == 0 {
            continue;
        }
        let mut buffer = vec![0u64; size.div_ceil(8)];
        let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
        // SAFETY: a buffer of the size the queue asked for.
        if unsafe { queue.GetMessage(i, Some(message), &mut size) }.is_ok() {
            let m = unsafe { &*message };
            let text = unsafe { std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength) };
            println!("      D3D12: id={} {}", m.ID.0, String::from_utf8_lossy(text).trim_end_matches('\0'));
        }
    }
    unsafe { queue.ClearStoredMessages() };
}

fn report(what: &str, r: windows::core::Result<ID3D12PipelineState>) {
    match r {
        Ok(_) => println!("  {what}: loaded"),
        Err(e) => println!("  {what}: REFUSED {e}"),
    }
}

fn main() {
    if std::env::var_os("DEBUG").is_some() {
        let mut layer: Option<ID3D12Debug> = None;
        unsafe { D3D12GetDebugInterface(&mut layer) }.unwrap();
        layer.iter().for_each(|l| unsafe { l.EnableDebugLayer() });
    }
    let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into());
    let read = |n: &str| std::fs::read(format!("{dir}/{n}")).unwrap_or_else(|e| panic!("{n}: {e}"));
    let (ms, ps, vs, cs) = (read("mesh.dxil"), read("pixel.dxil"), read("vs.dxil"), read("cs.dxil"));
    let (ms, ps, vs, cs) = (code(&ms), code(&ps), code(&vs), code(&cs));

    let mut device: Option<ID3D12Device> = None;
    if std::env::var_os("WARP").is_some() {
        let factory: windows::Win32::Graphics::Dxgi::IDXGIFactory4 = unsafe { CreateDXGIFactory1() }.unwrap();
        let mut chosen = None;
        for i in 0.. {
            let adapter: windows::core::Result<windows::Win32::Graphics::Dxgi::IDXGIAdapter1> =
                unsafe { factory.EnumAdapters1(i) };
            let adapter = match adapter {
                Ok(a) => a,
                Err(_) => break,
            };
            let desc = unsafe { adapter.GetDesc1() }.unwrap();
            if (desc.Flags & windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) != 0 {
                chosen = Some(adapter);
                break;
            }
        }
        let adapter = chosen.expect("no WARP adapter");
        unsafe { D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) }.unwrap();
    } else {
        unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device) }.unwrap();
    }
    let device = device.unwrap();
    let mesh_device: ID3D12Device7 = device.cast().unwrap();

    let root = make_root(&device, D3D12_ROOT_SIGNATURE_FLAG_NONE);
    let root_graphics = make_root(&device, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);

    // SAFETY: the descriptions point at live data.
    unsafe {
        let mut formats = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, RTFormats: [DXGI_FORMAT_UNKNOWN; 8] };
        formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
        let g = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
            pRootSignature: std::mem::transmute_copy(&root_graphics),
            VS: vs,
            PS: ps,
            BlendState: Default::default(),
            SampleMask: u32::MAX,
            RasterizerState: D3D12_RASTERIZER_DESC {
                FillMode: D3D12_FILL_MODE_SOLID,
                CullMode: D3D12_CULL_MODE_NONE,
                DepthClipEnable: true.into(),
                ..Default::default()
            },
            PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
            NumRenderTargets: 1,
            RTVFormats: formats.RTFormats,
            DSVFormat: DXGI_FORMAT_UNKNOWN,
            SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
            ..Default::default()
        };
        let c = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: cs, ..Default::default() };
        // Zeroed first: the padding between a type and eight-byte data is ours to set.
        let mut s: Mesh = std::mem::zeroed();
        s.root.0 = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE;
        s.root.1 = root.as_raw();
        s.ms = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms);
        s.ps = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps);
        s.targets = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats);
        s.dsv = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_UNKNOWN);
        s.samples = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 });
        let m = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::<Mesh>(), pPipelineStateSubobjectStream: (&raw const s).cast_mut().cast() };

        let gso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&g).unwrap();
        let cso: ID3D12PipelineState = device.CreateComputePipelineState(&c).unwrap();
        let mso: ID3D12PipelineState = mesh_device.CreatePipelineState(&m).unwrap();

        let library: ID3D12PipelineLibrary1 = {
            let made: windows::core::Result<ID3D12PipelineLibrary> = mesh_device.CreatePipelineLibrary(&[]);
            made.unwrap().cast().unwrap()
        };
        let n = |s: &str| PCWSTR(HSTRING::from(s).as_ptr());
        println!("store:");
        println!("  graphics: {:?}", library.StorePipeline(n("g"), &gso));
        println!("  compute:  {:?}", library.StorePipeline(n("c"), &cso));
        println!("  mesh:     {:?}", library.StorePipeline(n("m"), &mso));
        println!("load, same library, the descriptions that created them:");
        report("graphics", library.LoadGraphicsPipeline(n("g"), &g));
        report("compute", library.LoadComputePipeline(n("c"), &c));
        report("mesh", library.LoadPipeline(n("m"), &m));
        drain(&device);

        println!("after Serialize, from a library made of the blob:");
        let mut blob = vec![0u8; library.GetSerializedSize()];
        library.Serialize(&mut blob).unwrap();
        let again: ID3D12PipelineLibrary1 = {
            let made: windows::core::Result<ID3D12PipelineLibrary> = mesh_device.CreatePipelineLibrary(&blob);
            made.unwrap().cast().unwrap()
        };
        report("graphics", again.LoadGraphicsPipeline(n("g"), &g));
        report("compute", again.LoadComputePipeline(n("c"), &c));
        report("mesh", again.LoadPipeline(n("m"), &m));
        drain(&device);
    }
}

/* The shaders, compiled with dxc:
mesh.hlsl   [ms_6_5]  struct Vtx { float4 pos : SV_Position; };
                      [outputtopology("triangle")] [numthreads(1, 1, 1)]
                      void main(out indices uint3 tri[1], out vertices Vtx v[3], uint g : SV_GroupID) {
                          SetMeshOutputCounts(3, 1);
                          tri[0] = uint3(0, 1, 2) + g * 0;
                          v[0].pos = float4(0, 0, 0, 1); v[1].pos = float4(1, 0, 0, 1); v[2].pos = float4(0, 1, 0, 1); }
pixel.hlsl  [ps_6_0]  float4 main(float4 pos : SV_Position) : SV_Target0 { return float4(0, 1, 0, 1) + pos * 0; }
vs.hlsl     [vs_6_0]  float4 main(uint id : SV_VertexID) : SV_Position { float2 p = float2((id << 1) & 2, id & 2); return float4(p - 1.0, 0, 1); }
cs.hlsl     [cs_6_0]  [numthreads(1,1,1)] void main(uint t : SV_DispatchThreadID) { if (t == 0xFFFFFFFF) { } }
Cargo.toml: windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common"] }
*/
**@⁠Pablo-Barros** on GitHub · 2026-11-24 20:43 UTC · [original](https://github.com/Marvisak/VIctory/issues/1683) **What happens.** `ID3D12PipelineLibrary1::LoadPipeline` refuses every mesh pipeline with `E_INVALIDARG`. With the D3D12 debug layer on it is message 972, "The pipeline state desc provided does not match the one used to create the PSO stored with name …". It does so with the description that created the PSO, passed right after `StorePipeline` succeeded. Graphics and compute pipelines load back. So the library has never served a mesh pipeline: each is compiled in every run, stored again (refused, message 970 "already exists"), and its entry stays in a library that only grows. **In the game.** RTX 3070, Windows 11 build 26300, system D3D12 runtime 10.0.26100.10068, `main` at ffe310e, debug layer on. A run over the library the previous run wrote (early start of 1,800 pipelines): | kind | loaded | compiled again | 970 "already exists" | 972 "does not match" | |---|---|---|---|---| | graphics | 551 | 0 | 0 | 0 | | compute | 506 | 0 (105 were new) | 0 | 0 | | mesh | **0** | **723** | 723 | 723 | The 1,000 graphics and compute pipelines load in about 7 s; the 723 mesh pipelines are compiled over the next 55 s as the title creates them. An unmodified `main` logs them too (567 of 970 and 568 of 972 by the end of the early start). `host-pipelines.bin` is 231 MB here. **Without the title.** The program below: trivial mesh (`ms_6_5`) and pixel shaders compiled with dxc, an empty root signature, a stream of root signature, MS, PS, render target formats, depth format and sample description. `CreatePipelineState`, `StorePipeline("m")`, then `LoadPipeline("m", <the same stream>)`: refused, before and after `Serialize`, in the same process. The graphics (VS + PS) and compute pipelines in the same program load. Output on the RTX 3070: ``` store: graphics: Ok(()) compute: Ok(()) mesh: Ok(()) load, same library, the descriptions that created them: graphics: loaded compute: loaded mesh: REFUSED El parámetro no es correcto. (0x80070057) D3D12: id=972 ID3D12PipelineLibrary::Load*Pipeline: The pipeline state desc provided does not match the one used to create the PSO stored with name "m". after Serialize, from a library made of the blob: graphics: loaded compute: loaded mesh: REFUSED (0x80070057) ``` The same on: - the system runtime on **WARP** (Microsoft Basic Render Driver), so it is not the NVIDIA driver; - the **Agility SDK runtime 1.618.1** (`ID3D12SDKConfiguration1::CreateDeviceFactory`, `D3D12Core.dll` 1.618.1 loaded, checked) on the RTX 3070. Also tried with a longer program, all refused: an explicit empty AS subobject; no PS; the ten subobjects VIctory hands over (blend, sample mask, rasterizer, depth-stencil, RT formats, DSV format, sample desc). **Found on the way: padding.** The library compares descriptions byte for byte, and two of ours carried bytes that are not fields. The depth-stencil description is copied from the title's stream as it stands, and the two bytes between `StencilWriteMask` and `FrontFace` hold the title's stack: in one run 192 mesh pipelines differed from a copy of themselves only there, under one name. A mesh pipeline's stream has four unwritten bytes between the type and each eight-byte subobject. This is masked today by the problem above (mesh pipelines do not load either way), but it would bite as soon as they do. **A fix on my fork** (pull requests are collaborators-only, so a branch): https://github.com/Pablo-Barros/VIctory/tree/gpu/pipeline-library, two commits on ffe310e. CI's two clippy commands and the workspace tests pass. 1. `0707260` zeroes that padding where the descriptions are read and built, and in the stream before it is handed over. Two tests: descriptions read from `0xff` bytes keep their fields and lose their padding; a stream with set values likewise. 2. `cae3f32` The first pipeline of a kind that is stored is loaded back at once. Refused, the library gets no more of that kind in the run, and says so once: `WARN host pipeline library refuses a mesh pipeline it just stored: mesh pipelines are compiled every run, none kept` Same cold run as above: 1 of message 970, 2 of 972, and the 1,051 graphics and compute pipelines still load. **What this does not solve.** The mesh pipelines are still compiled in every run. That needs a runtime that loads them, or another cache. Old libraries keep their dead mesh entries (`ID3D12PipelineLibrary` cannot remove one); deleting `host-pipelines.bin` once reclaims the space. I cannot tell whether it is the same with the AMD driver. On a second run, `host pipeline library saved … made=… loaded=…` tells: with 1,800 pipelines started early, `loaded` should be well over 1,000 if mesh pipelines load. Written with Claude (Anthropic); the runs, the measurements and the program below are from this machine. <details> <summary>The program (Rust, <code>windows</code> 0.62.2) and the four shaders</summary> ```rust //! Does D3D12's pipeline library load a mesh pipeline it just stored? //! Controls: a graphics pipeline and a compute one, treated the same. //! //! `DEBUG=1`: the D3D12 debug layer, its messages printed after each step. //! `WARP=1`: the Microsoft Basic Render Driver instead of the default adapter. //! The argument is the folder holding mesh.dxil, pixel.dxil, vs.dxil, cs.dxil, //! made with dxc from the four one-line shaders below the program. use std::ffi::c_void; use windows::core::{HSTRING, Interface, PCWSTR}; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::Win32::Graphics::Dxgi::CreateDXGIFactory1; /// A stream subobject: its type, then its description, pointer-aligned. #[repr(C, align(8))] struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); #[repr(C)] struct Mesh { root: Sub<*mut c_void>, ms: Sub<D3D12_SHADER_BYTECODE>, ps: Sub<D3D12_SHADER_BYTECODE>, targets: Sub<D3D12_RT_FORMAT_ARRAY>, dsv: Sub<DXGI_FORMAT>, samples: Sub<DXGI_SAMPLE_DESC>, } fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() } } fn make_root(device: &ID3D12Device, flags: D3D12_ROOT_SIGNATURE_FLAGS) -> ID3D12RootSignature { let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { Version: D3D_ROOT_SIGNATURE_VERSION_1_1, Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { NumParameters: 0, pParameters: std::ptr::null(), NumStaticSamplers: 0, pStaticSamplers: std::ptr::null(), Flags: flags, }, }, }; // SAFETY: a description of live data; the blob is read before it is released. unsafe { let mut blob = None; let mut err = None; D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut err)).unwrap(); let blob = blob.unwrap(); let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); device.CreateRootSignature(0, bytes).unwrap() } } fn drain(device: &ID3D12Device) { let Ok(queue) = device.cast::<ID3D12InfoQueue>() else { return }; for i in 0..unsafe { queue.GetNumStoredMessages() } { let mut size = 0; if unsafe { queue.GetMessage(i, None, &mut size) }.is_err() || size == 0 { continue; } let mut buffer = vec![0u64; size.div_ceil(8)]; let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); // SAFETY: a buffer of the size the queue asked for. if unsafe { queue.GetMessage(i, Some(message), &mut size) }.is_ok() { let m = unsafe { &*message }; let text = unsafe { std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength) }; println!(" D3D12: id={} {}", m.ID.0, String::from_utf8_lossy(text).trim_end_matches('\0')); } } unsafe { queue.ClearStoredMessages() }; } fn report(what: &str, r: windows::core::Result<ID3D12PipelineState>) { match r { Ok(_) => println!(" {what}: loaded"), Err(e) => println!(" {what}: REFUSED {e}"), } } fn main() { if std::env::var_os("DEBUG").is_some() { let mut layer: Option<ID3D12Debug> = None; unsafe { D3D12GetDebugInterface(&mut layer) }.unwrap(); layer.iter().for_each(|l| unsafe { l.EnableDebugLayer() }); } let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into()); let read = |n: &str| std::fs::read(format!("{dir}/{n}")).unwrap_or_else(|e| panic!("{n}: {e}")); let (ms, ps, vs, cs) = (read("mesh.dxil"), read("pixel.dxil"), read("vs.dxil"), read("cs.dxil")); let (ms, ps, vs, cs) = (code(&ms), code(&ps), code(&vs), code(&cs)); let mut device: Option<ID3D12Device> = None; if std::env::var_os("WARP").is_some() { let factory: windows::Win32::Graphics::Dxgi::IDXGIFactory4 = unsafe { CreateDXGIFactory1() }.unwrap(); let mut chosen = None; for i in 0.. { let adapter: windows::core::Result<windows::Win32::Graphics::Dxgi::IDXGIAdapter1> = unsafe { factory.EnumAdapters1(i) }; let adapter = match adapter { Ok(a) => a, Err(_) => break, }; let desc = unsafe { adapter.GetDesc1() }.unwrap(); if (desc.Flags & windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) != 0 { chosen = Some(adapter); break; } } let adapter = chosen.expect("no WARP adapter"); unsafe { D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) }.unwrap(); } else { unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device) }.unwrap(); } let device = device.unwrap(); let mesh_device: ID3D12Device7 = device.cast().unwrap(); let root = make_root(&device, D3D12_ROOT_SIGNATURE_FLAG_NONE); let root_graphics = make_root(&device, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); // SAFETY: the descriptions point at live data. unsafe { let mut formats = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, RTFormats: [DXGI_FORMAT_UNKNOWN; 8] }; formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; let g = D3D12_GRAPHICS_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root_graphics), VS: vs, PS: ps, BlendState: Default::default(), SampleMask: u32::MAX, RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1, RTVFormats: formats.RTFormats, DSVFormat: DXGI_FORMAT_UNKNOWN, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }; let c = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: cs, ..Default::default() }; // Zeroed first: the padding between a type and eight-byte data is ours to set. let mut s: Mesh = std::mem::zeroed(); s.root.0 = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE; s.root.1 = root.as_raw(); s.ms = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); s.ps = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps); s.targets = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats); s.dsv = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_UNKNOWN); s.samples = Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }); let m = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::<Mesh>(), pPipelineStateSubobjectStream: (&raw const s).cast_mut().cast() }; let gso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&g).unwrap(); let cso: ID3D12PipelineState = device.CreateComputePipelineState(&c).unwrap(); let mso: ID3D12PipelineState = mesh_device.CreatePipelineState(&m).unwrap(); let library: ID3D12PipelineLibrary1 = { let made: windows::core::Result<ID3D12PipelineLibrary> = mesh_device.CreatePipelineLibrary(&[]); made.unwrap().cast().unwrap() }; let n = |s: &str| PCWSTR(HSTRING::from(s).as_ptr()); println!("store:"); println!(" graphics: {:?}", library.StorePipeline(n("g"), &gso)); println!(" compute: {:?}", library.StorePipeline(n("c"), &cso)); println!(" mesh: {:?}", library.StorePipeline(n("m"), &mso)); println!("load, same library, the descriptions that created them:"); report("graphics", library.LoadGraphicsPipeline(n("g"), &g)); report("compute", library.LoadComputePipeline(n("c"), &c)); report("mesh", library.LoadPipeline(n("m"), &m)); drain(&device); println!("after Serialize, from a library made of the blob:"); let mut blob = vec![0u8; library.GetSerializedSize()]; library.Serialize(&mut blob).unwrap(); let again: ID3D12PipelineLibrary1 = { let made: windows::core::Result<ID3D12PipelineLibrary> = mesh_device.CreatePipelineLibrary(&blob); made.unwrap().cast().unwrap() }; report("graphics", again.LoadGraphicsPipeline(n("g"), &g)); report("compute", again.LoadComputePipeline(n("c"), &c)); report("mesh", again.LoadPipeline(n("m"), &m)); drain(&device); } } /* The shaders, compiled with dxc: mesh.hlsl [ms_6_5] struct Vtx { float4 pos : SV_Position; }; [outputtopology("triangle")] [numthreads(1, 1, 1)] void main(out indices uint3 tri[1], out vertices Vtx v[3], uint g : SV_GroupID) { SetMeshOutputCounts(3, 1); tri[0] = uint3(0, 1, 2) + g * 0; v[0].pos = float4(0, 0, 0, 1); v[1].pos = float4(1, 0, 0, 1); v[2].pos = float4(0, 1, 0, 1); } pixel.hlsl [ps_6_0] float4 main(float4 pos : SV_Position) : SV_Target0 { return float4(0, 1, 0, 1) + pos * 0; } vs.hlsl [vs_6_0] float4 main(uint id : SV_VertexID) : SV_Position { float2 p = float2((id << 1) & 2, id & 2); return float4(p - 1.0, 0, 1); } cs.hlsl [cs_6_0] [numthreads(1,1,1)] void main(uint t : SV_DispatchThreadID) { if (t == 0xFFFFFFFF) { } } Cargo.toml: windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common"] } */ ``` </details>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:41:27 +00:00
Author
Owner

@⁠AgneyaK on GitHub · 2026-11-24 20:57 UTC · original

For the "or another cache" part: the per-pipeline cached blob doesn't work for mesh pipelines either.

I tried ID3D12PipelineState::GetCachedBlob + a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO subobject, with a standalone program: a trivial ms_6_5 + ps_6_5, an empty root signature, a stream of root signature, MS, PS, RT formats and sample desc, and CreatePipelineState, then GetCachedBlob, then CreatePipelineState of the same stream plus CACHED_PSO with that blob.

RTX 3050 Laptop (driver 32.0.16.2124) WARP
mesh pipeline from its own cached blob, same process refused E_INVALIDARG refused E_INVALIDARG
mesh pipeline from the previous process's blob refused not tried
control: VS + PS pipeline, same stream path, from its cached blob made made

System runtime D3D12Core.dll 10.0.26100.10068, Windows 11 26300, windows 0.62.2. A corrupted or truncated blob is also E_INVALIDARG, so a stale cache can't be told apart from this. So it looks like the same runtime-side mismatch for mesh pipeline descriptions as in your library repro, through a second route. Not tried with the Agility SDK runtime.

One thing that may make "compiled every run" cheaper than it sounds on NVIDIA: the driver's own shader cache. The same mesh pipeline took 19.4 ms to create in the first process and 0.97–2.1 ms in the following ones. I haven't measured that for the title's 723.

The program is about 120 lines; I can post it if useful.

AI use: Claude Code (Claude Opus 5.5) wrote the probe, ran it on my machine and drafted this.

**@⁠AgneyaK** on GitHub · 2026-11-24 20:57 UTC · [original](https://github.com/Marvisak/VIctory/issues/1683#issuecomment-7144292797) For the "or another cache" part: the per-pipeline cached blob doesn't work for mesh pipelines either. I tried `ID3D12PipelineState::GetCachedBlob` + a `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO` subobject, with a standalone program: a trivial `ms_6_5` + `ps_6_5`, an empty root signature, a stream of root signature, MS, PS, RT formats and sample desc, and `CreatePipelineState`, then `GetCachedBlob`, then `CreatePipelineState` of the same stream plus `CACHED_PSO` with that blob. | | RTX 3050 Laptop (driver 32.0.16.2124) | WARP | |---|---|---| | mesh pipeline from its own cached blob, same process | **refused** `E_INVALIDARG` | **refused** `E_INVALIDARG` | | mesh pipeline from the previous process's blob | **refused** | not tried | | control: VS + PS pipeline, same stream path, from its cached blob | made | made | System runtime `D3D12Core.dll` 10.0.26100.10068, Windows 11 26300, `windows` 0.62.2. A corrupted or truncated blob is also `E_INVALIDARG`, so a stale cache can't be told apart from this. So it looks like the same runtime-side mismatch for mesh pipeline descriptions as in your library repro, through a second route. Not tried with the Agility SDK runtime. One thing that may make "compiled every run" cheaper than it sounds on NVIDIA: the driver's own shader cache. The same mesh pipeline took 19.4 ms to create in the first process and 0.97–2.1 ms in the following ones. I haven't measured that for the title's 723. The program is about 120 lines; I can post it if useful. AI use: Claude Code (Claude Opus 5.5) wrote the probe, ran it on my machine and drafted this.
Author
Owner

@⁠AgneyaK on GitHub · 2026-11-24 21:52 UTC · original

Correction to my comment above: CACHED_PSO does work for mesh pipelines. My probe had the same gap that main 9c58a1c fixes for the library: its mesh stream had no PRIMITIVE_TOPOLOGY subobject.

Same standalone program (trivial ms_6_5 + ps_6_5, empty root signature), the only change being a PRIMITIVE_TOPOLOGY = TRIANGLE subobject in the mesh stream:

without topology (my earlier run) with topology
RTX 3050 6 GB Laptop, driver 32.0.16.2124: from its own cached blob refused, E_INVALIDARG made, 0.73 ms (first build 28.5 ms)
same, blob from the previous process refused made, 0.52 ms
WARP: from its own cached blob refused made
corrupted or truncated blob refused refused, E_INVALIDARG
control: VS+PS from its cached blob made made

So the cause is the same one 9c58a1c names ("the library refused every mesh pipeline without it"), and a per-pipeline blob is a working fallback too, as long as the stream gives the topology. Sorry for the noise.

Not tested: the title itself, or main 70564ae loading mesh pipelines from the library in a run.

AI use: Claude Code (Claude Opus 5.5) wrote the probe and this comment; the results are from the runs described.

**@⁠AgneyaK** on GitHub · 2026-11-24 21:52 UTC · [original](https://github.com/Marvisak/VIctory/issues/1683#issuecomment-7145500450) Correction to my comment above: **`CACHED_PSO` does work for mesh pipelines.** My probe had the same gap that `main` `9c58a1c` fixes for the library: its mesh stream had no `PRIMITIVE_TOPOLOGY` subobject. Same standalone program (trivial `ms_6_5` + `ps_6_5`, empty root signature), the only change being a `PRIMITIVE_TOPOLOGY` = `TRIANGLE` subobject in the mesh stream: | | without topology (my earlier run) | with topology | |---|---|---| | RTX 3050 6 GB Laptop, driver 32.0.16.2124: from its own cached blob | refused, `E_INVALIDARG` | made, 0.73 ms (first build 28.5 ms) | | same, blob from the previous process | refused | made, 0.52 ms | | WARP: from its own cached blob | refused | made | | corrupted or truncated blob | refused | refused, `E_INVALIDARG` | | control: VS+PS from its cached blob | made | made | So the cause is the same one `9c58a1c` names ("the library refused every mesh pipeline without it"), and a per-pipeline blob is a working fallback too, as long as the stream gives the topology. Sorry for the noise. Not tested: the title itself, or `main` `70564ae` loading mesh pipelines from the library in a run. AI use: Claude Code (Claude Opus 5.5) wrote the probe and this comment; the results are from the runs described.
Author
Owner

@⁠BaggyALPHA on GitHub · 2026-11-24 22:23 UTC · original

Independent cold-build and cross-process replay on the RTX 3080 12 GiB, driver 621.24, using main with the mesh topology fix. A bounded local probe selected 48 preparable pack records per kind and forced the normal D3D12 library lookup on replay, including for pipelines marked as prebuilt. Both invocations used the same 144 records and the same local library.

Kind Cold run Native creation time on cold run Warm replay
Mesh 25 created, 23 reused within the cold process 3.108 s 48 hits, zero creations
Graphics 48 created 0.328 s 48 hits, zero creations
Compute 21 created, 26 native refusals, one translation refusal 0.396 s 21 hits, the same 27 refusals

The time column sums elapsed time inside native creation calls across workers and includes failures. In this sample, all 117 usable records hit the library on replay, including every mesh record. Mesh accounted for most of the cold creation time. This measures offline pack compilation and cannot establish the startup gain in the title. In-game runs on this setup hit early device removal before reaching a representative mesh workload.

AI-assisted (Codex). Aggregate results only.

**@⁠BaggyALPHA** on GitHub · 2026-11-24 22:23 UTC · [original](https://github.com/Marvisak/VIctory/issues/1683#issuecomment-7146172160) Independent cold-build and cross-process replay on the RTX 3080 12 GiB, driver 621.24, using main with the mesh topology fix. A bounded local probe selected 48 preparable pack records per kind and forced the normal D3D12 library lookup on replay, including for pipelines marked as prebuilt. Both invocations used the same 144 records and the same local library. | Kind | Cold run | Native creation time on cold run | Warm replay | | --- | --- | ---: | --- | | Mesh | 25 created, 23 reused within the cold process | 3.108 s | 48 hits, zero creations | | Graphics | 48 created | 0.328 s | 48 hits, zero creations | | Compute | 21 created, 26 native refusals, one translation refusal | 0.396 s | 21 hits, the same 27 refusals | The time column sums elapsed time inside native creation calls across workers and includes failures. In this sample, all 117 usable records hit the library on replay, including every mesh record. Mesh accounted for most of the cold creation time. This measures offline pack compilation and cannot establish the startup gain in the title. In-game runs on this setup hit early device removal before reaching a representative mesh workload. AI-assisted (Codex). Aggregate results only.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 12:46 UTC · original

Automated triage for the maintainers.

  • Mesh pipelines never load from the library: fixed on main by commit 9c58a1c (mesh pipelines load from the library). The mesh stream in crates/victory-gpu/src/pipeline/host.rs (the mesh pipeline builder that calls library::pipeline) now carries an explicit PRIMITIVE_TOPOLOGY subobject. AgneyaK's probe and BaggyALPHA's replay above (48 of 48 mesh hits on a warm run) both show the library now serves mesh pipelines.
  • Padding (still on main 940d32f, confirmed): in the same file, GraphicsState reads the depth-stencil description with read_unaligned straight from the title's stream (subobject 11), so the two bytes after StencilWriteMask keep whatever the title left there. The mesh Stream struct is built from a struct literal, so its padding between each subobject type and its 8-byte-aligned data is never zeroed either. Now that mesh pipelines load, this can produce library misses for descriptions that differ only in padding.

Your fork commit 0707260 (zero the padding, with tests) addresses the second part; cae3f32 is no longer needed after 9c58a1c. Pull requests are open to everyone, so please open 0707260 as a PR on current main.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 12:46 UTC · [original](https://github.com/Marvisak/VIctory/issues/1683#issuecomment-7162825326) <!-- victory-issue-triage v1 verdict=confirmed seen=2026-11-24T22:23:32Z at=2026-11-25T12:45:52Z --> Automated triage for the maintainers. - **Mesh pipelines never load from the library:** fixed on `main` by commit `9c58a1c` (mesh pipelines load from the library). The mesh stream in `crates/victory-gpu/src/pipeline/host.rs` (the mesh pipeline builder that calls `library::pipeline`) now carries an explicit `PRIMITIVE_TOPOLOGY` subobject. AgneyaK's probe and BaggyALPHA's replay above (48 of 48 mesh hits on a warm run) both show the library now serves mesh pipelines. - **Padding (still on `main` 940d32f, confirmed):** in the same file, `GraphicsState` reads the depth-stencil description with `read_unaligned` straight from the title's stream (subobject 11), so the two bytes after `StencilWriteMask` keep whatever the title left there. The mesh `Stream` struct is built from a struct literal, so its padding between each subobject type and its 8-byte-aligned data is never zeroed either. Now that mesh pipelines load, this can produce library misses for descriptions that differ only in padding. Your fork commit `0707260` (zero the padding, with tests) addresses the second part; `cae3f32` is no longer needed after `9c58a1c`. Pull requests are open to everyone, so please open `0707260` as a PR on current `main`. --- _Generated by [Claude Code](https://claude.ai/code)_
This discussion has been locked. Commenting is limited to contributors.
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#1683
No description provided.