diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..33550d9103 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2748,7 +2748,7 @@ Pipeline creation: folders can share one; the file names and the driver's checks keep a pipeline from one build from being taken for another's. `gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--all] [--smallest-first] [--limit N] - [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list]` fills the journal ahead of play, with + [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list | --verify]` fills the journal ahead of play, with no game: it creates the Vulkan device as `--run` does (so the same environment gives the same journal names and driver keys: LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, and LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, whose diagnostics config @@ -2772,6 +2772,19 @@ Pipeline creation: took them all from the journal (none built in the game) and ended as runs with the skip list do, in an idle-queue device loss or a stop with the GPU idle ([running.md](running.md#settings-every-platform-needs)); whether their output is correct is not measured. + After precompiling, run `gta6rt --precompile-pipelines --verify` in a fresh process with the same environment + and selection flags. It reads each selected compute pipeline's local journal file into a separate Vulkan cache + and asks the driver to create that pipeline with `FAIL_ON_PIPELINE_COMPILE_REQUIRED`. A verified entry requires a + successful creation and valid, pipeline-level `APPLICATION_PIPELINE_CACHE_HIT` feedback for that cache. A driver + may return a pipeline without confirming a hit. That entry counts as unverified, as does a response that + compilation is required. [Vulkan pipeline creation feedback](https://docs.vulkan.org/refpages/latest/refpages/source/VkPipelineCreationFeedbackFlagBits.html) + The verifier makes one probe per selected entry with a usable local file, bypassing the shared and external seed + caches, helpers, journal writes, LRU touches and eviction. It exits 0 for a nonempty selection of verified + entries, 2 for an empty selection or any missing, unusable, unverified or failed entry, and 1 when setup fails + (including disabled journaling or unavailable cache control). After name and explicit `--skip-listed` filtering, a missing or empty + module counts as an input error before size filters and leaves the `--limit` slots available for buildable + entries. The summary includes counts for filtered, unbuildable and explicitly skipped entries. To test on generated inputs, run + `python -I scripts/check_precompile_verify.py --require-hit`. `LEONIDA_COMPILE_HELPER=1` (`shims/d3d12_compile_helper.h`) keeps first-ever compiles out of the title's process: the driver's locks, which a long `vkCreateComputePipelines` holds and a `vkQueueSubmit` of the same process waits for, are per process. A compute build of `LEONIDA_COMPILE_HELPER_MIN_BYTES` or more (128 KiB) with no journal file diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 11736c83d2..8511ce9665 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4541,6 +4541,11 @@ if(TARGET Vulkan::Headers) RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" ) if(Python3_FOUND) + if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING) + add_test(NAME precompile_verify COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/check_precompile_verify.py" "$") + set_tests_properties(precompile_verify PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 240) + endif() add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" "$" "--probe=$" ${_trace_runner}) diff --git a/runtime/shims/d3d12_precompile.h b/runtime/shims/d3d12_precompile.h index ca96bb764a..0c601d682b 100644 --- a/runtime/shims/d3d12_precompile.h +++ b/runtime/shims/d3d12_precompile.h @@ -32,6 +32,7 @@ struct PrecompileOptions { std::vector filters; // only entries whose name contains one of these bool skip_listed = false; // --skip-listed: leave out the entries LEONIDA_SKIP_COMPUTE names bool dry_run = false; // --list: print the plan, build nothing + bool verify = false; // --verify: require a driver-reported hit from each local journal file bool via_helper = false; // --via-helper: as a title does with LEONIDA_COMPILE_HELPER=1 (a test) }; @@ -45,7 +46,7 @@ struct CompileServerOptions { int compile_server(const CompileServerOptions& options); // Returns 0 when every selected entry was built or already journaled, 2 when some could not be built, 1 when the -// device or the library could not be had. +// device or the library could not be had. Verification returns 0 only for a nonempty selection of confirmed hits. int precompile_compute_pipelines(const PrecompileOptions& options); } // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index de623b6040..d6b9bd9a8e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1742,14 +1742,16 @@ std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) { // The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. // LEONIDA_PIPELINE_CACHE_DIR= keeps it there instead, so several builds of gta6rt share one warmed cache. -std::filesystem::path pipeline_cache_path() { +std::filesystem::path pipeline_cache_path(bool create_directory = true) { { std::wstring dir(32768, L'\0'); const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", dir.data(), static_cast(dir.size())); if (n > 0 && n < dir.size()) { dir.resize(n); - std::error_code ec; - std::filesystem::create_directories(dir, ec); + if (create_directory) { + std::error_code ec; + std::filesystem::create_directories(dir, ec); + } return std::filesystem::path(dir) / L"pipeline_cache.bin"; } } @@ -1899,7 +1901,7 @@ const leonida::pipeline_journal::Roots& pipeline_journal_roots() { if (GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL", value, 2) == 1 && value[0] == L'0') return {}; if (!pipeline_cache_save_limit()) return {}; - std::filesystem::path path = pipeline_cache_path(); + std::filesystem::path path = pipeline_cache_path(false); // naming a journal file needs no writes if (!path.empty()) path.replace_filename(L"pipeline_cache.d"); std::wstring seed(32768, L'\0'); const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_SEED_DIR", seed.data(), @@ -1938,14 +1940,15 @@ std::size_t pipeline_cache_save_limit() { // and deny writers while the view is in use. class PipelineCacheSeed { public: - explicit PipelineCacheSeed(const std::filesystem::path& path) { + explicit PipelineCacheSeed(const std::filesystem::path& path, std::size_t limit = SIZE_MAX) { if (path.empty()) return; file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file_ == INVALID_HANDLE_VALUE) return; LARGE_INTEGER length{}; constexpr auto header_size = static_cast(sizeof(VkPipelineCacheHeaderVersionOne)); - if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size) + if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size || + static_cast(length.QuadPart) > limit) return; const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); if (!mapping) return; @@ -11726,6 +11729,8 @@ class JournalCache { VkResult result_ = VK_SUCCESS; }; +enum class JournalProbe { error, missing_or_unusable, unverified, verified }; + // What one compute pipeline build did (build_compute_pipeline). struct ComputeBuild { VkPipeline pipeline = VK_NULL_HANDLE; // the caller's from here on @@ -11739,6 +11744,7 @@ struct ComputeBuild { bool journal_hit = false; // found in its journal file bool journaled = false; // compiled and written to its journal file bool from_shared = false; // found in the shared cache + JournalProbe probe = JournalProbe::error; // --verify only; early failures never count as hits }; struct ComputeBuildOptions { @@ -11751,8 +11757,46 @@ struct ComputeBuildOptions { std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size bool mark_building = false; // precompile, helper: claim the entry, skip it when another process has it bool key_only = false; // only name the journal file (journal_path), build nothing + bool verify = false; // probe this file alone, without upkeep, publishing or fallback }; +// Probe exactly one local application cache. Only a successful creation with valid application-hit feedback +// identifies the supplied cache as useful. A driver can succeed using its internal cache without setting that bit. +void probe_compute_journal(DeviceState& device, const std::vector& words, + VkComputePipelineCreateInfo pipeline_info, ComputeBuild& out) { + // Take size, header and payload from one handle, even if a concurrent writer replaces this entry. + const PipelineCacheSeed file(out.journal_path, leonida::pipeline_journal::entry_read_limit); + if (file.size() <= leonida::pipeline_cache_store::header_bytes || !file.compatible(device.pso_identity)) { + out.probe = JournalProbe::missing_or_unusable; + return; + } + auto& vk = device.context->vk; + const VkDevice dev = device.info.device; + VkPipelineCache cache = VK_NULL_HANDLE; + const VkPipelineCacheCreateInfo seed{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, + file.size(), file.data()}; + out.result = vk.vkCreatePipelineCache(dev, &seed, nullptr, &cache); + if (out.result != VK_SUCCESS) return; + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * sizeof(words[0]); + module_info.pCode = words.data(); + out.result = vk.vkCreateShaderModule(dev, &module_info, nullptr, &pipeline_info.stage.module); + if (out.result == VK_SUCCESS) { + CompileTrace feedback; + feedback.request_feedback(pipeline_info); + pipeline_info.flags |= VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; + VkPipeline pipeline = VK_NULL_HANDLE; + out.result = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline); + if (out.result == VK_SUCCESS && pipeline) + out.probe = feedback.hit() == 1 ? JournalProbe::verified : JournalProbe::unverified; + else if (out.result == VK_PIPELINE_COMPILE_REQUIRED) + out.probe = JournalProbe::unverified; + if (pipeline) vk.vkDestroyPipeline(dev, pipeline, nullptr); + vk.vkDestroyShaderModule(dev, pipeline_info.stage.module, nullptr); + } + vk.vkDestroyPipelineCache(dev, cache, nullptr); +} + // A compute pipeline from a library entry: what a PSO's first dispatch, the warm-up worker and gta6rt // --precompile-pipelines all build, so their journal names and the driver's keys are the same. `layout` is the push // range of leonida::ShaderUserData, with the device's bindless set 0 when the entry declares bindings; `subgroup` is @@ -11796,7 +11840,8 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage); pipeline_info.layout = layout; pipeline_info.flags |= fast_pipeline_flags(true); // before the journal key, which hashes the flags - const VkPipelineCache shared = device.pipeline_cache(); + // pipeline_cache() also runs upkeep and may start a helper. The verifier uses only the named file. + const VkPipelineCache shared = options.verify ? VK_NULL_HANDLE : device.pipeline_cache(); auto& submits = device.context->submit_mutex(); // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): the pipeline is created against its own cache, made @@ -11823,9 +11868,15 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn key.value(std::uint32_t(leonida::aftermath::extra_config_flags())); } if (entry->binding_count) hash_bindless_layout(key, device.bindless->features()); - const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest()); - out.journal_path = path; - if (options.key_only) return out; + out.journal_path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest()); + } + if (options.verify) { + if (!out.journal_path.empty()) probe_compute_journal(device, words, pipeline_info, out); + return out; + } + if (options.key_only) return out; + if (!out.journal_path.empty()) { + const auto& path = out.journal_path; // Precompile: a usable file is there already, so the pipeline is not built (only its header is read). if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) { out.skipped = true; @@ -23445,7 +23496,7 @@ class BuildHost { d3d_->Release(); } - bool open() { + bool open(bool verify = false) { // The GPU address arena holds nothing here and does not change a pipeline: 64 MB, not a title's 2 GB. _putenv_s("LEONIDA_ARENA_MB", "64"); compile_helper::build_host = true; @@ -23464,13 +23515,25 @@ class BuildHost { std::fprintf(stderr, "%s no translated shader library (LEONIDA_SHADERS)\n", tag_); return false; } - if (pipeline_journal_dir().empty()) - std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or " - "LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_); - state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline - // Every pipeline goes into a journal file: one found in the shared cache would not be. - state.journal_ask_shared = false; auto& vk = state.context->vk; + if (verify) { + if (pipeline_journal_dir().empty()) { + std::fprintf(stderr, "%s verification requires an enabled local pipeline journal\n", tag_); + return false; + } + if (!state.info.pipeline_cache_control || !state.info.pipeline_creation_feedback || + !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) { + std::fprintf(stderr, "%s verification requires enabled pipelineCreationCacheControl and " + "pipeline creation feedback\n", tag_); + return false; + } + } else { + if (pipeline_journal_dir().empty()) + std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or " + "LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_); + state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline + state.journal_ask_shared = false; // every pipeline goes into its own journal file + } const VkDevice dev = state.info.device; if (state.info.max_push_constants_size && state.info.max_push_constants_size < sizeof(leonida::ShaderUserData)) { std::fprintf(stderr, "%s maxPushConstantsSize %u is under the shaders' %zu bytes: the runtime builds no " @@ -23536,7 +23599,7 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { using Clock = std::chrono::steady_clock; const auto began = Clock::now(); BuildHost host("[precompile]"); - if (!host.open()) return 1; + if (!host.open(options.verify)) return 1; const leonida::ShaderLibrary* library = host.library(); // What to build: every compute entry the runtime could create a pipeline for. LEONIDA_SKIP_COMPUTE is a setting @@ -23547,7 +23610,7 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { std::size_t bytes; }; std::vector jobs; - std::size_t not_buildable = 0, filtered = 0, listed = 0, listed_left_out = 0; + std::size_t not_buildable = 0, filtered = 0, listed = 0, listed_left_out = 0, input_errors = 0; for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) { if (!options.filters.empty() && std::none_of(options.filters.begin(), options.filters.end(), @@ -23556,7 +23619,9 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { continue; } const std::size_t bytes = library->spirv_bytes(*entry); - if ((options.min_bytes && bytes < options.min_bytes) || (options.max_bytes && bytes > options.max_bytes)) { + const bool missing_input = options.verify && !bytes; + if (!missing_input && ((options.min_bytes && bytes < options.min_bytes) || + (options.max_bytes && bytes > options.max_bytes))) { ++filtered; continue; } @@ -23569,6 +23634,12 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { continue; } } + if (missing_input) { + // A missing or empty module has no usable size. Report it without displacing a buildable job at --limit. + ++input_errors; + std::fprintf(stderr, "[precompile] %s: missing, unreadable or empty SPIR-V file\n", entry->name.c_str()); + continue; + } if (const char* why = host.unbuildable(*entry, bytes)) { ++not_buildable; std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why); @@ -23583,6 +23654,33 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { filtered += jobs.size() - options.limit; jobs.resize(options.limit); } + if (options.verify) { + ComputeBuildOptions probe_options; + probe_options.verify = true; + std::size_t verified = 0, missing = 0, unverified = 0, errors = input_errors; + for (const Job& job : jobs) { + ComputeBuild build; + try { + build = host.build(*job.entry, probe_options); + } catch (const std::exception& e) { + std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what()); + } + switch (build.probe) { + case JournalProbe::verified: ++verified; break; + case JournalProbe::missing_or_unusable: ++missing; break; + case JournalProbe::unverified: ++unverified; break; + case JournalProbe::error: ++errors; break; + } + if (build.probe == JournalProbe::error || build.probe == JournalProbe::unverified) + std::fprintf(stderr, "[precompile] %s: %s (VkResult %d)\n", job.entry->name.c_str(), + build.probe == JournalProbe::error ? "probe failed" : "no confirmed application-cache hit", + int(build.result)); + } + std::fprintf(stderr, "[precompile] verify selected=%zu verified=%zu missing_or_unusable=%zu unverified=%zu " + "errors=%zu filtered=%zu not_buildable=%zu skipped_listed=%zu\n", + jobs.size(), verified, missing, unverified, errors, filtered, not_buildable, listed_left_out); + return !jobs.empty() && verified == jobs.size() && !errors ? 0 : 2; + } std::uint64_t total_bytes = 0; for (const Job& job : jobs) total_bytes += job.bytes; const unsigned threads = (std::max)(1u, options.threads); diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index c8545f338e..29625e7490 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -10,7 +10,7 @@ // The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. // // gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] -// [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list] +// [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list | --verify] // No game: creates the Vulkan device as --run does and builds every compute pipeline of the shader library // (LEONIDA_SHADERS) into the pipeline journal and the driver's cache, so a title's first dispatch of a large one // does not stall it. Resumable: entries already journaled are skipped (--all: built anyway). Programs named by @@ -263,7 +263,7 @@ int usage() { " gta6rt --init [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" " gta6rt --first-run-ui [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n" - " gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list] [--via-helper]\n" + " gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first] [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--skip-listed] [--list | --verify] [--via-helper]\n" " gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]\n"); return 2; } @@ -293,6 +293,7 @@ int precompile_main(int argc, wchar_t** argv) { else if (a == L"--smallest-first") options.smallest_first = true; else if (a == L"--skip-listed") options.skip_listed = true; else if (a == L"--list") options.dry_run = true; + else if (a == L"--verify") options.verify = true; else if (a == L"--via-helper") options.via_helper = true; else if (a == L"--filter" && i + 1 < argc) { const std::wstring part = argv[++i]; @@ -300,6 +301,7 @@ int precompile_main(int argc, wchar_t** argv) { } else ok = false; if (!ok) return usage(); } + if (options.verify && (options.dry_run || options.rebuild || options.via_helper)) return usage(); return rt::d3d12::precompile_compute_pipelines(options); } diff --git a/scripts/check_precompile_verify.py b/scripts/check_precompile_verify.py new file mode 100644 index 0000000000..10a6e67698 --- /dev/null +++ b/scripts/check_precompile_verify.py @@ -0,0 +1,178 @@ +"""Exercise gta6rt's offline journal writer and verifier in separate processes using two authored compute shaders.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +from spirv_asm import assemble + + +SHADER = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 1 1 1 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%main = OpFunction %void None %fn +%entry = OpLabel +OpReturn +OpFunctionEnd +""" + +# Write a literal through a device address in the push constants. Unlike the empty shader, this has an +# observable side effect. Both use the runtime's plain compute layout and are never dispatched here. +STORE_SHADER = """OpCapability Shader +OpCapability PhysicalStorageBufferAddresses +OpExtension "SPV_KHR_physical_storage_buffer" +OpMemoryModel PhysicalStorageBuffer64 GLSL450 +OpEntryPoint GLCompute %main "main" %push +OpExecutionMode %main LocalSize 1 1 1 +OpDecorate %args Block +OpMemberDecorate %args 0 Offset 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%address = OpTypeVector %uint 2 +%args = OpTypeStruct %address +%p_args = OpTypePointer PushConstant %args +%p_address = OpTypePointer PushConstant %address +%p_word = OpTypePointer PhysicalStorageBuffer %uint +%zero = OpConstant %uint 0 +%value = OpConstant %uint {value} +%push = OpVariable %p_args PushConstant +%main = OpFunction %void None %fn +%entry = OpLabel +%field = OpAccessChain %p_address %push %zero +%addr = OpLoad %address %field +%dst = OpBitcast %p_word %addr +OpStore %dst %value Aligned 4 +OpReturn +OpFunctionEnd +""" + + +def snapshot(root): + """Include directories, bytes and modification times, so even journal upkeep is observable.""" + return { + p.relative_to(root): (p.stat().st_mtime_ns, hashlib.sha256(p.read_bytes()).digest() if p.is_file() else None) + for p in root.rglob("*") + } + + +def check(exe, root, device, require_hit): + shaders = root / "shaders" + shaders.mkdir() + module = assemble(SHADER, "vulkan1.0") + (shaders / "authored.spv").write_bytes(module) + index = {"authored": {"stage": "cs", "fssm_sha256": hashlib.sha256(module).hexdigest(), "local_size": [1, 1, 1]}} + (shaders / "index.json").write_text(json.dumps(index), encoding="utf-8", newline="\n") + cache = root / "cache" + env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} + env.update(LEONIDA_SHADERS=str(shaders), LEONIDA_PIPELINE_CACHE_DIR=str(cache)) + if device: + env["LEONIDA_VK_DEVICE"] = device + + def run(*args): + return subprocess.run([str(exe), "--precompile-pipelines", *args], cwd=root, env=env, + stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace", timeout=60) + + def verify(*args): + before = snapshot(root) + result = run("--verify", *args) + if snapshot(root) != before: + raise RuntimeError("verification changed the temporary library or cache tree") + return result + + def expect(result, code, summary): + if result.returncode != code or summary not in result.stderr: + raise RuntimeError(f"expected exit {code} and {summary!r}, got {result.returncode}\n{result.stderr}") + + missing = verify() + if missing.returncode == 1 and any(reason in missing.stderr for reason in ( + "the Vulkan device could not be created", "the runtime builds no compute pipeline on this device", + "requires enabled pipelineCreationCacheControl")): + print("SKIP: device cannot run the journal probe") + return 77 + expect(missing, 2, "selected=1 verified=0 missing_or_unusable=1 unverified=0 errors=0") + expect(verify("--filter", "no-such-name"), 2, "selected=0 verified=0") + env["LEONIDA_PIPELINE_JOURNAL"] = "0" + expect(verify(), 1, "verification requires an enabled local pipeline journal") + del env["LEONIDA_PIPELINE_JOURNAL"] + warm = run("--threads", "1") + expect(warm, 0, "0 failed") + files = list((cache / "pipeline_cache.d").glob("cs-*.bin")) + if not files and "no cache data for authored" in warm.stderr and not require_hit: + print("SKIP: the driver returned no opaque cache payload") + return 77 + if len(files) != 1: + raise RuntimeError(f"expected one published cache file, found {len(files)}\n{warm.stderr}") + entry, = files + # Upkeep would evict the entry under this budget, remove the stale staging file or touch a hit. + stale = entry.with_name(entry.name + ".tmp.1.1") + stale.write_bytes(b"stale") + for path in (entry, stale): + os.utime(path, (1000000000, 1000000000)) + env["LEONIDA_PIPELINE_JOURNAL_BYTES"] = "1" + hit = verify() + confirmed = hit.returncode == 0 + if confirmed or require_hit: + expect(hit, 0, "selected=1 verified=1 missing_or_unusable=0 unverified=0 errors=0") + else: + expect(hit, 2, "selected=1 verified=0 missing_or_unusable=0 unverified=1 errors=0") + + # A second entry changes the actual module, so the first entry's hit cannot satisfy the full selection. + # Vary the literal to avoid reusing a previous run's store module. + value = int.from_bytes(hashlib.sha256(root.name.encode()).digest()[:4], "little") + changed = assemble(STORE_SHADER.format(value=value), "vulkan1.2") + (shaders / "second.spv").write_bytes(changed) + index["second"] = {"stage": "cs", "fssm_sha256": hashlib.sha256(changed).hexdigest(), "local_size": [1, 1, 1]} + (shaders / "index.json").write_text(json.dumps(index), encoding="utf-8", newline="\n") + expect(verify(), 2, f"selected=2 verified={int(confirmed)} missing_or_unusable=1 " + f"unverified={int(not confirmed)} errors=0") + del env["LEONIDA_PIPELINE_JOURNAL_BYTES"] + expect(run("--filter", "second", "--threads", "1"), 0, "0 failed") + second_files = set(entry.parent.glob("cs-*.bin")) - {entry} + if len(second_files) != 1: + raise RuntimeError("expected a second local journal file for the store shader") + second, = second_files + second.write_bytes(entry.read_bytes()) + expect(verify("--filter", "second"), 2, "selected=1 verified=0 missing_or_unusable=0 unverified=1 errors=0") + (shaders / "second.spv").unlink() + expect(verify("--limit", "1", "--smallest-first", "--min-bytes", "1"), 2, + f"selected=1 verified={int(confirmed)} missing_or_unusable=0 unverified={int(not confirmed)} errors=1") + + env["LEONIDA_SKIP_COMPUTE"] = "second" + expect(verify("--skip-listed"), 0 if confirmed else 2, + f"selected=1 verified={int(confirmed)} missing_or_unusable=0 unverified={int(not confirmed)} " + "errors=0 filtered=0 not_buildable=0 skipped_listed=1") + expect(verify(), 2, "errors=1") + del env["LEONIDA_SKIP_COMPUTE"] + + # The identical entry in an external seed does not certify a missing local journal file. + seed = root / "seed" + seed.mkdir() + original = entry.rename(seed / entry.name) + env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed) + expect(verify("--filter", "authored"), 2, "selected=1 verified=0 missing_or_unusable=1 unverified=0 errors=0") + entry.write_bytes(original.read_bytes()[:32]) # matching header alone cannot confirm reuse + expect(verify("--filter", "authored"), 2, "selected=1 verified=0 missing_or_unusable=1 unverified=0 errors=0") + (shaders / "authored.spv").write_bytes(b"bad!") + expect(verify("--filter", "authored"), 2, "selected=1 verified=0 missing_or_unusable=0 unverified=0 errors=1") + print("Verified read-only journal checks; driver reported application-cache hit:", confirmed) + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("executable", type=Path, help="built gta6rt.exe") + parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") + parser.add_argument("--require-hit", action="store_true", help="require a driver-confirmed hit after warming") + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="leonida-precompile-verify-") as tmp: + sys.exit(check(args.executable.resolve(strict=True), Path(tmp), args.device, args.require_hit))