Skip to content

runtime: fix ShaderCacheStore disk accounting/temp cleanup and Win11 DISABLE parity - #9083

Closed
DenRakEiw wants to merge 1 commit into
ProjectLeonida:mainfrom
DenRakEiw:fix/d3d12-shader-cache-store-parity
Closed

DenRakEiw wants to merge 1 commit into
ProjectLeonida:mainfrom
DenRakEiw:fix/d3d12-shader-cache-store-parity

Conversation

@DenRakEiw

Copy link
Copy Markdown
Contributor

Summary

Fixes two ShaderCacheStore disk-persistence bugs and one Windows 11 host-parity mismatch in runtime/shims/d3d12_vulkan_device.cpp:

  1. ShaderCacheStore::load_from_disk_locked duplicate-key byte accounting: Only count val_len toward bytes (and check bytes > max_file_bytes - val_len) when loaded.emplace(...) actually inserts a new key, preventing duplicate keys in an on-disk cache file from inflating total_bytes and causing premature DXGI_ERROR_CACHE_FULL rejections on subsequent StoreValue calls.
  2. ShaderCacheStore::save_to_disk_locked temp-file cleanup on write failure: Flush and check out.good() inside the stream scope, and remove the .tmp file after closing the stream if writing fails so temporary files never leak on disk.
  3. ID3D12Device9::CreateShaderCacheSession DISABLE precedence over null-output capability check: Empirical probing against live Windows 11 WARP and native NVIDIA GeForce RTX 5090 D3D12 runtimes confirmed that when D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED is disabled via ShaderCacheControl(..., DISABLE), CreateShaderCacheSession(&valid_desc, riid, nullptr) returns DXGI_ERROR_NOT_CURRENTLY_AVAILABLE (not S_FALSE), while invalid-argument checks (E_INVALIDARG) still take precedence.

Tests

Expanded runtime/test/d3d12_shader_cache_test.cpp (and added FAIL_REGULAR_EXPRESSION "Validation Error;VUID-" to d3d12_shader_cache in runtime/CMakeLists.txt) to cover:

  • Duplicate-key on-disk reload byte accounting under tight MaximumValueFileSizeBytes limits
  • Rollback and zero .tmp file leaks when save_to_disk_locked fails
  • Live Windows 11 host-runtime parity for null-output CreateShaderCacheSession (including wrong riid and DISABLE precedence), MODE_MEMORY with disk-oriented flags / MaximumValueFileSizeBytes, FindValue missing-key size queries and zero-sized buffer DXGI_ERROR_MORE_DATA, and ShaderCacheControl unknown-kind and combined CLEAR | DISABLE / CLEAR | ENABLE flags

Verified on NVIDIA GeForce RTX 5090 with LEONIDA_VK_VALIDATION=1 (0 VUIDs):

  • d3d12_shader_cache — Passed (0 validation errors, Vulkan layer + live RTX 5090 D3D12 host parity)
  • d3d12_com — Passed (0 validation errors)

Claim: #8868 (comment)

AI-assisted (Gemini 4 Neon).

@smowlyy

smowlyy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Reproduced a test failure on head 7f0d87dc6 merged onto main (867d922f0) on native Windows 11 (10.0.26300.9974, MSVC 19.44, RelWithDebInfo, Vulkan SDK 1.4.363.0):

Defect

The Vulkan layer checks and disk-persistence checks pass on both NVIDIA GeForce RTX 5060 Ti (610.88) and AMD Radeon(TM) Graphics (24.10.24) with LEONIDA_VK_VALIDATION=1, but the new DISABLE block in exercise_shader_cache() fails on the native Windows 11 host D3D12 device:

shader cache (Vulkan layer): validation, StoreValue/FindValue, size queries, sharing and SetDeleteOnDestroy OK
shader cache (disk persistence + cross-device sharing + clear + bounds): OK
line 184: dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED, D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR | D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) == S_OK
line 519: exercise_shader_cache(host9.p, adapter_name.c_str(), false) == 0

Root cause

On Windows 11 without Windows Developer Mode enabled, Microsoft's native D3D12 ID3D12Device9::ShaderCacheControl refuses valid control flags (CLEAR | DISABLE) rather than returning S_OK (per D3D12 docs, ShaderCacheControl is gated on Developer Mode, returning E_ACCESSDENIED otherwise). Because exercise_shader_cache() unconditionally asserts == S_OK on host9.p (not just is_vulkan_layer), d3d12_shader_cache_test fails on standard Windows 11 machines.

