From 871788a57f7df72d9a3baeaeedfb374b6b04d707 Mon Sep 17 00:00:00 2001 From: Krashgamer <64923888+Krashgamer@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:38:01 +0100 Subject: [PATCH 1/4] d3d12: rewrite a missed journal file from an empty cache when the seeded one kept its data (RT-JOURNAL-SEEDED-REWRITE) A compute pipeline that missed its journal file was rewritten from the cache made from that file. On NVIDIA (RTX 3080, 610.88) that cache came back exactly as loaded, without the pipeline just compiled, so the rewrite gave the same file and the same multi-second miss on every boot. After a seeded miss whose cache is still the loaded size, the pipeline is built once more against an empty cache (15-78 ms: the driver still has it) and that is written. A seeded cache that took the pipeline is rewritten as before. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1c97dad489..4173ad6828 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -17501,6 +17501,25 @@ class JournalCache { std::vector().swap(file_.data); // the driver has its own copy } + // In the build's driver turn, after a create against a seeded cache that missed. Measured on NVIDIA (RTX 3080, + // 610.88): such a cache can keep its data exactly as loaded, without the pipeline just compiled, so the rewrite + // gave the same file and the same miss on every boot. When the cache's data is still the loaded size, it is + // swapped for an empty one for one more create (the driver still has the pipeline: tens of milliseconds). + bool restart_empty() { + if (!cache || !seeded) return false; + const auto& vk = device_.context->vk; + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr) != VK_SUCCESS || size != file_.bytes) + return false; // it took the pipeline (or cannot say): rewritten from it as before + vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); + cache = VK_NULL_HANDLE; + seeded = false; + const VkPipelineCacheCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) == VK_SUCCESS) return true; + cache = VK_NULL_HANDLE; + return false; + } + // In the build's driver turn, after the create against `cache`. `built`: that create made the pipeline; `hit`: // its creation feedback; `driver_ms`: the vkCreateComputePipelines call alone. void finish(bool built, int hit, std::uint64_t driver_ms) { @@ -17812,6 +17831,23 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn const ULONGLONG at = GetTickCount64(); created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); driver_ms = GetTickCount64() - at; + // A seeded miss the cache did not take: built once more against an empty cache, so the file is rewritten + // with this pipeline instead of as it was read. + if (created == VK_SUCCESS && built && journal.seeded && + leonida::pipeline_journal::should_write(true, trace.hit(), driver_ms) && journal.restart_empty()) { + VkPipeline again = VK_NULL_HANDLE; + const ULONGLONG at_again = GetTickCount64(); + const VkResult again_result = vk.vkCreateComputePipelines(dev, journal.cache, 1, &pipeline_info, nullptr, &again); + const ULONGLONG again_ms = GetTickCount64() - at_again; + if (again_result == VK_SUCCESS && again) { + vk.vkDestroyPipeline(dev, built, nullptr); + built = again; + } + std::fprintf(stderr, "[rt] d3d12: pipeline journal: %s missed its journal file (%llu ms); built again " + "against an empty cache in %llu ms (VkResult %d) to rewrite it\n", + entry->name.c_str(), static_cast(driver_ms), + static_cast(again_ms), int(again_result)); + } } compiling.name.store(nullptr, std::memory_order_release); vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists From c5bc7b0c5bf39ca90e68ed4b088426d0b71c8024 Mon Sep 17 00:00:00 2001 From: Krashgamer <64923888+Krashgamer@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:50:34 +0100 Subject: [PATCH 2/4] d3d12: keep the journal file when the create against the empty cache fails Found by ecox982745 in review: a failed second create left an empty cache that finish() still wrote over the old file (36 bytes on NVIDIA). The first pipeline is kept and nothing is published on that path. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4173ad6828..f6a84408a7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -17787,6 +17787,7 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn auto& compiling = leonida::driver_compile; VkResult created = VK_ERROR_UNKNOWN; bool from_shared = false, probe_compiled = false; + bool journal_retry_failed = false; // the create against the empty cache failed: nothing to write int hit_reported = -1; // what the journal sees as its hit, printed below to explain a missing write ULONGLONG probe_ms = 0, driver_ms = 0; { @@ -17839,7 +17840,8 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn const ULONGLONG at_again = GetTickCount64(); const VkResult again_result = vk.vkCreateComputePipelines(dev, journal.cache, 1, &pipeline_info, nullptr, &again); const ULONGLONG again_ms = GetTickCount64() - at_again; - if (again_result == VK_SUCCESS && again) { + journal_retry_failed = again_result != VK_SUCCESS || !again; + if (!journal_retry_failed) { vk.vkDestroyPipeline(dev, built, nullptr); built = again; } @@ -17852,7 +17854,8 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn compiling.name.store(nullptr, std::memory_order_release); vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists hit_reported = trace.hit(); // what finish() sees; decides whether the file is written - journal.finish(!from_shared && created == VK_SUCCESS && built, hit_reported, driver_ms); + journal.finish(!from_shared && !journal_retry_failed && created == VK_SUCCESS && built, hit_reported, + driver_ms); } std::vector().swap(words); profile.finish(int(created)); From 7a70814b6de1048deebc78eda0500ebae0ed99b6 Mon Sep 17 00:00:00 2001 From: Krashgamer <64923888+Krashgamer@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:46:54 +0100 Subject: [PATCH 3/4] d3d12: the empty-cache retry compares with the payload the cache was made from restart_empty() compared the cache's size with file_.bytes, the writable file's size. That is zero or wrong when the payload came from the external seed (missing or invalid local file), and 24 bytes too many once #2511 strips its stamp. The retry was then skipped and the same miss came back on every boot. create() now records the size Vulkan took; file_.bytes stays for the disk budget. Found by zmasi, ecox982745 and timbot103 in review; the change follows ecox982745's patch. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_vulkan_device.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index f6a84408a7..5525c033e7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -17492,6 +17492,7 @@ class JournalCache { file_.data.empty() ? nullptr : file_.data.data()}; if (!file_.data.empty() && vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) == VK_SUCCESS) { seeded = true; + seeded_bytes_ = info.initialDataSize; // the payload the driver took: may be the seed's, or stamp-stripped } else { cache = VK_NULL_HANDLE; // no file, or one the driver declined: start empty, and the build rewrites it info.initialDataSize = 0; @@ -17509,7 +17510,7 @@ class JournalCache { if (!cache || !seeded) return false; const auto& vk = device_.context->vk; std::size_t size = 0; - if (vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr) != VK_SUCCESS || size != file_.bytes) + if (vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr) != VK_SUCCESS || size != seeded_bytes_) return false; // it took the pipeline (or cannot say): rewritten from it as before vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); cache = VK_NULL_HANDLE; @@ -17597,6 +17598,7 @@ class JournalCache { leonida::SubmitMutex* submits_ = nullptr; // null: compute_driver_turn, for a build outside the submit lock const char* trigger_ = ""; const char* name_; + std::size_t seeded_bytes_ = 0; // create(): bytes the seeded cache was made from (file_.bytes is the local file) bool enabled_ = false; bool built_ = false; bool write_ = false; From f230da5182bcae7408238a6ee5a5ef9d19ea8046 Mon Sep 17 00:00:00 2001 From: Krashgamer <64923888+Krashgamer@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:21:00 +0100 Subject: [PATCH 4/4] test: a seeded journal miss is rewritten from an empty cache (d3d12_compute_journal_seeded_miss) d3d12_compute_journal_test gets a test-only layer between the runtime and the driver (--keep-seeded-cache-data): a pipeline cache made from initial data answers vkGetPipelineCacheData with exactly that data, as NVIDIA 610.88 did on an RTX 3080 after a seeded miss. Other drivers grow the cache instead, so the layer makes the case reproducible on any GPU; pipelines, dispatches and readbacks stay the real driver's. --fail-cache-retry also fails the create against the empty cache. scripts/check_compute_journal_seeded_miss.py runs each case in its own process with A's journal data under B's key: a stale local file, the same data only in the seed folder, seven invalid local bytes with the seed, and a failed retry. The file has to be rewritten with B's pipeline (and hit in a fresh process when the driver reports hits), the seed has to keep its bytes and last-write time, and a failed retry has to leave the file alone. Registered in CTest as d3d12_compute_journal_seeded_miss. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 10 + runtime/test/d3d12_compute_journal_test.cpp | 143 +++++++++++- scripts/check_compute_journal_seeded_miss.py | 217 +++++++++++++++++++ 3 files changed, 366 insertions(+), 4 deletions(-) create mode 100644 scripts/check_compute_journal_seeded_miss.py diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 765b2611a6..c8c8c221f3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3606,6 +3606,16 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compute_journal_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compute_journal COMMAND d3d12_compute_journal_test) set_tests_properties(d3d12_compute_journal PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # A seeded miss whose cache kept its data as loaded (NVIDIA 610.88): the journal file is rewritten from a + # retry against an empty cache, also when the data came from the seed folder, and a failed retry leaves the + # file alone. Separate processes, so a hit is the journal file's and not the driver's memory. + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND) + add_test(NAME d3d12_compute_journal_seeded_miss COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/check_compute_journal_seeded_miss.py" + $) + set_tests_properties(d3d12_compute_journal_seeded_miss PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() endif() # The cache vk_pipeline_check saves has to hit on the runtime's device (docs/pipeline_check.md): the test diff --git a/runtime/test/d3d12_compute_journal_test.cpp b/runtime/test/d3d12_compute_journal_test.cpp index f250767595..5cf1bea69c 100644 --- a/runtime/test/d3d12_compute_journal_test.cpp +++ b/runtime/test/d3d12_compute_journal_test.cpp @@ -8,16 +8,132 @@ #include "../shims/d3d12_com.h" #include "../src/shader_library.h" +#include #include #include #include #include +#include +#include +#include using namespace d3d12test; #define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) namespace { +// --keep-seeded-cache-data: a test-only layer between the runtime and the driver that makes every pipeline cache +// created from initial data answer vkGetPipelineCacheData with exactly that data, whatever was built against it. +// This is what NVIDIA 610.88 did on an RTX 3080 after a seeded miss (the cache kept its data as loaded, without the +// pipeline just compiled), so the journal file was rewritten unchanged and missed again on every boot. Other drivers +// grow the cache instead, so the layer makes that case reproducible on any GPU. Pipelines, dispatches and readbacks +// stay the real driver's. --fail-cache-retry also fails the first create against an empty cache made after a seeded +// cache was destroyed (the journal's retry against an empty cache) with VK_ERROR_OUT_OF_HOST_MEMORY. +struct SeededCacheLayer { + std::mutex mutex; + bool fail_retry = false; + PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; + PFN_vkGetDeviceProcAddr real_device_proc = nullptr; + PFN_vkCreatePipelineCache real_create_cache = nullptr; + PFN_vkDestroyPipelineCache real_destroy_cache = nullptr; + PFN_vkGetPipelineCacheData real_cache_data = nullptr; + PFN_vkCreateComputePipelines real_create_compute = nullptr; + std::map> loaded; // live caches made from initial data + bool seeded_destroyed = false; + VkPipelineCache retry_cache = VK_NULL_HANDLE; // the first empty cache made after a seeded one was destroyed + unsigned seeded_caches = 0, kept_answers = 0, failed_retries = 0; +}; +SeededCacheLayer seeded_layer; + +VKAPI_ATTR VkResult VKAPI_CALL layer_create_cache(VkDevice device, const VkPipelineCacheCreateInfo* info, + const VkAllocationCallbacks* allocator, VkPipelineCache* cache) { + const VkResult result = seeded_layer.real_create_cache(device, info, allocator, cache); + if (result != VK_SUCCESS) return result; + const std::lock_guard lock(seeded_layer.mutex); + if (info->initialDataSize && info->pInitialData) { + const auto* first = static_cast(info->pInitialData); + seeded_layer.loaded[*cache].assign(first, first + info->initialDataSize); + ++seeded_layer.seeded_caches; + } else if (seeded_layer.seeded_destroyed && seeded_layer.retry_cache == VK_NULL_HANDLE) { + seeded_layer.retry_cache = *cache; + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL layer_destroy_cache(VkDevice device, VkPipelineCache cache, + const VkAllocationCallbacks* allocator) { + { + const std::lock_guard lock(seeded_layer.mutex); + if (seeded_layer.loaded.erase(cache)) seeded_layer.seeded_destroyed = true; + } + seeded_layer.real_destroy_cache(device, cache, allocator); +} + +VKAPI_ATTR VkResult VKAPI_CALL layer_cache_data(VkDevice device, VkPipelineCache cache, size_t* size, void* data) { + std::unique_lock lock(seeded_layer.mutex); + const auto it = seeded_layer.loaded.find(cache); + if (it == seeded_layer.loaded.end()) { + lock.unlock(); + return seeded_layer.real_cache_data(device, cache, size, data); + } + ++seeded_layer.kept_answers; + const auto& bytes = it->second; + if (!data) { + *size = bytes.size(); + return VK_SUCCESS; + } + const size_t copied = std::min(*size, bytes.size()); + std::memcpy(data, bytes.data(), copied); + *size = copied; + return copied < bytes.size() ? VK_INCOMPLETE : VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL layer_create_compute(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo* infos, + const VkAllocationCallbacks* allocator, VkPipeline* pipelines) { + { + const std::lock_guard lock(seeded_layer.mutex); + if (seeded_layer.fail_retry && cache != VK_NULL_HANDLE && cache == seeded_layer.retry_cache) { + std::fill(pipelines, pipelines + count, VkPipeline(VK_NULL_HANDLE)); + ++seeded_layer.failed_retries; + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + } + return seeded_layer.real_create_compute(device, cache, count, infos, allocator, pipelines); +} + +PFN_vkVoidFunction layer_function(const char* name) { + if (std::strcmp(name, "vkCreatePipelineCache") == 0) return reinterpret_cast(&layer_create_cache); + if (std::strcmp(name, "vkDestroyPipelineCache") == 0) return reinterpret_cast(&layer_destroy_cache); + if (std::strcmp(name, "vkGetPipelineCacheData") == 0) return reinterpret_cast(&layer_cache_data); + if (std::strcmp(name, "vkCreateComputePipelines") == 0) return reinterpret_cast(&layer_create_compute); + return nullptr; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL layer_device_proc(VkDevice device, const char* name) { + if (const auto own = layer_function(name)) return own; + return seeded_layer.real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL layer_instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) return reinterpret_cast(&layer_device_proc); + if (const auto own = layer_function(name)) return own; + return seeded_layer.real_instance_proc(instance, name); +} + +// The real entry points, looked up once before the runtime sees the device. +bool install_layer(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) { + seeded_layer.real_instance_proc = instance_proc; + seeded_layer.real_device_proc = reinterpret_cast(instance_proc(instance, "vkGetDeviceProcAddr")); + if (!seeded_layer.real_device_proc) return false; + const auto get = [&](const char* name) { return seeded_layer.real_device_proc(device, name); }; + seeded_layer.real_create_cache = reinterpret_cast(get("vkCreatePipelineCache")); + seeded_layer.real_destroy_cache = reinterpret_cast(get("vkDestroyPipelineCache")); + seeded_layer.real_cache_data = reinterpret_cast(get("vkGetPipelineCacheData")); + seeded_layer.real_create_compute = reinterpret_cast(get("vkCreateComputePipelines")); + return seeded_layer.real_create_cache && seeded_layer.real_destroy_cache && seeded_layer.real_cache_data && seeded_layer.real_create_compute; +} + int dispatch_once(ID3D12Device* dev, const std::vector& container, UINT expected_sum) { D3D12_ROOT_PARAMETER param{}; param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; @@ -96,10 +212,20 @@ int dispatch_once(ID3D12Device* dev, const std::vector& container, } // namespace int main(int argc, char** argv) { - const bool second = argc == 2 && std::strcmp(argv[1], "--second-shader") == 0; - if (argc != 1 && !second) { - std::fputs("usage: d3d12_compute_journal_test [--second-shader]\n", stderr); - return 2; + bool second = false, keep_seeded = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--second-shader") == 0) { + second = true; + } else if (std::strcmp(argv[i], "--keep-seeded-cache-data") == 0) { + keep_seeded = true; + } else if (std::strcmp(argv[i], "--fail-cache-retry") == 0) { + keep_seeded = true; + seeded_layer.fail_retry = true; + } else { + std::fputs("usage: d3d12_compute_journal_test [--second-shader] [--keep-seeded-cache-data] " + "[--fail-cache-retry]\n", stderr); + return 2; + } } // One additional constant per group in the second module: (1+2+3+4) versus (2+3+4+5). const UINT expected_sum = second ? 14u : 10u; @@ -131,6 +257,10 @@ int main(int argc, char** argv) { CHECK(index); rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = vk.instance_proc; + if (keep_seeded) { + CHECK(install_layer(vk.instance_proc, vk.instance, vk.device)); + info.get_instance_proc = &layer_instance_proc; + } info.instance = vk.instance; info.physical = vk.physical; info.device = vk.device; @@ -148,6 +278,11 @@ int main(int argc, char** argv) { CHECK(dispatch_once(dev.p, container, expected_sum) == 0); } CHECK(vktest::validation_error_count() == 0); // includes device teardown + if (keep_seeded) { + // Read by scripts/check_compute_journal_seeded_miss.py: proof that the layer was in the path. + std::printf("seeded cache layer: %u seeded cache(s), %u kept-data answer(s), %u failed retry create(s)\n", + seeded_layer.seeded_caches, seeded_layer.kept_answers, seeded_layer.failed_retries); + } std::printf("compute journal: direct Dispatch(4,1,1) copied both expected words (4,%u)\n", expected_sum); return 0; } diff --git a/scripts/check_compute_journal_seeded_miss.py b/scripts/check_compute_journal_seeded_miss.py new file mode 100644 index 0000000000..204a0d0607 --- /dev/null +++ b/scripts/check_compute_journal_seeded_miss.py @@ -0,0 +1,217 @@ +"""Check the pipeline journal's retry after a seeded miss. No game files needed. + +A journal file the driver loads but does not take (a miss) is rewritten with the pipeline just built. NVIDIA 610.88 +(RTX 3080) kept such a cache's data exactly as loaded, so the rewrite gave the same file and the same miss on every +boot; the journal then builds once more against an empty cache. Other drivers grow the cache instead, so +d3d12_compute_journal_test's --keep-seeded-cache-data layer makes every seeded cache answer with the data it was +loaded from, on any GPU. Pipelines, dispatches and readbacks stay the real driver's. + +Each case runs in its own process with its own cache folder. The journal file of the second authored shader (B) is +replaced by the first shader's (A), which the driver loads and misses on: + +- stale-local: A's data in B's local file. The file has to be rewritten with B's pipeline, and a fresh process + seeded from it has to hit (when the driver reports application-cache hits at all: the control case says). +- external-seed: no local file, A's data in B's file of the read-only seed folder. The local file has to be + written with B's pipeline; the seed keeps its bytes and last-write time. +- invalid-local-external-seed: seven invalid bytes in the local file, A's data in the seed. As external-seed. +- failed-retry: as stale-local, and the create against the empty cache fails. The dispatch still has to work + and the file has to keep its bytes and last-write time. + +Build d3d12_compute_journal_test first, then run this script with the path to that executable. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time + +LAYER = re.compile(r"seeded cache layer: (\d+) seeded cache\(s\), (\d+) kept-data answer\(s\), " + r"(\d+) failed retry create\(s\)") +OLD_NS = None # a last-write time two days back, set once + + +def require(ok, message): + if not ok: + raise RuntimeError(message) + + +def journal_dir(cache): + return cache / "pipeline_cache.d" + + +def files(cache): + d = journal_dir(cache) + if not d.exists(): + return {} + require(d.is_dir(), f"{d} is not a directory") + out = {} + for p in d.iterdir(): + require(p.is_file() and re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name), f"unexpected journal entry {p}") + out[p.name] = (hashlib.sha256(p.read_bytes()).digest(), p.stat().st_size, p.stat().st_mtime_ns) + return out + + +def place(cache, name, data): + d = journal_dir(cache) + d.mkdir(parents=True, exist_ok=True) + path = d / name + path.write_bytes(data) + # An old last-write time makes a rewrite (or an LRU touch) visible without depending on the clock's resolution. + os.utime(path, ns=(OLD_NS, OLD_NS)) + return path + + +def run(exe, cache, device, second, flags=(), seed=None): + cache.mkdir(parents=True, exist_ok=True) + # Only the caller's Khronos validation switch crosses over; every other LEONIDA_ variable is this case's own. + env = {k: v for k, v in os.environ.items() + if not k.upper().startswith("LEONIDA_") or k.upper() == "LEONIDA_VK_VALIDATION"} + env.update(LEONIDA_PIPELINE_CACHE_DIR=str(cache), LEONIDA_TRACE_PIPELINE_COMPILE="1", + LEONIDA_PIPELINE_CACHE_BYTES=str(8 << 20), LEONIDA_PIPELINE_JOURNAL_BYTES=str(8 << 20), + LEONIDA_PIPELINE_JOURNAL="1") + if device: + env["LEONIDA_VK_DEVICE"] = device + if seed is not None: + env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(journal_dir(seed)) + args = [str(exe)] + (["--second-shader"] if second else []) + list(flags) + p = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding="utf-8", + errors="replace", cwd=cache, env=env, timeout=120) + if p.returncode == 77: + return None + expected = 14 if second else 10 + label = cache.name + if p.returncode != 0 or (f"compute journal: direct Dispatch(4,1,1) copied both expected words (4,{expected})" + not in p.stdout.splitlines()): + raise RuntimeError(f"{label}: exit {p.returncode} or wrong GPU readback\n{p.stdout}\n{p.stderr[-4000:]}") + calls = [x for x in p.stderr.splitlines() if x.startswith("[rt] pipeline-compile trigger=")] + require(len(calls) == 1, f"{label}: expected one compute pipeline build, saw {len(calls)}") + m = re.search(r" hit=(-1|0|1) bytes=\d+ variant=\d+ result=0 ", calls[0]) + require(m is not None, f"{label}: no creation feedback field, or the create failed: {calls[0]}") + layer = LAYER.search(p.stdout) + require((layer is not None) == bool(flags), f"{label}: the test layer line is {'missing' if flags else 'there'}") + return {"hit": int(m[1]), "layer": tuple(int(x) for x in layer.groups()) if layer else None} + + +def only_file(cache, label): + entries = files(cache) + require(len(entries) == 1, f"{label}: expected one journal file, found {len(entries)}") + name = next(iter(entries)) + return name, (journal_dir(cache) / name).read_bytes() + + +def check(exe, root, device): + global OLD_NS + OLD_NS = time.time_ns() - 48 * 3600 * 10**9 + results = {} + + # A and B cold: their journal files, and B's file name (its key) to put A's data under. + r = run(exe, root / "cold-A", device, False) + if r is None: + return 77 + _, data_a = only_file(root / "cold-A", "cold-A") + run(exe, root / "cold-B", device, True) + name_b, data_b = only_file(root / "cold-B", "cold-B") + require(data_a != data_b, "A and B produced the same journal data") + + # Control: B's own file in a fresh process. Says whether this driver reports application-cache hits. + place(root / "control-B", name_b, data_b) + control = run(exe, root / "control-B", device, True) + reports_hits = control["hit"] == 1 + results["control-B"] = control + + # stale-local + place(root / "stale-local", name_b, data_a) + r = run(exe, root / "stale-local", device, True, ["--keep-seeded-cache-data"]) + require(r["hit"] == 0, f"stale-local: expected a seeded miss, driver reported hit={r['hit']}") + require(r["layer"][0] >= 1 and r["layer"][1] >= 1, f"stale-local: the layer kept no seeded cache's data {r}") + name, rewritten = only_file(root / "stale-local", "stale-local") + require(name == name_b, "stale-local: the journal file changed its name") + require(rewritten != data_a, + "stale-local: the journal file was rewritten with the data it was read from (no retry against an " + "empty cache), so it misses again on every start") + results["stale-local"] = r + + # The repaired file in a fresh process, without the layer. + place(root / "repaired", name_b, rewritten) + before = files(root / "repaired") + r = run(exe, root / "repaired", device, True) + if reports_hits: + require(r["hit"] == 1, f"repaired: the rewritten file still misses (hit={r['hit']})") + # A hit may refresh the file's last use (the journal's LRU touch), never its bytes. + after = files(root / "repaired") + require({k: v[:2] for k, v in after.items()} == {k: v[:2] for k, v in before.items()}, + "repaired: a hit rewrote its journal file") + results["repaired"] = r + + # external-seed and invalid-local-external-seed + for label, local in (("external-seed", None), ("invalid-local-external-seed", b"invalid")): + seed = root / f"{label}-seed" + place(seed, name_b, data_a) + seed_before = files(seed) + cache = root / label + if local is not None: + place(cache, name_b, local) + r = run(exe, cache, device, True, ["--keep-seeded-cache-data"], seed=seed) + require(r["hit"] == 0, f"{label}: expected a seeded miss, driver reported hit={r['hit']}") + require(r["layer"][0] >= 1 and r["layer"][1] >= 1, f"{label}: the layer kept no seeded cache's data {r}") + name, written = only_file(cache, label) + require(name == name_b, f"{label}: the local journal file has another name") + require(written != data_a, + f"{label}: the local journal file holds the seed's data it missed on (no retry against an " + "empty cache), so it misses again on every start") + require(files(seed) == seed_before, f"{label}: the seed's bytes or last-write time changed") + results[label] = r + + # failed-retry + place(root / "failed-retry", name_b, data_a) + before = files(root / "failed-retry") + r = run(exe, root / "failed-retry", device, True, ["--fail-cache-retry"]) + require(r["layer"][2] == 1, f"failed-retry: expected one failed retry create, the layer saw {r['layer'][2]}") + require(files(root / "failed-retry") == before, + "failed-retry: the journal file was rewritten or touched although the retry create failed") + results["failed-retry"] = r + + print(json.dumps({"reports_cache_hits": reports_hits, "runs": results}, sort_keys=True)) + return 0 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe") + parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") + parser.add_argument("--keep", type=Path, help="keep the case folders under this (new) folder") + args = parser.parse_args(argv) + try: + exe = args.executable.resolve(strict=True) + except OSError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + if not exe.is_file() or exe.stem.lower() != "d3d12_compute_journal_test": + print(f"ERROR: expected the compute journal test executable, not {exe.name}", file=sys.stderr) + return 2 + try: + if args.keep: + args.keep.mkdir(parents=True) + code = check(exe, args.keep.resolve(), args.device) + else: + with tempfile.TemporaryDirectory(prefix="leonida-journal-seeded-miss-") as tmp: + code = check(exe, Path(tmp), args.device) + except (RuntimeError, subprocess.TimeoutExpired, OSError) as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 1 + if code == 77: + print("SKIP: the authored compute fixture is unsupported on this device") + return code + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + raise SystemExit(main())