From 303115182a846a48be68fd1be1f777fdcfdf2b35 Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Mon, 30 Nov 2026 16:54:00 -0800 Subject: [PATCH 1/6] startup: write mesh pipeline requests on a background thread Slot 57 and slot 86 mesh pipeline creations wrote each new key's request parts (a probe, a temporary file and a rename each) under one lock before they answered. A title that creates thousands of mesh pipelines then waits on that file work one creation at a time. Creations now copy the parts into a bounded queue and return; one thread writes them in order (request_publisher.h). A key is queued once per process and at most 64 MiB wait. X2W_SYNC_MESH_REQUESTS=1 restores the inline writes. Co-Authored-By: Claude Opus 5.5 --- CMakePresets.json | 4 +- docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_draw.inl | 68 +++++- src/startup_stubs/d3d12_xs_device.cpp | 4 + src/startup_stubs/mesh86_cache.inl | 26 ++- src/startup_stubs/request_publisher.h | 217 ++++++++++++++++++++ tests/cmake/startup_request_publisher.cmake | 9 + tests/startup_request_publisher_check.cpp | 141 +++++++++++++ 8 files changed, 457 insertions(+), 13 deletions(-) create mode 100644 src/startup_stubs/request_publisher.h create mode 100644 tests/cmake/startup_request_publisher.cmake create mode 100644 tests/startup_request_publisher_check.cpp diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..95756e69a0 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -36,7 +36,7 @@ "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", - "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" + "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check", "startup_request_publisher_check" ] }, { "name": "release", "configurePreset": "release" }, @@ -50,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|startup_request_publisher(_inline_control)?)$" } } }, diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976e2f80ee..4069613b58 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1865,6 +1865,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_INLINE_DESCRIPTORS=1` | opt-in: leaves byte +0x18 of the guest device at 0, so the title writes constant buffer views and copies CBV/SRV/UAV descriptors itself instead of calling device slots 17 and 24 (sampler copies still arrive through slot 24); with `X2W_D3D12_RELEASE_RETIRED=1`, a retired resource is then freed once its release fences pass ([details](#d3d12-inline-descriptors)). Unset, nothing changes | | `X2W_D3D12_NO_VISIBLE_HEAP_MIRROR=1` | negative control only: title view and sampler heaps created shader-visible get no CPU-only mirror. By default every view, sampler and copy the stand-in writes into a shader-visible range goes to the mirror first and is copied from there, and copies and `ClearUnorderedAccessView*` read a visible descriptor from the mirror, because desktop D3D12 reads those only from CPU-only heaps (debug layer message 654; a driver fault on a GTX 1060, #3558). The switch restores the direct read | +| `X2W_SYNC_MESH_REQUESTS=1` | negative control only: mesh pipeline creations write their requests themselves, under the path's lock, before they answer: slot 57 (`req_.ps57`, `.root`, `.m57`, and `.s57` with `X2W_MESH57_CAPTURE_STATE=1`) and slot 86 (`.ps86`, `.root`, `.stream86`, `.m86`). By default a creation queues its request and returns; one background thread writes the parts in order (`src/startup_stubs/request_publisher.h`). A key is queued once per process, at most 64 MiB of parts wait at a time (a request past that is dropped; slot 57 keeps its stages and queues it again on a later call, slot 86 asks again in a later run), and what is still queued is written at module unload for at most 2 s. The periodic `x2w-render mesh request publisher:` line counts queued, repeated, written, failed and dropped requests. On a GTX 1060 a title creating thousands of mesh pipelines waited on these writes one creation at a time: about 7 slot 86 creations a second, and a 45 s gap in presents while title threads queued on the slot 57 request lock. `ctest --preset dev --no-tests=error -R '^startup_request_publisher'` (the inline control must fail) | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | | `X2W_D3D12_AGILITY=` | opt-in: the stand-ins select the Agility SDK `D3D12Core.dll` in `` before the first D3D12 device of the process (Windows Developer Mode only; `` on the executable's drive). Unset, the in-box runtime stays and nothing is read ([details](#d3d12-agility-sdk-runtime)) | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b012ca84d..02b3e6de24 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -590,6 +590,60 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return exists; } +// Mesh pipeline requests (slot 57 and slot 86) are written on one background thread (request_publisher.h), so a title +// that creates thousands of mesh pipelines does not wait on a probe, a temporary file and a rename per request part, +// one creation at a time. At most mesh_request_publish_limit bytes of copied parts wait; a request past that is +// dropped and counted, and the title asks for it again in a later run. X2W_SYNC_MESH_REQUESTS=1 (negative control) +// writes them on the creating thread, as before. +constexpr std::size_t mesh_request_publish_limit = std::size_t{64} << 20; + +bool sync_mesh_requests() +{ + static const bool on = x2w_local::env_on("X2W_SYNC_MESH_REQUESTS"); + return on; +} + +bool write_mesh_request_part(void*, u64 key, const wchar_t* extension, const void* data, std::size_t bytes) +{ + return publish_shader_request(key, extension, data, bytes); +} + +// Never destroyed: the drain below runs at module unload, after function-local statics are gone. +x2w_startup::RequestPublisher& mesh_request_publisher() +{ + static auto* publisher = new x2w_startup::RequestPublisher(write_mesh_request_part, nullptr, mesh_request_publish_limit); + return *publisher; +} + +// At process exit the publisher's thread is already gone. Write what is still queued, for at most two seconds, so a +// short run (a fixture) leaves its requests on disk. +struct MeshRequestDrain { + ~MeshRequestDrain() + { + if (!sync_mesh_requests()) mesh_request_publisher().drain(2000); + } +} mesh_request_drain; + +// Publishes the parts of one request in order: queued, or written now under X2W_SYNC_MESH_REQUESTS=1. False when the +// request was dropped (queued) or a part could not be written (sync). +bool publish_mesh_request(u64 key, const x2w_startup::RequestPublisher::Part* parts, std::size_t count) +{ + if (!sync_mesh_requests()) return mesh_request_publisher().enqueue(key, parts, count); + for (std::size_t i = 0; i < count; ++i) + if (!publish_shader_request(key, parts[i].extension, parts[i].data, parts[i].bytes)) return false; + return true; +} + +void mesh_request_publisher_line(char (&line)[256]) +{ + const auto s = mesh_request_publisher().stats(); + line[0] = 0; + if (!s.queued && !s.dropped) return; + std::snprintf(line, sizeof(line), + "x2w-render mesh request publisher: queued %lld repeated %lld written %lld failed %lld dropped %lld pending %zu (%zu KiB, high water %zu KiB)", + s.queued, s.repeated, s.written, s.failed, s.dropped, s.pending, s.pending_bytes >> 10, s.high_water_bytes >> 10); +} + bool native_shaders_only() { static const bool enabled = [] { @@ -1067,13 +1121,19 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo std::memcpy(packed.data() + sizeof(key), lengths, sizeof(lengths)); for (const auto* bytes : {&desc, &info->state_a, &info->state_b}) packed.insert(packed.end(), bytes->begin(), bytes->end()); - if (!publish_shader_request(variant, L".s57", packed.data(), packed.size())) + const x2w_startup::RequestPublisher::Part state{L".s57", packed.data(), packed.size()}; + if (!publish_mesh_request(variant, &state, 1)) log("x2w-draw fixed mesh state %016llx could not be published", variant); } const unsigned char none = 0; - if (written.count(key) || (publish_shader_request(key, L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()) && - publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - publish_shader_request(key, L".m57", mesh.data(), mesh.size()))) { + // The parts are copied into the publisher's queue (or written now with X2W_SYNC_MESH_REQUESTS=1); a dropped + // request keeps its stages, so a later call queues it again. + const x2w_startup::RequestPublisher::Part parts[]{ + {L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()}, + {L".root", root_blob.data(), root_blob.size()}, + {L".m57", mesh.data(), mesh.size()}, + }; + if (written.count(key) || publish_mesh_request(key, parts, std::size(parts))) { const bool first = written.insert(key).second; static LONG logged; if (first && first_calls(logged, 12)) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..c2ebd109cc 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -53,6 +53,7 @@ #include #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" +#include "startup_stubs/request_publisher.h" #include "startup_stubs/resource_address_index.h" #include "startup_stubs/placed_build.h" #include "startup_stubs/placed_buffer_range.h" @@ -8991,6 +8992,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa char mesh57_line[1536]; mesh57_outcome_line(mesh57_line); log("%s", mesh57_line); + char mesh_request_line[256]; + mesh_request_publisher_line(mesh_request_line); + if (mesh_request_line[0]) log("%s", mesh_request_line); } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 1696db4c34..6a8866a394 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -265,15 +265,27 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d auto key = fnv_bytes(revision, sizeof(revision) - 1); for (const auto* part : {&request.ms, &request.ps, &root_blob, &request.stream}) key = fnv_part(*part, key); static SRWLOCK lock = SRWLOCK_INIT; - x2w_startup::ExclusiveNoteLock guard(lock); const unsigned char none = 0; - if (!publish_shader_request(key, L".ps86", request.ps.empty() ? &none : request.ps.data(), request.ps.size()) || - !publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) || - !publish_shader_request(key, L".stream86", request.stream.data(), request.stream.size()) || - !publish_shader_request(key, L".m86", request.ms.data(), request.ms.size())) { - std::snprintf(why, why_size, "slot86 mesh request %016llx publication failed", key); - return nullptr; + const x2w_startup::RequestPublisher::Part parts[]{ + {L".ps86", request.ps.empty() ? &none : request.ps.data(), request.ps.size()}, + {L".root", root_blob.data(), root_blob.size()}, + {L".stream86", request.stream.data(), request.stream.size()}, + {L".m86", request.ms.data(), request.ms.size()}, + }; + if (sync_mesh_requests()) { + // X2W_SYNC_MESH_REQUESTS=1: every creation writes its request under the lock, as before the publisher. + x2w_startup::ExclusiveNoteLock guard(lock); + for (const auto& part : parts) + if (!publish_shader_request(key, part.extension, part.data, part.bytes)) { + std::snprintf(why, why_size, "slot86 mesh request %016llx publication failed", key); + return nullptr; + } + } else { + // The request is written on the publisher's thread; until the translator answers it the creation below finds + // no marker and reports it pending, the same answer a creation gave while its own write was in progress. + publish_mesh_request(key, parts, std::size(parts)); } + x2w_startup::ExclusiveNoteLock guard(lock); published_key = key; const auto* params = root_info(request.root); // Only the resource heap can be indexed, and only through a published heap-buffer window (bind_mesh86_heap). The diff --git a/src/startup_stubs/request_publisher.h b/src/startup_stubs/request_publisher.h new file mode 100644 index 0000000000..510a42f2f8 --- /dev/null +++ b/src/startup_stubs/request_publisher.h @@ -0,0 +1,217 @@ +// Experimental (docs/startup-runtime.md): writes shader-cache request parts on one background thread. +// +// A slot 86 mesh pipeline creation publishes its request (four parts, each a probe, a temporary file and a rename) +// before it can answer. A title that creates thousands of mesh pipelines through slot 86 then waits on that file +// work, one creation at a time. The publisher takes a copy of a request's parts and returns; its thread writes them. +// +// - The parts of one request are written in the order given, and requests in the order queued. +// - A key is queued once per process. A repeated enqueue of it returns true without copying anything. +// - The queued bytes are bounded. A request that would pass the bound is dropped and counted; the title asks for the +// same pipeline again in a later run. +// - A request stays at the front of the queue while it is written, so drain() at module unload (the thread is gone +// at process exit) writes it again from the start, and nothing popped is lost. drain() stops after its time limit. +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace x2w_startup { + +class RequestPublisher { +public: + // Writes one part; returns false when the part could not be written. + using Write = bool (*)(void* context, std::uint64_t key, const wchar_t* extension, const void* data, std::size_t bytes); + + struct Part { + const wchar_t* extension; + const void* data; + std::size_t bytes; + }; + + struct Stats { + long long queued = 0; // requests accepted + long long repeated = 0; // enqueues of a key already accepted + long long written = 0; // requests whose parts were all written + long long failed = 0; // requests with a part that could not be written + long long dropped = 0; // requests over the byte bound + std::size_t pending = 0, pending_bytes = 0, high_water_bytes = 0; + }; + + RequestPublisher(Write write, void* context, std::size_t byte_limit, bool start_thread = true) noexcept + : write_(write), context_(context), byte_limit_(byte_limit), start_thread_(start_thread) + { + } + RequestPublisher(const RequestPublisher&) = delete; + RequestPublisher& operator=(const RequestPublisher&) = delete; + + // Copies the parts and queues them as one request. False when the request was dropped (or out of memory). + bool enqueue(std::uint64_t key, const Part* parts, std::size_t count) + { + std::size_t bytes = 0; + for (std::size_t i = 0; i < count; ++i) bytes += parts[i].bytes; + AcquireSRWLockExclusive(&lock_); + if (seen_.count(key)) { + ++stats_.repeated; + ReleaseSRWLockExclusive(&lock_); + return true; + } + if (bytes > byte_limit_ || stats_.pending_bytes > byte_limit_ - bytes) { + ++stats_.dropped; + ReleaseSRWLockExclusive(&lock_); + return false; + } + try { + Request request{key, bytes, {}}; + request.parts.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const auto* begin = static_cast(parts[i].data); + request.parts.push_back({parts[i].extension, std::vector(begin, begin + parts[i].bytes)}); + } + seen_.insert(key); + queue_.push_back(std::move(request)); + } catch (...) { + ++stats_.dropped; + ReleaseSRWLockExclusive(&lock_); + return false; + } + ++stats_.queued; + ++stats_.pending; + stats_.pending_bytes += bytes; + if (stats_.pending_bytes > stats_.high_water_bytes) stats_.high_water_bytes = stats_.pending_bytes; + const bool start = start_thread_ && !thread_started_; + thread_started_ = thread_started_ || start; + // No thread could be started: the queuing thread writes, as before the publisher. + while (inline_writes_ && !queue_.empty()) write_front(); + ReleaseSRWLockExclusive(&lock_); + if (start) start_thread(); + WakeConditionVariable(&work_); + return true; + } + + // Waits until every queued request is written or timeout_ms passes; true when the queue is empty. + bool flush(DWORD timeout_ms) + { + const ULONGLONG deadline = GetTickCount64() + timeout_ms; + AcquireSRWLockExclusive(&lock_); + while (!queue_.empty()) { + const ULONGLONG now = GetTickCount64(); + if (now >= deadline || !thread_started_) break; + SleepConditionVariableSRW(&idle_, &lock_, static_cast(deadline - now), 0); + } + const bool empty = queue_.empty(); + ReleaseSRWLockExclusive(&lock_); + return empty; + } + + // Writes queued requests on the calling thread until the queue is empty or timeout_ms passes. Only for module + // unload, when the writer thread no longer runs (never while it does); it never waits for the lock. + std::size_t drain(DWORD timeout_ms) + { + if (!TryAcquireSRWLockExclusive(&lock_)) return 0; + const ULONGLONG deadline = GetTickCount64() + timeout_ms; + std::size_t done = 0; + while (!queue_.empty() && GetTickCount64() < deadline) { + write_front(); + ++done; + } + ReleaseSRWLockExclusive(&lock_); + return done; + } + + Stats stats() const + { + AcquireSRWLockShared(&lock_); + const Stats copy = stats_; + ReleaseSRWLockShared(&lock_); + return copy; + } + +private: + struct OwnedPart { + std::wstring extension; + std::vector data; + }; + struct Request { + std::uint64_t key; + std::size_t bytes; + std::vector parts; + }; + + // Writes the front request and pops it. Called with lock_ held exclusive; releases it while writing when unlock. + void write_front(bool unlock = false) + { + Request& request = queue_.front(); + if (unlock) ReleaseSRWLockExclusive(&lock_); + bool complete = true; + for (const auto& part : request.parts) + if (!write_(context_, request.key, part.extension.c_str(), part.data.data(), part.data.size())) { + complete = false; + break; + } + if (unlock) AcquireSRWLockExclusive(&lock_); + ++(complete ? stats_.written : stats_.failed); + --stats_.pending; + stats_.pending_bytes -= request.bytes; + queue_.pop_front(); + } + + static DWORD WINAPI thread_main(void* self) + { + static_cast(self)->run(); + return 0; + } + + void run() + { + AcquireSRWLockExclusive(&lock_); + for (;;) { + while (queue_.empty()) { + WakeAllConditionVariable(&idle_); + SleepConditionVariableSRW(&work_, &lock_, INFINITE, 0); + } + // Only this thread pops while it runs, so the front request stays valid while the lock is released. + write_front(true); + if (queue_.empty()) WakeAllConditionVariable(&idle_); + } + } + + void start_thread() + { + // The thread holds a reference on this module so a FreeLibrary cannot unmap the code it runs. + HMODULE module = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(&thread_main), &module); + if (HANDLE thread = CreateThread(nullptr, 0, thread_main, this, 0, nullptr)) { + CloseHandle(thread); + return; + } + if (module) FreeLibrary(module); + // No thread: write on the queuing threads instead, as before the publisher. + AcquireSRWLockExclusive(&lock_); + thread_started_ = false; + start_thread_ = false; + inline_writes_ = true; + while (!queue_.empty()) write_front(); + ReleaseSRWLockExclusive(&lock_); + } + + Write write_; + void* context_; + std::size_t byte_limit_; + bool start_thread_; + bool thread_started_ = false; + bool inline_writes_ = false; + mutable SRWLOCK lock_ = SRWLOCK_INIT; + CONDITION_VARIABLE work_ = CONDITION_VARIABLE_INIT, idle_ = CONDITION_VARIABLE_INIT; + std::deque queue_; + std::unordered_set seen_; + Stats stats_; +}; + +} // namespace x2w_startup diff --git a/tests/cmake/startup_request_publisher.cmake b/tests/cmake/startup_request_publisher.cmake new file mode 100644 index 0000000000..29dd4d7d9a --- /dev/null +++ b/tests/cmake/startup_request_publisher.cmake @@ -0,0 +1,9 @@ +# Background writes of shader-cache request parts (src/startup_stubs/request_publisher.h), without a device. A slot 86 +# mesh creation queues its request and returns. The inline control waits for each write, as creation did before, and +# must fail. +add_executable(startup_request_publisher_check tests/startup_request_publisher_check.cpp) +target_include_directories(startup_request_publisher_check PRIVATE src) +target_compile_features(startup_request_publisher_check PRIVATE cxx_std_17) +add_test(NAME startup_request_publisher COMMAND startup_request_publisher_check) +add_test(NAME startup_request_publisher_inline_control COMMAND startup_request_publisher_check --mutate inline) +set_tests_properties(startup_request_publisher_inline_control PROPERTIES WILL_FAIL TRUE) diff --git a/tests/startup_request_publisher_check.cpp b/tests/startup_request_publisher_check.cpp new file mode 100644 index 0000000000..008837d5f4 --- /dev/null +++ b/tests/startup_request_publisher_check.cpp @@ -0,0 +1,141 @@ +// Checks src/startup_stubs/request_publisher.h without a device: a queued request returns while its writer is held, +// parts and requests are written in order, a repeated key is written once, the byte bound drops and counts, a failed +// part stops its request, and drain() writes the queue on the calling thread (module unload). --mutate inline is the +// negative control: each enqueue waits for its write, as a slot 86 mesh creation did before the publisher, so the +// held-writer case must fail. +#include "startup_stubs/request_publisher.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using x2w_startup::RequestPublisher; + +bool inline_mutation = false; +int failures = 0; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL %s\n", what); + ++failures; + } +} + +struct Writer { + SRWLOCK lock = SRWLOCK_INIT; + std::vector writes; // "::" + HANDLE gate = nullptr; // when set, every write waits for it + std::wstring fail_extension; + + static bool write(void* context, std::uint64_t key, const wchar_t* extension, const void* data, std::size_t bytes) + { + auto& self = *static_cast(context); + if (self.gate) WaitForSingleObject(self.gate, 5000); + if (bytes && !data) return false; + if (extension == self.fail_extension) return false; + char line[64]; + std::snprintf(line, sizeof(line), "%llx:%ls:%zu", static_cast(key), extension, bytes); + AcquireSRWLockExclusive(&self.lock); + self.writes.push_back(line); + ReleaseSRWLockExclusive(&self.lock); + return true; + } + std::vector snapshot() + { + AcquireSRWLockShared(&lock); + auto copy = writes; + ReleaseSRWLockShared(&lock); + return copy; + } +}; + +const unsigned char bytes[64]{}; + +bool queue(RequestPublisher& publisher, std::uint64_t key, std::size_t size = 4) +{ + const RequestPublisher::Part parts[]{{L".a", bytes, size}, {L".b", bytes, size}, {L".m", bytes, size}}; + const bool queued = publisher.enqueue(key, parts, std::size(parts)); + if (inline_mutation) publisher.flush(500); // the creation waits for its own write + return queued; +} + +void held_writer() +{ + Writer writer; + writer.gate = CreateEventW(nullptr, TRUE, FALSE, nullptr); + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + const ULONGLONG start = GetTickCount64(); + for (std::uint64_t key = 1; key <= 3; ++key) queue(publisher, key); + const ULONGLONG queued_ms = GetTickCount64() - start; + expect(queued_ms < 250, "three requests queue while the writer is held"); + expect(writer.snapshot().empty(), "nothing is written before the writer is released"); + SetEvent(writer.gate); + expect(publisher.flush(5000), "flush returns once every request is written"); + const std::vector want{"1:.a:4", "1:.b:4", "1:.m:4", "2:.a:4", "2:.b:4", "2:.m:4", + "3:.a:4", "3:.b:4", "3:.m:4"}; + expect(writer.snapshot() == want, "parts and requests are written in the order queued"); + const auto s = publisher.stats(); + expect(s.queued == 3 && s.written == 3 && s.pending == 0 && s.pending_bytes == 0 && s.high_water_bytes == 36, + "stats count three written requests and a 36-byte high water"); + + expect(queue(publisher, 2), "a repeated key is accepted"); + publisher.flush(5000); + expect(writer.snapshot().size() == want.size() && publisher.stats().repeated == 1, + "a repeated key is not written again"); + std::printf("held writer: %llu ms to queue three requests\n", static_cast(queued_ms)); + CloseHandle(writer.gate); +} + +void byte_bound_and_drain() +{ + Writer writer; + RequestPublisher publisher(Writer::write, &writer, 100, /*start_thread=*/false); + expect(publisher.enqueue(7, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), "a 60-byte request fits"); + expect(!publisher.enqueue(8, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), "a second one is dropped"); + expect(!publisher.enqueue(9, std::begin({RequestPublisher::Part{L".a", bytes, 101}}), 1), "one over the bound is dropped"); + expect(publisher.stats().dropped == 2 && publisher.stats().pending == 1, "two drops, one pending"); + expect(writer.snapshot().empty(), "nothing is written without the thread"); + expect(publisher.drain(1000) == 1, "drain writes the pending request"); + expect(writer.snapshot() == std::vector{"7:.a:60"}, "drain wrote it on the calling thread"); + expect(publisher.enqueue(8, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), + "a dropped key is accepted once there is room"); + expect(publisher.drain(1000) == 1 && publisher.stats().pending_bytes == 0, "the queue is empty after drain"); +} + +void failed_part() +{ + Writer writer; + writer.fail_extension = L".b"; + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + queue(publisher, 5); + publisher.flush(5000); + expect(writer.snapshot() == std::vector{"5:.a:4"}, "a failed part stops its request"); + expect(publisher.stats().failed == 1 && publisher.stats().written == 0, "the request counts as failed"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], "inline")) inline_mutation = true; + else if (argc != 1) { + std::printf("usage: %s [--mutate inline]\n", argv[0]); + return 2; + } + held_writer(); + byte_bound_and_drain(); + failed_part(); + if (failures) { + std::printf("request publisher: %d failed\n", failures); + return 1; + } + std::printf("request publisher: all cases passed\n"); + return 0; +} From e0080a36e5c40870b63dd579e0480566a4ae763e Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Mon, 30 Nov 2026 16:59:44 -0800 Subject: [PATCH 2/6] startup: drain mesh requests at unload without locks; stop and join the writer The unload drain writes with its own writer (a temporary name of its own, a rename, no cache index) from a directory read when the publisher is made, and only once the writer thread has ended; while it still runs the drain waits for it. Nothing is made at unload when no request was queued. stop() ends and joins the thread (the destructor calls it), and a request that could not be written forgets its key so it is accepted again. The check covers the retry, the unload writer, a drain while the thread runs and stop. Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/d3d12_draw.inl | 45 +++++++++-- src/startup_stubs/request_publisher.h | 98 +++++++++++++++++------ tests/startup_request_publisher_check.cpp | 39 ++++++++- 3 files changed, 148 insertions(+), 34 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 02b3e6de24..59f3235eb3 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -608,19 +608,50 @@ bool write_mesh_request_part(void*, u64 key, const wchar_t* extension, const voi return publish_shader_request(key, extension, data, bytes); } -// Never destroyed: the drain below runs at module unload, after function-local statics are gone. +// The cache directory, read once when the publisher is made, so the unload writer reads no environment variable. +wchar_t mesh_request_dir[MAX_PATH]; + +// Made on first use and never destroyed: the drain below runs at module unload, after function-local statics are gone. +x2w_startup::RequestPublisher* volatile mesh_request_instance; + x2w_startup::RequestPublisher& mesh_request_publisher() { - static auto* publisher = new x2w_startup::RequestPublisher(write_mesh_request_part, nullptr, mesh_request_publish_limit); + static auto* publisher = [] { + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", mesh_request_dir, MAX_PATH); + if (!n || n >= MAX_PATH) mesh_request_dir[0] = 0; + auto* made = new x2w_startup::RequestPublisher(write_mesh_request_part, nullptr, mesh_request_publish_limit); + mesh_request_instance = made; + return made; + }(); return *publisher; } -// At process exit the publisher's thread is already gone. Write what is still queued, for at most two seconds, so a -// short run (a fixture) leaves its requests on disk. +// The unload writer: a temporary file of its own and a rename, without the cache index (whose lock a terminated +// thread may hold) or anything else that locks. A part already on disk is left as it is. +bool write_mesh_request_part_at_exit(void*, u64 key, const wchar_t* extension, const void* data, std::size_t bytes) +{ + if (!mesh_request_dir[0]) return false; + wchar_t path[MAX_PATH], temporary[MAX_PATH]; + if (swprintf(path, MAX_PATH, L"%s\\req_%016llx%s", mesh_request_dir, key, extension) < 0 || + swprintf(temporary, MAX_PATH, L"%s.%lu.exit.tmp", path, GetCurrentProcessId()) < 0) + return false; + if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + if (complete && MoveFileExW(temporary, path, 0)) return true; + DeleteFileW(temporary); + return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; +} + +// At module unload, write what is still queued, for at most two seconds, so a short run (a fixture) leaves its +// requests on disk. Nothing is made here when no request was queued. struct MeshRequestDrain { ~MeshRequestDrain() { - if (!sync_mesh_requests()) mesh_request_publisher().drain(2000); + if (auto* publisher = mesh_request_instance) publisher->drain(2000, write_mesh_request_part_at_exit); } } mesh_request_drain; @@ -636,8 +667,10 @@ bool publish_mesh_request(u64 key, const x2w_startup::RequestPublisher::Part* pa void mesh_request_publisher_line(char (&line)[256]) { - const auto s = mesh_request_publisher().stats(); line[0] = 0; + auto* publisher = mesh_request_instance; + if (!publisher) return; + const auto s = publisher->stats(); if (!s.queued && !s.dropped) return; std::snprintf(line, sizeof(line), "x2w-render mesh request publisher: queued %lld repeated %lld written %lld failed %lld dropped %lld pending %zu (%zu KiB, high water %zu KiB)", diff --git a/src/startup_stubs/request_publisher.h b/src/startup_stubs/request_publisher.h index 510a42f2f8..c2bf02c22d 100644 --- a/src/startup_stubs/request_publisher.h +++ b/src/startup_stubs/request_publisher.h @@ -1,15 +1,18 @@ // Experimental (docs/startup-runtime.md): writes shader-cache request parts on one background thread. // -// A slot 86 mesh pipeline creation publishes its request (four parts, each a probe, a temporary file and a rename) -// before it can answer. A title that creates thousands of mesh pipelines through slot 86 then waits on that file -// work, one creation at a time. The publisher takes a copy of a request's parts and returns; its thread writes them. +// A mesh pipeline creation publishes its request (several parts, each a probe, a temporary file and a rename) before +// it can answer. A title that creates thousands of mesh pipelines then waits on that file work, one creation at a +// time. The publisher takes a copy of a request's parts and returns; its thread writes them. // // - The parts of one request are written in the order given, and requests in the order queued. -// - A key is queued once per process. A repeated enqueue of it returns true without copying anything. -// - The queued bytes are bounded. A request that would pass the bound is dropped and counted; the title asks for the -// same pipeline again in a later run. -// - A request stays at the front of the queue while it is written, so drain() at module unload (the thread is gone -// at process exit) writes it again from the start, and nothing popped is lost. drain() stops after its time limit. +// - A key is queued once per process. A repeated enqueue of it returns true without copying anything. A request that +// could not be written forgets its key, so a later enqueue of it is accepted again. +// - The queued bytes are bounded. A request that would pass the bound is dropped and counted. +// - stop() ends the thread and joins it (the destructor calls it). +// - drain() is for module unload: it writes what is still queued on the calling thread, with its own writer (one that +// takes no lock a terminated thread may hold), and only once the writer thread has ended. While the thread still +// runs (an executable's static destructors) it waits for the thread instead. A request stays at the front of the +// queue while it is written, so a drain after the thread was terminated mid-write writes it again from the start. #pragma once #include @@ -50,6 +53,7 @@ class RequestPublisher { } RequestPublisher(const RequestPublisher&) = delete; RequestPublisher& operator=(const RequestPublisher&) = delete; + ~RequestPublisher() { stop(); } // Copies the parts and queues them as one request. False when the request was dropped (or out of memory). bool enqueue(std::uint64_t key, const Part* parts, std::size_t count) @@ -62,7 +66,7 @@ class RequestPublisher { ReleaseSRWLockExclusive(&lock_); return true; } - if (bytes > byte_limit_ || stats_.pending_bytes > byte_limit_ - bytes) { + if (stopping_ || bytes > byte_limit_ || stats_.pending_bytes > byte_limit_ - bytes) { ++stats_.dropped; ReleaseSRWLockExclusive(&lock_); return false; @@ -88,7 +92,7 @@ class RequestPublisher { const bool start = start_thread_ && !thread_started_; thread_started_ = thread_started_ || start; // No thread could be started: the queuing thread writes, as before the publisher. - while (inline_writes_ && !queue_.empty()) write_front(); + while (inline_writes_ && !queue_.empty()) write_front(write_); ReleaseSRWLockExclusive(&lock_); if (start) start_thread(); WakeConditionVariable(&work_); @@ -102,7 +106,7 @@ class RequestPublisher { AcquireSRWLockExclusive(&lock_); while (!queue_.empty()) { const ULONGLONG now = GetTickCount64(); - if (now >= deadline || !thread_started_) break; + if (now >= deadline || !thread_running()) break; SleepConditionVariableSRW(&idle_, &lock_, static_cast(deadline - now), 0); } const bool empty = queue_.empty(); @@ -110,15 +114,35 @@ class RequestPublisher { return empty; } - // Writes queued requests on the calling thread until the queue is empty or timeout_ms passes. Only for module - // unload, when the writer thread no longer runs (never while it does); it never waits for the lock. - std::size_t drain(DWORD timeout_ms) + // Ends the writer thread after the request it is writing, and joins it. What is still queued stays queued. + void stop() { + AcquireSRWLockExclusive(&lock_); + stopping_ = true; + const HANDLE thread = thread_; + ReleaseSRWLockExclusive(&lock_); + WakeAllConditionVariable(&work_); + if (thread && thread_alive(thread)) WaitForSingleObject(thread, INFINITE); + } + + // Module unload. Once the writer thread has ended (or never started), writes what is still queued on the calling + // thread with `write` (nullptr: the publisher's writer) until the queue is empty or timeout_ms passes. While the + // thread still runs, waits for it instead. Never waits for the lock. Returns the requests written here. + std::size_t drain(DWORD timeout_ms, Write write = nullptr) + { + if (!TryAcquireSRWLockExclusive(&lock_)) return 0; + const HANDLE thread = thread_; + const bool running = thread && thread_alive(thread); + ReleaseSRWLockExclusive(&lock_); + if (running) { + flush(timeout_ms); + return 0; + } if (!TryAcquireSRWLockExclusive(&lock_)) return 0; const ULONGLONG deadline = GetTickCount64() + timeout_ms; std::size_t done = 0; while (!queue_.empty() && GetTickCount64() < deadline) { - write_front(); + write_front(write ? write : write_); ++done; } ReleaseSRWLockExclusive(&lock_); @@ -144,19 +168,26 @@ class RequestPublisher { std::vector parts; }; - // Writes the front request and pops it. Called with lock_ held exclusive; releases it while writing when unlock. - void write_front(bool unlock = false) + static bool thread_alive(HANDLE thread) { return WaitForSingleObject(thread, 0) == WAIT_TIMEOUT; } + + // With lock_ held: the writer thread exists and has not ended. + bool thread_running() const { return thread_ && thread_alive(thread_); } + + // Writes the front request with `write` and pops it. Called with lock_ held exclusive; releases it while writing + // when unlock (only the writer thread pops while it runs, so the front stays valid). + void write_front(Write write, bool unlock = false) { Request& request = queue_.front(); if (unlock) ReleaseSRWLockExclusive(&lock_); bool complete = true; for (const auto& part : request.parts) - if (!write_(context_, request.key, part.extension.c_str(), part.data.data(), part.data.size())) { + if (!write(context_, request.key, part.extension.c_str(), part.data.data(), part.data.size())) { complete = false; break; } if (unlock) AcquireSRWLockExclusive(&lock_); ++(complete ? stats_.written : stats_.failed); + if (!complete) seen_.erase(request.key); --stats_.pending; stats_.pending_bytes -= request.bytes; queue_.pop_front(); @@ -164,7 +195,10 @@ class RequestPublisher { static DWORD WINAPI thread_main(void* self) { - static_cast(self)->run(); + auto* publisher = static_cast(self); + const HMODULE module = publisher->module_; + publisher->run(); + if (module) FreeLibraryAndExitThread(module, 0); return 0; } @@ -172,32 +206,41 @@ class RequestPublisher { { AcquireSRWLockExclusive(&lock_); for (;;) { - while (queue_.empty()) { + while (queue_.empty() && !stopping_) { WakeAllConditionVariable(&idle_); SleepConditionVariableSRW(&work_, &lock_, INFINITE, 0); } - // Only this thread pops while it runs, so the front request stays valid while the lock is released. - write_front(true); + if (stopping_) break; + write_front(write_, true); if (queue_.empty()) WakeAllConditionVariable(&idle_); } + WakeAllConditionVariable(&idle_); + ReleaseSRWLockExclusive(&lock_); } void start_thread() { - // The thread holds a reference on this module so a FreeLibrary cannot unmap the code it runs. + // The thread holds a reference on this module so a FreeLibrary cannot unmap the code it runs; it releases it + // when stop() ends it. HMODULE module = nullptr; GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(&thread_main), &module); - if (HANDLE thread = CreateThread(nullptr, 0, thread_main, this, 0, nullptr)) { - CloseHandle(thread); + module_ = module; + // Created suspended so stop() always finds the handle of a thread that has started. + if (HANDLE thread = CreateThread(nullptr, 0, thread_main, this, CREATE_SUSPENDED, nullptr)) { + AcquireSRWLockExclusive(&lock_); + thread_ = thread; + ReleaseSRWLockExclusive(&lock_); + ResumeThread(thread); return; } + module_ = nullptr; if (module) FreeLibrary(module); // No thread: write on the queuing threads instead, as before the publisher. AcquireSRWLockExclusive(&lock_); thread_started_ = false; start_thread_ = false; inline_writes_ = true; - while (!queue_.empty()) write_front(); + while (!queue_.empty()) write_front(write_); ReleaseSRWLockExclusive(&lock_); } @@ -207,6 +250,9 @@ class RequestPublisher { bool start_thread_; bool thread_started_ = false; bool inline_writes_ = false; + bool stopping_ = false; + HANDLE thread_ = nullptr; + HMODULE module_ = nullptr; mutable SRWLOCK lock_ = SRWLOCK_INIT; CONDITION_VARIABLE work_ = CONDITION_VARIABLE_INIT, idle_ = CONDITION_VARIABLE_INIT; std::deque queue_; diff --git a/tests/startup_request_publisher_check.cpp b/tests/startup_request_publisher_check.cpp index 008837d5f4..b26c1f307c 100644 --- a/tests/startup_request_publisher_check.cpp +++ b/tests/startup_request_publisher_check.cpp @@ -47,6 +47,17 @@ struct Writer { ReleaseSRWLockExclusive(&self.lock); return true; } + // The unload writer: recorded with an "exit " prefix. + static bool exit_write(void* context, std::uint64_t key, const wchar_t* extension, const void* data, std::size_t bytes) + { + auto& self = *static_cast(context); + char line[64]; + std::snprintf(line, sizeof(line), "exit %llx:%ls:%zu", static_cast(key), extension, bytes); + AcquireSRWLockExclusive(&self.lock); + self.writes.push_back(line); + ReleaseSRWLockExclusive(&self.lock); + return data || !bytes; + } std::vector snapshot() { AcquireSRWLockShared(&lock); @@ -102,8 +113,8 @@ void byte_bound_and_drain() expect(!publisher.enqueue(9, std::begin({RequestPublisher::Part{L".a", bytes, 101}}), 1), "one over the bound is dropped"); expect(publisher.stats().dropped == 2 && publisher.stats().pending == 1, "two drops, one pending"); expect(writer.snapshot().empty(), "nothing is written without the thread"); - expect(publisher.drain(1000) == 1, "drain writes the pending request"); - expect(writer.snapshot() == std::vector{"7:.a:60"}, "drain wrote it on the calling thread"); + expect(publisher.drain(1000, Writer::exit_write) == 1, "drain writes the pending request"); + expect(writer.snapshot() == std::vector{"exit 7:.a:60"}, "drain wrote it with the unload writer"); expect(publisher.enqueue(8, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), "a dropped key is accepted once there is room"); expect(publisher.drain(1000) == 1 && publisher.stats().pending_bytes == 0, "the queue is empty after drain"); @@ -118,6 +129,29 @@ void failed_part() publisher.flush(5000); expect(writer.snapshot() == std::vector{"5:.a:4"}, "a failed part stops its request"); expect(publisher.stats().failed == 1 && publisher.stats().written == 0, "the request counts as failed"); + writer.fail_extension.clear(); + queue(publisher, 5); + publisher.flush(5000); + const auto s = publisher.stats(); + expect(s.queued == 2 && s.repeated == 0 && s.written == 1, "a failed request is accepted and written again"); +} + +void drain_while_running_and_stop() +{ + Writer writer; + writer.gate = CreateEventW(nullptr, TRUE, FALSE, nullptr); + { + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + queue(publisher, 9); + // The thread still runs (an executable's static destructors): drain waits for it and writes nothing itself. + SetEvent(writer.gate); + expect(publisher.drain(5000, Writer::exit_write) == 0, "drain writes nothing while the thread runs"); + expect(writer.snapshot().size() == 3 && writer.snapshot()[0] == "9:.a:4", "the thread wrote the request"); + publisher.stop(); + expect(!publisher.enqueue(10, std::begin({RequestPublisher::Part{L".a", bytes, 4}}), 1), + "a stopped publisher accepts nothing"); + } // the destructor joins the stopped thread + CloseHandle(writer.gate); } } // namespace @@ -132,6 +166,7 @@ int main(int argc, char** argv) held_writer(); byte_bound_and_drain(); failed_part(); + drain_while_running_and_stop(); if (failures) { std::printf("request publisher: %d failed\n", failures); return 1; From 3cc63af9248f4bfe8c9bea13a3e8547ff66fa05f Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Mon, 30 Nov 2026 17:21:23 -0800 Subject: [PATCH 3/6] tests: queue one-part requests through a helper instead of std::begin on a brace list Another MSVC version resolves std::begin({...}) to the array overload and rejects it (C2664), which failed the Windows build on CI. Co-Authored-By: Claude Opus 5.5 --- tests/startup_request_publisher_check.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/startup_request_publisher_check.cpp b/tests/startup_request_publisher_check.cpp index b26c1f307c..2d8a3da88b 100644 --- a/tests/startup_request_publisher_check.cpp +++ b/tests/startup_request_publisher_check.cpp @@ -69,6 +69,13 @@ struct Writer { const unsigned char bytes[64]{}; +// Queues a one-part request. +bool one_part(RequestPublisher& publisher, std::uint64_t key, std::size_t size) +{ + const RequestPublisher::Part part{L".a", bytes, size}; + return publisher.enqueue(key, &part, 1); +} + bool queue(RequestPublisher& publisher, std::uint64_t key, std::size_t size = 4) { const RequestPublisher::Part parts[]{{L".a", bytes, size}, {L".b", bytes, size}, {L".m", bytes, size}}; @@ -108,14 +115,14 @@ void byte_bound_and_drain() { Writer writer; RequestPublisher publisher(Writer::write, &writer, 100, /*start_thread=*/false); - expect(publisher.enqueue(7, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), "a 60-byte request fits"); - expect(!publisher.enqueue(8, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), "a second one is dropped"); - expect(!publisher.enqueue(9, std::begin({RequestPublisher::Part{L".a", bytes, 101}}), 1), "one over the bound is dropped"); + expect(one_part(publisher, 7, 60), "a 60-byte request fits"); + expect(!one_part(publisher, 8, 60), "a second one is dropped"); + expect(!one_part(publisher, 9, 101), "one over the bound is dropped"); expect(publisher.stats().dropped == 2 && publisher.stats().pending == 1, "two drops, one pending"); expect(writer.snapshot().empty(), "nothing is written without the thread"); expect(publisher.drain(1000, Writer::exit_write) == 1, "drain writes the pending request"); expect(writer.snapshot() == std::vector{"exit 7:.a:60"}, "drain wrote it with the unload writer"); - expect(publisher.enqueue(8, std::begin({RequestPublisher::Part{L".a", bytes, 60}}), 1), + expect(one_part(publisher, 8, 60), "a dropped key is accepted once there is room"); expect(publisher.drain(1000) == 1 && publisher.stats().pending_bytes == 0, "the queue is empty after drain"); } @@ -148,7 +155,7 @@ void drain_while_running_and_stop() expect(publisher.drain(5000, Writer::exit_write) == 0, "drain writes nothing while the thread runs"); expect(writer.snapshot().size() == 3 && writer.snapshot()[0] == "9:.a:4", "the thread wrote the request"); publisher.stop(); - expect(!publisher.enqueue(10, std::begin({RequestPublisher::Part{L".a", bytes, 4}}), 1), + expect(!one_part(publisher, 10, 4), "a stopped publisher accepts nothing"); } // the destructor joins the stopped thread CloseHandle(writer.gate); From 0a3d65dee93b20b2ccac048aa606ef9b173b0ce0 Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Mon, 30 Nov 2026 19:19:11 -0800 Subject: [PATCH 4/6] startup: forget a mesh request key when queuing its copy runs out of memory enqueue recorded the key before pushing the request. If the push threw, the key stayed recorded, so a retry of the same key was counted as repeated and never written. The catch now erases the key under the same lock. The publisher test fails each allocation of an enqueue in turn and checks that the drop is counted and that a retry of the same key is queued and written. Without the rollback that case fails. Co-Authored-By: Claude Opus 5.5 --- src/startup_stubs/request_publisher.h | 4 +- tests/startup_request_publisher_check.cpp | 48 ++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/request_publisher.h b/src/startup_stubs/request_publisher.h index c2bf02c22d..969099e6ad 100644 --- a/src/startup_stubs/request_publisher.h +++ b/src/startup_stubs/request_publisher.h @@ -6,7 +6,7 @@ // // - The parts of one request are written in the order given, and requests in the order queued. // - A key is queued once per process. A repeated enqueue of it returns true without copying anything. A request that -// could not be written forgets its key, so a later enqueue of it is accepted again. +// could not be queued (out of memory) or written forgets its key, so a later enqueue of it is accepted again. // - The queued bytes are bounded. A request that would pass the bound is dropped and counted. // - stop() ends the thread and joins it (the destructor calls it). // - drain() is for module unload: it writes what is still queued on the calling thread, with its own writer (one that @@ -81,6 +81,8 @@ class RequestPublisher { seen_.insert(key); queue_.push_back(std::move(request)); } catch (...) { + // The key may already be recorded when queuing the copy fails: forget it, so a retry is accepted. + seen_.erase(key); ++stats_.dropped; ReleaseSRWLockExclusive(&lock_); return false; diff --git a/tests/startup_request_publisher_check.cpp b/tests/startup_request_publisher_check.cpp index 2d8a3da88b..9f66df67c4 100644 --- a/tests/startup_request_publisher_check.cpp +++ b/tests/startup_request_publisher_check.cpp @@ -1,18 +1,37 @@ // Checks src/startup_stubs/request_publisher.h without a device: a queued request returns while its writer is held, // parts and requests are written in order, a repeated key is written once, the byte bound drops and counts, a failed -// part stops its request, and drain() writes the queue on the calling thread (module unload). --mutate inline is the +// part stops its request, an enqueue that runs out of memory at any allocation can be retried, and drain() writes the queue on the calling thread (module unload). --mutate inline is the // negative control: each enqueue waits for its write, as a slot 86 mesh creation did before the publisher, so the // held-writer case must fail. #include "startup_stubs/request_publisher.h" #include #include +#include #include #include +#include #include #include #include +// Allocation failure injection for this thread only (the writer thread is unaffected): with allocations_left >= 0, +// that many allocations succeed and the next one throws std::bad_alloc. +thread_local long allocations_left = -1; + +void* operator new(std::size_t size) +{ + if (allocations_left == 0) { + allocations_left = -1; + throw std::bad_alloc(); + } + if (allocations_left > 0) --allocations_left; + if (void* p = std::malloc(size ? size : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } + namespace { using x2w_startup::RequestPublisher; @@ -143,6 +162,32 @@ void failed_part() expect(s.queued == 2 && s.repeated == 0 && s.written == 1, "a failed request is accepted and written again"); } +// Fails each allocation of an enqueue in turn, from the first one until the enqueue no longer fails. Every failed +// enqueue must report a drop and leave its key unrecorded, so the same key is queued (not counted as repeated) on retry. +void allocation_failure_retry() +{ + Writer writer; + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + int failed = 0; + for (long n = 0; n < 256; ++n) { + const std::uint64_t key = 0x100 + static_cast(n); + const auto before = publisher.stats(); + allocations_left = n; + const bool queued = queue(publisher, key); + allocations_left = -1; + if (queued) break; + ++failed; + expect(publisher.stats().dropped == before.dropped + 1, "an enqueue out of memory counts a drop"); + expect(queue(publisher, key), "a retry after an allocation failure is accepted"); + const auto after = publisher.stats(); + expect(after.queued == before.queued + 1 && after.repeated == before.repeated, + "a retry after an allocation failure queues the request"); + } + expect(failed >= 3, "allocation failures were injected inside enqueue"); + publisher.flush(5000); + expect(publisher.stats().written == publisher.stats().queued, "every retried request is written"); +} + void drain_while_running_and_stop() { Writer writer; @@ -173,6 +218,7 @@ int main(int argc, char** argv) held_writer(); byte_bound_and_drain(); failed_part(); + allocation_failure_retry(); drain_while_running_and_stop(); if (failures) { std::printf("request publisher: %d failed\n", failures); From 534b3ee9d6bd9dcb9e32b622eeeff576cccffd87 Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Tue, 1 Dec 2026 00:51:18 -0800 Subject: [PATCH 5/6] tests: wait for both complete slot 57 requests before checking the cache The request fixture enumerated the shader cache right after its dispatches. With the background publisher a request can still be in flight then, so the exact count of two requests and six files failed intermittently (startup_mesh57_runtime_warp). It now waits, for at most 10 s, until both .m57 ready markers exist and no part is still under its temporary name, then runs the same byte and count checks. The async default is kept. Co-Authored-By: Claude Opus 5.5 --- tests/startup_indirect_draw_indexed.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 02b7c56c32..64af0dd0b2 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -3549,6 +3549,22 @@ int main(int argc, char** argv) try if (!dispatch(pair.Get(), root.Get(), "mesh with PS") || !dispatch(depth.Get(), root.Get(), "mesh with no PS") || !dispatch(pair.Get(), root.Get(), "repeat mesh with PS")) return 1; + // Requests are written by the background publisher (request_publisher.h), .m57 last as the ready marker. + // Wait, bounded, for both complete requests and no part still in its temporary name before the exact checks. + const auto complete_requests = [&cache] { + unsigned markers = 0; + for (const auto& file : std::filesystem::directory_iterator(cache)) { + if (file.path().extension() == ".tmp") return ~0u; + if (file.path().extension() == ".m57") ++markers; + } + return markers; + }; + const ULONGLONG wait_start = GetTickCount64(); + while (complete_requests() != 2 && GetTickCount64() - wait_start < 10000) Sleep(10); + if (complete_requests() != 2) { + std::puts("FAIL: the two slot 57 requests were not complete within 10 s"); + return 1; + } unsigned requests = 0, with_ps = 0, files = 0; const auto matches = [](const std::filesystem::path& path, const void* bytes, std::size_t size) { std::ifstream stream(path, std::ios::binary); From 1319a11f15d1d83de411941e044b75357364d80b Mon Sep 17 00:00:00 2001 From: Jess-Doit Date: Tue, 1 Dec 2026 13:36:36 -0800 Subject: [PATCH 6/6] tests: leave debug iterator proxies out of the publisher allocation failures The Debug build (the dev preset) allocates an iterator proxy inside noexcept container constructors. The first injected failure landed there, so the test called std::terminate and the CRT's modal report waited until the CI job's 30-minute limit. Those allocations are now neither failed nor counted. Debug build, cl /Od /MDd: 0 cases failed; --mutate inline still fails (1). Release: startup_request_publisher and its inline control pass. Co-Authored-By: Claude Opus 5.5 --- tests/startup_request_publisher_check.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/startup_request_publisher_check.cpp b/tests/startup_request_publisher_check.cpp index 9f66df67c4..0ff8e5815b 100644 --- a/tests/startup_request_publisher_check.cpp +++ b/tests/startup_request_publisher_check.cpp @@ -16,11 +16,19 @@ #include // Allocation failure injection for this thread only (the writer thread is unaffected): with allocations_left >= 0, -// that many allocations succeed and the next one throws std::bad_alloc. +// that many allocations succeed and the next one throws std::bad_alloc. Debug builds (_ITERATOR_DEBUG_LEVEL != 0) +// also allocate an iterator proxy inside noexcept container constructors, where a throw ends in std::terminate and +// the CRT's modal report: those allocations are neither failed nor counted. thread_local long allocations_left = -1; void* operator new(std::size_t size) { +#if _ITERATOR_DEBUG_LEVEL != 0 + if (size == sizeof(std::_Container_proxy)) { + if (void* p = std::malloc(size)) return p; + throw std::bad_alloc(); + } +#endif if (allocations_left == 0) { allocations_left = -1; throw std::bad_alloc();