Steps to reproduce

  1. Merge 7f0d87dc6 onto main (867d922f0) on native Windows 11 (Developer Mode off).
  2. cmake --build runtime/build --target d3d12_shader_cache_test --parallel
  3. LEONIDA_VK_VALIDATION=1 .\runtime\build\d3d12_shader_cache_test.exe
  4. Observe the failure at d3d12_shader_cache_test.cpp:184 / :519 (exit 1).

AI-assisted.

@comtek21516

Copy link
Copy Markdown

Tested 7f0d87dc6 on main at 867d922f0, in one tree with #9023, #8527, #7571 (four clean merges): pass.

For this change. d3d12_shader_cache is skipped on the Windows machine (no Vulkan driver), so the GPU run is the one that counts: under Wine on the RTX 4000 it passes, with the PR's changes to d3d12_shader_cache_test.cpp in.

#8213 could not be put in the same tree: it conflicts with this PR in runtime/CMakeLists.txt, so whichever lands second needs a rebase there. The Win11 DISABLE path the title mentions was not exercised natively, since the test skips without a device.

Setup. Built with MSVC 14.52 (Visual Studio 18), Windows SDK 10.0.26100, Vulkan SDK 1.4.363.1, Ninja RelWithDebInfo on Windows Server 2025 (no Vulkan driver there), then the same binaries run through scripts/run_wine_tests.py under wine-11.0 (WineHQ stable, xvfb-run) on a Quadro RTX 4000 (Turing), NVIDIA 615.71.09, Ubuntu 22.04.5, where the layer tests report device: Quadro RTX 4000.

passed failed skipped
native Windows, this tree 147 4 124
Wine on the GPU, main 867d922f0 210 12 54
Wine on the GPU, this tree 210 12 54

Under Wine the tree is test by test the same as main. The four native failures are gameinput_host, d3d12_sparse_queue_family, vk_bindless_ps_tex and vk_bindless_ps_imgatomic, which fail the same way on main on that machine (#7452). The 12 under Wine are the same 12 as on main (host comparisons Wine cannot answer, and d3d12_xdxr_rt, d3d12_indirect_rt, d3d12_indirect_dispatch_count).

Because the four were built together, there is no per-PR negative control in this run: a regression would have shown as a difference from main, and there is none. No game files used. AI-assisted (Claude Code).

@eizispark

Copy link
Copy Markdown

Tested 7f0d87d merged onto main (5d74c27) on AMD Radeon RX 9070 XT, Adrenalin 26.11.1 (LLPC / Vulkan 1.4.359), Windows 11:

  • d3d12_shader_cache: FAILED in the live Windows 11 host-parity phase (exercise_shader_cache(host9.p, adapter_name.c_str(), false) at runtime/test/d3d12_shader_cache_test.cpp:519) on line 184:
    dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED, D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR | D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) == S_OK
    • Both Vulkan-layer phases of d3d12_shader_cache passed (shader cache (Vulkan layer): validation, StoreValue/FindValue, size queries, sharing and SetDeleteOnDestroy OK and shader cache (disk persistence + cross-device sharing + clear + bounds): OK).
    • Verified pure main (5d74c27) passes d3d12_shader_cache (1/1 passed, including the live AMD Radeon RX 9070 XT host ID3D12Device9 check). On standard Windows 11 without Windows Developer Mode enabled, native ID3D12Device9::ShaderCacheControl rejects valid control calls such as CLEAR | DISABLE rather than returning S_OK, whereas invalid flag combinations still return E_INVALIDARG first.
  • d3d12_draw: Passed (0.76s — B8G8R8X8 alpha, castable RTVs, strip cut, 4x MSAA + sample mask, instance step rate, M1 5-draw + XOR logic op + fullscreen pass: all 4096/4096 pixel checks matched)
  • d3d12_translated_draw: Passed

@amonkataki

Copy link
Copy Markdown

Tested 7f0d87dc6 merged onto main 5d74c2723 on RTX 4070 Laptop GPU, NVIDIA 621.24, Windows 11 build 26300, Developer Mode off: fail. It's the same line 184 failure as the three reports above. Below: the HRESULT behind it, a guard for the test (tested here, the whole suite then matches main), and a code read of the runtime changes.

Why line 184 fails

The Microsoft docs for ID3D12Device9::ShaderCacheControl say it "may be used only in developer mode". They don't say what it returns otherwise. Measured here with a temporary print (not committed):

Call Vulkan layer Native D3D12
ShaderCacheControl(APPLICATION_MANAGED, CLEAR | DISABLE) S_OK 0x887A002D DXGI_ERROR_SDK_COMPONENT_MISSING
ShaderCacheControl(…, DISABLE) / (…, CLEAR) S_OK 0x887A002D
CreateShaderCacheSession(&desc, riid, nullptr) afterwards 0x887A0022 DXGI_ERROR_NOT_CURRENTLY_AVAILABLE S_FALSE

