diff --git a/CMakeLists.txt b/CMakeLists.txt index 57c821c564..066431a6b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -669,9 +669,11 @@ add_test(NAME startup_descriptor_heap_type COMMAND startup_descriptor_heap_type_ add_test(NAME startup_descriptor_heap_type_off_by_one_control COMMAND startup_descriptor_heap_type_check --mutate off-by-one) add_test(NAME startup_descriptor_heap_type_signed_control COMMAND startup_descriptor_heap_type_check --mutate signed) set_tests_properties(startup_descriptor_heap_type_off_by_one_control startup_descriptor_heap_type_signed_control PROPERTIES WILL_FAIL TRUE) -# The one-time shader-cache listing that gates the native slot-57 profile open (src/startup_stubs/cache_index.h), -# without a device. The per-call control probes the disk for every name, as before the index, and must fail on the -# probe count alone. +# The one-time shader-cache listing that gates the native slot-57 profile open and the draw and Dispatch existence +# probes (src/startup_stubs/cache_index.h), and its change feed, without a device. The per-call control probes the +# disk for every name, as before the index, and must fail on the probe count alone. The feed controls drop created +# files, drop renamed-to names, or answer translator names from the listing alone; the retry controls trust a mark +# whatever changed, or watch names but not writes. Each must fail only those parts. add_executable(startup_cache_index_check tests/startup_cache_index_check.cpp) target_include_directories(startup_cache_index_check PRIVATE src) target_compile_features(startup_cache_index_check PRIVATE cxx_std_17) @@ -679,7 +681,27 @@ add_test(NAME startup_cache_index COMMAND startup_cache_index_check) add_test(NAME startup_cache_index_per_call_control COMMAND startup_cache_index_check --mutate per-call) set_tests_properties(startup_cache_index_per_call_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: \\(a\\) 515 disk probes for 515 lookups.*startup_cache_index_check: 1 failed" - FAIL_REGULAR_EXPRESSION "FAIL: \\([b-h]\\)") + FAIL_REGULAR_EXPRESSION "FAIL: \\([b-q]\\)") +add_test(NAME startup_cache_index_no_added_control COMMAND startup_cache_index_check --mutate no-added) +set_tests_properties(startup_cache_index_no_added_control PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: \\(j\\) a file created by another process after the listing never read present.*FAIL: \\(j\\) a file this process wrote after the listing never read present.*startup_cache_index_check: 2 failed" + FAIL_REGULAR_EXPRESSION "FAIL: \\([a-ik-q]\\)|renamed into place by another process after the listing") +add_test(NAME startup_cache_index_no_rename_control COMMAND startup_cache_index_check --mutate no-rename) +set_tests_properties(startup_cache_index_no_rename_control PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: \\(j\\) a file renamed into place by another process after the listing never read present.*startup_cache_index_check: 1 failed" + FAIL_REGULAR_EXPRESSION "FAIL: \\([a-ik-q]\\)|created by another process|this process wrote") +add_test(NAME startup_cache_index_listing_only_control COMMAND startup_cache_index_check --mutate listing-only) +set_tests_properties(startup_cache_index_listing_only_control PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: \\(k\\) fresh, without a feed,.*FAIL: \\(l\\) fresh, feed started after the listing,.*FAIL: \\(m\\) fresh, after the dropped batch,.*startup_cache_index_check: 4 failed" + FAIL_REGULAR_EXPRESSION "FAIL: \\([a-j]\\)|FAIL: \\([n-q]\\)") +add_test(NAME startup_cache_index_ignore_changes_control COMMAND startup_cache_index_check --mutate ignore-changes) +set_tests_properties(startup_cache_index_ignore_changes_control PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: \\(q\\) a manifest published after the miss was never picked up.*startup_cache_index_check: 1 failed" + FAIL_REGULAR_EXPRESSION "FAIL: \\([a-p]\\)") +add_test(NAME startup_cache_index_names_only_control COMMAND startup_cache_index_check --mutate names-only) +set_tests_properties(startup_cache_index_names_only_control PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: \\(o\\) a file another process rewrote in place never read changed.*startup_cache_index_check: 1 failed" + FAIL_REGULAR_EXPRESSION "FAIL: \\([a-np-q]\\)") # The same header without a GPU (src/startup_stubs/null_texture_view.h): fake adapters that lack # or have each use, R8G8B8A8 with one use, only B8G8R8A8, and failed queries. WARP has both uses, so # only this check reaches the rewrite on CI. The mutated run is the negative control. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c9e7b07785..fc61da6c6f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1809,7 +1809,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | | `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | | `X2W_PIPELINE_COLOUR=1` | diagnostic only, debug switch, in render mode: a `DrawInstanced`, `DrawIndexedInstanced` or `ExecuteIndirect` draw that draws nothing gets one flat marker tile in render target 0, in a colour taken from its pipeline key, and logs `x2w-draw colour #rrggbb for ` once per key ([details](experiments/pipeline-colour-fallback.md)). Not a fallback: the refused draw still draws nothing, and the tiles can tint later passes. Unset, nothing is drawn or logged | -| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | +| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first cache lookup the runtime starts a change feed on the directory (`ReadDirectoryChangesW`, top-level file names), then lists the directory's top-level file names once on the feed's thread and logs `x2w-draw cache index: names in ms; change feed ` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. The request-part and compute-marker probes (`req_` names, which only runtimes write) skip the disk for a name that is absent from the listing and from this process's own writes. The probes for `.txt` (graphics and compute manifests and the slot 57 base manifest) and `.cs.hlsl` skip it only while the change feed is reading and was reading before the listing began, so a file the translator writes later is found once its change record arrives. After a dropped batch or a feed error they use the disk again. A compute manifest retry (an absent, stale or unmarked `.txt`) whose `.*` names have no change record from the feed since its last miss repeats that miss without a file-system call; the feed records created, removed, renamed and rewritten files, and without a reading feed every retry looks on disk. Every 10 s while probes run, `x2w-draw cache probes (skipped as absent/on disk): ...` gives each probe's counts (and the compute retries repeated without I/O), the feed state, records and added names, the lookups that found a name added after the listing, and contradictions (a write that found a file the index had reported absent). | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | diff --git a/src/startup_stubs/cache_index.h b/src/startup_stubs/cache_index.h index 9c4335c12a..2557305a45 100644 --- a/src/startup_stubs/cache_index.h +++ b/src/startup_stubs/cache_index.h @@ -7,14 +7,28 @@ // ASCII names case-insensitively, and so does the index. A hash collision can only report a missing name as // present: the caller then opens it and takes its missing-file path. A listed name is never reported absent. // -// CacheDirectoryIndex lists one directory once, at its first lookup (std::call_once; FindFirstFileExW on -// "\*", files only, so names in subdirectories are not indexed). A lookup answers present, absent or -// unknown. unknown means "look on disk": the listing failed (any error, including a missing directory), or the -// lookup names a directory other than the listed one. An empty directory lists empty, through its "." and ".." -// entries; a directory with no entry at all, such as an empty volume root, fails with ERROR_FILE_NOT_FOUND and so -// uses the disk, as the stand-in did before the index. A file that another process creates after the listing reads -// absent until the next process starts. add() records the caller's own writes, and count_contradiction() counts a -// write that found a file the index had reported absent. +// CacheDirectoryIndex lists one directory once (std::call_once; FindFirstFileExW on "\*", files only, so +// names in subdirectories are not indexed): at the first lookup(), or on the change feed's thread (watch()). A +// lookup answers present, absent or unknown. unknown means "look on disk": the listing failed (any error, including +// a missing directory), is not made yet (peek()), or the lookup names a directory other than the listed one. An +// empty directory lists empty, through its "." and ".." entries; a directory with no entry at all, such as an empty +// volume root, fails with ERROR_FILE_NOT_FOUND and so uses the disk, as the stand-in did before the index. +// +// Names created after the listing: add() records the caller's own writes, and count_contradiction() counts a write +// that found a file the index had reported absent. Without the change feed, a file that another process creates +// after the listing reads absent until the next process starts. watch() starts the feed: one thread queues +// ReadDirectoryChangesW on the directory (file names, top level), then makes the listing, so that every file created +// after the listing began is in a change record; each created or renamed-to name is added as add() would. peek() with +// fresh set trusts absent only while that feed is reading and was reading before the listing began; a dropped batch +// (ERROR_NOTIFY_ENUM_DIR or an empty completion) or any feed error ends the feed, and fresh lookups are unknown from +// then on. A name created just before its record is read still reads absent until then. +// +// Change marks: the feed also numbers every record (created, removed, renamed or rewritten in place: the feed watches +// last writes and sizes too) whose name starts with a cache key, "<16 hex digits>.". change_mark() taken before a +// look on disk, and key_changed() later, tell whether any .* name may have changed since: true for a record +// numbered from the mark on, and always true when the feed is not reading, was not reading when the listing began, +// or the mark is 0 (change_mark() gives 0 in those states). A record read after the mark for a change made before +// it also answers true, so a caller that marks first never trusts a look that raced a change. #pragma once #include @@ -29,18 +43,25 @@ inline wchar_t cache_name_fold(wchar_t c) noexcept return c >= L'A' && c <= L'Z' ? static_cast(c - L'A' + L'a') : c; } -// FNV-1a-64 over the folded name's UTF-16 code units, low byte first. -inline std::uint64_t cache_name_hash(const wchar_t* name) noexcept +// FNV-1a-64 over the folded name's UTF-16 code units, low byte first: the first length units, or up to the NUL. +inline std::uint64_t cache_name_hash(const wchar_t* name, std::size_t length) noexcept { std::uint64_t hash = 1469598103934665603ull; - for (; *name; ++name) { - const auto unit = static_cast(cache_name_fold(*name)) & 0xffffu; + for (std::size_t i = 0; i < length; ++i) { + const auto unit = static_cast(cache_name_fold(name[i])) & 0xffffu; hash = (hash ^ (unit & 0xffu)) * 1099511628211ull; hash = (hash ^ (unit >> 8)) * 1099511628211ull; } return hash; } +inline std::uint64_t cache_name_hash(const wchar_t* name) noexcept +{ + std::size_t length = 0; + while (name[length]) ++length; + return cache_name_hash(name, length); +} + // add() every name, then seal() once; contains() and size() answer for the sealed set. class CacheNameIndex { public: @@ -67,6 +88,7 @@ class CacheNameIndex { #include #include #include +#include #include #ifndef WIN32_LEAN_AND_MEAN @@ -81,14 +103,49 @@ namespace x2w_startup { enum class CacheLookup : unsigned char { absent, present, unknown }; +// The change records that name a file that now exists: a created file and the new name of a rename. +inline bool cache_feed_adds(DWORD action) noexcept +{ + return action == FILE_ACTION_ADDED || action == FILE_ACTION_RENAMED_NEW_NAME; +} + +// What the feed watches: names (create, delete, rename), and last writes and sizes, so that a file rewritten in place +// has a record too. +constexpr DWORD cache_feed_filter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE; + +// The key that name starts with: "<16 hex digits>." in either case, else false. +inline bool cache_name_key(const wchar_t* name, std::size_t length, std::uint64_t& key) noexcept +{ + if (length < 17 || name[16] != L'.') return false; + key = 0; + for (int i = 0; i < 16; ++i) { + const wchar_t c = cache_name_fold(name[i]); + const int digit = c >= L'0' && c <= L'9' ? c - L'0' : c >= L'a' && c <= L'f' ? c - L'a' + 10 : -1; + if (digit < 0) return false; + key = key << 4 | static_cast(digit); + } + return true; +} + class CacheDirectoryIndex { public: - CacheDirectoryIndex() = default; + // off: watch() not called. starting: until the first read is queued. reading: fresh lookups may answer absent. + // failed: the feed could not start or a read failed. dropped: the system dropped a batch. stopped: destroyed. + enum FeedState : LONG { feed_off, feed_starting, feed_reading, feed_failed, feed_dropped, feed_stopped }; + + // feed_bytes is the size of each ReadDirectoryChangesW batch; feed_adds picks the records that add a name, and + // feed_filter is what the feed watches. + explicit CacheDirectoryIndex(DWORD feed_bytes = 64 * 1024, bool (*feed_adds)(DWORD) = cache_feed_adds, + DWORD feed_filter = cache_feed_filter) noexcept + : feed_bytes_(feed_bytes), feed_adds_(feed_adds), feed_filter_(feed_filter) + { + } CacheDirectoryIndex(const CacheDirectoryIndex&) = delete; CacheDirectoryIndex& operator=(const CacheDirectoryIndex&) = delete; + ~CacheDirectoryIndex() { stop_feed(); } - // Whether \ exists. The first call lists directory; *listed_now is set for that one call, so - // its caller can log the listing. + // Whether \ exists. The first call lists directory, or waits for the feed thread's listing; + // *listed_now is set for the one call that made it, so its caller can log the listing. CacheLookup lookup(const wchar_t* directory, const wchar_t* name, bool* listed_now = nullptr) noexcept { if (listed_now) *listed_now = false; @@ -101,32 +158,79 @@ class CacheDirectoryIndex { return CacheLookup::unknown; } if (!ready_.load(std::memory_order_acquire) || !same_directory(directory)) return CacheLookup::unknown; - if (listed_.contains(name)) return CacheLookup::present; - SharedLock guard(lock_); - return written_.count(cache_name_hash(name)) ? CacheLookup::present : CacheLookup::absent; + return answer(name); } - // A file the caller created in the listed directory, after or during the listing. - void add(const wchar_t* name) noexcept + // lookup() without making or waiting for the listing: unknown until it is ready. With fresh, absent also needs + // the change feed to be reading, and to have been reading when the listing began; otherwise unknown. + CacheLookup peek(const wchar_t* directory, const wchar_t* name, bool fresh) noexcept { - try { - ExclusiveLock guard(lock_); - written_.insert(cache_name_hash(name)); - } catch (...) { - // The name keeps its listed answer. - } + if (!ready_.load(std::memory_order_acquire) || !same_directory(directory)) return CacheLookup::unknown; + if (fresh && (!listed_while_reading_ || feed_state() != feed_reading)) return CacheLookup::unknown; + return answer(name); } + // A file the caller created in the listed directory, after or during the listing. + void add(const wchar_t* name) noexcept { add_hash(cache_name_hash(name)); } + // A write found a file that the index had reported absent: another writer created it after the listing. void count_contradiction() noexcept { InterlockedIncrement(&contradictions_); } LONG contradictions() const noexcept { return contradictions_; } - // The listing, once lookup() has made it: usable, number of distinct names, time taken, and the error that - // made it unusable (0 when usable). + // Starts the change feed on directory and waits up to 5 s for its first read to be queued. Its thread then + // makes the listing (the one lookup() makes) unless a lookup made it first. Later calls do nothing. + void watch(const wchar_t* directory) noexcept + { + if (InterlockedCompareExchange(&feed_state_, feed_starting, feed_off) != feed_off) return; + try { + feed_directory_ = directory; + } catch (...) { + feed_end(feed_failed, ERROR_NOT_ENOUGH_MEMORY); + return; + } + queued_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (queued_) feed_thread_ = CreateThread(nullptr, 0, feed_main, this, 0, nullptr); + if (!feed_thread_) { + feed_end(feed_failed, GetLastError()); + return; + } + WaitForSingleObject(queued_, 5000); + } + + // The listing: usable, number of distinct names, time taken, the error that made it unusable (0 when usable), + // and whether it is finished, usable or not. bool ready() const noexcept { return ready_.load(std::memory_order_acquire); } std::size_t names() const noexcept { return ready() ? listed_.size() : 0; } unsigned long long listing_ms() const noexcept { return listing_ms_.load(std::memory_order_acquire); } DWORD listing_error() const noexcept { return listing_error_.load(std::memory_order_acquire); } + bool listing_finished() const noexcept { return listing_finished_.load(std::memory_order_acquire); } + + // The change feed: its state, the error that ended it, records read, names those records added, whether its + // listing began after its first read was queued, and lookups that found a name added after the listing (by + // add() or the feed). + LONG feed_state() const noexcept { return InterlockedCompareExchange(const_cast(&feed_state_), 0, 0); } + DWORD feed_error() const noexcept { return feed_error_.load(std::memory_order_acquire); } + LONG64 feed_records() const noexcept { return read64(feed_records_); } + LONG64 feed_added() const noexcept { return read64(feed_added_); } + bool listed_while_reading() const noexcept { return ready() && listed_while_reading_; } + LONG64 later_present() const noexcept { return read64(later_present_); } + + // A mark for key_changed(), taken before a look on disk; 0 while fresh lookups would be unknown. + std::uint64_t change_mark() const noexcept + { + if (!fresh_ready()) return 0; + SharedLock guard(lock_); + return key_records_ + 1; + } + + // Whether any .* name may have changed since mark (see the comment at the top). + bool key_changed(std::uint64_t key, std::uint64_t mark) const noexcept + { + if (!mark || !fresh_ready()) return true; + SharedLock guard(lock_); + const auto found = key_changes_.find(key); + return found != key_changes_.end() && found->second >= mark; + } private: struct SharedLock { @@ -140,6 +244,47 @@ class CacheDirectoryIndex { SRWLOCK& lock; }; + static LONG64 read64(const volatile LONG64& value) noexcept + { + return InterlockedCompareExchange64(const_cast(&value), 0, 0); + } + + bool fresh_ready() const noexcept + { + return ready_.load(std::memory_order_acquire) && listed_while_reading_ && feed_state() == feed_reading; + } + + CacheLookup answer(const wchar_t* name) noexcept + { + if (listed_.contains(name)) return CacheLookup::present; + SharedLock guard(lock_); + if (!written_.count(cache_name_hash(name))) return CacheLookup::absent; + InterlockedIncrement64(&later_present_); + return CacheLookup::present; + } + + void note_key_change(std::uint64_t key) noexcept + { + ExclusiveLock guard(lock_); + const std::uint64_t number = ++key_records_; + try { + key_changes_[key] = number; + } catch (...) { + // Out of memory: the feed can no longer say which keys changed. + feed_end(feed_failed, ERROR_NOT_ENOUGH_MEMORY); + } + } + + void add_hash(std::uint64_t hash) noexcept + { + try { + ExclusiveLock guard(lock_); + written_.insert(hash); + } catch (...) { + // The name keeps its listed answer. + } + } + bool same_directory(const wchar_t* directory) const noexcept { std::size_t i = 0; @@ -150,6 +295,7 @@ class CacheDirectoryIndex { void list(const wchar_t* directory) noexcept { + listed_while_reading_ = feed_state() == feed_reading; LARGE_INTEGER start{}, end{}, frequency{}; QueryPerformanceCounter(&start); DWORD error = ERROR_SUCCESS; @@ -187,17 +333,148 @@ class CacheDirectoryIndex { std::memory_order_release); listing_error_.store(error, std::memory_order_release); ready_.store(error == ERROR_SUCCESS, std::memory_order_release); + listing_finished_.store(true, std::memory_order_release); + } + + // The feed ends once: a failure or a dropped batch keeps the first reason, and stop_feed() marks it stopped. + void feed_end(LONG state, DWORD error) noexcept + { + for (LONG now = feed_state(); now == feed_starting || now == feed_reading; now = feed_state()) { + if (InterlockedCompareExchange(&feed_state_, state, now) == now) { + feed_error_.store(error, std::memory_order_release); + break; + } + } + if (queued_) SetEvent(queued_); + } + + static DWORD WINAPI feed_main(void* self) + { + static_cast(self)->feed(); + return 0; + } + + bool queue_read(HANDLE directory, HANDLE event, void* buffer, OVERLAPPED& overlapped) noexcept + { + overlapped = {}; + overlapped.hEvent = event; + ResetEvent(event); + return !stopping_.load(std::memory_order_acquire) && + ReadDirectoryChangesW(directory, buffer, feed_bytes_, FALSE, feed_filter_, nullptr, + &overlapped, nullptr); + } + + void feed() noexcept + { + const HANDLE directory = CreateFileW(feed_directory_.c_str(), FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr); + DWORD error = directory == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS; + const HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!event && !error) error = GetLastError(); + // ReadDirectoryChangesW needs a DWORD-aligned buffer; VirtualAlloc gives a page. + void* const buffer = feed_bytes_ ? VirtualAlloc(nullptr, feed_bytes_, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) + : nullptr; + if (!buffer && !error) error = feed_bytes_ ? GetLastError() : ERROR_INVALID_PARAMETER; + OVERLAPPED overlapped{}; + bool reading = false; + if (error) { + feed_end(feed_failed, error); + } else { + feed_handle_.store(directory, std::memory_order_release); + reading = queue_read(directory, event, buffer, overlapped); + if (reading) InterlockedCompareExchange(&feed_state_, feed_reading, feed_starting); + else feed_end(feed_failed, GetLastError()); + } + SetEvent(queued_); + // From here on, a file created in the directory is in a change record, so the listing misses none. + try { + std::call_once(once_, [&] { list(feed_directory_.c_str()); }); + } catch (...) { + // Lookups stay unknown. + } + while (reading) { + DWORD got = 0; + if (!GetOverlappedResult(directory, &overlapped, &got, TRUE)) { + const DWORD failure = GetLastError(); + feed_end(failure == ERROR_NOTIFY_ENUM_DIR ? feed_dropped : feed_failed, failure); + break; + } + if (!got) { + feed_end(feed_dropped, ERROR_NOTIFY_ENUM_DIR); + break; + } + for (DWORD at = 0; at + sizeof(FILE_NOTIFY_INFORMATION) <= got;) { + const auto* info = reinterpret_cast(static_cast(buffer) + at); + InterlockedIncrement64(&feed_records_); + const std::size_t length = info->FileNameLength / sizeof(WCHAR); + if (feed_adds_(info->Action)) { + add_hash(cache_name_hash(info->FileName, length)); + InterlockedIncrement64(&feed_added_); + } + std::uint64_t key = 0; + if (cache_name_key(info->FileName, length, key)) note_key_change(key); + if (!info->NextEntryOffset) break; + at += info->NextEntryOffset; + } + reading = queue_read(directory, event, buffer, overlapped); + if (!reading) feed_end(feed_failed, stopping_.load(std::memory_order_acquire) ? ERROR_OPERATION_ABORTED : GetLastError()); + } + { + // stop_feed() cancels through feed_handle_ under the shared lock, never on a closed handle. + ExclusiveLock guard(feed_handle_lock_); + feed_handle_.store(INVALID_HANDLE_VALUE, std::memory_order_release); + } + if (directory != INVALID_HANDLE_VALUE) { + CancelIoEx(directory, nullptr); + CloseHandle(directory); + } + if (event) CloseHandle(event); + if (buffer) VirtualFree(buffer, 0, MEM_RELEASE); + } + + // The stand-in never destroys its index; a test does, and this ends the feed thread first. + void stop_feed() noexcept + { + if (!feed_thread_) { + if (queued_) CloseHandle(queued_); + return; + } + stopping_.store(true, std::memory_order_release); + do { + SharedLock guard(feed_handle_lock_); + const HANDLE directory = feed_handle_.load(std::memory_order_acquire); + if (directory != INVALID_HANDLE_VALUE) CancelIoEx(directory, nullptr); + } while (WaitForSingleObject(feed_thread_, 100) == WAIT_TIMEOUT); + CloseHandle(feed_thread_); + CloseHandle(queued_); + InterlockedExchange(&feed_state_, feed_stopped); } std::once_flag once_; - std::atomic ready_{false}; + std::atomic ready_{false}, listing_finished_{false}; std::atomic listing_ms_{0}; std::atomic listing_error_{0}; std::wstring directory_; // folded CacheNameIndex listed_; + bool listed_while_reading_ = false; // written by list() before ready_ mutable SRWLOCK lock_ = SRWLOCK_INIT; // leaf lock for written_; never held across I/O std::unordered_set written_; + std::uint64_t key_records_ = 0; // under lock_: records that named a key, numbered from 1 + std::unordered_map key_changes_; // under lock_: key -> number of its latest record volatile LONG contradictions_ = 0; + + const DWORD feed_bytes_; + bool (*const feed_adds_)(DWORD); + const DWORD feed_filter_; + std::wstring feed_directory_; // as given to watch() + HANDLE feed_thread_ = nullptr, queued_ = nullptr; + std::atomic feed_handle_{INVALID_HANDLE_VALUE}; + SRWLOCK feed_handle_lock_ = SRWLOCK_INIT; // leaf lock: the feed thread clears feed_handle_ under it + std::atomic stopping_{false}; + volatile LONG feed_state_ = feed_off; + std::atomic feed_error_{0}; + volatile LONG64 feed_records_ = 0, feed_added_ = 0, later_present_ = 0; }; } // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index b729ce04e2..665adde515 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -56,6 +56,8 @@ struct ComputeTranslation { u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable x2w_startup::ManifestRetry manifest_retry; // absent and stale manifests can become ready later + u64 manifest_mark = 0; // the cache change mark taken before the last miss's look (cache_change_mark) + const char* manifest_miss = nullptr; // what that miss returned std::vector uds, srvs, uavs; UINT heap_srvs = 0; UINT sampler_heap_bytes = 0; // `smpidx`: the program reads the title's sampler heap (directly indexed) up to this byte @@ -298,28 +300,38 @@ const char* load_compute_translation(ComputeTranslation& tr) tr.manifest_retry.found(); return nullptr; } - wchar_t path[MAX_PATH]; - std::string manifest; - if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { + // A retry while no .* name has a change record since the last miss's mark repeats that miss without I/O. + if (tr.manifest_mark && !cache_key_changed(tr.key, tr.manifest_mark)) { tr.manifest_retry.missed(GetTickCount64()); - return nullptr; + return tr.manifest_miss; } + // Marked before the first look on disk, so a change that races the looks below sends the next retry to disk. + const u64 mark = cache_change_mark(tr.manifest_mark != 0); + const auto miss = [&](const char* reason) { + tr.manifest_retry.missed(GetTickCount64()); + tr.manifest_mark = mark; + tr.manifest_miss = reason; + return reason; + }; + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", tr.key, L".txt") || cache_absent(probe_compute_manifest, L"", tr.key, L".txt", true) || + !read_text(path, manifest)) + return miss(nullptr); // A native manifest from another compiler revision, or an unmarked one without the Python translator's // .cs.hlsl, is stale: it is looked for again on the same schedule as an absent one. const auto output = x2w::native_compute_output(manifest); - if (output == x2w::NativeComputeOutput::incompatible) { - tr.manifest_retry.missed(GetTickCount64()); - return "native translation from another compiler revision; rebuild it"; - } + if (output == x2w::NativeComputeOutput::incompatible) + return miss("native translation from another compiler revision; rebuild it"); if (output == x2w::NativeComputeOutput::unmarked) { - const DWORD attributes = cache_path(path, L"", tr.key, L".cs.hlsl") + const DWORD attributes = cache_path(path, L"", tr.key, L".cs.hlsl") && + !cache_absent(probe_compute_hlsl, L"", tr.key, L".cs.hlsl", true) ? GetFileAttributesW(path) : INVALID_FILE_ATTRIBUTES; - if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY)) { - tr.manifest_retry.missed(GetTickCount64()); - return "native translation without a revision; rebuild it"; - } + if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY)) + return miss("native translation without a revision; rebuild it"); } tr.manifest_retry.found(); + tr.manifest_mark = 0; unsigned declared_uds = 0, line_number = 0; for (std::size_t at = 0; at < manifest.size(); ++line_number) { std::size_t end = manifest.find('\n', at); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 28f3f550ac..ce86756d19 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -265,13 +265,40 @@ bool cache_path(wchar_t* out, const wchar_t* prefix, u64 key, const wchar_t* ext return true; } -// X2W_SHADER_CACHE's top-level names, listed at the first cache_lookup (src/startup_stubs/cache_index.h). +// X2W_SHADER_CACHE's top-level names (src/startup_stubs/cache_index.h). The first use starts the change feed, whose +// thread then lists the directory. The index is never destroyed: the feed thread reads until the process exits. x2w_startup::CacheDirectoryIndex& cache_index() { - static x2w_startup::CacheDirectoryIndex index; + static x2w_startup::CacheDirectoryIndex& index = []() -> x2w_startup::CacheDirectoryIndex& { + auto* made = new x2w_startup::CacheDirectoryIndex; + wchar_t dir[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (n && n < MAX_PATH) made->watch(dir); + return *made; + }(); return index; } +const char* cache_feed_state_name(LONG state) +{ + static const char* const names[] = {"off", "starting", "reading", "failed", "dropped a batch", "stopped"}; + return state >= 0 && state < static_cast(std::size(names)) ? names[state] : "?"; +} + +// The listing's one log line, once it is finished, from whichever lookup sees that first. +void log_cache_listing(const x2w_startup::CacheDirectoryIndex& index) +{ + static LONG logged; + if (!index.listing_finished() || InterlockedCompareExchange(&logged, 1, 0)) return; + if (index.ready()) + log("x2w-draw cache index: %zu names in %llu ms; change feed %s%s", index.names(), index.listing_ms(), + cache_feed_state_name(index.feed_state()), + index.listed_while_reading() ? "" : " (not reading when the listing began: translator files use the disk)"); + else + log("x2w-draw cache index: listing failed with error %lu after %llu ms; lookups use the disk", + static_cast(index.listing_error()), index.listing_ms()); +} + // Whether the file cache_path would name exists, by the listing: absent needs no file-system call, and unknown // (no usable listing) means look on disk. x2w_startup::CacheLookup cache_lookup(const wchar_t* prefix, u64 key, const wchar_t* extension) @@ -281,16 +308,97 @@ x2w_startup::CacheLookup cache_lookup(const wchar_t* prefix, u64 key, const wcha if (!n || n >= MAX_PATH) return x2w_startup::CacheLookup::unknown; swprintf(name, MAX_PATH, L"%s%016llx%s", prefix, key, extension); auto& index = cache_index(); - bool listed_now = false; - const auto result = index.lookup(dir, name, &listed_now); - if (listed_now && index.ready()) - log("x2w-draw cache index: %zu names in %llu ms", index.names(), index.listing_ms()); - else if (listed_now) - log("x2w-draw cache index: listing failed with error %lu after %llu ms; lookups use the disk", - static_cast(index.listing_error()), index.listing_ms()); + const auto result = index.lookup(dir, name); + log_cache_listing(index); return result; } +// The existence probes of the draw and Dispatch paths that the index answers (cache_absent). The request parts and +// the compute request marker are req_ names, which only runtimes write; the rest are the translator's files. The +// compute retry count is of manifest retries repeated without I/O (cache_key_changed) or looked for on disk. +enum CacheProbe { probe_request_part, probe_base_manifest, probe_graphics_manifest, probe_compute_manifest, + probe_compute_hlsl, probe_compute_marker, probe_compute_retry, cache_probe_count }; +volatile LONG cache_probes_skipped[cache_probe_count], cache_probes_on_disk[cache_probe_count]; + +// Every 10 s while the probes run (so also after presents stop): each probe's skipped and on-disk counts, and how +// the change feed keeps the index current for files that appear after the listing. +void report_cache_probes(const x2w_startup::CacheDirectoryIndex& index) +{ + static volatile LONG64 next_report; + static volatile LONG64 reported_total; + const auto now = static_cast(GetTickCount64()); + const LONG64 due = InterlockedCompareExchange64(&next_report, 0, 0); + if (now < due || InterlockedCompareExchange64(&next_report, now + 10000, due) != due) return; + LONG64 total = 0; + LONG skipped[cache_probe_count], on_disk[cache_probe_count]; + for (int i = 0; i < cache_probe_count; ++i) { + skipped[i] = InterlockedCompareExchange(&cache_probes_skipped[i], 0, 0); + on_disk[i] = InterlockedCompareExchange(&cache_probes_on_disk[i], 0, 0); + total += skipped[i] + on_disk[i]; + } + if (InterlockedExchange64(&reported_total, total) == total) return; + log("x2w-draw cache probes (skipped as absent/on disk): request part %ld/%ld, slot 57 base manifest %ld/%ld, " + "graphics manifest %ld/%ld, compute manifest %ld/%ld, compute .cs.hlsl %ld/%ld, compute marker %ld/%ld, " + "compute retry unchanged %ld/%ld; " + "change feed %s (error %lu), %lld records, %lld names added, %lld lookups found a name added after the listing; " + "%ld contradictions", + skipped[0], on_disk[0], skipped[1], on_disk[1], skipped[2], on_disk[2], skipped[3], on_disk[3], skipped[4], + on_disk[4], skipped[5], on_disk[5], skipped[6], on_disk[6], cache_feed_state_name(index.feed_state()), + static_cast(index.feed_error()), static_cast(index.feed_records()), + static_cast(index.feed_added()), static_cast(index.later_present()), + index.contradictions()); +} + +// Whether the index says is absent from X2W_SHADER_CACHE, so that the caller skips its +// file-system call and takes its missing-file path. fresh is for a name the translator writes: absent then also +// needs the change feed (CacheDirectoryIndex::peek). present and unknown leave the probe to the disk. Never lists +// or waits for the listing, so a caller holding draw_lock does not wait for it. +bool cache_absent(CacheProbe probe, const wchar_t* prefix, u64 key, const wchar_t* extension, bool fresh) +{ + wchar_t dir[MAX_PATH], name[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + auto& index = cache_index(); + bool absent = false; + if (n && n < MAX_PATH) { + swprintf(name, MAX_PATH, L"%s%016llx%s", prefix, key, extension); + absent = index.peek(dir, name, fresh) == x2w_startup::CacheLookup::absent; + } + InterlockedIncrement(absent ? &cache_probes_skipped[probe] : &cache_probes_on_disk[probe]); + log_cache_listing(index); + report_cache_probes(index); + return absent; +} + +// The change mark a retry takes before it looks on disk (CacheDirectoryIndex::change_mark); 0 when the feed cannot +// say. retry counts it as a compute retry that went to disk. +u64 cache_change_mark(bool retry) +{ + auto& index = cache_index(); + if (retry) { + InterlockedIncrement(&cache_probes_on_disk[probe_compute_retry]); + report_cache_probes(index); + } + return index.change_mark(); +} + +// Whether any .* name may have changed since mark; false lets a retry repeat its miss without I/O. +bool cache_key_changed(u64 key, u64 mark) +{ + auto& index = cache_index(); + const bool changed = index.key_changed(key, mark); + if (!changed) InterlockedIncrement(&cache_probes_skipped[probe_compute_retry]); + report_cache_probes(index); + return changed; +} + +// A request part this process published (publish_shader_request), for the index. +void note_cache_write(const wchar_t* prefix, u64 key, const wchar_t* extension) +{ + wchar_t name[MAX_PATH]; + swprintf(name, MAX_PATH, L"%s%016llx%s", prefix, key, extension); + cache_index().add(name); +} + bool read_text(const wchar_t* path, std::string& out) { HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); @@ -458,7 +566,9 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: wchar_t path[MAX_PATH], temporary[MAX_PATH], suffix[32]; write_cache_revision(); if (!cache_path(path, L"req_", key, ext)) return false; - if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; + // Only runtimes write req_ names, so the listing and this process's own writes answer absent (cache_absent). + const bool absent = cache_absent(probe_request_part, L"req_", key, ext, false); + if (!absent && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; swprintf(suffix, std::size(suffix), L"%s.%lu.tmp", ext, GetCurrentProcessId()); if (!cache_path(temporary, L"req_", key, suffix)) return false; HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); @@ -466,9 +576,18 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: 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; + if (complete && MoveFileExW(temporary, path, 0)) { + note_cache_write(L"req_", key, ext); + return true; + } DeleteFileW(temporary); - return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; + const bool exists = GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; + if (exists) { + // Another writer published the part after the listing; the index reported it absent. + if (absent) cache_index().count_contradiction(); + note_cache_write(L"req_", key, ext); + } + return exists; } bool native_shaders_only() @@ -490,7 +609,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: wchar_t path[MAX_PATH]; const bool provided = !manifest.empty(); if (!cache_path(path, L"", tr.key, L".txt")) return; - if (!provided && !read_text(path, manifest)) { + if (!provided && (cache_absent(probe_graphics_manifest, L"", tr.key, L".txt", true) || !read_text(path, manifest))) { if (!tr.manifest_retry.pending()) { InterlockedIncrement(&translation_missing); static LONG missing; @@ -697,11 +816,18 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* // request. Only a cold pipeline keeps the entry in its key. In native-shaders-only mode .txt // manifests are ignored, so a leftover Python manifest must not strip the entry from the request // the native path receives: the reuse is skipped there and the entry stays in the key. + // A plain-key manifest the cache index lists as absent cannot be reused (cache_absent), so that pipeline + // is cold and keeps the entry without the disk probe below. wchar_t base_path[MAX_PATH]; - const bool base_cached = !native_shaders_only() && cache_path(base_path, L"", key, L".txt") && - GetFileAttributesW(base_path) != INVALID_FILE_ATTRIBUTES; - if (base_cached) pixel_entry.clear(); - else key = fnv_bytes(pixel_entry.data(), pixel_entry.size(), key); + if (!native_shaders_only() && cache_path(base_path, L"", key, L".txt") && + cache_absent(probe_base_manifest, L"", key, L".txt", true)) { + key = fnv_bytes(pixel_entry.data(), pixel_entry.size(), key); + } else { + const bool base_cached = !native_shaders_only() && cache_path(base_path, L"", key, L".txt") && + GetFileAttributesW(base_path) != INVALID_FILE_ATTRIBUTES; + if (base_cached) pixel_entry.clear(); + else key = fnv_bytes(pixel_entry.data(), pixel_entry.size(), key); + } } auto& entry = translation_by_key()[key]; if (!entry) { @@ -863,7 +989,8 @@ u64 publish_compute_request(const void* desc) bool present = already_seen; bool written = present; if (!present) { - present = cache_path(marker, L"req_", key, L".c67") && GetFileAttributesW(marker) != INVALID_FILE_ATTRIBUTES; + present = cache_path(marker, L"req_", key, L".c67") && !cache_absent(probe_compute_marker, L"req_", key, L".c67", false) && + GetFileAttributesW(marker) != INVALID_FILE_ATTRIBUTES; // Parts left by an interrupted earlier write are kept; the marker comes last, so the request completes here. written = present || (write(L".desc", fields) && write(L".sa", state_a) && write(L".sb", state_b) && write(L".data", data) && write(L".root", root_blob) && write(L".c67", code)); diff --git a/tests/startup_cache_index_check.cpp b/tests/startup_cache_index_check.cpp index c5071f0a61..0725129423 100644 --- a/tests/startup_cache_index_check.cpp +++ b/tests/startup_cache_index_check.cpp @@ -5,7 +5,29 @@ // (c) one listing of the top-level files only; (d) other directories and subdirectories: unknown; // (e) add() and the contradiction counter; (f) an empty directory lists empty, a missing one // is unknown; (g) concurrent first lookups list once and agree; (h) the name hash and the sorted set. +// The change feed (watch() and peek(), which the draw and Dispatch probes use; fresh = a translator-written name): +// (i) peek() never lists: unknown until a listing exists; +// (j) with the feed reading, the feed thread lists, and a file that another process creates, or renames into +// place, after the listing reads absent before and present after (fresh and plain); one written in this +// process too; +// (k) without the feed, such a file stays absent for plain lookups and fresh lookups are unknown; +// (l) a feed started after the listing leaves fresh lookups unknown; +// (m) a dropped batch (a batch buffer smaller than one record) ends the feed: fresh lookups are unknown; +// (n) a feed on a missing directory fails, and its lookups are unknown; destroying a watching index ends its thread. +// Change marks (the compute manifest retry, load_compute_translation, repeats an unchanged miss without I/O): +// (o) a key whose file another process creates, rewrites in place or renames into place after the mark reads +// changed; a change to another key or to a name that is no key leaves a key unchanged; a later mark resets it; +// (p) with no feed, or after a dropped batch, the mark is 0 and every key reads changed; +// (q) the retry loop: 50 retries of an absent manifest look on disk once; a manifest another process publishes +// later is picked up, with one more look on disk. // --mutate per-call probes the disk for every name, as the stand-in did before the index; it must fail (a) only. +// --mutate no-added drops created-file records (j: the created file never reads present); --mutate no-rename drops +// renamed-to records (j: the renamed file never reads present); --mutate listing-only answers fresh lookups from the +// listing and own writes alone (k, l and m: absent instead of unknown); --mutate ignore-changes lets a retry trust its +// mark whatever changed (q: the late manifest is never picked up); --mutate names-only watches names but not writes +// (o: the file rewritten in place never reads changed). Each must fail only those parts. +// --child-create , --child-rename and --child-rewrite are the other process of (j), +// (k), (o) and (q). // --measure lists once and opens one missing name there, timing both; it changes nothing. #include "startup_stubs/cache_index.h" @@ -29,8 +51,29 @@ using x2w_startup::CacheLookup; using Clock = std::chrono::steady_clock; bool per_call = false; +enum class Mutation { none, no_added, no_rename, listing_only, ignore_changes, names_only } mutation = Mutation::none; int failures = 0; +// The feed's record filter: cache_feed_adds, or a mutated one that drops created files or renamed-to names. +bool feed_adds(DWORD action) +{ + if (mutation == Mutation::no_added && action == FILE_ACTION_ADDED) return false; + if (mutation == Mutation::no_rename && action == FILE_ACTION_RENAMED_NEW_NAME) return false; + return x2w_startup::cache_feed_adds(action); +} + +// What the feeds of (o) and (q) watch; --mutate names-only leaves out writes. +DWORD feed_filter() +{ + return mutation == Mutation::names_only ? FILE_NOTIFY_CHANGE_FILE_NAME : x2w_startup::cache_feed_filter; +} + +// A fresh lookup as cache_absent makes it; --mutate listing-only ignores the feed. +CacheLookup fresh(x2w_startup::CacheDirectoryIndex& index, const fs::path& directory, const std::wstring& name) +{ + return index.peek(directory.c_str(), name.c_str(), mutation != Mutation::listing_only); +} + void fail(const char* part, const std::string& what) { std::printf("FAIL: (%s) %s\n", part, what.c_str()); @@ -103,13 +146,311 @@ int measure(const fs::path& directory) return 0; } +void expect_peek(const char* part, CacheLookup got, const std::wstring& name, const char* how, CacheLookup expected) +{ + if (got == expected) return; + char narrow[96]; + std::snprintf(narrow, sizeof(narrow), "%ls", name.c_str()); + fail(part, std::string(how) + " " + narrow + " is " + text(got) + ", expected " + text(expected)); +} + +// Runs this program as another process with arguments, and waits for it. +bool run_child(const std::wstring& arguments) +{ + wchar_t self[MAX_PATH]; + if (!GetModuleFileNameW(nullptr, self, MAX_PATH)) return false; + std::wstring line = L"\"" + std::wstring(self) + L"\" " + arguments; + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION process{}; + if (!CreateProcessW(nullptr, line.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process)) + return false; + WaitForSingleObject(process.hProcess, 30000); + DWORD code = 1; + GetExitCodeProcess(process.hProcess, &code); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + return code == 0; +} + +int child_create(const wchar_t* path) +{ + const HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return 3; + DWORD done = 0; + const bool ok = WriteFile(file, "child", 5, &done, nullptr) && done == 5; + CloseHandle(file); + return ok ? 0 : 4; +} + +int child_rename(const wchar_t* temporary, const wchar_t* path) +{ + if (child_create(temporary)) return 5; + return MoveFileExW(temporary, path, 0) ? 0 : 6; +} + +// Writes over the start of an existing file: no name changes, only its last write. +int child_rewrite(const wchar_t* path) +{ + const HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return 7; + DWORD done = 0; + const bool ok = WriteFile(file, "REWRITE", 7, &done, nullptr) && done == 7; + CloseHandle(file); + return ok ? 0 : 8; +} + +// Polls until the lookup answers expected, for up to 5 s (the feed thread reads change records asynchronously). +CacheLookup settle(x2w_startup::CacheDirectoryIndex& index, const fs::path& directory, const std::wstring& name, + bool fresh_lookup, CacheLookup expected) +{ + CacheLookup got = CacheLookup::unknown; + for (int i = 0; i < 250; ++i) { + got = fresh_lookup ? fresh(index, directory, name) : index.peek(directory.c_str(), name.c_str(), false); + if (got == expected) break; + Sleep(20); + } + return got; +} + +bool wait_listing(const x2w_startup::CacheDirectoryIndex& index) +{ + for (int i = 0; i < 500 && !index.listing_finished(); ++i) Sleep(20); + return index.listing_finished(); +} + +std::wstring key_file(unsigned long long key, const wchar_t* extension) +{ + wchar_t name[64]; + std::swprintf(name, 64, L"%016llx%s", key, extension); + return name; +} + +// Polls until key reads changed since mark, for up to 5 s. +bool settle_changed(const x2w_startup::CacheDirectoryIndex& index, unsigned long long key, std::uint64_t mark) +{ + for (int i = 0; i < 250; ++i) { + if (index.key_changed(key, mark)) return true; + Sleep(20); + } + return false; +} + +// Parts (o) to (q), in their own directory under cache. +void check_marks(const fs::path& cache) +{ + const fs::path dir = cache / L"marks"; + fs::create_directory(dir); + const auto created = key(40000), rewritten = key(40001), renamed = key(40002), untouched = key(40003), other = key(40004); + write(dir / key_file(rewritten, L".txt"), "manifest 1"); + { + x2w_startup::CacheDirectoryIndex index(64 * 1024, feed_adds, feed_filter()); + index.watch(dir.c_str()); + if (!wait_listing(index)) fail("o", "the feed thread made no listing in 10 s"); + const auto mark = index.change_mark(); + if (!mark) fail("o", "no change mark while the feed reads"); + if (index.key_changed(created, mark)) fail("o", "a key nothing touched reads changed"); + if (!run_child(L"--child-create \"" + (dir / key_file(created, L".txt")).wstring() + L"\"")) + fail("o", "the other process could not create its file"); + else if (!settle_changed(index, created, mark)) fail("o", "a file another process created never read changed"); + if (!run_child(L"--child-rewrite \"" + (dir / key_file(rewritten, L".txt")).wstring() + L"\"")) + fail("o", "the other process could not rewrite its file"); + else if (!settle_changed(index, rewritten, mark)) fail("o", "a file another process rewrote in place never read changed"); + if (!run_child(L"--child-rename \"" + (dir / L"mark.tmp").wstring() + L"\" \"" + (dir / key_file(renamed, L".cs.hlsl")).wstring() + L"\"")) + fail("o", "the other process could not rename its file"); + else if (!settle_changed(index, renamed, mark)) fail("o", "a file another process renamed into place never read changed"); + write(dir / key_file(other, L".fail"), "other key"); + write(dir / L"revision.txt", "no key"); + Sleep(300); + if (index.key_changed(untouched, mark)) fail("o", "a change to another key or to a name that is no key flagged a key"); + const auto later = index.change_mark(); + if (index.key_changed(created, later)) fail("o", "a mark taken after the change still reads changed"); + std::printf("(o) marks: %lld records, mark %llu then %llu\n", static_cast(index.feed_records()), + static_cast(mark), static_cast(later)); + } + { + x2w_startup::CacheDirectoryIndex index; + index.lookup(dir.c_str(), L"x"); + if (index.change_mark() || !index.key_changed(untouched, 1)) fail("p", "without a feed a mark is given or a key reads unchanged"); + x2w_startup::CacheDirectoryIndex dropping(16, feed_adds, feed_filter()); + dropping.watch(dir.c_str()); + wait_listing(dropping); + const auto mark = dropping.change_mark(); + if (!mark || dropping.key_changed(untouched, mark)) fail("p", "no usable mark before the dropped batch"); + write(dir / key_file(other, L".txt"), "drop"); + for (int i = 0; i < 250 && dropping.feed_state() == x2w_startup::CacheDirectoryIndex::feed_reading; ++i) Sleep(20); + if (dropping.change_mark() || !dropping.key_changed(untouched, mark)) + fail("p", "after a dropped batch a mark is given or a key reads unchanged"); + } + { + x2w_startup::CacheDirectoryIndex index(64 * 1024, feed_adds, feed_filter()); + index.watch(dir.c_str()); + wait_listing(index); + const auto late = key(40010); + unsigned disk = 0, skipped = 0; + std::uint64_t manifest_mark = 0; + bool found = false; + // load_compute_translation's retry: repeat an unchanged miss, else mark, then look on disk. + const auto retry = [&] { + if (manifest_mark && (mutation == Mutation::ignore_changes || !index.key_changed(late, manifest_mark))) { + ++skipped; + return; + } + const auto mark = index.change_mark(); + ++disk; + if (fs::exists(dir / key_file(late, L".txt"))) { + found = true; + manifest_mark = 0; + } else { + manifest_mark = mark; + } + }; + for (int i = 0; i < 50; ++i) retry(); + if (disk != 1 || skipped != 49) + fail("q", "50 retries of an unchanged absent manifest: " + std::to_string(disk) + " on disk, " + + std::to_string(skipped) + " without I/O"); + if (!run_child(L"--child-create \"" + (dir / key_file(late, L".txt")).wstring() + L"\"")) + fail("q", "the other process could not publish its manifest"); + for (int i = 0; i < 250 && !found; ++i) { + retry(); + Sleep(20); + } + if (!found) fail("q", "a manifest published after the miss was never picked up"); + else if (disk != 2) fail("q", "the late manifest took " + std::to_string(disk) + " looks on disk, expected 2"); + std::printf("(q) retry loop: %u looks on disk, %u retries without I/O, late manifest %s\n", disk, skipped, + found ? "picked up" : "missed"); + } +} + +// Parts (i) to (n), in their own directory under cache. +void check_feed(const fs::path& cache) +{ + const fs::path dir = cache / L"feed"; + fs::create_directory(dir); + for (unsigned i = 0; i < 64; ++i) write(dir / profile(key(30000 + i)), "x"); + const auto listed = profile(key(30000)), missing = profile(key(31000)); + + { + x2w_startup::CacheDirectoryIndex index; + expect_peek("i", index.peek(dir.c_str(), listed.c_str(), false), listed, "plain peek before any listing", + CacheLookup::unknown); + expect_peek("i", fresh(index, dir, listed), listed, "fresh peek before any listing", CacheLookup::unknown); + if (index.listing_finished() || index.ready()) fail("i", "peek() made a listing"); + } + + { + x2w_startup::CacheDirectoryIndex index(64 * 1024, feed_adds); + index.watch(dir.c_str()); + if (!wait_listing(index)) fail("j", "the feed thread made no listing in 10 s"); + if (index.feed_state() != x2w_startup::CacheDirectoryIndex::feed_reading || !index.listed_while_reading()) + fail("j", "feed state " + std::to_string(index.feed_state()) + ", listed while reading " + + std::to_string(index.listed_while_reading()) + ", error " + std::to_string(index.feed_error())); + if (index.names() != 64) fail("j", std::to_string(index.names()) + " names listed, expected 64"); + expect_peek("j", fresh(index, dir, listed), listed, "fresh", CacheLookup::present); + expect_peek("j", fresh(index, dir, missing), missing, "fresh", CacheLookup::absent); + + const auto created = profile(key(31001)), renamed = profile(key(31002)), own = profile(key(31003)); + expect_peek("j", fresh(index, dir, created), created, "fresh, before the other process creates it,", CacheLookup::absent); + if (!run_child(L"--child-create \"" + (dir / created).wstring() + L"\"")) + fail("j", "the other process could not create its file"); + else if (settle(index, dir, created, true, CacheLookup::present) != CacheLookup::present) + fail("j", "a file created by another process after the listing never read present (fresh)"); + else expect_peek("j", index.peek(dir.c_str(), created.c_str(), false), created, "plain", CacheLookup::present); + + expect_peek("j", fresh(index, dir, renamed), renamed, "fresh, before the other process renames it,", CacheLookup::absent); + if (!run_child(L"--child-rename \"" + (dir / L"rename.tmp").wstring() + L"\" \"" + (dir / renamed).wstring() + L"\"")) + fail("j", "the other process could not rename its file"); + else if (settle(index, dir, renamed, true, CacheLookup::present) != CacheLookup::present) + fail("j", "a file renamed into place by another process after the listing never read present (fresh)"); + + write(dir / own, "own"); + if (settle(index, dir, own, true, CacheLookup::present) != CacheLookup::present) + fail("j", "a file this process wrote after the listing never read present (fresh)"); + expect_peek("j", fresh(index, dir, missing), missing, "fresh, after the writes,", CacheLookup::absent); + std::printf("(j) feed %ld: %lld records, %lld names added, %lld lookups of names added after the listing\n", + index.feed_state(), static_cast(index.feed_records()), + static_cast(index.feed_added()), static_cast(index.later_present())); + } + + { + x2w_startup::CacheDirectoryIndex index(64 * 1024, feed_adds); + index.lookup(dir.c_str(), listed.c_str()); + const auto late = profile(key(31004)); + if (!run_child(L"--child-create \"" + (dir / late).wstring() + L"\"")) fail("k", "the other process could not create its file"); + Sleep(200); + expect_peek("k", index.peek(dir.c_str(), late.c_str(), false), late, "plain, without a feed,", CacheLookup::absent); + expect_peek("k", fresh(index, dir, late), late, "fresh, without a feed,", CacheLookup::unknown); + expect_peek("k", fresh(index, dir, missing), missing, "fresh, without a feed,", CacheLookup::unknown); + + // (l) The same index, now with a feed: its listing began before the feed read, so fresh stays unknown. + index.watch(dir.c_str()); + if (index.feed_state() != x2w_startup::CacheDirectoryIndex::feed_reading || index.listed_while_reading()) + fail("l", "feed state " + std::to_string(index.feed_state()) + ", listed while reading " + + std::to_string(index.listed_while_reading())); + expect_peek("l", fresh(index, dir, missing), missing, "fresh, feed started after the listing,", CacheLookup::unknown); + expect_peek("l", index.peek(dir.c_str(), missing.c_str(), false), missing, "plain", CacheLookup::absent); + } + + { + // 16 bytes hold no record with a name of more than one character: the system drops the batch. + x2w_startup::CacheDirectoryIndex index(16, feed_adds); + index.watch(dir.c_str()); + if (!wait_listing(index)) fail("m", "the feed thread made no listing in 10 s"); + expect_peek("m", fresh(index, dir, missing), missing, "fresh, before the dropped batch,", CacheLookup::absent); + write(dir / profile(key(31005)), "dropped"); + for (int i = 0; i < 250 && index.feed_state() == x2w_startup::CacheDirectoryIndex::feed_reading; ++i) Sleep(20); + if (index.feed_state() != x2w_startup::CacheDirectoryIndex::feed_dropped) + fail("m", "feed state " + std::to_string(index.feed_state()) + " after an overflowing batch, error " + + std::to_string(index.feed_error()) + ", expected dropped"); + expect_peek("m", fresh(index, dir, missing), missing, "fresh, after the dropped batch,", CacheLookup::unknown); + expect_peek("m", index.peek(dir.c_str(), missing.c_str(), false), missing, "plain, after the dropped batch,", + CacheLookup::absent); + std::printf("(m) feed %ld, error %lu\n", index.feed_state(), static_cast(index.feed_error())); + } + + { + const auto gone = cache / L"no-such-directory"; + const auto start = Clock::now(); + { + x2w_startup::CacheDirectoryIndex index(64 * 1024, feed_adds); + index.watch(gone.c_str()); + wait_listing(index); + if (index.feed_state() != x2w_startup::CacheDirectoryIndex::feed_failed || !index.feed_error()) + fail("n", "a feed on a missing directory is in state " + std::to_string(index.feed_state())); + expect_peek("n", fresh(index, gone, missing), missing, "fresh, missing directory,", CacheLookup::unknown); + expect_peek("n", index.peek(gone.c_str(), missing.c_str(), false), missing, "plain, missing directory,", + CacheLookup::unknown); + x2w_startup::CacheDirectoryIndex reading; + reading.watch(dir.c_str()); + wait_listing(reading); + } + const double ms = std::chrono::duration(Clock::now() - start).count(); + if (ms > 10000) fail("n", "destroying two watching indexes took " + std::to_string(ms) + " ms"); + std::printf("(n) missing directory and teardown: %.0f ms\n", ms); + } +} + } // namespace int main(int argc, char** argv) { if (argc == 3 && std::strcmp(argv[1], "--measure") == 0) return measure(argv[2]); + if (argc == 3 && std::strcmp(argv[1], "--child-create") == 0) return child_create(fs::path(argv[2]).c_str()); + if (argc == 3 && std::strcmp(argv[1], "--child-rewrite") == 0) return child_rewrite(fs::path(argv[2]).c_str()); + if (argc == 4 && std::strcmp(argv[1], "--child-rename") == 0) + return child_rename(fs::path(argv[2]).c_str(), fs::path(argv[3]).c_str()); if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "per-call") == 0) { per_call = true; + } else if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "no-added") == 0) { + mutation = Mutation::no_added; + } else if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "no-rename") == 0) { + mutation = Mutation::no_rename; + } else if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "listing-only") == 0) { + mutation = Mutation::listing_only; + } else if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "ignore-changes") == 0) { + mutation = Mutation::ignore_changes; + } else if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "names-only") == 0) { + mutation = Mutation::names_only; } else if (argc != 1) { return 2; } @@ -226,6 +567,9 @@ int main(int argc, char** argv) if (names.size() != 3 || !names.contains(L"a.txt") || !names.contains(L"B.TXT") || names.contains(L"d.txt")) fail("h", "sorted name set gives the wrong answers (" + std::to_string(names.size()) + " names)"); + check_feed(cache); + check_marks(cache); + std::printf("startup_cache_index_check: %d failed\n", failures); if (!failures) fs::remove_all(cache); return failures ? 1 : 0;