From 9f1f5bf9a653d6cd4568a879887b4483f37ad465 Mon Sep 17 00:00:00 2001 From: kawaii-shakal Date: Wed, 25 Nov 2026 20:40:23 +0500 Subject: [PATCH 1/3] d3d12: a pipeline cache for the offline cache's misses, written while the game runs (RT-HEAVY-PIPELINE-CACHE) pipeline_cache.session.bin can't keep what a crashed run compiled: it is written at device teardown only, and a cache seeded from the multi-GiB corpus returns the whole corpus, over its write limit. So the slow builds the corpus misses (the pipeline library's compute programs, 3 to 7 s each on an RTX 5070 Ti) are compiled again on every boot. Each graphics and compute build now first asks the corpus cache with VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT. A miss is built against a second cache, seeded from pipeline_cache.heavy.bin next to pipeline_cache.bin, so that cache holds only the misses. A build of at least LEONIDA_HEAVY_PIPELINE_CACHE_MS (500 by default) schedules a write. A thread of its own writes the cache 3 s after the newest slow build and no later than 20 s after the first unwritten one, through the session cache's staging file and rename. At teardown it writes what is left. 0 turns it off, and with it pipelineCreationCacheControl unless LEONIDA_PIPELINE_COMPILE=cache-only asks for it. Measured with vk_pipeline_check on the RTX 5070 Ti (617.42): a cache-only create of four library compute programs the corpus lacks returns VK_PIPELINE_COMPILE_REQUIRED in under 1 ms. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 13 ++ runtime/CMakeLists.txt | 8 + runtime/shims/d3d12_com.h | 3 + runtime/shims/d3d12_vulkan_device.cpp | 197 +++++++++++++++++++- runtime/src/heavy_pipeline_cache.h | 73 ++++++++ runtime/test/d3d12_mesh_test.cpp | 1 + runtime/test/d3d12_translated_draw_test.cpp | 1 + runtime/test/heavy_pipeline_cache_test.cpp | 68 +++++++ runtime/test/vk_test_device.h | 10 +- 9 files changed, 368 insertions(+), 6 deletions(-) create mode 100644 runtime/src/heavy_pipeline_cache.h create mode 100644 runtime/test/heavy_pipeline_cache_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 53d9747968..772cd2e600 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2359,6 +2359,19 @@ Pipeline creation: The files must match the Vulkan vendor, device and pipeline-cache UUID. Vulkan supplies an opaque snapshot. Replacing part of the previous file would corrupt it. `LEONIDA_PIPELINE_CACHE_BYTES` caps session writes (256 MiB by default, zero disables the session file). + The session file can't keep a crashed run's compiles. It is written at teardown only, and a cache seeded from + the corpus returns the whole corpus, so it's over that cap. The heavy pipeline cache (RT-HEAVY-PIPELINE-CACHE, + `runtime/src/heavy_pipeline_cache.h`) keeps them. Every graphics and compute build first asks the corpus cache with + `VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT`. A pipeline the corpus doesn't have is built against a + second cache, seeded from `pipeline_cache.heavy.bin` next to `pipeline_cache.bin`, so that cache holds only the + corpus's misses. + A build that takes at least `LEONIDA_HEAVY_PIPELINE_CACHE_MS` (500 by default) marks the heavy cache for writing. + A thread of its own writes it whole: 3 s after the newest slow build, and no later than 20 s after the first unwritten + one, through the same staging file and rename as the session cache. A crash therefore loses at most the last 20 s + of slow builds, and the next launch starts with the rest. The thread stops and writes what is left at device + teardown. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the + `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create + (`cache-only`) is left as it is. `LEONIDA_SKIP_COMPUTE=[,...]` (`all`: every compute program) never builds the matching compute programs and drops their dispatches, direct and indirect; the first dropped dispatch of each is logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 86378dfc86..4ebca855a2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -780,6 +780,9 @@ if(BUILD_TESTING) add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + add_executable(heavy_pipeline_cache_test test/heavy_pipeline_cache_test.cpp) + add_test(NAME heavy_pipeline_cache COMMAND heavy_pipeline_cache_test) + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) @@ -3996,6 +3999,11 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) + # The same draws through the heavy pipeline cache (src/heavy_pipeline_cache.h): every build first asks the + # offline cache without compiling, and a miss is built against the heavy cache in a folder of its own. + add_test(NAME d3d12_mesh_heavy_cache COMMAND d3d12_mesh_test) + set_tests_properties(d3d12_mesh_heavy_cache PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT + "LEONIDA_HEAVY_PIPELINE_CACHE_MS=1;LEONIDA_PIPELINE_CACHE_DIR=${CMAKE_CURRENT_BINARY_DIR}/heavy_cache_test") else() message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") endif() diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 849791a262..a084abe42d 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -160,6 +160,9 @@ struct VulkanDeviceInfo { bool occlusion_query_precise = false; bool prepare_on_bind = false; bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. + // pipelineCreationCacheControl is on for the heavy pipeline cache (src/heavy_pipeline_cache.h): a pipeline the + // offline cache does not have is created against the cache of pipeline_cache.heavy.bin, written back as it grows. + bool heavy_pipeline_cache = false; bool pipeline_statistics_query = false; bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index aeecf05b0d..ca029d60b2 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -45,6 +45,7 @@ #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" +#include "../src/heavy_pipeline_cache.h" #include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" @@ -1238,6 +1239,30 @@ std::filesystem::path pipeline_cache_session_path() { return path; } +// The pipelines the offline seed does not have, kept next to it and written while the game runs +// (src/heavy_pipeline_cache.h). +std::filesystem::path pipeline_cache_heavy_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.heavy.bin"); + return path; +} + +// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write of the heavy cache; 0 turns the +// heavy cache off. One line for a value that is not a number. +std::uint32_t heavy_pipeline_cache_ms() { + static const std::uint32_t ms = [] { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_HEAVY_PIPELINE_CACHE_MS") == 0 && length > 1; + const auto threshold = leonida::heavy_pipeline_cache::parse_threshold(present ? text : ""); + if (!threshold.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAVY_PIPELINE_CACHE_MS=%s is not a number of milliseconds; " + "using %u\n", text, threshold.ms); + return threshold.ms; + }(); + return ms; +} + // LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. std::size_t pipeline_cache_save_limit() { char text[32] = {}; @@ -1459,6 +1484,64 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); } +// The heavy cache, seeded from pipeline_cache.heavy.bin when it is there and made for this device; empty otherwise. +VkPipelineCache create_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, + const leonida::cached_pso::Identity& identity) { + const auto path = pipeline_cache_heavy_path(); + clean_stale_cache_files(path); + VkPipelineCache cache = VK_NULL_HANDLE; + { + const PipelineCacheSeed seed(path); + if (seed.data() && seed.compatible(identity)) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, + seed.size(), seed.data()}; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) == VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.heavy.bin\n", seed.size()); + return cache; + } + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.heavy.bin; starting it empty\n"); + } else if (seed.data()) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin does not match this Vulkan device; starting " + "it empty\n"); + } + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) != VK_SUCCESS) return VK_NULL_HANDLE; + return cache; +} + +// Writes the heavy cache whole: a staging file renamed over pipeline_cache.heavy.bin, so the file on disk is always +// a complete blob. It only holds what the offline seed missed, so it has no size limit of its own. +bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + std::uint64_t compiles, std::uint64_t hits) { + if (!cache || !vk.vkGetPipelineCacheData) return false; + const auto path = pipeline_cache_heavy_path(); + if (path.empty()) return false; + const auto start = compile_us(); + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) + return false; + CacheStagingFile staging(path, size); + if (!staging.data) { + std::fprintf(stderr, "[rt] d3d12: could not map a staging file for %zu heavy pipeline cache bytes\n", size); + return false; + } + auto written = size; + const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); + const bool ok = (result == VK_SUCCESS || result == VK_INCOMPLETE) && + written > sizeof(VkPipelineCacheHeaderVersionOne) && staging.publish(path, written); + if (ok) + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds " + "and %llu other builds past the offline cache so far)\n", + written, double(compile_us() - start) / 1e6, static_cast(compiles), + static_cast(hits)); + else + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin not written (%d); the previous file is kept\n", + int(result)); + return ok; +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, @@ -1989,6 +2072,98 @@ struct DeviceState { return pipeline_cache_handle; } + // The heavy pipeline cache (src/heavy_pipeline_cache.h) and the thread that writes it. + std::once_flag heavy_cache_once; + VkPipelineCache heavy_cache_handle = VK_NULL_HANDLE; + std::mutex heavy_mutex; + std::condition_variable heavy_wake; + leonida::heavy_pipeline_cache::WriteSchedule heavy_schedule; // under heavy_mutex + bool heavy_stop = false; // under heavy_mutex + std::thread heavy_writer; // started at the first slow build + std::atomic heavy_compiles{0}, heavy_hits{0}; + + VkPipelineCache heavy_cache() { + std::call_once(heavy_cache_once, [this] { + if (context->vk.vkCreatePipelineCache) + heavy_cache_handle = create_heavy_pipeline_cache(context->vk, info.device, pso_identity); + }); + return heavy_cache_handle; + } + + // A build past the offline cache took `took_ms`: a slow one schedules a write. + void note_heavy_build(ULONGLONG took_ms) { + if (took_ms < heavy_pipeline_cache_ms()) { + ++heavy_hits; + return; + } + ++heavy_compiles; + std::lock_guard lock(heavy_mutex); + if (heavy_stop) return; + heavy_schedule.note_heavy(GetTickCount64()); + if (!heavy_writer.joinable()) { + try { + heavy_writer = std::thread([this] { write_heavy_cache_loop(); }); + } catch (const std::exception&) { + return; // no thread: the cache is still written at teardown + } + } + heavy_wake.notify_one(); + } + + void write_heavy_cache_loop() { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + std::unique_lock lock(heavy_mutex); + while (!heavy_stop) { + if (!heavy_schedule.dirty()) { + heavy_wake.wait(lock); + continue; + } + const std::uint64_t now = GetTickCount64(); + if (!heavy_schedule.due(now)) { + heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now)); + continue; + } + lock.unlock(); + save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), + heavy_hits.load()); + lock.lock(); + heavy_schedule.written(now); + } + } + + // At device teardown, with no build running: stop the writer and write what is still unwritten. + void finish_heavy_cache() { + { + std::lock_guard lock(heavy_mutex); + heavy_stop = true; + } + heavy_wake.notify_all(); + if (heavy_writer.joinable()) heavy_writer.join(); + if (!heavy_cache_handle) return; + if (heavy_schedule.dirty() && !active_compiles.load()) + save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), + heavy_hits.load()); + context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr); + heavy_cache_handle = VK_NULL_HANDLE; + } + + // vkCreate*Pipelines through `create(cache, flags)`. With the heavy cache, the offline cache is asked first + // without compiling; a pipeline it does not have is built against the heavy cache, which a slow build then + // writes back to disk. A caller that already asked for a cache-only create keeps exactly that. + template + VkResult create_pipeline(VkPipelineCreateFlags flags, Create&& create) { + constexpr VkPipelineCreateFlags cache_only = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; + const VkPipelineCache corpus = pipeline_cache(); + if (!info.heavy_pipeline_cache || (flags & cache_only)) return create(corpus, flags); + const VkResult cached = create(corpus, flags | cache_only); + if (cached != VK_PIPELINE_COMPILE_REQUIRED) return cached; + const VkPipelineCache heavy = heavy_cache(); + const ULONGLONG started = GetTickCount64(); + const VkResult built = create(heavy ? heavy : corpus, flags); + if (built == VK_SUCCESS && heavy) note_heavy_build(GetTickCount64() - started); + return built; + } + QueueClock clock; // device-wide calibration entry points std::vector timestamp_bits; @@ -9145,7 +9320,12 @@ class PipelineState final CompileTrace trace; trace.begin(pipeline_info, device_.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, cache_key_); const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); - const VkResult created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); + const VkPipelineCreateFlags flags = pipeline_info.flags; + const VkResult created = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { + pipeline_info.flags = f; + built = VK_NULL_HANDLE; + return vk.vkCreateComputePipelines(dev, with, 1, &pipeline_info, nullptr, &built); + }); profile.finish(int(created)); trace.end(trigger, entry->name.c_str(), 0, bytes, created); if (big_lock.owns_lock()) big_lock.unlock(); @@ -9455,7 +9635,11 @@ class PipelineState final trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", program, fragment, unbound); - const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); + const auto result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { + info.flags = f; + pipeline = VK_NULL_HANDLE; + return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline); + }); if (status) *status = result; profile.finish(int(result)); trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); @@ -11571,6 +11755,7 @@ class Device final vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } + state_.finish_heavy_cache(); if (state_.pipeline_cache_handle) { // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. @@ -17810,8 +17995,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin v13.compute_full_subgroups, info.subgroup); const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; - v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; - info.cold_graphics_compile = v13.enable_pipeline_cache_control; + // pipelineCreationCacheControl: for LEONIDA_PIPELINE_COMPILE=cache-only, and for the heavy pipeline cache unless + // LEONIDA_HEAVY_PIPELINE_CACHE_MS=0 turns it off. + v13.enable_pipeline_cache_control = + (mode == "cache-only" || heavy_pipeline_cache_ms()) && v13.core && v13.pipeline_cache_control; + info.cold_graphics_compile = mode == "cache-only" && v13.enable_pipeline_cache_control; + info.heavy_pipeline_cache = heavy_pipeline_cache_ms() && v13.enable_pipeline_cache_control; info.prepare_on_bind = mode == "on-demand"; void* v13_chain = v13.enable(ext_chain); // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. diff --git a/runtime/src/heavy_pipeline_cache.h b/runtime/src/heavy_pipeline_cache.h new file mode 100644 index 0000000000..d8ca04e2d0 --- /dev/null +++ b/runtime/src/heavy_pipeline_cache.h @@ -0,0 +1,73 @@ +// A pipeline cache that survives a crash, for the pipelines the offline corpus does not have (RT-HEAVY-PIPELINE-CACHE). +// +// The offline seed (pipeline_cache.bin, several GiB) covers what the `pipelines` build stage creates. A pipeline it +// misses is compiled on the spot, and some of those take the driver seconds each. pipeline_cache.session.bin cannot +// keep them across a crash: it is written at device teardown only, and a cache seeded from the corpus returns the +// whole corpus, over its write limit, so it is not written at all. +// +// So a pipeline is first created against the corpus cache with VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED. +// When the driver would have to compile, it is created again against a cache of its own, seeded from +// pipeline_cache.heavy.bin. That cache holds only the corpus's misses, so it stays small. After a compile that took +// at least LEONIDA_HEAVY_PIPELINE_CACHE_MS (default 500 ms), it is written back to disk on a thread of its own: a +// staging file renamed over the old one, so a crash at any point leaves the last complete file. +// +// This header holds the pure decisions (the threshold and when to write). Vulkan and the file live in the device. +#pragma once + +#include +#include + +namespace leonida::heavy_pipeline_cache { + +inline constexpr std::uint32_t default_threshold_ms = 500; + +struct Threshold { + std::uint32_t ms = default_threshold_ms; // 0: off + bool valid = true; // false: the text was not a number; ms stays the default +}; + +// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write; 0 turns the heavy cache off. +inline Threshold parse_threshold(const char* text) { + if (!text || !*text) return {}; + std::uint64_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_threshold_ms, false}; + value = value * 10 + std::uint64_t(*p - '0'); + if (value > 3'600'000) return {default_threshold_ms, false}; // an hour: past it the text is a mistake + } + return {std::uint32_t(value), true}; +} + +// When the writer thread writes. A heavy compile marks the cache dirty; the write waits `settle_ms` after the +// newest one (heavy compiles come in bursts at a load, and each write copies the whole heavy cache) but never more +// than `max_delay_ms` after the first unwritten one, so a long burst is still saved as it goes. +class WriteSchedule { +public: + static constexpr std::uint64_t settle_ms = 3000; + static constexpr std::uint64_t max_delay_ms = 20000; + + void note_heavy(std::uint64_t now_ms) { + if (!dirty_) first_ = now_ms; + dirty_ = true; + last_ = now_ms; + } + bool dirty() const { return dirty_; } + // The time to write at; only meaningful while dirty. + std::uint64_t due_ms() const { + const std::uint64_t settled = last_ + settle_ms, latest = first_ + max_delay_ms; + return settled < latest ? settled : latest; + } + bool due(std::uint64_t now_ms) const { return dirty_ && now_ms >= due_ms(); } + // A write started at `started_ms` took the cache as it was then: a heavy compile noted later than that keeps + // the cache dirty for the next write. + void written(std::uint64_t started_ms) { + if (last_ <= started_ms) dirty_ = false; + else first_ = started_ms; + } + +private: + bool dirty_ = false; + std::uint64_t first_ = 0, last_ = 0; +}; + +} // namespace leonida::heavy_pipeline_cache diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 2d9bc5212e..5a2eb5a243 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -149,6 +149,7 @@ int main(int argc, char** argv) { rt::d3d12::VulkanDeviceInfo info{}; info.prepare_on_bind=d.prepare_on_bind; info.cold_graphics_compile=d.cold_graphics_compile; + info.heavy_pipeline_cache=d.heavy_pipeline_cache; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 5601102409..b45cc2c841 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -193,6 +193,7 @@ int main(int argc, char** argv) { rt::d3d12::VulkanDeviceInfo info{}; info.prepare_on_bind=d.prepare_on_bind; info.cold_graphics_compile=d.cold_graphics_compile; + info.heavy_pipeline_cache=d.heavy_pipeline_cache; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp new file mode 100644 index 0000000000..36ff27ad24 --- /dev/null +++ b/runtime/test/heavy_pipeline_cache_test.cpp @@ -0,0 +1,68 @@ +// src/heavy_pipeline_cache.h: the LEONIDA_HEAVY_PIPELINE_CACHE_MS threshold and when the heavy cache is written. +// No Vulkan, no GPU, no files. +#include "../src/heavy_pipeline_cache.h" + +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace heavy = leonida::heavy_pipeline_cache; + +static int test_threshold() { + CHECK(heavy::parse_threshold(nullptr).ms == heavy::default_threshold_ms); + CHECK(heavy::parse_threshold("").ms == heavy::default_threshold_ms); + CHECK(heavy::parse_threshold("0").ms == 0 && heavy::parse_threshold("0").valid); // off + CHECK(heavy::parse_threshold("2000").ms == 2000); + CHECK(heavy::parse_threshold("0750").ms == 750); + // Not a number, a sign, a unit or an absurd value: the default, reported as invalid. + for (const char* bad : {"-1", "+5", "1s", "1.5", "abc", "3600001", "99999999999999999999"}) { + const auto t = heavy::parse_threshold(bad); + CHECK(!t.valid && t.ms == heavy::default_threshold_ms); + } + CHECK(heavy::parse_threshold("3600000").valid); + return 0; +} + +static int test_schedule() { + using S = heavy::WriteSchedule; + S s; + CHECK(!s.dirty() && !s.due(1'000'000)); + // One heavy compile: written once it has settled. + s.note_heavy(1000); + CHECK(s.dirty() && !s.due(1000 + S::settle_ms - 1) && s.due(1000 + S::settle_ms)); + s.written(1000 + S::settle_ms); + CHECK(!s.dirty()); + // A burst, one compile a second for a minute: the write does not wait for the burst to end. + S burst; + for (std::uint64_t t = 10'000; t <= 70'000; t += 1000) { + burst.note_heavy(t); + if (burst.due(t)) { + CHECK(t - 10'000 >= S::max_delay_ms); // first write no later than max_delay after the first compile + burst.written(t); + break; + } + } + CHECK(!burst.dirty()); + // A compile that finishes while a write is running is not lost: the cache stays dirty for the next write. + S racing; + racing.note_heavy(5000); + const std::uint64_t start = 5000 + S::settle_ms; + racing.note_heavy(start + 10); // during the write + racing.written(start); + CHECK(racing.dirty()); + CHECK(racing.due(start + 10 + S::settle_ms)); + return 0; +} + +int main() { + if (const int r = test_threshold()) return r; + if (const int r = test_schedule()) return r; + std::printf("heavy_pipeline_cache: threshold parsing and the write schedule\n"); + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index fd63fca665..f0b9081557 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -123,6 +123,7 @@ class Device { bool occlusion_query_precise = false; // occlusionQueryPrecise enabled bool prepare_on_bind=false; bool cold_graphics_compile = false; + bool heavy_pipeline_cache = false; // LEONIDA_HEAVY_PIPELINE_CACHE_MS set and pipelineCreationCacheControl on bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled bool request_multi_draw_indirect = false, request_draw_indirect_count = false; bool draw_indirect_count_enabled = false; @@ -408,8 +409,13 @@ class Device { // (zero-based VS ids) is in; harmless before. const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; - v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; - cold_graphics_compile = v13_.enable_pipeline_cache_control; + // LEONIDA_HEAVY_PIPELINE_CACHE_MS other than 0: the heavy pipeline cache path, as the runtime takes it by default + // (src/heavy_pipeline_cache.h). Tests leave it off unless asked. + const char* heavy_ms = std::getenv("LEONIDA_HEAVY_PIPELINE_CACHE_MS"); + const bool heavy = heavy_ms && *heavy_ms && std::strcmp(heavy_ms, "0") != 0; + v13_.enable_pipeline_cache_control = (cache_only || heavy) && v13_.core && v13_.pipeline_cache_control; + cold_graphics_compile = cache_only && v13_.enable_pipeline_cache_control; + heavy_pipeline_cache = heavy && v13_.enable_pipeline_cache_control; prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; From e4c413a3a5fe18b99ede727d02b9a561fc8ca56e Mon Sep 17 00:00:00 2001 From: kawaii-shakal Date: Wed, 25 Nov 2026 20:57:43 +0500 Subject: [PATCH 2/3] heavy pipeline cache: a write covers what was noted before it started, counted, not timed; teardown keeps fast builds too GetTickCount64 moves in 10-16 ms steps, so a slow build noted during a write in the write's own tick was taken as written. The schedule now counts notes. And without an offline seed every build goes to the heavy cache: fast ones never schedule a write, so teardown writes the cache whenever any build went into it, which is what pipeline_cache.session.bin used to keep. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 5 +++-- runtime/shims/d3d12_vulkan_device.cpp | 11 ++++++++--- runtime/src/heavy_pipeline_cache.h | 13 ++++++++----- runtime/test/heavy_pipeline_cache_test.cpp | 15 ++++++++++++--- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 772cd2e600..4afb78d2ff 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2368,8 +2368,9 @@ Pipeline creation: A build that takes at least `LEONIDA_HEAVY_PIPELINE_CACHE_MS` (500 by default) marks the heavy cache for writing. A thread of its own writes it whole: 3 s after the newest slow build, and no later than 20 s after the first unwritten one, through the same staging file and rename as the session cache. A crash therefore loses at most the last 20 s - of slow builds, and the next launch starts with the rest. The thread stops and writes what is left at device - teardown. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the + of slow builds, and the next launch starts with the rest. At device teardown the thread stops, and the cache is + written if any build went into it. Fast builds are kept that way: without an offline seed every build is a miss, + so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create (`cache-only`) is left as it is. `LEONIDA_SKIP_COMPUTE=[,...]` (`all`: every compute program) never builds the matching diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index ca029d60b2..5c4548433e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2081,6 +2081,7 @@ struct DeviceState { bool heavy_stop = false; // under heavy_mutex std::thread heavy_writer; // started at the first slow build std::atomic heavy_compiles{0}, heavy_hits{0}; + std::atomic heavy_changed{false}; // a build went into the heavy cache since it was loaded VkPipelineCache heavy_cache() { std::call_once(heavy_cache_once, [this] { @@ -2092,6 +2093,7 @@ struct DeviceState { // A build past the offline cache took `took_ms`: a slow one schedules a write. void note_heavy_build(ULONGLONG took_ms) { + heavy_changed = true; if (took_ms < heavy_pipeline_cache_ms()) { ++heavy_hits; return; @@ -2123,15 +2125,18 @@ struct DeviceState { heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now)); continue; } + const std::uint64_t generation = heavy_schedule.generation(); lock.unlock(); save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), heavy_hits.load()); lock.lock(); - heavy_schedule.written(now); + heavy_schedule.written(generation, now); } } - // At device teardown, with no build running: stop the writer and write what is still unwritten. + // At device teardown, with no build running: stop the writer and write the cache if any build went into it. + // Fast builds never schedule a write, so this is where they are kept: without an offline seed every build is + // a miss, and these are the builds pipeline_cache.session.bin used to keep. void finish_heavy_cache() { { std::lock_guard lock(heavy_mutex); @@ -2140,7 +2145,7 @@ struct DeviceState { heavy_wake.notify_all(); if (heavy_writer.joinable()) heavy_writer.join(); if (!heavy_cache_handle) return; - if (heavy_schedule.dirty() && !active_compiles.load()) + if (heavy_changed.load() && !active_compiles.load()) save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), heavy_hits.load()); context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr); diff --git a/runtime/src/heavy_pipeline_cache.h b/runtime/src/heavy_pipeline_cache.h index d8ca04e2d0..f7b55aebc6 100644 --- a/runtime/src/heavy_pipeline_cache.h +++ b/runtime/src/heavy_pipeline_cache.h @@ -50,6 +50,7 @@ class WriteSchedule { if (!dirty_) first_ = now_ms; dirty_ = true; last_ = now_ms; + ++generation_; } bool dirty() const { return dirty_; } // The time to write at; only meaningful while dirty. @@ -58,16 +59,18 @@ class WriteSchedule { return settled < latest ? settled : latest; } bool due(std::uint64_t now_ms) const { return dirty_ && now_ms >= due_ms(); } - // A write started at `started_ms` took the cache as it was then: a heavy compile noted later than that keeps - // the cache dirty for the next write. - void written(std::uint64_t started_ms) { - if (last_ <= started_ms) dirty_ = false; + // Taken when a write starts; the write covers every heavy compile noted up to then. + std::uint64_t generation() const { return generation_; } + // A write that started at `generation` and `started_ms` is done. A heavy compile noted after it started, even in + // the same millisecond tick, keeps the cache dirty for the next write, due as if it were first noted then. + void written(std::uint64_t generation, std::uint64_t started_ms) { + if (generation_ == generation) dirty_ = false; else first_ = started_ms; } private: bool dirty_ = false; - std::uint64_t first_ = 0, last_ = 0; + std::uint64_t first_ = 0, last_ = 0, generation_ = 0; }; } // namespace leonida::heavy_pipeline_cache diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp index 36ff27ad24..fe1a350817 100644 --- a/runtime/test/heavy_pipeline_cache_test.cpp +++ b/runtime/test/heavy_pipeline_cache_test.cpp @@ -36,7 +36,7 @@ static int test_schedule() { // One heavy compile: written once it has settled. s.note_heavy(1000); CHECK(s.dirty() && !s.due(1000 + S::settle_ms - 1) && s.due(1000 + S::settle_ms)); - s.written(1000 + S::settle_ms); + s.written(s.generation(), 1000 + S::settle_ms); CHECK(!s.dirty()); // A burst, one compile a second for a minute: the write does not wait for the burst to end. S burst; @@ -44,7 +44,7 @@ static int test_schedule() { burst.note_heavy(t); if (burst.due(t)) { CHECK(t - 10'000 >= S::max_delay_ms); // first write no later than max_delay after the first compile - burst.written(t); + burst.written(burst.generation(), t); break; } } @@ -53,10 +53,19 @@ static int test_schedule() { S racing; racing.note_heavy(5000); const std::uint64_t start = 5000 + S::settle_ms; + const std::uint64_t taken = racing.generation(); racing.note_heavy(start + 10); // during the write - racing.written(start); + racing.written(taken, start); CHECK(racing.dirty()); CHECK(racing.due(start + 10 + S::settle_ms)); + // The same, inside one tick of a coarse clock: the compile noted at the write's own start time is still kept. + S tick; + tick.note_heavy(9000); + const std::uint64_t at = 9000 + S::settle_ms; + const std::uint64_t before = tick.generation(); + tick.note_heavy(at); + tick.written(before, at); + CHECK(tick.dirty()); return 0; } From aab7653566e4ecf80a8026cfbd48e74966a4d04c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 22:10:37 +0000 Subject: [PATCH 3/3] d3d12: retry a failed heavy cache write and never publish a VK_INCOMPLETE snapshot Review of RT-HEAVY-PIPELINE-CACHE: - The writer thread marked a generation written even when the save failed, so the cache stayed unsaved until teardown. A failed save now keeps the cache dirty and is retried after a bounded backoff (5 s, doubling, capped at 2 min), so a write that keeps failing does not spin. WriteSchedule::failed() holds that decision and heavy_pipeline_cache_test checks it. - save_heavy_pipeline_cache accepted VK_INCOMPLETE and published the truncated blob over a complete file. It now requires VK_SUCCESS, like the session cache, and keeps the previous file; the next try queries a fresh size. Changes made by Claude Code (AI-assisted). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JPqXc6svM4pbBagTsVEYA3 --- docs/d3d12_vulkan.md | 6 +++- runtime/shims/d3d12_vulkan_device.cpp | 14 +++++---- runtime/src/heavy_pipeline_cache.h | 22 ++++++++++++-- runtime/test/heavy_pipeline_cache_test.cpp | 34 +++++++++++++++++++++- 4 files changed, 67 insertions(+), 9 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index fc11cc0c75..4640850c9a 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2392,7 +2392,11 @@ Pipeline creation: A build that takes at least `LEONIDA_HEAVY_PIPELINE_CACHE_MS` (500 by default) marks the heavy cache for writing. A thread of its own writes it whole: 3 s after the newest slow build, and no later than 20 s after the first unwritten one, through the same staging file and rename as the session cache. A crash therefore loses at most the last 20 s - of slow builds, and the next launch starts with the rest. At device teardown the thread stops, and the cache is + of slow builds, and the next launch starts with the rest. A write that fails, or whose + `vkGetPipelineCacheData` returns anything but `VK_SUCCESS` (`VK_INCOMPLETE` means the cache grew after the size + query, so the blob is truncated), leaves the previous file in place and the cache dirty: it is tried again 5 s + later, the delay doubling with each failure in a row up to 2 min, so the cache is not left unsaved until teardown + and a write that keeps failing does not spin. At device teardown the thread stops, and the cache is written if any build went into it. Fast builds are kept that way: without an offline seed every build is a miss, so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 214edbaea4..675070f7f3 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1530,8 +1530,10 @@ bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevic } auto written = size; const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); - const bool ok = (result == VK_SUCCESS || result == VK_INCOMPLETE) && - written > sizeof(VkPipelineCacheHeaderVersionOne) && staging.publish(path, written); + // VK_INCOMPLETE means the cache grew after the size query and the blob is a truncated snapshot; it must not + // replace a complete file. The writer tries again later with a fresh size. + const bool ok = result == VK_SUCCESS && written > sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && + staging.publish(path, written); if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds " "and %llu other builds past the offline cache so far)\n", @@ -2184,10 +2186,12 @@ struct DeviceState { } const std::uint64_t generation = heavy_schedule.generation(); lock.unlock(); - save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), - heavy_hits.load()); + const bool saved = save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, + heavy_compiles.load(), heavy_hits.load()); lock.lock(); - heavy_schedule.written(generation, now); + // A failed write leaves the cache dirty: it is tried again after a growing delay, not only at teardown. + if (saved) heavy_schedule.written(generation, now); + else heavy_schedule.failed(now); } } diff --git a/runtime/src/heavy_pipeline_cache.h b/runtime/src/heavy_pipeline_cache.h index f7b55aebc6..8cad10e660 100644 --- a/runtime/src/heavy_pipeline_cache.h +++ b/runtime/src/heavy_pipeline_cache.h @@ -40,11 +40,15 @@ inline Threshold parse_threshold(const char* text) { // When the writer thread writes. A heavy compile marks the cache dirty; the write waits `settle_ms` after the // newest one (heavy compiles come in bursts at a load, and each write copies the whole heavy cache) but never more -// than `max_delay_ms` after the first unwritten one, so a long burst is still saved as it goes. +// than `max_delay_ms` after the first unwritten one, so a long burst is still saved as it goes. A write that fails +// keeps the cache dirty and is tried again `retry_ms` later, the delay doubling with each failure in a row up to +// `max_retry_ms`, so a disk that stays full or a driver that keeps failing does not make the writer spin. class WriteSchedule { public: static constexpr std::uint64_t settle_ms = 3000; static constexpr std::uint64_t max_delay_ms = 20000; + static constexpr std::uint64_t retry_ms = 5000; + static constexpr std::uint64_t max_retry_ms = 120000; void note_heavy(std::uint64_t now_ms) { if (!dirty_) first_ = now_ms; @@ -56,7 +60,8 @@ class WriteSchedule { // The time to write at; only meaningful while dirty. std::uint64_t due_ms() const { const std::uint64_t settled = last_ + settle_ms, latest = first_ + max_delay_ms; - return settled < latest ? settled : latest; + const std::uint64_t at = settled < latest ? settled : latest; + return at > retry_at_ ? at : retry_at_; } bool due(std::uint64_t now_ms) const { return dirty_ && now_ms >= due_ms(); } // Taken when a write starts; the write covers every heavy compile noted up to then. @@ -64,13 +69,26 @@ class WriteSchedule { // A write that started at `generation` and `started_ms` is done. A heavy compile noted after it started, even in // the same millisecond tick, keeps the cache dirty for the next write, due as if it were first noted then. void written(std::uint64_t generation, std::uint64_t started_ms) { + failures_ = 0; + retry_at_ = 0; if (generation_ == generation) dirty_ = false; else first_ = started_ms; } + // A write that started at `started_ms` failed: the cache stays dirty and the next try waits out the backoff. + void failed(std::uint64_t started_ms) { + std::uint64_t delay = retry_ms; + for (std::uint32_t i = 0; i < failures_ && delay < max_retry_ms; ++i) delay *= 2; + if (delay > max_retry_ms) delay = max_retry_ms; + if (failures_ < 64) ++failures_; + retry_at_ = started_ms + delay; + } + std::uint32_t failures() const { return failures_; } private: bool dirty_ = false; std::uint64_t first_ = 0, last_ = 0, generation_ = 0; + std::uint32_t failures_ = 0; // failed writes in a row + std::uint64_t retry_at_ = 0; // no write before this time after a failure }; } // namespace leonida::heavy_pipeline_cache diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp index fe1a350817..8181a047cd 100644 --- a/runtime/test/heavy_pipeline_cache_test.cpp +++ b/runtime/test/heavy_pipeline_cache_test.cpp @@ -69,9 +69,41 @@ static int test_schedule() { return 0; } +static int test_failed_write() { + using S = heavy::WriteSchedule; + S s; + s.note_heavy(1000); + std::uint64_t now = 1000 + S::settle_ms; + CHECK(s.due(now)); + // A failed write keeps the cache dirty and waits out the backoff before the next try. + s.failed(now); + CHECK(s.dirty() && s.failures() == 1); + CHECK(!s.due(now) && !s.due(now + S::retry_ms - 1) && s.due(now + S::retry_ms)); + // Failures in a row double the delay up to the cap, so a write that keeps failing does not spin. + std::uint64_t expect = S::retry_ms; + for (int i = 0; i < 12; ++i) { + now = s.due_ms(); + s.failed(now); + expect = expect * 2 > S::max_retry_ms ? S::max_retry_ms : expect * 2; + CHECK(s.due_ms() == now + expect); + } + CHECK(s.due_ms() - now == S::max_retry_ms); + // A heavy compile during the backoff does not bring the retry forward. + s.note_heavy(now + 1); + CHECK(!s.due(now + S::settle_ms + 1) && s.due(now + S::max_retry_ms)); + // A successful write clears the dirty flag and the backoff. + now = s.due_ms(); + s.written(s.generation(), now); + CHECK(!s.dirty() && s.failures() == 0); + s.note_heavy(now + 10); + CHECK(s.due(now + 10 + S::settle_ms)); + return 0; +} + int main() { if (const int r = test_threshold()) return r; if (const int r = test_schedule()) return r; - std::printf("heavy_pipeline_cache: threshold parsing and the write schedule\n"); + if (const int r = test_failed_write()) return r; + std::printf("heavy_pipeline_cache: threshold parsing, the write schedule and retries after a failed write\n"); return 0; }