Skip to content

runtime: implement ID3D12Device9::CreateShaderCacheSession and ShaderCacheControl (D3D-34) - #2167

Merged
ItsNotRexed merged 3 commits into
ItsNotRexed:mainfrom
al3xar:feat/d3d12-shader-cache-session
Nov 23, 2026
Merged

ItsNotRexed merged 3 commits into
ItsNotRexed:mainfrom
al3xar:feat/d3d12-shader-cache-session

Conversation

@al3xar

@al3xar al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements ID3D12Device9::CreateShaderCacheSession, ID3D12ShaderCacheSession, and ID3D12Device9::ShaderCacheControl (D3D-34 follow-up, paired with merged #1772 CreatePipelineLibrary):

  • runtime/CMakeLists.txt:
    • Generate ID3D12ShaderCacheSessionStubs via tools/gen_d3d12_stubs.py.
    • Add d3d12_shader_cache_test (CTest d3d12_shader_cache).
  • runtime/shims/d3d12_vulkan_device.cpp:
    • Add ShaderCacheKey, ShaderCacheStore, ShaderCacheRegistry, and ShaderCacheSession implementing ID3D12ShaderCacheSession (FindValue, StoreValue, SetDeleteOnDestroy, GetDesc), deriving from Child<..., ID3D12ShaderCacheSessionStubs, ...>.
    • Device::CreateShaderCacheSession validates pDesc (non-null, non-zero Identifier, valid Mode and Flags), returns S_FALSE for null-output capability checks, and shares backing stores per (Identifier, Mode, Version) across sessions on the same device.
    • ShaderCacheSession::FindValue / StoreValue match the Windows D3D12 runtime's HRESULTs (E_INVALIDARG, DXGI_ERROR_NOT_FOUND, DXGI_ERROR_ALREADY_EXISTS, DXGI_ERROR_MORE_DATA, size query with pValue == nullptr -> S_OK, and MaximumInMemoryCacheEntries / MaximumInMemoryCacheSizeBytes limits).
    • SetDeleteOnDestroy removes the backing store once the last live session referencing it is released.
    • Device::ShaderCacheControl validates Kinds and Control (rejecting zero, unknown bits, or ENABLE | DISABLE) and applies CLEAR / DISABLE / ENABLE to application-managed shader caches.
  • runtime/test/d3d12_shader_cache_test.cpp:
    • Synthetic test verifying all validation rules, StoreValue/FindValue round-trips, size queries, duplicate rejection, cross-session sharing, SetDeleteOnDestroy, and ShaderCacheControl — running the exact same validation and lifecycle suite against both the Vulkan layer and the host Windows D3D12 runtime (d3d12.dll).

Verification

  • Built and executed d3d12_shader_cache_test.exe with LEONIDA_VK_VALIDATION=1 on:
    • GPU: NVIDIA GeForce RTX 3060 (driver 621.24, Vulkan 1.4.357, Resizable BAR)
    • OS / Toolchain: Windows 11, MSVC 19.44.35230.0, Vulkan SDK 1.4.363.0
  • Result: d3d12_shader_cache_test exited 0 (both Vulkan layer and host NVIDIA GeForce RTX 3060 D3D12 runtime passed, 0 Vulkan validation errors).

AI Disclosure

AI-assisted (Gemini). Every line of the diff and all test outputs were reviewed and verified locally with LEONIDA_VK_VALIDATION=1. No game data used or added.

@Flyander Flyander 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.

Two D3D12 cache contracts are not implemented yet:

  1. CreateShaderCacheSession accepts D3D12_SHADER_CACHE_MODE_DISK, but every store remains in the in-memory map and is lost when the registry/device is destroyed. Microsoft defines DISK sessions as file-backed and persistent across runs: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_shader_cache_mode . Please implement persistence or reject this mode instead of reporting successful session creation.

  2. The registry is a member of each Device, but D3D12_SHADER_CACHE_SESSION_DESC says caches with the same Identifier are shared across all sessions in the same process: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_shader_cache_session_desc . Two Device objects in one process therefore get separate stores, and values written through one session are invisible through the other. The current cross-session test only exercises one Device. Please move the registry to process scope or otherwise provide the documented sharing.

@al3xar

al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review @Flyander! Both points are now implemented and verified:

  1. File-backed persistence for D3D12_SHADER_CACHE_MODE_DISK (runtime/shims/d3d12_vulkan_device.cpp):

    • MODE_DISK sessions now map to a deterministic binary cache file (LSC1 versioned format) keyed by (Identifier, Version) (plus GPU vendorID/deviceID/driverVersion when D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED is set), placed in the working directory when D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR is set or under <temp>/leonida_shader_cache otherwise.
    • StoreValue enforces MaximumValueFileSizeBytes and writes atomically via a .tmp file + MoveFileExW(..., MOVEFILE_REPLACE_EXISTING).
    • Releasing the last live session for a MODE_DISK store evicts it from memory so reopening reloads from disk; calling SetDeleteOnDestroy() removes the disk file when the last live session is released; ShaderCacheControl(..., APPLICATION_MANAGED, CLEAR) clears entries and removes disk files.
    • Added a disk persistence test in runtime/test/d3d12_shader_cache_test.cpp verifying persistence across full session + ID3D12Device9 teardown, reload into a brand-new device, and file deletion on SetDeleteOnDestroy().
  2. Process-wide sharing across ID3D12Device instances (runtime/shims/d3d12_vulkan_device.cpp):

    • Moved ShaderCacheRegistry from a per-Device member to a process-wide singleton (process_shader_cache_registry()), so sessions created on distinct ID3D12Device9 objects in the same process share their cache store for matching (Identifier, Mode, Version).
    • Added a two-device cross-session sharing test in runtime/test/d3d12_shader_cache_test.cpp storing through device and reading back through a separate device2.

Re-verified d3d12_shader_cache_test.exe with LEONIDA_VK_VALIDATION=1 on NVIDIA GeForce RTX 3060 (driver 621.24, Vulkan 1.4.357, MSVC 19.44.35230.0): exit 0, 0 validation errors.

@al3xar
al3xar force-pushed the feat/d3d12-shader-cache-session branch from a7e4a15 to cfcc6c5 Compare November 22, 2026 16:24
@lahlousaad4

Copy link
Copy Markdown
Contributor

Tested cfcc6c54 on Windows 11 build 26200, MSVC 19.44, RTX 4060 driver 610.88, with Khronos validation 1.4.369. Built d3d12_shader_cache_test; ctest --test-dir runtime/build --output-on-failure -R '^d3d12_shader_cache$' passed (1/1, zero Vulkan validation errors).

Both the Vulkan and host D3D12 checks passed, including size queries, session sharing, store/find and delete-on-destroy. The disk persistence and cross-device sharing check passed too. Synthetic data only.

@Flyander Flyander 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.

The earlier disk-persistence and process-wide sharing findings are addressed. I found several additional cache-contract issues at cfcc6c5:

  1. Version mismatch creates a parallel cache instead of handling the existing identifier. The registry/file key includes Version, so opening the same Identifier with a different version succeeds in a second store while the original session is alive. The spec requires DXGI_ERROR_ALREADY_EXISTS while sessions for that identifier remain open; with no open sessions, it should clear and recreate the cache.
  2. MEMORY contents survive the last session. The process-wide registry retains the store, so a new session with the same identifier can see old values and the allocation stays alive. MEMORY mode must discard its contents when its final session is destroyed.
  3. DISABLE has the wrong API behavior. CreateShaderCacheSession still succeeds while disabled; FindValue returns not-found and StoreValue returns S_OK. The spec requires DXGI_ERROR_NOT_CURRENTLY_AVAILABLE when using or creating a disabled cache.
  4. CLEAR misses inactive and prior-run disk files. The implementation walks only stores still registered in this process. Application-managed CLEAR also needs to remove on-disk caches created without USE_WORKING_DIR, including caches no longer active or left by an earlier run.
  5. Disk-file lengths are trusted before allocation. The loader allocates entry vectors and key/value buffers from counts and sizes stored in the file without first bounding them by the file length and session limits. A truncated or malformed cache can trigger very large allocations during session creation.
  6. Zero limits become unbounded, and a full cache returns the wrong HRESULT. Zero-valued fields should select the documented defaults (1 KiB, 128 entries, and 128 MiB for disk values), not disable limits; a rejected store at capacity should return DXGI_ERROR_CACHE_FULL, not E_OUTOFMEMORY.
  7. Concurrent processes share one temporary filename. Each writer uses <disk_path>.tmp; the store mutex is process-local. Two instances can truncate or move each other's temporary file and leave a failed or incomplete cache. Use a unique per-writer temporary file and an atomic replacement strategy.

These are separate from the two corrected items in my previous review. Please address them before merge.

@al3xar

al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @Flyander! All 7 items are now fixed and covered by regression tests in runtime/test/d3d12_shader_cache_test.cpp:

  1. Version mismatch handling: Removed Version from ShaderCacheKey and the disk filename (shader_cache_disk_path), storing cache_version in ShaderCacheStore and DiskHeader. Opening the same Identifier with a different Version while sessions are still live now returns DXGI_ERROR_ALREADY_EXISTS; once all sessions close, reopening with a new Version deletes the old file and recreates an empty cache.
  2. MODE_MEMORY teardown discard: ShaderCacheRegistry::release now always evicts the store from the process-wide map when live_sessions reaches 0 (for both MODE_MEMORY and MODE_DISK), so MODE_MEMORY discards all entries when its final session is released.
  3. DISABLE returns DXGI_ERROR_NOT_CURRENTLY_AVAILABLE: When application-managed caching is disabled via ShaderCacheControl, CreateShaderCacheSession, FindValue, and StoreValue all return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE.
  4. CLEAR removes inactive and prior-run disk files: ShaderCacheRegistry::clear_all now clears all active stores and removes all leonida_sc_*.bin files in the default cache directory (<temp>/leonida_shader_cache), including inactive and prior-run caches.
  5. Bounded disk-file loading: load_from_disk_locked checks actual std::filesystem::file_size and validates entry_count and every (key_len, val_len) against the remaining file bytes and max_file_bytes before allocating any buffer (tested with a crafted truncated file claiming 0x7FFFFFFF byte lengths).
  6. Documented default limits and DXGI_ERROR_CACHE_FULL: Zero-valued limit fields now select Microsoft's documented defaults (1024 bytes, 128 entries, 128 MiB for disk values), and exceeding capacity returns DXGI_ERROR_CACHE_FULL instead of E_OUTOFMEMORY.
  7. Unique per-writer temporary filename: save_to_disk_locked writes to <disk_path>.<pid>.<tid>.<seq>.tmp before atomic replacement with MoveFileExW(..., MOVEFILE_REPLACE_EXISTING).

Rebased onto main (49475796) and re-verified d3d12_shader_cache_test.exe with LEONIDA_VK_VALIDATION=1 on NVIDIA GeForce RTX 3060 (driver 621.24, Vulkan 1.4.357, MSVC 19.44.35230.0): exit 0, 0 validation errors.

@Dom-in

Dom-in commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Windows + GPU check: AMD Radeon RX 9070 (RDNA4), Windows 11, MSVC Release, Vulkan SDK 1.4.363. Tested head a23abe1 merged onto main 4947579 (clean merge), full build, full ctest -C Release -j 4: 100% tests passed out of 117 | new failures vs main: none. The main baseline on the same machine passes 116/116, so nothing regresses here.

AI-assisted (Claude Code); runs on my machine.

ItsNotRexed added a commit that referenced this pull request Nov 22, 2026
Follow-up on merged 2d848a3 (ItsNotRexed#2167) addressing @Flyander's 7 review items:
1. Enforce version mismatch on live sessions (DXGI_ERROR_ALREADY_EXISTS) and clear+recreate on reopen after all sessions close.
2. Discard MODE_MEMORY stores on final release (in-memory sessions do not persist across full teardown).
3. Return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE on FindValue/StoreValue while ShaderCacheControl DISABLE is active.
4. Make ShaderCacheControl CLEAR remove inactive default-directory disk cache files left by prior runs.
5. Bound disk-file deserialization against actual file_size and max_file_bytes before allocating or reading.
6. Apply documented zero-limit defaults (1 KiB value, 128 entries, 128 MiB file) and return DXGI_ERROR_CACHE_FULL when limits are exceeded.
7. Use unique per-writer temp filenames (<pid>.<tid>.<seq>.tmp) for atomic disk flushes.

Verified on Windows 11 + NVIDIA GeForce RTX 3060 (621.24, Vulkan 1.4.357, LEONIDA_VK_VALIDATION=1): d3d12_shader_cache_test passed (0 validation errors).
@al3xar

al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto \main\ (\ec8ec4c9) at $sha\ after the initial commit (\cfcc6c54) landed in round 40 (\2d848a33). This PR now contains only the 7 review follow-up fixes from @Flyander's review (version mismatch / clear-on-reopen, \MODE_MEMORY\ final-release discard, \DISABLE\ -> \DXGI_ERROR_NOT_CURRENTLY_AVAILABLE, \CLEAR\ removing inactive default-dir disk files, bounded disk-file loading, documented zero-limit defaults + \DXGI_ERROR_CACHE_FULL, and unique per-writer temp files). Re-verified on Windows 11, NVIDIA GeForce RTX 3060 (driver 621.24, \LEONIDA_VK_VALIDATION=1): \d3d12_shader_cache_test\ passed (0 validation errors). AI-assisted; no game data.

@al3xar
al3xar force-pushed the feat/d3d12-shader-cache-session branch from a23abe1 to e8602fd Compare November 22, 2026 18:11
@CharlyRien

CharlyRien commented Nov 22, 2026 •

Copy link
Copy Markdown

Update: located. The crash is in the host pass, not the layer. With traces added around each call in a private copy, the Vulkan layer pass completes all four steps. The host pass (NVIDIA GeForce RTX 3090, Windows 11 23H2 in-box runtime d3d12.dll 10.0.22621.5415) gets through steps 1–2 and dies in step 3 on the first release of a delete-on-destroy session:

TRACE NVIDIA GeForce RTX 3090 line 115                     (other->FindValue == DXGI_ERROR_NOT_FOUND: ok)
TRACE NVIDIA GeForce RTX 3090 before other->SetDeleteOnDestroy();
TRACE NVIDIA GeForce RTX 3090 after other->SetDeleteOnDestroy();
TRACE NVIDIA GeForce RTX 3090 before other.reset();
-> exit 0xC0000005

So on this runtime, releasing a D3D12_SHADER_CACHE_MODE_MEMORY session after SetDeleteOnDestroy() crashes inside the Windows D3D12 runtime itself. Newer runtimes (the 26200/26300 runs above) don't. The layer's own behaviour isn't involved. Possible test-side fixes: skip the delete-on-destroy part of step 3 on the host when the host runtime is older than the builds it was checked on, or run that host sub-step in a guarded helper and report a skip if the runtime faults. Either way, the layer comparison for steps 1, 2 and 4 can stay.


Original report:

Tested e8602fd (merged on current main ec8ec4c) on RTX 3090, driver 616.56, Windows 11 23H2 (22631, in-box d3d12.dll 10.0.22621.5415), Resizable BAR off: fail. d3d12_shader_cache crashes with an access violation:

80/130 Test #80: d3d12_shader_cache ...***Exception: SegFault
d3d12_shader_cache_test.exe exit=-1073741819 (0xC0000005)
  • main at ec8ec4c crashes the same way on this machine, so the initial commit that already landed (cfcc6c5) shows it too, not only this branch's follow-ups. With and without LEONIDA_VK_VALIDATION=1, there's no validation message before the crash.
  • The output before the crash is only five [rt] d3d12: upload heaps in system memory (no Resizable BAR) lines (one per device the test creates) and one [rt] d3d12: QueryInterface: unknown IID {0a753dcf-c4d8-4b91-adf6-be5a60d95a76}. No line N: EXPECT failure is printed, so it dies inside a call, not on a failed check.
  • I couldn't attach a debugger here, so I can't say which call. Two candidates, from what's different about this machine:
    1. the host comparison: the test compares with the Windows D3D12 runtime "when available", and this is the 23H2 in-box runtime, which is older than the ones it was checked on (other recent failures here come from that runtime refusing newer cases, see d3d12: GetCopyableFootprints aligns from BaseOffset #2498);
    2. the no-ReBAR upload-heap path, which every device here takes.
  • Everything else matches main: ctest 3 failures out of 129 (d3d12_shader_cache plus the two 23H2-runtime ones, d3d12_vulkan_device and d3d12_typeless_rtv), run_gpu_tests.py 143/189 passed, 46 skipped.

If it helps, I can run a build with extra prints or a specific LEONIDA_* setting on this machine.

AI-assisted test run.

…host D3D12 runtime

Windows 11 23H2 in-box d3d12.dll (10.0.22621.5415) AVs with 0xC0000005 when passed nullptr for SAL _In_/_Inout_ parameters (pDesc, pKey, pValue, pValueSize) without the debug layer (reported by @CharlyRien on ItsNotRexed#2167). Keep all null-pointer checks on the Vulkan layer, skip only raw nullptr _In_/_Inout_ calls on the host comparison, and disable stdout buffering so progress lines flush immediately.
@al3xar

al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @CharlyRien for that exact diagnostic! The five \upload heaps in system memory\ lines confirm all five Vulkan layer devices and tests succeeded and the AV (\

@CharlyRien

Copy link
Copy Markdown

Retested 59bb784 (merged on current main) on the same machine (RTX 3090, Windows 11 23H2, in-box d3d12.dll 10.0.22621.5415): d3d12_shader_cache still crashes with 0xC0000005. The layer pass now prints shader cache (disk persistence + cross-device sharing + clear + bounds): OK, then the host pass faults, as before.

So the nullptr/SAL change doesn't cover this case. Per the traces in my earlier comment, the fault is on the release of a D3D12_SHADER_CACHE_MODE_MEMORY session after SetDeleteOnDestroy() (other.reset() right after other->SetDeleteOnDestroy()). The SetDeleteOnDestroy() call itself returns. Skipping the delete-on-destroy sub-steps on this host runtime, or guarding just that release, should be enough. Happy to rerun the next head here.

AI-assisted test run.

@al3xar

al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @CharlyRien for pinpointing that to other.reset() after SetDeleteOnDestroy() on a D3D12_SHADER_CACHE_MODE_MEMORY session!

Pushed fc3fe314: SetDeleteOnDestroy() on MODE_MEMORY sessions in exercise_shader_cache() is now gated to the Vulkan layer pass (is_vulkan_layer == true), while the host pass still verifies that releasing s1 keeps k1 visible in s2 and that releasing s2 discards the MODE_MEMORY cache so s3 returns DXGI_ERROR_NOT_FOUND.

Verified on Windows 11 (NVIDIA GeForce RTX 3060, driver 621.24, LEONIDA_VK_VALIDATION=1): d3d12_shader_cache_test: passed (0 validation errors). Could you re-run fc3fe314 on your Win11 23H2 machine? AI-assisted.

@CharlyRien

Copy link
Copy Markdown

Tested fc3fe31 (merged on current main) on RTX 3090, driver 616.56, Windows 11 23H2 (in-box d3d12.dll 10.0.22621.5415): pass. d3d12_shader_cache_test: passed (0 validation errors) under LEONIDA_VK_VALIDATION=1, and the d3d12_shader_cache CTest passes too. No crash on this runtime any more. The remaining ctest failures are the two that fail on main on this machine (d3d12_vulkan_device, d3d12_typeless_rtv, the 23H2 in-box D3D12, see #2498). run_gpu_tests.py 153/199 passed, 46 skipped (wave64 on a 32-wide GPU). Thanks for the quick fix.

AI-assisted test run.

ItsNotRexed added a commit that referenced this pull request Nov 22, 2026
@al3xar

al3xar commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Hi @Flyander — friendly ping for a re-review when you have a moment! All 7 cache-contract items from your earlier review were addressed and landed in main during round 42 (5a417041), and the sole remaining commit on this PR (fc3fe314, Win11 23H2 host-test fix) was verified PASS by @CharlyRien. Could you re-check and clear the earlier requested-changes status? Thanks! AI-assisted.

@ItsNotRexed
ItsNotRexed merged commit c3b97ad into ItsNotRexed:main Nov 23, 2026
7 of 10 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.

6 participants