So the native refusal is DXGI_ERROR_SDK_COMPONENT_MISSING, not E_ACCESSDENIED. The cache is never disabled, so the rest of the host DISABLE block can't hold either: with the print in place, the next failure is FindValue(...) == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE. The E_INVALIDARG checks before line 184 pass on the native device.

A guard for the test

The guard skips the host side of the DISABLE block only when the native runtime refuses the control with exactly that code. Any other host result still has to be S_OK. The Vulkan layer always runs the whole block. It returns 0 rather than SKIP_RETURN_CODE 77, so CTest keeps the layer checks as a pass instead of marking the whole test skipped.

@@ -179,9 +179,19 @@ int exercise_shader_cache(ID3D12Device9* dev, const char* label, bool is_vulkan_
     {
         Ref<ID3D12ShaderCacheSession> s_dis;
         EXPECT(SUCCEEDED(dev->CreateShaderCacheSession(&desc, IID_PPV_ARGS(&s_dis.p))) && s_dis.p);
-        EXPECT(dev->ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
-                                       D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR |
-                                           D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) == S_OK);
+        const HRESULT disable_hr = dev->ShaderCacheControl(
+            D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED,
+            D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR | D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE);
+        // ShaderCacheControl "may be used only in developer mode" (MS docs); without it the in-box runtime
+        // refuses every valid control with DXGI_ERROR_SDK_COMPONENT_MISSING, so there is no DISABLE to compare.
+        if (!is_vulkan_layer && disable_hr == DXGI_ERROR_SDK_COMPONENT_MISSING) {
+            std::printf("shader cache (%s): validation, StoreValue/FindValue, size queries and sharing OK; "
+                        "DISABLE parity SKIP (ShaderCacheControl: DXGI_ERROR_SDK_COMPONENT_MISSING, "
+                        "needs Developer Mode)\n",
+                        label);
+            return 0;
+        }
+        EXPECT(disable_hr == S_OK);
         EXPECT(dev->CreateShaderCacheSession(&desc, __uuidof(ID3D12ShaderCacheSession), nullptr) ==
                DXGI_ERROR_NOT_CURRENTLY_AVAILABLE);

With the guard, on the same machine, LEONIDA_VK_VALIDATION=1:

shader cache (Vulkan layer): validation, StoreValue/FindValue, size queries, sharing and SetDeleteOnDestroy OK
shader cache (disk persistence + cross-device sharing + clear + bounds): OK
shader cache (NVIDIA GeForce RTX 4070 Laptop GPU): validation, StoreValue/FindValue, size queries and sharing OK; DISABLE parity SKIP (ShaderCacheControl: DXGI_ERROR_SDK_COMPONENT_MISSING, needs Developer Mode)
100% tests passed, 0 tests failed out of 1

The full suite with the guard gives 237/239, the same as main.

With Developer Mode on, the native device should return S_OK and run the full parity block. I haven't run that case, so the native side of the DISABLE parity is still unchecked.

Code read of the runtime changes

  • CreateShaderCacheSession while disabled: it now returns DXGI_ERROR_NOT_CURRENTLY_AVAILABLE after the E_INVALIDARG checks and before the null-output S_FALSE. The D3D12_SHADER_CACHE_CONTROL_FLAGS docs describe the same for DISABLE: using or creating a cache while it's disabled gives DXGI_ERROR_NOT_CURRENTLY_AVAILABLE. So the layer behaviour has a documented basis even where the native side can't be compared.
  • load_from_disk_locked: a duplicate key no longer counts toward bytes. val_len > max_file_bytes is still checked before the allocation, so the budget subtraction can't underflow. An over-budget entry still returns before entries is assigned, so the file is rejected whole as before. With duplicates, the first value wins (emplace). That only matters for a file not written by save_to_disk_locked, which writes from a std::map.
  • save_to_disk_locked: the explicit flush() before good() and the .tmp removal on failure look right. The only other early return is the failed open, where no file exists.

No problems found.

Setup
  • MSVC 19.44 (toolset 14.44.35207), Ninja RelWithDebInfo, fresh build folders for main and the merged tree, Vulkan SDK 1.4.363.0, LEONIDA_VK_VALIDATION=1 for the shader-cache runs (validation on, no VUIDs). No game files. check_no_game_data.py and git diff --check are clean on the changed file.
  • Full ctest: main 237/239, main + PR 236/239 (only d3d12_shader_cache differs), main + PR + guard 237/239. The two failures common to all three, d3d12_vulkan_device and d3d12_depth_resolve, are the RTX 4070 ones already tracked in main dde82f27 on NVIDIA RTX 4070: 4 ctest failures; #8496 fixes d3d12_vulkan_device, d3d12_depth_resolve is new #8720.

AI-assisted (Claude Code).

@wavehs wavehs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read-only audit of 7f0d87dc (diff against 867d922f0, clean): I cannot run d3d12_shader_cache_test here — it is an MSVC-only target and this Mac has no Vulkan 1.3 device — so below is the code/test verification, with the one arithmetic claim reproduced against the exact bytes the new test writes.

The DISABLE change is not just host parity — main contradicted the documented contract

The D3D12_SHADER_CACHE_CONTROL_FLAGS page says of D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE: "Attempts to use/create a cache while it's disabled result in DXGI_ERROR_NOT_CURRENTLY_AVAILABLE" (learn.microsoft.com). FindValue/StoreValue already answer that way in main, so CreateShaderCacheSession returning S_OK (and registering a live session) while disabled was the odd one out; putting the check in after the desc validation and before if (!out) … S_FALSE (d3d12_vulkan_device.cpp:5893-5897) matches both the doc and the "shouldn't be used to create" wording. The redundant re-check in ShaderCacheRegistry::acquire (4280) is harmless.

Disk accounting: the inserted guard is right, including the check's position

val_len > max_file_bytes has to stay outside if (inserted) (4197): it is what bounds the single v allocation, and it is also what keeps max_file_bytes - val_len from wrapping. Inside, emplace consumes k/v either way, and a duplicate keeps the first value — which is what the new test asserts (got_v == v).

I replayed both loops over the exact 64-byte file the test writes (d3d12_shader_cache_test.cpp:424-446, max 12):

loader result
main whole file dropped: the pre-read check sees bytes(8) > 12-8 on the second copy and returns, so entries stays empty
this branch {k: v}, total_bytes = 8

So at this tight bound the assertion that binds on main is FindValue(k) == S_OK, not the CACHE_FULL one — worth knowing when reading the failure output on an unfixed tree (it will look like "the cache ignored the file", not "it thought the cache was full"). At the 128 MiB default a duplicate only overcounts, so note that this branch is unreachable from this writer at all: entries is a std::map and StoreValue answers DXGI_ERROR_ALREADY_EXISTS for a live key, so only a foreign/hand-edited/corrupt file can contain one. The commit message's "fix ShaderCacheStore disk accounting" reads as if a normal cache hits it; "harden the loader against duplicate keys" would describe it better.

Remaining gap in the same function (pre-existing, but this is the place to fix it): a rejected file is never removed

load_from_disk_locked deletes the file on a version mismatch, but returns from every malformed/oversized case (4190, 4197, 4206) leaving it in place. A file written under a larger MaximumValueFileSizeBytes — the doc calls the field "the maximum file size", so a smaller value on reopen is legal — is therefore re-read and re-dropped on every CreateShaderCacheSession, silently, until the first StoreValue rewrites it. std::filesystem::remove(disk_path, ec) before those returns (or a log_once naming the reason) would make the empty cache observable.

Temp-file cleanup: correct, and the two "no cleanup needed" paths are genuinely clean

write_ok set from out.good() after out.flush(), removal outside the ofstream scope, plus the existing MoveFileExW failure path (4226-4246) — an ENOSPC/ERROR_DISK_FULL surfaces at flush() on MSVC's filebuf, so flush() before the scope end is what makes the check meaningful (a close() error after a successful flush is not reachable in practice). The if (!out) return false path creates nothing, and the PID/TID/write_seq name makes a pre-existing temp for that name impossible after a restart. The new test (:462-483) covers the interesting half: the temp write succeeds (a different path) and only MoveFileExW onto the directory fails, so the rollback and the .tmp scan are both exercised.

Two claims in the new test are asserted for the host runtime as well

exercise_shader_cache also runs against Microsoft's ID3D12Device9 (:416), so :185-186 (E_INVALIDARG wins over the disabled state) and :180-182 (DISABLE wins over the null-output S_FALSE, and S_FALSE for an unsupported IID with a null output) become host expectations. Neither precedence is in the docs, so if the Windows run is not green yet, those are the lines to check; the null-output S_FALSE shape, by contrast, is already asserted by main at :50.

Nits: auto [it, inserted] binds an unused it (no warning on /W4, structured bindings are exempt from C4189); the new FAIL_REGULAR_EXPRESSION (CMakeLists.txt:1807-1808) is consistent with the other thirteen tests and is the only thing that can catch validation output emitted after the in-test d.validation_errors() check, i.e. during static destruction.

AI-assisted. macOS 27.2.1 arm64, Python 3.15.2; diff/loader replay only, the C++ test was not run and no game files were used.

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.

7 participants