From 40e94ebb20782fdb942c1ca377740c070e74cee6 Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:33:17 +0100 Subject: [PATCH 1/4] runtime: pipeline order recorder and replay request hook (RT-PIPELINE-PREWARM-ORDER, phase 1) pipeline_order.h: a passive recorder of the first request of each pipeline and variant, with its text file format (checksummed lines, truncated or damaged lines skipped on read) and a lock-free, allocation-free hot path with a writer thread of its own. ComputePipeline and GraphicsPipeline get a `requested` callback, called where a submission is prepared, also for handles that exist already. Nothing uses either yet; the device wiring is the next commit. Tests (CPU only): pipeline_order_test (first request only, variants, order, round trip, truncation at every byte, damaged lines, sessions, full record, bounded file, unwritable file, 8 threads, no allocation, counts line) and replay_pipeline_order_hook_test (ready, lazy, skipped, unbound variant). Co-Authored-By: Claude Fable 5.2 --- runtime/CMakeLists.txt | 13 + runtime/src/pipeline_order.h | 582 ++++++++++++++++++ runtime/src/vulkan_replay.h | 9 + runtime/test/pipeline_order_test.cpp | 535 ++++++++++++++++ .../test/replay_pipeline_order_hook_test.cpp | 213 +++++++ 5 files changed, 1352 insertions(+) create mode 100644 runtime/src/pipeline_order.h create mode 100644 runtime/test/pipeline_order_test.cpp create mode 100644 runtime/test/replay_pipeline_order_hook_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index bea9a82d88..af48b83f1a 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -790,6 +790,12 @@ if(BUILD_TESTING) add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + # RT-PIPELINE-PREWARM-ORDER phase 1: the file format and the recorder of src/pipeline_order.h (pure stdlib, no GPU). + add_executable(pipeline_order_test test/pipeline_order_test.cpp) + target_link_libraries(pipeline_order_test PRIVATE Threads::Threads) + add_test(NAME pipeline_order COMMAND pipeline_order_test) + set_tests_properties(pipeline_order PROPERTIES TIMEOUT 120) + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) @@ -4313,6 +4319,13 @@ if(TARGET Vulkan::Headers) add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test) add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test) set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1") + # The request hook of ComputePipeline / GraphicsPipeline that pipeline_order.h's recorder hangs on (no GPU). + add_executable(replay_pipeline_order_hook_test test/replay_pipeline_order_hook_test.cpp) + target_link_libraries(replay_pipeline_order_hook_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_pipeline_order_hook_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_pipeline_order_hook COMMAND replay_pipeline_order_hook_test) # Compiling unbuilt pipelines releases resource_mutex_ and tracker_mutex_ while keeping pipeline_mutex_ (no GPU). add_executable(replay_pipeline_compile_unlock_test test/replay_pipeline_compile_unlock_test.cpp) target_link_libraries(replay_pipeline_compile_unlock_test PRIVATE Vulkan::Headers Threads::Threads) diff --git a/runtime/src/pipeline_order.h b/runtime/src/pipeline_order.h new file mode 100644 index 0000000000..4cb9379f80 --- /dev/null +++ b/runtime/src/pipeline_order.h @@ -0,0 +1,582 @@ +// RT-PIPELINE-PREWARM-ORDER, phase 1: a passive record of which pipelines the title asks for first. Off unless +// LEONIDA_PIPELINE_ORDER_LOG=1; it changes nothing the title or the replay does. +// +// For each pipeline state and variant (the unbound-attachment mask of a graphics pipeline, 0 for compute) that a +// dispatch or draw names for the first time in a run, one line is appended to pipeline_order.log beside +// pipeline_cache.session.bin: the description key of the PSO, the variant, when the PSO was created and when it was +// first used (milliseconds since the process started) and how long its build took. At exit one line of counts says how +// many were asked for, how many were ready already, and the median lead between creation and first use. +// +// The hot path (claim, publish, note_build) takes no lock, makes no system call and allocates nothing: a fixed table +// of 64-bit identities decides "first time" with one compare-and-swap and a preallocated slot takes the record. A +// thread of its own appends published slots to the file every few hundred milliseconds, so a process that is killed +// loses at most the last interval. The file is text so that it can be read with any tool; each line ends with a +// checksum, a truncated or damaged line is skipped when read back, never fatal. +// +// # leonida pipeline order 1 first line of a new file +// S 1 a run starts here +// P * +// B * the build of a P line whose time was not known yet +// +// c = compute, g = graphics, m = mesh. The checksum is FNV-1a over the line before " *". No game data is in the file: +// the key is a SHA-256 of the title's own description of the pipeline (cached_pso.h), the rest are numbers. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::pipeline_order { + +inline constexpr std::uint32_t unknown_ms = 0xffffffffu; // a build time nobody measured +inline constexpr std::size_t key_chars = 64; // a SHA-256 in hex; longer keys are cut +inline constexpr std::size_t default_capacity = 8192; // records per run +inline constexpr std::size_t max_capacity = 16000; // the table packs the slot into 14 bits +inline constexpr std::uintmax_t default_max_file_bytes = 8u << 20; // a larger file is set aside as .prev at open + +// LEONIDA_PIPELINE_ORDER_LOG: "1" turns the record on. Unset, empty, "0" and anything else leave it off. +inline bool parse_enabled(const char* text) { return text && text[0] == '1' && text[1] == '\0'; } + +struct Record { + char kind = 'c'; // c compute, g graphics, m mesh + std::string key; + std::uint32_t variant = 0; + std::uint32_t created_ms = 0; + std::uint32_t first_ms = 0; + std::uint32_t build_ms = unknown_ms; + bool ready = false; // its handle existed when it was first asked for + bool operator==(const Record&) const = default; +}; + +struct Session { + std::uint32_t vendor = 0; + std::uint32_t device = 0; + std::vector records; // in the order the title asked for them +}; + +struct ReadResult { + std::vector sessions; + std::size_t bad_lines = 0; // complete lines that could not be read: skipped + bool cut_tail = false; // the last line had no newline: a write that did not finish, skipped +}; + +inline std::uint32_t checksum(std::string_view text) { + std::uint32_t h = 0x811c9dc5u; + for (const char c : text) h = (h ^ std::uint8_t(c)) * 0x01000193u; + return h; +} + +inline std::uint64_t key_hash(std::string_view key) { + std::uint64_t h = 0xcbf29ce484222325ull; + for (const char c : key) h = (h ^ std::uint8_t(c)) * 0x100000001b3ull; + return h ? h : 1; +} + +namespace detail { + +inline std::uint64_t mix(std::uint64_t key, std::uint32_t variant) { + std::uint64_t z = key + 0x9e3779b97f4a7c15ull * (std::uint64_t(variant) + 1); + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebull; + return z ^ (z >> 31); +} + +inline void append_line(std::string& out, std::string body) { + char tail[16]; + std::snprintf(tail, sizeof(tail), " *%08x\n", checksum(body)); + out += body; + out += tail; +} + +inline std::string number_or_dash(std::uint32_t v) { return v == unknown_ms ? "-" : std::to_string(v); } + +inline bool parse_u32(std::string_view s, int base, std::uint32_t& out) { + if (s.empty() || s.size() > 10) return false; + std::uint64_t v = 0; + for (const char c : s) { + int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (base == 16 && c >= 'a' && c <= 'f') d = c - 'a' + 10; + else return false; + if (d >= base) return false; + v = v * std::uint64_t(base) + std::uint64_t(d); + if (v > 0xffffffffull) return false; + } + out = std::uint32_t(v); + return true; +} + +inline std::vector split(std::string_view s) { + std::vector out; + std::size_t i = 0; + while (i < s.size()) { + const std::size_t j = s.find(' ', i); + if (j == std::string_view::npos) { + out.push_back(s.substr(i)); + break; + } + out.push_back(s.substr(i, j - i)); + i = j + 1; + } + return out; +} + +} // namespace detail + +inline std::string format_header() { return "# leonida pipeline order 1\n"; } + +inline std::string format_session(std::uint32_t vendor, std::uint32_t device) { + char text[64]; + std::snprintf(text, sizeof(text), "S 1 %x %x", vendor, device); + std::string out; + detail::append_line(out, text); + return out; +} + +inline std::string format_record(const Record& r) { + std::string body = "P "; + body += r.kind; + body += ' '; + body += r.key; + char numbers[32]; + std::snprintf(numbers, sizeof(numbers), " %x ", r.variant); + body += numbers; + body += std::to_string(r.created_ms) + ' ' + std::to_string(r.first_ms) + ' ' + detail::number_or_dash(r.build_ms) + + (r.ready ? " 1" : " 0"); + std::string out; + detail::append_line(out, std::move(body)); + return out; +} + +inline std::string format_build(std::string_view key, std::uint32_t variant, std::uint32_t build_ms) { + char numbers[32]; + std::snprintf(numbers, sizeof(numbers), " %x ", variant); + std::string body = "B "; + body += key; + body += numbers; + body += std::to_string(build_ms); + std::string out; + detail::append_line(out, std::move(body)); + return out; +} + +// Reads what a file holds: whole sessions in file order, a record per P line (its B line merged in), every damaged line +// skipped. Never throws on any input. +inline ReadResult parse(std::string_view text) { + ReadResult result; + if (!text.empty() && text.back() != '\n') { + result.cut_tail = true; + const std::size_t last = text.rfind('\n'); + text = last == std::string_view::npos ? std::string_view{} : text.substr(0, last + 1); + } + const auto session = [&]() -> Session& { + if (result.sessions.empty()) result.sessions.emplace_back(); + return result.sessions.back(); + }; + std::size_t at = 0; + while (at < text.size()) { + const std::size_t end = text.find('\n', at); + if (end == std::string_view::npos) break; // not reached: the unfinished last line was cut off above + std::string_view line = text.substr(at, end - at); + at = end + 1; + if (!line.empty() && line.back() == '\r') line.remove_suffix(1); + if (line.empty() || line[0] == '#') continue; + const std::size_t star = line.rfind(" *"); + std::uint32_t sum = 0; + if (star == std::string_view::npos || star + 2 + 8 != line.size() || + !detail::parse_u32(line.substr(star + 2), 16, sum) || sum != checksum(line.substr(0, star))) { + ++result.bad_lines; + continue; + } + const auto f = detail::split(line.substr(0, star)); + bool ok = false; + if (f.size() == 4 && f[0] == "S") { + Session s; + ok = f[1] == "1" && detail::parse_u32(f[2], 16, s.vendor) && detail::parse_u32(f[3], 16, s.device); + if (ok) result.sessions.push_back(std::move(s)); + } else if (f.size() == 8 && f[0] == "P") { + Record r; + ok = f[1].size() == 1 && (f[1][0] == 'c' || f[1][0] == 'g' || f[1][0] == 'm') && !f[2].empty() && + f[2].size() <= key_chars && detail::parse_u32(f[3], 16, r.variant) && + detail::parse_u32(f[4], 10, r.created_ms) && detail::parse_u32(f[5], 10, r.first_ms) && + (f[6] == "-" || detail::parse_u32(f[6], 10, r.build_ms)) && (f[7] == "0" || f[7] == "1"); + if (ok) { + r.kind = f[1][0]; + r.key = std::string(f[2]); + r.ready = f[7] == "1"; + session().records.push_back(std::move(r)); + } + } else if (f.size() == 4 && f[0] == "B") { + std::uint32_t variant = 0, ms = 0; + ok = !f[1].empty() && f[1].size() <= key_chars && detail::parse_u32(f[2], 16, variant) && + detail::parse_u32(f[3], 10, ms); + if (ok) { + // The newest record of the run with that key and variant that still has no build time. + auto& records = session().records; + for (auto it = records.rbegin(); it != records.rend(); ++it) + if (it->variant == variant && it->key == f[1] && it->build_ms == unknown_ms) { + it->build_ms = ms; + break; + } + } + } + if (!ok) ++result.bad_lines; + } + return result; +} + +struct Counts { + std::size_t requested = 0; // distinct pipelines and variants asked for, recorded + std::size_t ready = 0; // of those, ready when first asked for + std::size_t overflow = 0; // requests that found the record full and were not kept (counted per request) + std::uint32_t median_lead_ms = 0; // first use minus creation, of the recorded ones +}; + +// The recorder. Thread-safe: claim, publish and note_build from any number of threads at once, flush from one +// thread at a time (it takes its own lock). +class Recorder { +public: + struct Config { + std::filesystem::path path; + std::size_t capacity = default_capacity; + std::uint32_t vendor = 0; + std::uint32_t device = 0; + std::uint32_t (*now_ms)() = nullptr; // milliseconds since the process started + std::uintmax_t max_file_bytes = default_max_file_bytes; + }; + + // A reserved record: valid for the one thread that was told it is the first to ask for this pipeline. + struct Claim { + std::uint32_t index = 0; + bool first = false; + explicit operator bool() const { return first; } + }; + + explicit Recorder(Config config) + : config_(std::move(config)), + capacity_(std::min(std::max(config_.capacity, 1), max_capacity)), + mask_(table_size(capacity_) - 1), + table_(new std::atomic[mask_ + 1]()), + slots_(new Slot[capacity_]) {} + Recorder(const Recorder&) = delete; + Recorder& operator=(const Recorder&) = delete; + ~Recorder() { stop(); } + + // The first thread to name this (key hash, variant) gets a claim and must publish() it; everyone else, and every + // request after the record is full, gets none. + Claim claim(std::uint64_t hash, std::uint32_t variant) noexcept { + const std::uint64_t id = detail::mix(hash, variant); + const std::uint64_t tag = id >> slot_bits; + std::size_t at = std::size_t(id) & mask_; + for (std::size_t probes = 0; probes <= mask_; ++probes, at = (at + 1) & mask_) { + std::uint64_t entry = table_[at].load(std::memory_order_acquire); + if (entry == 0) { + const std::uint32_t slot = next_.load(std::memory_order_relaxed); + if (slot >= capacity_) { + overflow_.fetch_add(1, std::memory_order_relaxed); + return {}; + } + const std::uint32_t mine = next_.fetch_add(1, std::memory_order_relaxed); + if (mine >= capacity_) { + overflow_.fetch_add(1, std::memory_order_relaxed); + return {}; + } + Slot& s = slots_[mine]; + s.state.store(claimed, std::memory_order_relaxed); + const std::uint64_t packed = (tag << slot_bits) | (mine + 1); + if (table_[at].compare_exchange_strong(entry, packed, std::memory_order_acq_rel)) { + s.first_ms = now(); + s.variant = variant; + return {mine, true}; + } + s.state.store(void_slot, std::memory_order_release); // lost the race: the entry is somebody's now + } + if ((entry >> slot_bits) == tag) return {}; + } + return {}; + } + + // Fills the claimed record and makes it visible to the writer. `key` is cut at key_chars. `build_ms` is what is + // known of the build now, or unknown_ms. + void publish(Claim claim, std::string_view key, char kind, bool ready, std::uint32_t created_ms, + std::uint32_t build_ms) noexcept { + if (!claim.first) return; + Slot& s = slots_[claim.index]; + s.key_len = std::uint8_t(std::min(key.size(), key_chars)); + for (std::size_t i = 0; i < s.key_len; ++i) { // a key is one word of the line: no space, no newline + const char c = key[i]; + s.key[i] = (c > ' ' && c < 0x7f && c != '*') ? c : '_'; + } + s.kind = kind; + s.ready = ready; + s.created_ms = created_ms; + if (build_ms != unknown_ms) { + std::uint32_t none = unknown_ms; + s.build_ms.compare_exchange_strong(none, build_ms, std::memory_order_relaxed); + } + s.state.store(published, std::memory_order_release); + } + + // claim() and publish() in one: what the title's hook does. `ready` and `build_ms` are called, in that order, only by + // the first request, after its claim: so a build that ends meanwhile is seen by one of them or by note_build(). + // Returns true when this call made the record. + template + bool request(std::uint64_t hash, std::string_view key, std::uint32_t variant, char kind, std::uint32_t created_ms, + Ready&& ready, Build&& build_ms) noexcept { + const Claim c = claim(hash, variant); + if (!c) return false; + const bool is_ready = ready(); + publish(c, key, kind, is_ready, created_ms, build_ms()); + return true; + } + + // The build of a pipeline that was asked for finished. Ignored for one that was not (its time is passed to + // publish() when it is) and when a time is already there. + void note_build(std::uint64_t hash, std::uint32_t variant, std::uint32_t ms) noexcept { + const std::uint64_t id = detail::mix(hash, variant); + const std::uint64_t tag = id >> slot_bits; + std::size_t at = std::size_t(id) & mask_; + for (std::size_t probes = 0; probes <= mask_; ++probes, at = (at + 1) & mask_) { + const std::uint64_t entry = table_[at].load(std::memory_order_acquire); + if (entry == 0) return; + if ((entry >> slot_bits) != tag) continue; + std::uint32_t none = unknown_ms; + slots_[(entry & slot_mask) - 1].build_ms.compare_exchange_strong(none, ms, std::memory_order_relaxed); + return; + } + } + + // Appends what was published since the last call. Returns the lines written; -1 when the file cannot be opened + // (the record is then off for the rest of the run). + long flush() { + std::lock_guard lock(io_mutex_); + return flush_locked(); + } + + // A thread that calls flush() every `period`. Idempotent. + void start(std::chrono::milliseconds period) { + std::lock_guard lock(thread_mutex_); + if (thread_.joinable()) return; + stopping_ = false; + thread_ = std::thread([this, period] { + std::unique_lock lock(thread_mutex_); + while (!stopping_) { + thread_cv_.wait_for(lock, period, [this] { return stopping_; }); + lock.unlock(); + flush(); + lock.lock(); + } + }); + } + + void stop() { + { + std::lock_guard lock(thread_mutex_); + stopping_ = true; + } + thread_cv_.notify_all(); + if (thread_.joinable()) thread_.join(); + } + + Counts counts() const { + Counts c; + std::vector leads; + const std::uint32_t used = std::min(next_.load(std::memory_order_acquire), std::uint32_t(capacity_)); + for (std::uint32_t i = 0; i < used; ++i) { + const Slot& s = slots_[i]; + if (s.state.load(std::memory_order_acquire) != published) continue; + ++c.requested; + if (s.ready) ++c.ready; + leads.push_back(s.first_ms > s.created_ms ? s.first_ms - s.created_ms : 0); + } + c.overflow = overflow_.load(std::memory_order_relaxed); + if (!leads.empty()) { + const std::size_t mid = (leads.size() - 1) / 2; + std::nth_element(leads.begin(), leads.begin() + std::ptrdiff_t(mid), leads.end()); + c.median_lead_ms = leads[mid]; + } + return c; + } + + // Stops the thread, writes what is left and returns the one-line report; empty after the first call. + std::string close() { + if (closed_.exchange(true)) return {}; + stop(); + flush(); + return report(counts(), config_.path); + } + + static std::string report(const Counts& c, const std::filesystem::path& path) { + std::string line = "[rt] pipeline-order: requested " + std::to_string(c.requested) + ", already ready " + + std::to_string(c.ready) + ", median lead " + std::to_string(c.median_lead_ms) + " ms"; + if (c.overflow) line += ", not recorded (record full) " + std::to_string(c.overflow); + line += " -> " + path.string(); + return line; + } + + // The file could not be opened or written: nothing more is recorded this run. + bool failed() { + std::lock_guard lock(io_mutex_); + return failed_; + } + const std::filesystem::path& path() const { return config_.path; } + std::size_t capacity() const { return capacity_; } + +private: + static constexpr unsigned slot_bits = 14; + static constexpr std::uint64_t slot_mask = (1u << slot_bits) - 1; + enum : std::uint32_t { free_slot = 0, claimed = 1, published = 2, void_slot = 3 }; + + struct Slot { + std::atomic state{free_slot}; + std::atomic build_ms{unknown_ms}; + std::uint32_t variant = 0; + std::uint32_t created_ms = 0; + std::uint32_t first_ms = 0; + std::uint8_t key_len = 0; + char kind = 'c'; + bool ready = false; + char key[key_chars] = {}; + bool written = false; // writer thread only + bool build_written = false; // writer thread only + }; + + static std::size_t table_size(std::size_t capacity) { + std::size_t n = 16; + while (n < capacity * 2) n <<= 1; + return n; + } + + std::uint32_t now() const noexcept { return config_.now_ms ? config_.now_ms() : 0; } + + long flush_locked() { + if (failed_) return -1; + std::string out; + long lines = 0; + // Published slots, in claim order; stop at one still being filled so that the order stays the order of asking. + const std::uint32_t used = std::min(next_.load(std::memory_order_acquire), std::uint32_t(capacity_)); + while (cursor_ < used) { + Slot& s = slots_[cursor_]; + const std::uint32_t state = s.state.load(std::memory_order_acquire); + if (state == void_slot) { + ++cursor_; + continue; + } + if (state != published) break; + Record r; + r.kind = s.kind; + r.key.assign(s.key, s.key_len); + r.variant = s.variant; + r.created_ms = s.created_ms; + r.first_ms = s.first_ms; + r.build_ms = s.build_ms.load(std::memory_order_relaxed); + r.ready = s.ready; + out += format_record(r); + ++lines; + s.written = true; + if (r.build_ms == unknown_ms) waiting_.push_back(cursor_); + ++cursor_; + } + // The builds that finished after their line was written. + for (std::size_t i = 0; i < waiting_.size();) { + Slot& s = slots_[waiting_[i]]; + const std::uint32_t ms = s.build_ms.load(std::memory_order_relaxed); + if (ms == unknown_ms) { + ++i; + continue; + } + out += format_build(std::string_view(s.key, s.key_len), s.variant, ms); + ++lines; + waiting_[i] = waiting_.back(); + waiting_.pop_back(); + } + if (out.empty()) return 0; + if (!file_) { + if (!open()) { + failed_ = true; + return -1; + } + } + std::string head; + if (!session_written_) { + if (new_file_) head += format_header(); + head += format_session(config_.vendor, config_.device); + session_written_ = true; + } + head += out; + const bool ok = std::fwrite(head.data(), 1, head.size(), file_.get()) == head.size() && std::fflush(file_.get()) == 0; + if (!ok) { + failed_ = true; + return -1; + } + return lines; + } + + bool open() { + std::error_code ec; + if (config_.path.empty()) return false; + if (config_.path.has_parent_path()) std::filesystem::create_directories(config_.path.parent_path(), ec); + const auto size = std::filesystem::file_size(config_.path, ec); + if (!ec && size >= config_.max_file_bytes) { + auto prev = config_.path; + prev += ".prev"; + std::filesystem::remove(prev, ec); + std::filesystem::rename(config_.path, prev, ec); + } + ec.clear(); + const auto now_size = std::filesystem::file_size(config_.path, ec); + new_file_ = ec || now_size == 0; + std::FILE* f = nullptr; +#ifdef _WIN32 + f = _wfsopen(config_.path.c_str(), L"ab", _SH_DENYNO); // others may read it while the title runs +#else + f = std::fopen(config_.path.c_str(), "ab"); +#endif + if (!f) return false; + file_.reset(f); + return true; + } + + struct Closer { + void operator()(std::FILE* f) const { if (f) std::fclose(f); } + }; + + Config config_; + const std::size_t capacity_; + const std::size_t mask_; + std::unique_ptr[]> table_; + std::unique_ptr slots_; + std::atomic next_{0}; + std::atomic overflow_{0}; + std::atomic closed_{false}; + + std::mutex io_mutex_; + std::unique_ptr file_; + std::uint32_t cursor_ = 0; + std::vector waiting_; + bool failed_ = false; + bool new_file_ = false; + bool session_written_ = false; + + std::mutex thread_mutex_; + std::condition_variable thread_cv_; + std::thread thread_; + bool stopping_ = false; +}; + +} // namespace leonida::pipeline_order diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 449f8de5d9..7ba5f40c2b 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -872,6 +872,10 @@ struct ComputePipeline { bool large = false; // PipelineCompiles limits how many of these compile at once bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take + // Told at every dispatch that names this pipeline, built or not, with variant 0 (pipeline_order.h records the first + // one). Null: nobody is told. Called while a submission is prepared: it must not block, take a lock or allocate. + void (*requested)(void*, std::uint32_t variant) = nullptr; + void* request_context = nullptr; }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -901,6 +905,9 @@ struct GraphicsPipeline { // What `variant` would return when it is built already and nobody is building one, else null; builds nothing. See // ComputePipeline::built. std::function built; + // As ComputePipeline::requested, at every draw that names this pipeline, with the variant flags it will use. + void (*requested)(void*, std::uint32_t variant) = nullptr; + void* request_context = nullptr; bool large = false; // as ComputePipeline::large std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count bool async_build = false; @@ -2784,6 +2791,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R for (std::size_t slot = 0; slot < p.colors.size(); ++slot) if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; + if (pipeline->requested) pipeline->requested(pipeline->request_context, unbound); if (unbound || !p.pipeline) { const bool indirect_rect_variant = arguments && (unbound & GraphicsPipeline::rectangle_stage); if (vk.compiles && pipeline->variant && pipeline->built && !pipeline->async_build && !indirect_rect_variant) { @@ -2886,6 +2894,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R // A compute pipeline that is built on first use: the one built already, the one vk.compiles will build with the // submission's others (true, with p.compile set and no pipeline yet), or the one built here. inline bool first_use(const ComputePipeline& pipeline, PipelineCompiles::User user, const ReplayFunctions& vk, Prepared& p) { + if (pipeline.requested) pipeline.requested(pipeline.request_context, 0); // also for a handle that exists already if (p.pipeline.pipeline || !pipeline.build) return p.pipeline.pipeline != VK_NULL_HANDLE; if (vk.compiles && pipeline.built && !pipeline.async_build && !pipeline.skipped && (!pipeline.bindless_set || vk.bind_descriptor_sets)) { diff --git a/runtime/test/pipeline_order_test.cpp b/runtime/test/pipeline_order_test.cpp new file mode 100644 index 0000000000..a041f3e907 --- /dev/null +++ b/runtime/test/pipeline_order_test.cpp @@ -0,0 +1,535 @@ +// RT-PIPELINE-PREWARM-ORDER phase 1: the file format and the recorder of runtime/src/pipeline_order.h. No GPU, no +// game data: keys are made up here. Covered: the first request of a pipeline and variant is recorded and a repeated one +// is not; the order of asking is the order in the file; a truncated or damaged file is read as far as it goes; many +// threads at once record each pipeline once; the hot path allocates nothing; the file stays bounded; the counts line. +#include "../src/pipeline_order.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace po = leonida::pipeline_order; + +// Counts the allocations made while `counting` is set, on any thread. +static std::atomic counting{false}; +static std::atomic allocations{0}; + +void* operator new(std::size_t size) { + if (counting.load(std::memory_order_relaxed)) allocations.fetch_add(1, std::memory_order_relaxed); + 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); } + +static int failures = 0; +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + ++failures; \ + } \ + } while (0) + +namespace { + +std::atomic clock_ms{0}; +std::uint32_t fake_now() { return clock_ms.load(); } + +std::filesystem::path scratch(const char* name) { + const auto dir = std::filesystem::temp_directory_path() / "leonida_pipeline_order_test"; + std::filesystem::create_directories(dir); + const auto path = dir / name; + std::error_code ec; + std::filesystem::remove(path, ec); + std::filesystem::remove(std::filesystem::path(path).concat(".prev"), ec); + return path; +} + +std::string slurp(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return std::string(std::istreambuf_iterator(in), {}); +} + +std::string key_of(int n) { + char text[80]; + std::snprintf(text, sizeof(text), "%064x", static_cast(n) * 2654435761u + 17u); + return text; +} + +po::Recorder::Config config(const std::filesystem::path& path, std::size_t capacity = 64) { + po::Recorder::Config c; + c.path = path; + c.capacity = capacity; + c.vendor = 0x10de; + c.device = 0x2504; + c.now_ms = &fake_now; + return c; +} + +// What the title's hook does for one request. +bool request(po::Recorder& r, int n, std::uint32_t variant = 0, char kind = 'c', bool ready = false, + std::uint32_t created = 0, std::uint32_t build = po::unknown_ms) { + const std::string key = key_of(n); + const auto claim = r.claim(po::key_hash(key), variant); + if (!claim) return false; + r.publish(claim, key, kind, ready, created, build); + return true; +} + +void test_switch() { + CHECK(!po::parse_enabled(nullptr)); + CHECK(!po::parse_enabled("")); + CHECK(!po::parse_enabled("0")); + CHECK(!po::parse_enabled("11")); + CHECK(!po::parse_enabled("true")); + CHECK(po::parse_enabled("1")); +} + +void test_first_request_only() { + const auto path = scratch("first.log"); + { + clock_ms = 100; + po::Recorder r(config(path)); + CHECK(request(r, 1)); + clock_ms = 200; + CHECK(!request(r, 1)); // asked again: not recorded again + CHECK(!request(r, 1)); + CHECK(request(r, 2)); + CHECK(!request(r, 2)); + CHECK(r.flush() == 2); + CHECK(r.flush() == 0); // nothing new + CHECK(!request(r, 1)); + CHECK(r.flush() == 0); + } + const auto read = po::parse(slurp(path)); + CHECK(read.bad_lines == 0 && !read.cut_tail); + CHECK(read.sessions.size() == 1); + CHECK(read.sessions[0].vendor == 0x10de && read.sessions[0].device == 0x2504); + CHECK(read.sessions[0].records.size() == 2); + CHECK(read.sessions[0].records[0].key == key_of(1)); + CHECK(read.sessions[0].records[0].first_ms == 100); // the time of the first ask, not of the later ones +} + +void test_variants_are_distinct() { + const auto path = scratch("variants.log"); + po::Recorder r(config(path)); + CHECK(request(r, 5, 0)); + CHECK(request(r, 5, 2)); // same pipeline, another variant: a record of its own + CHECK(request(r, 5, 6)); + CHECK(!request(r, 5, 2)); + CHECK(request(r, 6, 2)); // same variant, another pipeline + CHECK(r.flush() == 4); + const auto read = po::parse(slurp(path)); + CHECK(read.sessions.size() == 1 && read.sessions[0].records.size() == 4); + CHECK(read.sessions[0].records[1].variant == 2 && read.sessions[0].records[2].variant == 6); +} + +void test_order_is_kept() { + const auto path = scratch("order.log"); + std::vector asked; + std::mt19937 rng(7); + { + po::Recorder r(config(path, 600)); + std::vector pool(500); + for (int i = 0; i < 500; ++i) pool[std::size_t(i)] = i; + std::shuffle(pool.begin(), pool.end(), rng); + std::set seen; + for (int round = 0; round < 3; ++round) + for (const int n : pool) { + ++clock_ms; + if (request(r, n)) asked.push_back(n); + if (n % 50 == 0) r.flush(); // some lines go out in several flushes + } + r.flush(); + } + CHECK(asked.size() == 500); + const auto read = po::parse(slurp(path)); + CHECK(read.sessions.size() == 1 && read.sessions[0].records.size() == 500); + bool same = read.sessions[0].records.size() == asked.size(); + for (std::size_t i = 0; same && i < asked.size(); ++i) same = read.sessions[0].records[i].key == key_of(asked[i]); + CHECK(same); + std::uint32_t last = 0; + bool monotonic = true; + for (const auto& rec : read.sessions[0].records) { + monotonic = monotonic && rec.first_ms >= last; + last = rec.first_ms; + } + CHECK(monotonic); +} + +void test_fields_round_trip() { + po::Record a; + a.kind = 'm'; + a.key = key_of(3); + a.variant = 0x2a0; + a.created_ms = 12; + a.first_ms = 3456; + a.build_ms = 789; + a.ready = true; + po::Record b = a; + b.kind = 'g'; + b.key = key_of(4); + b.build_ms = po::unknown_ms; + b.ready = false; + std::string text = po::format_header() + po::format_session(0x1002, 0x73bf) + po::format_record(a) + + po::format_record(b) + po::format_build(b.key, b.variant, 4000); + const auto read = po::parse(text); + CHECK(read.bad_lines == 0 && !read.cut_tail && read.sessions.size() == 1); + CHECK(read.sessions[0].vendor == 0x1002 && read.sessions[0].device == 0x73bf); + CHECK(read.sessions[0].records.size() == 2); + CHECK(read.sessions[0].records[0] == a); + b.build_ms = 4000; // the late B line completes the record of the same key and variant + CHECK(read.sessions[0].records[1] == b); + // A B line for a pipeline that was never recorded is dropped, not invented. + const auto stray = po::parse(po::format_session(1, 2) + po::format_build(key_of(99), 0, 5)); + CHECK(stray.sessions.size() == 1 && stray.sessions[0].records.empty()); +} + +// request(): the callbacks run for the first request only, ready before build, both after the claim. +void test_request_helper() { + const auto path = scratch("helper.log"); + po::Recorder r(config(path)); + int ready_calls = 0, build_calls = 0; + std::string order; + const auto ready = [&] { + ++ready_calls; + order += 'r'; + return true; + }; + const auto build = [&] { + ++build_calls; + order += 'b'; + return std::uint32_t(77); + }; + const std::string key = key_of(1); + const auto hash = po::key_hash(key); + CHECK(r.request(hash, key, 0, 'c', 3, ready, build)); + CHECK(!r.request(hash, key, 0, 'c', 3, ready, build)); + CHECK(!r.request(hash, key, 0, 'c', 3, ready, build)); + CHECK(r.request(hash, key, 2, 'c', 3, ready, build)); + CHECK(ready_calls == 2 && build_calls == 2 && order == "rbrb"); + CHECK(r.flush() == 2); + const auto read = po::parse(slurp(path)); + CHECK(read.sessions.size() == 1 && read.sessions[0].records.size() == 2); + CHECK(read.sessions[0].records[0].ready && read.sessions[0].records[0].build_ms == 77 && + read.sessions[0].records[0].created_ms == 3 && read.sessions[0].records[0].kind == 'c'); + // The hot path with callbacks does not allocate either. + allocations = 0; + counting = true; + for (int i = 0; i < 100; ++i) r.request(hash, key, 0, 'c', 3, ready, build); + counting = false; + CHECK(allocations.load() == 0); +} + +void test_late_build() { + const auto path = scratch("late.log"); + po::Recorder r(config(path)); + // A build time known when the record is made is in its line; one that arrives later is a B line. + CHECK(request(r, 1, 0, 'c', true, 5, 40)); + CHECK(request(r, 2, 0, 'g', false, 5)); + CHECK(r.flush() == 2); + r.note_build(po::key_hash(key_of(2)), 0, 1500); + r.note_build(po::key_hash(key_of(2)), 0, 9999); // a second time is ignored + r.note_build(po::key_hash(key_of(77)), 0, 5); // never asked for: ignored + CHECK(r.flush() == 1); + CHECK(r.flush() == 0); + // A build that ends between the claim and the publish is not lost. + const std::string key = key_of(3); + const auto claim = r.claim(po::key_hash(key), 4); + CHECK(claim); + r.note_build(po::key_hash(key), 4, 321); + r.publish(claim, key, 'g', false, 1, po::unknown_ms); + CHECK(r.flush() == 1); + const auto read = po::parse(slurp(path)); + CHECK(read.bad_lines == 0 && read.sessions.size() == 1 && read.sessions[0].records.size() == 3); + CHECK(read.sessions[0].records[0].build_ms == 40 && read.sessions[0].records[0].ready); + CHECK(read.sessions[0].records[1].build_ms == 1500); + CHECK(read.sessions[0].records[2].build_ms == 321); +} + +// The file of a few records, cut at every byte: each cut reads as far as it goes, never more, never an error. +void test_truncated() { + std::string text = po::format_header() + po::format_session(0x10de, 0x2504); + std::vector ends; + for (int i = 0; i < 6; ++i) { + po::Record r; + r.key = key_of(i); + r.variant = std::uint32_t(i); + r.first_ms = std::uint32_t(100 * i); + r.build_ms = std::uint32_t(i); + text += po::format_record(r); + ends.push_back(text.size()); + } + for (std::size_t cut = 0; cut <= text.size(); ++cut) { + const auto read = po::parse(std::string_view(text).substr(0, cut)); + std::size_t whole = 0; + for (const auto end : ends) whole += cut >= end; + std::size_t records = 0; + for (const auto& s : read.sessions) records += s.records.size(); + CHECK(records == whole); + CHECK(read.bad_lines == 0); + const bool at_line_end = cut == 0 || text[cut - 1] == '\n'; + CHECK(read.cut_tail == !at_line_end); + } +} + +void test_damaged() { + std::string text = po::format_session(0x10de, 0x2504); + std::vector> lines; // [begin, end) of each record line + for (int i = 0; i < 5; ++i) { + po::Record r; + r.key = key_of(i); + r.first_ms = std::uint32_t(i); + const std::size_t begin = text.size(); + text += po::format_record(r); + lines.push_back({begin, text.size()}); + } + // One byte changed anywhere in the third line: that line goes, the four others are kept. + for (std::size_t at = lines[2].first; at + 1 < lines[2].second; ++at) { + for (const char replacement : {'X', '0', ' '}) { + std::string damaged = text; + if (damaged[at] == replacement) continue; + damaged[at] = replacement; + const auto read = po::parse(damaged); + CHECK(read.sessions.size() == 1); + std::size_t records = read.sessions.empty() ? 0 : read.sessions[0].records.size(); + CHECK(records == 4); + CHECK(read.bad_lines == 1); + for (const auto& rec : read.sessions.empty() ? std::vector{} : read.sessions[0].records) + CHECK(rec.key != key_of(2)); + } + } + // Garbage between good lines, a line without a checksum, an empty file, binary noise, Windows line ends. + const auto noisy = po::parse(text.substr(0, lines[1].second) + "garbage\n\n*\n P x\n" + text.substr(lines[1].second)); + CHECK(noisy.sessions.size() == 1 && noisy.sessions[0].records.size() == 5 && noisy.bad_lines == 3); + CHECK(po::parse("").sessions.empty()); + std::mt19937 rng(11); + for (int round = 0; round < 200; ++round) { + std::string noise(std::size_t(rng() % 600), '\0'); + for (char& c : noise) c = char(rng()); + po::parse(noise); // must not crash or throw + std::string mixed = text; + for (int k = 0; k < 6; ++k) mixed[rng() % mixed.size()] = char(rng()); + po::parse(mixed); + } + std::string crlf; + for (const char c : text) { + if (c == '\n') crlf += '\r'; + crlf += c; + } + const auto windows = po::parse(crlf); + CHECK(windows.sessions.size() == 1 && windows.sessions[0].records.size() == 5 && windows.bad_lines == 0); +} + +void test_sessions_append() { + const auto path = scratch("sessions.log"); + for (int run = 0; run < 3; ++run) { + po::Recorder r(config(path)); + CHECK(request(r, run)); // different in each run + CHECK(request(r, 100)); // the same in each run: recorded in each + CHECK(r.flush() == 2); + } + const std::string text = slurp(path); + CHECK(text.rfind("# leonida pipeline order 1\n", 0) == 0); + CHECK(text.find("# leonida", 5) == std::string::npos); // the header once + const auto read = po::parse(text); + CHECK(read.sessions.size() == 3 && read.bad_lines == 0); + for (const auto& s : read.sessions) CHECK(s.records.size() == 2 && s.records[1].key == key_of(100)); +} + +void test_full_record() { + const auto path = scratch("full.log"); + po::Recorder r(config(path, 100)); + int kept = 0; + for (int n = 0; n < 300; ++n) kept += request(r, n); + CHECK(kept == 100); + for (int n = 0; n < 300; ++n) CHECK(!request(r, n)); // the full record neither grows nor fails + CHECK(r.flush() == 100); + const auto counts = r.counts(); + CHECK(counts.requested == 100); + CHECK(counts.overflow >= 200); + CHECK(po::parse(slurp(path)).sessions[0].records.size() == 100); + CHECK(r.close().find("not recorded") != std::string::npos); +} + +void test_file_is_bounded() { + const auto path = scratch("bounded.log"); + auto c = config(path); + c.max_file_bytes = 600; + for (int run = 0; run < 6; ++run) { + po::Recorder r(c); + for (int n = 0; n < 5; ++n) request(r, run * 10 + n); + CHECK(r.flush() == 5); + } + // A file past the limit is set aside as .prev and a new one is started: never more than two files of about the limit. + CHECK(std::filesystem::exists(std::filesystem::path(path).concat(".prev"))); + CHECK(std::filesystem::file_size(path) < 600 + 1000); + CHECK(std::filesystem::file_size(std::filesystem::path(path).concat(".prev")) < 600 + 1000); + CHECK(po::parse(slurp(path)).bad_lines == 0); +} + +void test_unwritable() { + // A directory where the file should be: the open fails, the recorder says so and the hot path goes on. + const auto dir = std::filesystem::temp_directory_path() / "leonida_pipeline_order_test" / "isdir.log"; + std::filesystem::create_directories(dir); + po::Recorder r(config(dir)); + CHECK(request(r, 1)); + CHECK(r.flush() == -1); + CHECK(r.failed()); + CHECK(request(r, 2)); + CHECK(r.flush() == -1); + CHECK(!r.close().empty()); +} + +void test_concurrent() { + const auto path = scratch("threads.log"); + constexpr int threads = 8, distinct = 1500, variants = 2; + po::Recorder r(config(path, 4096)); + r.start(std::chrono::milliseconds(2)); // the writer runs while the threads ask + std::atomic recorded{0}; + std::atomic go{false}; + std::vector pool; + for (int t = 0; t < threads; ++t) + pool.emplace_back([&, t] { + std::mt19937 rng(unsigned(t) + 1); + while (!go.load()) std::this_thread::yield(); + for (int i = 0; i < distinct * variants * 3; ++i) { + const int n = int(rng() % distinct); + const std::uint32_t variant = (rng() % variants) * 2; + const std::string key = key_of(n); + const auto claim = r.claim(po::key_hash(key), variant); + if (!claim) continue; + ++recorded; + r.publish(claim, key, 'g', false, 1, po::unknown_ms); + if (i % 7 == 0) r.note_build(po::key_hash(key), variant, std::uint32_t(i)); + } + }); + go = true; + for (auto& th : pool) th.join(); + r.close(); + const auto read = po::parse(slurp(path)); + CHECK(read.bad_lines == 0 && !read.cut_tail && read.sessions.size() == 1); + std::set> seen; + std::size_t duplicates = 0; + for (const auto& rec : read.sessions[0].records) duplicates += !seen.insert({rec.key, rec.variant}).second; + CHECK(duplicates == 0); // each pipeline and variant once, whoever asked first + CHECK(int(read.sessions[0].records.size()) == recorded.load()); // and every one that was claimed reached the file + CHECK(recorded.load() > distinct * variants * 9 / 10); // almost all of the 3000 were asked at least once + CHECK(recorded.load() <= distinct * variants); +} + +// The hot path (claim, publish, note_build) does not allocate, on a first request or a repeated one. +void test_no_allocation() { + const auto path = scratch("alloc.log"); + po::Recorder r(config(path, 2000)); + std::vector keys; + for (int n = 0; n < 1000; ++n) keys.push_back(key_of(n)); + allocations = 0; + counting = true; + for (int round = 0; round < 3; ++round) + for (const auto& key : keys) { + const auto hash = po::key_hash(key); + const auto claim = r.claim(hash, 0); + if (claim) r.publish(claim, key, 'c', false, 0, po::unknown_ms); + r.note_build(hash, 0, 5); + } + counting = false; + CHECK(allocations.load() == 0); + CHECK(r.counts().requested == 1000); +} + +// The writer thread alone puts a record in the file, and stop() leaves nothing running. +void test_thread_writes() { + const auto path = scratch("thread.log"); + po::Recorder r(config(path)); + r.start(std::chrono::milliseconds(5)); + r.start(std::chrono::milliseconds(5)); // idempotent + CHECK(request(r, 1)); + for (int i = 0; i < 400 && slurp(path).find("\nP ") == std::string::npos; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + CHECK(po::parse(slurp(path)).sessions.size() == 1); + CHECK(!po::parse(slurp(path)).sessions.empty() && po::parse(slurp(path)).sessions[0].records.size() == 1); + r.stop(); + r.stop(); +} + +void test_counts_and_report() { + const auto path = scratch("counts.log"); + po::Recorder r(config(path)); + // created, first use: leads 10, 20, 30, 40, 1000 (median 30), two ready out of five. + const std::uint32_t leads[] = {40, 10, 1000, 30, 20}; + for (int i = 0; i < 5; ++i) { + clock_ms = 5000; + request(r, i, 0, 'c', i < 2, 5000 - leads[i]); + } + request(r, 2); // a repeat changes nothing + const auto c = r.counts(); + CHECK(c.requested == 5 && c.ready == 2 && c.overflow == 0 && c.median_lead_ms == 30); + // A first use before the creation time (clocks, a restart of the counter) is a lead of 0, not a huge number. + clock_ms = 10; + request(r, 50, 0, 'c', false, 900); + CHECK(r.counts().requested == 6); + const std::string line = r.close(); + CHECK(line.find("requested 6") != std::string::npos); + CHECK(line.find("already ready 2") != std::string::npos); + CHECK(line.find("median lead 20 ms") != std::string::npos); // leads 0 10 20 30 40 1000: the lower middle one + CHECK(r.close().empty()); // once + CHECK(slurp(path).find("\nP ") != std::string::npos); // close() wrote the rest +} + +void test_key_is_one_word() { + const auto path = scratch("word.log"); + po::Recorder r(config(path)); + const std::string odd = "a b\nc*d" + std::string(100, 'z'); + const auto claim = r.claim(po::key_hash(odd), 0); + CHECK(claim); + r.publish(claim, odd, 'c', false, 0, po::unknown_ms); + CHECK(r.flush() == 1); + const auto read = po::parse(slurp(path)); + CHECK(read.bad_lines == 0 && read.sessions.size() == 1 && read.sessions[0].records.size() == 1); + CHECK(read.sessions[0].records[0].key.size() == po::key_chars); + CHECK(read.sessions[0].records[0].key.rfind("a_b_c_d", 0) == 0); +} + +} // namespace + +int main() { + test_switch(); + test_first_request_only(); + test_variants_are_distinct(); + test_order_is_kept(); + test_fields_round_trip(); + test_request_helper(); + test_late_build(); + test_truncated(); + test_damaged(); + test_sessions_append(); + test_full_record(); + test_file_is_bounded(); + test_unwritable(); + test_concurrent(); + test_no_allocation(); + test_thread_writes(); + test_counts_and_report(); + test_key_is_one_word(); + if (failures) { + std::fprintf(stderr, "%d failure(s)\n", failures); + return 1; + } + std::puts("pipeline_order_test: ok"); + return 0; +} diff --git a/runtime/test/replay_pipeline_order_hook_test.cpp b/runtime/test/replay_pipeline_order_hook_test.cpp new file mode 100644 index 0000000000..8d8294c6f3 --- /dev/null +++ b/runtime/test/replay_pipeline_order_hook_test.cpp @@ -0,0 +1,213 @@ +// The request hook of ComputePipeline and GraphicsPipeline (RT-PIPELINE-PREWARM-ORDER phase 1, pipeline_order.h): it is +// called at every dispatch and draw that names the pipeline, whether the pipeline is built already, built on this very +// request, not built at all (skipped) or an unbound-slot variant, and it changes nothing prepare() returns. A hook that +// only saw the requests that had to build would miss exactly the pipelines that were ready in time. No GPU: pipelines +// and resources are fakes (the same shape as replay_pipeline_compiles_test.cpp). +#include "../src/vulkan_replay.h" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace leonida; + +int failures = 0; +void check(bool ok, const std::string& what) { + if (ok) return; + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; +} + +template +T handle(std::uintptr_t n) { + return reinterpret_cast(n); +} + +constexpr ResourceId color_id = 1; + +// What the hook was told, per pipeline: the variants, in order of the calls. +struct Seen { + std::vector variants; +}; +std::map seen; +struct Context { + int id; +}; +Context contexts[8] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}}; + +void on_request(void* context, std::uint32_t variant) { + auto& s = seen[static_cast(context)->id]; + s.variants.push_back(variant); +} + +VkPipeline lazy_build(void*) { return handle(0x5000); } + +ReplayFunctions functions(std::map& compute, + std::map& graphics) { + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, std::uint32_t, + const void*) {}; + vk.dispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology) {}; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) {}; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, const VkDeviceSize*, + const VkDeviceSize*, const VkDeviceSize*) {}; + vk.draw = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::int32_t, std::uint32_t) {}; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return handle(8); }; + vk.buffer_at = [](std::uint64_t, std::uint64_t&, VkBuffer& buffer, VkDeviceSize& offset) { + buffer = handle(9); + offset = 0; + return true; + }; + vk.graphics_pipeline = [&graphics](std::uintptr_t id) -> const GraphicsPipeline* { + const auto it = graphics.find(id); + return it == graphics.end() ? nullptr : &it->second; + }; + vk.compute_pipeline = [&compute](std::uintptr_t id) -> const ComputePipeline* { + const auto it = compute.find(id); + return it == compute.end() ? nullptr : &it->second; + }; + return vk; +} + +const ResourceBinding* resolve(ResourceId id) { + static const ResourceBinding color = [] { + ResourceBinding b{}; + b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + b.format = VK_FORMAT_R8G8B8A8_UNORM; + b.width = b.height = 16; + b.image = handle(10); + return b; + }(); + return id == color_id ? &color : nullptr; +} + +Draw draw_of(std::uintptr_t pipeline, int colors_bound) { + Draw d{}; + d.pipeline = pipeline; + d.topology = 4; + d.count = 3; + d.instances = 1; + d.first = 1; + auto views = std::make_shared(); + for (int i = 0; i < colors_bound; ++i) views->render_targets[std::size_t(i)] = {color_id, 0, 0, 1}; + views->vertex_buffers[0].va = 0x1000; + views->vertex_buffers[0].size = 64; + d.views = views; + return d; +} + +GraphicsPipeline graphics_pipeline(int id, bool built) { + GraphicsPipeline p{}; + p.layout = handle(7); + if (built) p.pipeline = handle(0x4000 + std::uintptr_t(id)); + p.color_formats.assign(2, VK_FORMAT_R8G8B8A8_UNORM); + p.vertex_slots = 1; + p.variant = [](std::uint32_t flags) { return handle(0x6000 + flags); }; + p.requested = &on_request; + p.request_context = &contexts[id]; + return p; +} + +} // namespace + +int main() { + std::map compute; + std::map graphics; + + // 1: compute, handle ready, no build function: the hook still runs. + ComputePipeline ready{}; + ready.layout = handle(7); + ready.pipeline = handle(0x1000); + ready.requested = &on_request; + ready.request_context = &contexts[1]; + compute[1] = ready; + // 2: compute, lazy, not built yet: it is built where prepare() meets it, and told all the same. + ComputePipeline lazy{}; + lazy.layout = handle(7); + lazy.build = &lazy_build; + lazy.requested = &on_request; + lazy.request_context = &contexts[2]; + compute[2] = lazy; + // 3: compute that is never built on request (skipped): a dispatch dropped, still a request. + ComputePipeline skipped{}; + skipped.layout = handle(7); + skipped.skipped = true; + skipped.build = [](void*) -> VkPipeline { return VK_NULL_HANDLE; }; + skipped.requested = &on_request; + skipped.request_context = &contexts[3]; + compute[3] = skipped; + // 4: compute with no hook at all (the log is off): nothing is called and nothing breaks. + ComputePipeline plain{}; + plain.layout = handle(7); + plain.pipeline = handle(0x1001); + compute[4] = plain; + // 5: graphics built, both targets bound: variant 0. 6: graphics not built, slot 1 unbound: variant 2. + graphics[5] = graphics_pipeline(5, true); + graphics[6] = graphics_pipeline(6, false); + + CommandList list; + list.dispatch({1, {}, 1, 1, 1}); + list.dispatch({2, {}, 1, 1, 1}); + list.dispatch({3, {}, 1, 1, 1}); + list.dispatch({4, {}, 1, 1, 1}); + list.dispatch({1, {}, 1, 1, 1}); // asked again: told again (the recorder decides what is new) + list.draw(draw_of(5, 2)); + list.draw(draw_of(6, 1)); + list.draw(draw_of(6, 2)); + list.close(); + + ReplayFunctions vk = functions(compute, graphics); + PreparedList prepared; + const ReplayResult result = prepare(list, resolve, vk, prepared); + check(result == ReplayResult::success, "prepare succeeds"); + + check(seen[1].variants == std::vector({0, 0}), "a ready compute pipeline is told at each dispatch"); + check(seen[2].variants == std::vector({0}), "a lazy compute pipeline is told once"); + check(seen[3].variants == std::vector({0}), "a skipped compute pipeline is still a request"); + check(seen.count(4) == 0, "no hook, no call"); + check(seen[5].variants == std::vector({0}), "a ready graphics pipeline is told, variant 0"); + check(seen[6].variants == std::vector({2, 0}), "unbound slot 1 is variant 2, then both bound is 0"); + + // What prepare() gives is what it gave without a hook. + auto without_compute = compute; + for (auto& entry : without_compute) { + entry.second.requested = nullptr; + entry.second.request_context = nullptr; + } + auto without_graphics = graphics; + for (auto& entry : without_graphics) { + entry.second.requested = nullptr; + entry.second.request_context = nullptr; + } + seen.clear(); + ReplayFunctions plain_vk = functions(without_compute, without_graphics); + PreparedList plain_prepared; + const ReplayResult plain_result = prepare(list, resolve, plain_vk, plain_prepared); + check(plain_result == result, "the same result without the hook"); + check(seen.empty(), "nobody is told when no pipeline has a hook"); + check(plain_prepared.commands.size() == prepared.commands.size() && plain_prepared.draw_count == prepared.draw_count, + "the same commands without the hook"); + for (std::size_t i = 0; i < plain_prepared.draw_count && i < prepared.draw_count; ++i) + check(plain_prepared.draws[i].pipeline == prepared.draws[i].pipeline, "the same pipeline for draw " + std::to_string(i)); + + if (failures) { + std::fprintf(stderr, "%d failure(s)\n", failures); + return 1; + } + std::puts("replay_pipeline_order_hook_test: ok"); + return 0; +} From 7a4d1f772104f015d84057f8274942bea4fce1b9 Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:33:18 +0100 Subject: [PATCH 2/4] runtime: record the order of first pipeline requests behind LEONIDA_PIPELINE_ORDER_LOG=1 RT-PIPELINE-PREWARM-ORDER phase 1. With the variable set to 1 the D3D12 device appends, per compute, graphics and mesh pipeline and variant that the title uses for the first time, one line to pipeline_order.log beside pipeline_cache.session.bin: the description key, the variant, creation and first-use times since the process started, the build time and whether the handle was ready. One line of counts at exit. Off by default: nothing reads the file yet, and a run without the variable carries no hook. It touches no cache file, the memory gate or the compile queue. The mesh pipeline's key folds in the MS hash (the graphics key does not cover it). Documented in runtime/README.md and docs/d3d12_vulkan.md, and the doc test checks the variable is read and named in both. Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_vulkan.md | 21 +++++ runtime/README.md | 1 + runtime/shims/d3d12_vulkan_device.cpp | 112 ++++++++++++++++++++++++++ tests/test_docs_env_vars.py | 9 +++ 4 files changed, 143 insertions(+) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index ce1a5f7bef..6a9f2a0ea6 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2398,6 +2398,27 @@ Pipeline creation: Replay skips a draw or dispatch while its pipeline is pending. Later uses find the completed handle. A skipped dispatch can lose a one-time resource update. Synchronous first use is the default and strict replay always uses it. `LEONIDA_COMPUTE_WARMUP=0` restricts the worker to pipelines requested by the title. + `LEONIDA_PIPELINE_ORDER_LOG=1` records the order in which the title first asks for pipelines + (RT-PIPELINE-PREWARM-ORDER, phase 1; `runtime/src/pipeline_order.h`). It is off by default: nothing reads the file yet, + so a run that does not ask for it writes nothing and its pipelines carry no hook. For each pipeline and variant (the + unbound-slot mask for graphics, 0 for compute) that a dispatch or draw names for the first time, one line is + appended to `pipeline_order.log` beside `pipeline_cache.session.bin` (so `LEONIDA_PIPELINE_CACHE_DIR` moves it): + `P *`, with the + times in milliseconds since the process started. The key is the SHA-256 of the title's own description of the PSO + (`GetCachedBlob`'s key; a mesh pipeline's MS is folded in), not of the SPIR-V, so a translator change keeps it. A + build that ends after its line was written adds `B *`; a session starts + with `S 1 `. Each line ends with an FNV-1a checksum: a cut or damaged line is skipped on + read, never fatal. The hook sits in replay's `ComputePipeline::requested` / `GraphicsPipeline::requested`, called + where a submission is prepared, also for a handle that exists already (a warm-up build, a cached one); the + recorder decides "first" with one compare-and-swap in a table made at start, takes no lock and allocates nothing, + and a thread of its own appends every 250 ms, so a killed process loses at most that. The record holds 8192 lines + per run (the rest is counted, not kept); a file past 8 MiB is set aside as `pipeline_order.log.prev`. At exit (the + exit cache save, or the device's release) one line gives the counts: `[rt] pipeline-order: requested N, already + ready M, median lead X ms`. "Lead" is first use minus creation. A PSO made from a pipeline state stream on the + console path is created when it is first bound, so its lead is the title's, not an upper bound on a head start. + A root signature the runtime does not know is hashed by its address, so the key of a pipeline made with one can + change from one run to the next. The file is local, like the cache files, and is not meant to be attached to a + report: quote the counts. It changes no build, order or cache. A queued build holds no reference to its PSO or device (`PipelineCompiler`, `runtime/shims/d3d12_pipeline_compile.h`). A PSO's last release drops its queued builds and returns at once; one already running is left to finish, and the worker deletes the PSO after it (`PipelineState::last_release`). The PSO's device reference goes at the release, so diff --git a/runtime/README.md b/runtime/README.md index 16cd4f1549..f18a3bf68f 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -321,6 +321,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | +| `LEONIDA_PIPELINE_ORDER_LOG` | unset (off) | `1` appends, for each pipeline and variant (the unbound-slot mask of a graphics pipeline) that a dispatch or draw names for the first time, one line to `pipeline_order.log` beside `pipeline_cache.session.bin`: the PSO's description key, the variant, when the title created the PSO and when it first used it (milliseconds since the process started), the build time and whether the handle was ready already. A line of counts is printed at exit (`[rt] pipeline-order: requested N, already ready M, median lead X ms`). Record only: nothing builds, orders or skips differently, and no cache file is touched. At most 8192 lines per run; a file past 8 MiB is set aside as `pipeline_order.log.prev`. The file holds hashes and numbers, no shader or game data, and stays local. See `docs/d3d12_vulkan.md`. | | `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side. | | `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. | | `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e424e1d0f3..6399bcdfef 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -46,6 +46,7 @@ #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" #include "../src/pipeline_cache_store.h" +#include "../src/pipeline_order.h" #include "../src/large_module_gate.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" @@ -2043,6 +2044,46 @@ struct DeviceState { // heap equivalents are in MEMORY_POOL_L0 and custom heaps in L1 are refused, as the host runtime does there. bool uma = false; leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against + // LEONIDA_PIPELINE_ORDER_LOG=1: which pipelines the title asks for first, appended to pipeline_order.log beside the + // session cache (pipeline_order.h). Null when off: the pipelines then carry no hook at all. + std::unique_ptr order_log; + void start_order_log() { + char text[8]{}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_PIPELINE_ORDER_LOG", text, sizeof(text)); + if (n == 0 || n >= sizeof(text) || !leonida::pipeline_order::parse_enabled(text)) return; + auto path = pipeline_cache_session_path(); + if (path.empty()) return; + path.replace_filename(L"pipeline_order.log"); + leonida::pipeline_order::Recorder::Config config; + config.path = std::move(path); + config.vendor = pso_identity.vendor; + config.device = pso_identity.device; + config.now_ms = &order_now_ms; + order_log = std::make_unique(std::move(config)); + order_log->start(std::chrono::milliseconds(250)); + } + // The one line of counts, once: at the exit save or when the device goes, whichever comes first. + void close_order_log() { + if (!order_log) return; + const std::string line = order_log->close(); + if (line.empty()) return; + if (order_log->failed()) + std::fprintf(stderr, "[rt] pipeline-order: could not write %ls\n", order_log->path().c_str()); + else + std::fprintf(stderr, "%s\n", line.c_str()); + } + // Milliseconds since this process started. + static std::uint32_t order_now_ms() { + static const ULONGLONG started = [] { + FILETIME created{}, exited{}, kernel{}, user{}; + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) return ULONGLONG(0); + return (ULONGLONG(created.dwHighDateTime) << 32) | created.dwLowDateTime; + }(); + FILETIME now{}; + GetSystemTimeAsFileTime(&now); + const ULONGLONG t = (ULONGLONG(now.dwHighDateTime) << 32) | now.dwLowDateTime; + return started && t > started ? std::uint32_t(std::min((t - started) / 10000, 0xfffffffeull)) : 0; + } std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; std::atomic next_checkpoint{GetTickCount64() + 120000}; @@ -7889,6 +7930,18 @@ struct PipelineStream { bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS }; +// What pipeline_order.log names a stream's pipeline by: the cache key, with the mesh shader's hash folded in (the +// graphics key does not cover the MS, so two mesh pipelines that differ only there would share it). +leonida::cached_pso::Key order_key(const PipelineStream& stream) { + if (stream.has_cs) return pipeline_key(stream.compute); + auto key = pipeline_key(stream.graphics); + if (stream.ms.BytecodeLength) { + key += leonida::sha256_hex({static_cast(stream.ms.pShaderBytecode), stream.ms.BytecodeLength}); + key = leonida::sha256_hex({reinterpret_cast(key.data()), key.size()}); + } + return key; +} + // Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). bool console_stream_enum_enabled() { static const bool enabled = [] { @@ -8194,6 +8247,47 @@ class PipelineState final unregistered_ = true; } void set_cache_key(leonida::cached_pso::Key key) { cache_key_ = std::move(key); } + // The key pipeline_order.log names this pipeline by, where the cache key does not tell two descriptions apart (a + // mesh pipeline's MS is not in it). Set before create_*, only while the log is on. + void set_order_key(leonida::cached_pso::Key key) { order_key_ = std::move(key); } + + // pipeline_order.h: the first dispatch or draw that names a pipeline and variant. Runs while a submission is + // prepared, so it takes no lock and allocates nothing: the first-time test is one compare-and-swap. + static void order_requested(void* self, std::uint32_t variant) { + static_cast(self)->order_request(variant); + } + void order_request(std::uint32_t variant) { + auto* const log = device_.order_log.get(); + if (!log) return; + const auto& key = order_key_.empty() ? cache_key_ : order_key_; + log->request(order_hash_, key, variant, order_kind_, order_created_ms_, + [&] { return order_ready(variant); }, + [&] { return variant == 0 ? order_build_ms_.load() : leonida::pipeline_order::unknown_ms; }); + } + // Its handle existed, and nobody was building it, when it was first asked for. + bool order_ready(std::uint32_t variant) { + if (is_graphics_) { + if (variant == 0 && graphics_.pipeline) return true; + return graphics_.built && graphics_.built(variant) != VK_NULL_HANDLE; + } + return pipeline_.built ? pipeline_.built(this) != VK_NULL_HANDLE : pipeline_.pipeline != VK_NULL_HANDLE; + } + // Called at the end of create_compute / create_graphics, before the pipeline is registered with the replay. + void order_install(void (*&requested)(void*, std::uint32_t), void*& context, char kind) { + if (!device_.order_log) return; + const auto& key = order_key_.empty() ? cache_key_ : order_key_; + if (key.empty()) return; + order_hash_ = leonida::pipeline_order::key_hash(key); + order_kind_ = kind; + requested = &order_requested; + context = this; + } + void order_note_build(std::uint32_t variant, ULONGLONG took_ms) { + if (!device_.order_log || !order_hash_) return; + const std::uint32_t ms = std::uint32_t(std::min(took_ms, 0xfffffffeull)); + if (variant == 0) order_build_ms_.store(ms); + device_.order_log->note_build(order_hash_, variant, ms); + } // A null pointer is accepted with S_OK, as by the PC runtime (measured on an RTX 3060 and WARP). HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override { @@ -8989,9 +9083,12 @@ class PipelineState final if (!lazy_) { VkResult compile_status = VK_SUCCESS; const bool cache_only = device_.info.cold_graphics_compile; + const ULONGLONG build_started = device_.order_log ? GetTickCount64() : 0; graphics_.pipeline = build(0, "graphics-create", cache_only ? VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT : 0, &compile_status); + if (graphics_.pipeline && device_.order_log) + order_build_ms_.store(std::uint32_t(std::min(GetTickCount64() - build_started, 0xfffffffeull))); // A cache-only create that the driver would have to compile stays null: the first draw builds it. if (!graphics_.pipeline && !(cache_only && compile_status == VK_PIPELINE_COMPILE_REQUIRED)) return E_FAIL; } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 @@ -9041,6 +9138,7 @@ class PipelineState final int(desc.PrimitiveTopologyType), desc.SampleDesc.Count); leonida::fsdraw::note_pipeline(id(), text); } + order_install(graphics_.requested, graphics_.request_context, graphics_.mesh ? 'm' : 'g'); if (device_.info.device_checkpoints) { leonida::CheckpointShaders shaders{}; for (std::size_t i = 0; i < std::size(stages); ++i) @@ -9188,6 +9286,7 @@ class PipelineState final code_bytes_ = code.size(); pipeline_.code_base = code_base_; } + if (!pipeline_.skipped) order_install(pipeline_.requested, pipeline_.request_context, 'c'); device_.context->add_pipeline(id(), pipeline_, device_.info.device_fault_diagnostics ? entry->name.c_str() : nullptr); registered_ = true; @@ -9280,6 +9379,7 @@ class PipelineState final maybe_checkpoint(cache); pipeline_.pipeline = built; compute_failed_ = false; + order_note_build(0, took); return built; } @@ -9661,7 +9761,9 @@ class PipelineState final const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand, [&] { return variants_.contains(unbound); }); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; + const ULONGLONG build_started = device_.order_log ? GetTickCount64() : 0; const VkPipeline pipeline = build(unbound, trigger); + if (pipeline && device_.order_log) order_note_build(unbound, GetTickCount64() - build_started); if (!pipeline) { if (leonida::pipeline_profile::enabled()) std::fprintf(stderr, "[rt] pso-variant failed stage=%s mask=%u\n", recipe_.mesh ? "ms" : "vs", unbound); @@ -9725,6 +9827,11 @@ class PipelineState final bool native_source_ready_ = false; std::shared_ptr native_owner_; leonida::cached_pso::Key cache_key_; + leonida::cached_pso::Key order_key_; // see set_order_key; empty: cache_key_ + std::uint64_t order_hash_ = 0; // 0: this pipeline is not in the order log + char order_kind_ = 'c'; + std::uint32_t order_created_ms_ = device_.order_log ? DeviceState::order_now_ms() : 0; + std::atomic order_build_ms_{leonida::pipeline_order::unknown_ms}; // variant 0, once built }; void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature) { @@ -10942,6 +11049,7 @@ class Device final state_.pso_identity.device = props.deviceID; state_.pso_identity.driver = props.driverVersion; std::memcpy(state_.pso_identity.cache_uuid, props.pipelineCacheUUID, VK_UUID_SIZE); + state_.start_order_log(); if (state_.info.max_push_constants_size == 0) { state_.info.max_push_constants_size = props.limits.maxPushConstantsSize; state_.info.push_constants_need_fallback = (state_.info.max_push_constants_size < 144); @@ -11706,6 +11814,7 @@ class Device final std::lock_guard lock(exit_cache_mutex); std::erase(exit_cache_devices, &state_); } + state_.close_order_log(); // the pipelines are gone by now (each held this device) leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress raw_images_.clear(); geometry_refresher_.reset(); // its refresh uses state_.geometry @@ -11836,6 +11945,7 @@ class Device final auto* pipeline=new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(stream.has_cs?pipeline_key(stream.compute):pipeline_key(stream.graphics)); + if(state_.order_log) pipeline->set_order_key(order_key(stream)); if(!rt::d3d12_xs::attach_pso_record(pipeline,std::move(record))){pipeline->Release();return E_OUTOFMEMORY;} pipeline->set_pending_stream(stream.has_cs); return hand_out(pipeline,iid,out); @@ -13921,6 +14031,7 @@ class Device final if (FAILED(parsed)) return finish(parsed); auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); + if (state_.order_log) pipeline->set_order_key(order_key(stream)); const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, stream.back_masks ? &stream.back_stencil : nullptr); @@ -17056,6 +17167,7 @@ bool save_pipeline_caches_at_exit(unsigned wait_ms) { bool wrote = false; const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms); for (DeviceState* d : exit_cache_devices) { + d->close_order_log(); // appends the last lines and prints the counts; no cache file is touched if (!d->context || !d->pipeline_cache_handle) continue; // A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is // given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is diff --git a/tests/test_docs_env_vars.py b/tests/test_docs_env_vars.py index a22c9729e6..a812f86ebb 100644 --- a/tests/test_docs_env_vars.py +++ b/tests/test_docs_env_vars.py @@ -80,6 +80,15 @@ def test_every_variable_is_named_in_a_document(self): self.assertEqual(missing, [], "read by the code and named in no .md file:\n" + "\n".join( f" {variable} ({where})" for variable, where in missing)) + def test_the_pipeline_order_log_switch_is_read_and_documented_where_the_cache_is(self): + # RT-PIPELINE-PREWARM-ORDER: off by default, so a person has to find it next to the cache variables. + found = variables_read(self.sources) + self.assertIn("LEONIDA_PIPELINE_ORDER_LOG", found) + self.assertTrue(found["LEONIDA_PIPELINE_ORDER_LOG"].startswith("runtime/shims/d3d12_vulkan_device.cpp:")) + for page in ("runtime/README.md", "docs/d3d12_vulkan.md"): + self.assertIn("LEONIDA_PIPELINE_ORDER_LOG", self.pages[page], page) + self.assertIn("pipeline_order.log", self.pages["runtime/README.md"]) + def test_an_undocumented_variable_is_reported(self): sources = {"runtime/shims/x.cpp": 'GetEnvironmentVariableA("LEONIDA_ONE", s, n);\n' 'kName[] = L"LEONIDA_TWO";\n// LEONIDA_COMMENT is not a literal\n', From dcdcade3260bbbae9d4458df75e2785cb401f63c Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:07:37 +0100 Subject: [PATCH 3/4] runtime: address review of the pipeline order recorder - open(): when the existing log does not end with a newline (a process killed mid-line), write one first so the next session line is not glued to the cut line and its records are not filed under the previous run. - Fix the hook comments (vulkan_replay.h, d3d12_vulkan_device.cpp, docs, README): the hook never blocks and allocates nothing, but the readiness callbacks take a non-blocking try_lock on the first request of a pipeline and of a variant. - Close the order log after the exit pipeline cache write, not before. - Remove the unused Slot::written and Slot::build_written. - Tests: cut file then new session, flush stops at an unpublished slot, unknown session version rejected. Trailing whitespace fixed. Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_vulkan.md | 2 +- runtime/README.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 10 ++- runtime/src/pipeline_order.h | 19 ++++- runtime/src/vulkan_replay.h | 2 +- runtime/test/pipeline_order_test.cpp | 71 +++++++++++++++++++ .../test/replay_pipeline_order_hook_test.cpp | 2 +- 7 files changed, 99 insertions(+), 9 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3023e0549d..77411ffd86 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2424,7 +2424,7 @@ Pipeline creation: with `S 1 `. Each line ends with an FNV-1a checksum: a cut or damaged line is skipped on read, never fatal. The hook sits in replay's `ComputePipeline::requested` / `GraphicsPipeline::requested`, called where a submission is prepared, also for a handle that exists already (a warm-up build, a cached one); the - recorder decides "first" with one compare-and-swap in a table made at start, takes no lock and allocates nothing, + recorder decides "first" with one compare-and-swap in a table made at start, never blocks and allocates nothing (a non-blocking `try_lock` on the first request of a pipeline and of a variant), and a thread of its own appends every 250 ms, so a killed process loses at most that. The record holds 8192 lines per run (the rest is counted, not kept); a file past 8 MiB is set aside as `pipeline_order.log.prev`. At exit (the exit cache save, or the device's release) one line gives the counts: `[rt] pipeline-order: requested N, already diff --git a/runtime/README.md b/runtime/README.md index dfaa73ae62..50262bf78a 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -328,7 +328,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | -| `LEONIDA_PIPELINE_ORDER_LOG` | unset (off) | `1` appends, for each pipeline and variant (the unbound-slot mask of a graphics pipeline) that a dispatch or draw names for the first time, one line to `pipeline_order.log` beside `pipeline_cache.session.bin`: the PSO's description key, the variant, when the title created the PSO and when it first used it (milliseconds since the process started), the build time and whether the handle was ready already. A line of counts is printed at exit (`[rt] pipeline-order: requested N, already ready M, median lead X ms`). Record only: nothing builds, orders or skips differently, and no cache file is touched. At most 8192 lines per run; a file past 8 MiB is set aside as `pipeline_order.log.prev`. The file holds hashes and numbers, no shader or game data, and stays local. See `docs/d3d12_vulkan.md`. | +| `LEONIDA_PIPELINE_ORDER_LOG` | unset (off) | `1` appends, for each pipeline and variant (the unbound-slot mask of a graphics pipeline) that a dispatch or draw names for the first time, one line to `pipeline_order.log` beside `pipeline_cache.session.bin`: the PSO's description key, the variant, when the title created the PSO and when it first used it (milliseconds since the process started), the build time and whether the handle was ready already. A line of counts is printed at exit (`[rt] pipeline-order: requested N, already ready M, median lead X ms`). The hook never blocks and allocates nothing; it takes only a non-blocking `try_lock`, on the first request of a pipeline and of a variant. Record only: nothing builds, orders or skips differently, and no cache file is touched. At most 8192 lines per run; a file past 8 MiB is set aside as `pipeline_order.log.prev`. The file holds hashes and numbers, no shader or game data, and stays local. See `docs/d3d12_vulkan.md`. | | `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side. | | `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. | | `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index edd5c9b26c..1eeaeddd80 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -8272,7 +8272,7 @@ class PipelineState final void set_order_key(leonida::cached_pso::Key key) { order_key_ = std::move(key); } // pipeline_order.h: the first dispatch or draw that names a pipeline and variant. Runs while a submission is - // prepared, so it takes no lock and allocates nothing: the first-time test is one compare-and-swap. + // prepared, so it never blocks and allocates nothing: the first-time test is one compare-and-swap (the readiness callbacks only try_lock, without waiting, on the first request of a pipeline and variant). static void order_requested(void* self, std::uint32_t variant) { static_cast(self)->order_request(variant); } @@ -17194,9 +17194,13 @@ bool save_pipeline_caches_at_exit(unsigned wait_ms) { return false; } bool wrote = false; + // After the cache write, so that the order log's final append (a join and a write) never delays the cache. It + // appends the last lines and prints the counts; no cache file is touched. + const auto close_order_logs = [] { + for (DeviceState* d : exit_cache_devices) d->close_order_log(); + }; const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms); for (DeviceState* d : exit_cache_devices) { - d->close_order_log(); // appends the last lines and prints the counts; no cache file is touched if (!d->context || !d->pipeline_cache_handle) continue; // A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is // given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is @@ -17229,10 +17233,12 @@ bool save_pipeline_caches_at_exit(unsigned wait_ms) { [&] { return write->done; })) { std::fprintf(stderr, "[rt] d3d12: pipeline cache still being written after %u ms at exit; the process " "ends without waiting for it\n", kExitCacheWriteMs); + close_order_logs(); return wrote; // the device list stays as it is: the write still uses this device } wrote = true; } + close_order_logs(); return wrote; } diff --git a/runtime/src/pipeline_order.h b/runtime/src/pipeline_order.h index 4cb9379f80..1ee4f7bd97 100644 --- a/runtime/src/pipeline_order.h +++ b/runtime/src/pipeline_order.h @@ -30,6 +30,7 @@ #include #include #include +#include #ifdef _WIN32 #include #endif @@ -452,8 +453,6 @@ class Recorder { char kind = 'c'; bool ready = false; char key[key_chars] = {}; - bool written = false; // writer thread only - bool build_written = false; // writer thread only }; static std::size_t table_size(std::size_t capacity) { @@ -488,7 +487,6 @@ class Recorder { r.ready = s.ready; out += format_record(r); ++lines; - s.written = true; if (r.build_ms == unknown_ms) waiting_.push_back(cursor_); ++cursor_; } @@ -527,6 +525,15 @@ class Recorder { return lines; } + static bool ends_with_newline(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary | std::ios::ate); + if (!in || in.tellg() <= 0) return true; + in.seekg(-1, std::ios::end); + char last = '\n'; + in.get(last); + return last == '\n'; + } + bool open() { std::error_code ec; if (config_.path.empty()) return false; @@ -549,6 +556,12 @@ class Recorder { #endif if (!f) return false; file_.reset(f); + // A process killed in the middle of a line leaves no newline: the next session's line would stick to it and + // the reader would file this run's records under the previous one. The reader skips empty lines. + if (!new_file_ && !ends_with_newline(config_.path) && std::fputc('\n', f) == EOF) { + file_.reset(); + return false; + } return true; } diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1a57d3085b..f465fde7e1 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -878,7 +878,7 @@ struct ComputePipeline { bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take // Told at every dispatch that names this pipeline, built or not, with variant 0 (pipeline_order.h records the first - // one). Null: nobody is told. Called while a submission is prepared: it must not block, take a lock or allocate. + // one). Null: nobody is told. Called while a submission is prepared: it must never block or allocate (the only lock it may take is a non-blocking try_lock, on the first request of a pipeline and of a variant). void (*requested)(void*, std::uint32_t variant) = nullptr; void* request_context = nullptr; }; diff --git a/runtime/test/pipeline_order_test.cpp b/runtime/test/pipeline_order_test.cpp index a041f3e907..2d0d4e09a8 100644 --- a/runtime/test/pipeline_order_test.cpp +++ b/runtime/test/pipeline_order_test.cpp @@ -505,6 +505,74 @@ void test_key_is_one_word() { CHECK(read.sessions[0].records[0].key.rfind("a_b_c_d", 0) == 0); } +// A process killed in the middle of a line leaves no newline; the next session must not stick to the cut line. +void test_cut_file_then_new_session() { + const auto path = scratch("cutfile.log"); + { + po::Recorder r(config(path)); + CHECK(request(r, 1)); + CHECK(request(r, 2)); + CHECK(r.flush() == 2); + } + std::string text = slurp(path); + CHECK(!text.empty() && text.back() == '\n'); + text.resize(text.size() - 7); // the last record line cut short, no newline + { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + out << text; + } + { + po::Recorder r(config(path)); + CHECK(request(r, 3)); + CHECK(request(r, 4)); + CHECK(r.flush() == 2); + } + const auto read = po::parse(slurp(path)); + CHECK(read.sessions.size() == 2); + if (read.sessions.size() == 2) { + CHECK(read.sessions[0].records.size() == 1 && read.sessions[0].records[0].key == key_of(1)); + CHECK(read.sessions[1].records.size() == 2); + if (read.sessions[1].records.size() == 2) { + CHECK(read.sessions[1].records[0].key == key_of(3)); + CHECK(read.sessions[1].records[1].key == key_of(4)); + } + } + CHECK(read.bad_lines == 1); // the cut line itself, skipped +} + +// The writer stops at a slot still being filled, so the file keeps the order of asking. +void test_flush_stops_at_unpublished() { + const auto path = scratch("holdback.log"); + po::Recorder r(config(path)); + const std::string ka = key_of(10), kb = key_of(11); + const auto a = r.claim(po::key_hash(ka), 0); + const auto b = r.claim(po::key_hash(kb), 0); + CHECK(a && b); + r.publish(b, kb, 'c', false, 0, po::unknown_ms); + CHECK(r.flush() == 0); // B is published but A, asked first, is not yet + r.publish(a, ka, 'c', false, 0, po::unknown_ms); + CHECK(r.flush() == 2); + const auto read = po::parse(slurp(path)); + CHECK(read.sessions.size() == 1 && read.sessions[0].records.size() == 2); + if (read.sessions.size() == 1 && read.sessions[0].records.size() == 2) { + CHECK(read.sessions[0].records[0].key == ka); + CHECK(read.sessions[0].records[1].key == kb); + } +} + +// A session line of a version this reader does not know is not read as one of this one. +void test_unknown_session_version() { + const std::string known = po::format_session(0x10de, 0x2504); + CHECK(po::parse(known).sessions.size() == 1); + // The same line with version 2 and a good checksum: the checksum is the one of the text before " *". + std::string body = "S 2 10de 2504"; + char sum[16]; + std::snprintf(sum, sizeof(sum), " *%08x\n", po::checksum(body)); + const auto read = po::parse(body + sum); + CHECK(read.sessions.empty()); + CHECK(read.bad_lines == 1); +} + } // namespace int main() { @@ -526,6 +594,9 @@ int main() { test_thread_writes(); test_counts_and_report(); test_key_is_one_word(); + test_cut_file_then_new_session(); + test_flush_stops_at_unpublished(); + test_unknown_session_version(); if (failures) { std::fprintf(stderr, "%d failure(s)\n", failures); return 1; diff --git a/runtime/test/replay_pipeline_order_hook_test.cpp b/runtime/test/replay_pipeline_order_hook_test.cpp index 8d8294c6f3..af85e85c21 100644 --- a/runtime/test/replay_pipeline_order_hook_test.cpp +++ b/runtime/test/replay_pipeline_order_hook_test.cpp @@ -158,7 +158,7 @@ int main() { // 5: graphics built, both targets bound: variant 0. 6: graphics not built, slot 1 unbound: variant 2. graphics[5] = graphics_pipeline(5, true); graphics[6] = graphics_pipeline(6, false); - + CommandList list; list.dispatch({1, {}, 1, 1, 1}); list.dispatch({2, {}, 1, 1, 1}); From 4263427b463337307aba8f73afb70e6c563b659d Mon Sep 17 00:00:00 2001 From: MoonEyes <14891700+MoonEyes@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:13:04 +0100 Subject: [PATCH 4/4] Record the library entry of each compute pipeline in the order log Add an E line after the P line of a compute pipeline. It holds the FNV-1a 64 hash of the library entry name, not the name. A reader from before E lines skips them, counted as lines not read. Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_vulkan.md | 5 +- runtime/shims/d3d12_vulkan_device.cpp | 11 ++- runtime/src/pipeline_order.h | 68 ++++++++++++++-- runtime/test/pipeline_order_test.cpp | 108 ++++++++++++++++++++++++++ 4 files changed, 183 insertions(+), 9 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6f319e57df..ad561d2fe9 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2529,7 +2529,10 @@ Pipeline creation: times in milliseconds since the process started. The key is the SHA-256 of the title's own description of the PSO (`GetCachedBlob`'s key; a mesh pipeline's MS is folded in), not of the SPIR-V, so a translator change keeps it. A build that ends after its line was written adds `B *`; a session starts - with `S 1 `. Each line ends with an FNV-1a checksum: a cut or damaged line is skipped on + with `S 1 `. A compute pipeline's `P` line is followed by + `E *`: the name hash is 16 hex digits of FNV-1a 64 over the name of + the library entry the pipeline was made from (the name itself is not written). A reader from before `E` lines + skips them (counted as lines not read). Each line ends with an FNV-1a checksum: a cut or damaged line is skipped on read, never fatal. The hook sits in replay's `ComputePipeline::requested` / `GraphicsPipeline::requested`, called where a submission is prepared, also for a handle that exists already (a warm-up build, a cached one); the recorder decides "first" with one compare-and-swap in a table made at start, never blocks and allocates nothing (a non-blocking `try_lock` on the first request of a pipeline and of a variant), diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 50e6e1bc48..61346bfa18 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -10682,7 +10682,8 @@ class PipelineState final const auto& key = order_key_.empty() ? cache_key_ : order_key_; log->request(order_hash_, key, variant, order_kind_, order_created_ms_, [&] { return order_ready(variant); }, - [&] { return variant == 0 ? order_build_ms_.load() : leonida::pipeline_order::unknown_ms; }); + [&] { return variant == 0 ? order_build_ms_.load() : leonida::pipeline_order::unknown_ms; }, + order_name_hash_); } // Its handle existed, and nobody was building it, when it was first asked for. bool order_ready(std::uint32_t variant) { @@ -10693,12 +10694,15 @@ class PipelineState final return pipeline_.built ? pipeline_.built(this) != VK_NULL_HANDLE : pipeline_.pipeline != VK_NULL_HANDLE; } // Called at the end of create_compute / create_graphics, before the pipeline is registered with the replay. - void order_install(void (*&requested)(void*, std::uint32_t), void*& context, char kind) { + // A compute pipeline passes the name of its library entry: the log then adds an E line for it. + void order_install(void (*&requested)(void*, std::uint32_t), void*& context, char kind, + std::string_view entry_name = {}) { if (!device_.order_log) return; const auto& key = order_key_.empty() ? cache_key_ : order_key_; if (key.empty()) return; order_hash_ = leonida::pipeline_order::key_hash(key); order_kind_ = kind; + if (!entry_name.empty()) order_name_hash_ = leonida::pipeline_order::entry_name_hash(entry_name); requested = &order_requested; context = this; } @@ -11717,7 +11721,7 @@ class PipelineState final code_bytes_ = code.size(); pipeline_.code_base = code_base_; } - if (!pipeline_.skipped) order_install(pipeline_.requested, pipeline_.request_context, 'c'); + if (!pipeline_.skipped) order_install(pipeline_.requested, pipeline_.request_context, 'c', entry->name); device_.context->add_pipeline(id(), pipeline_, device_.info.device_fault_diagnostics ? entry->name.c_str() : nullptr); registered_ = true; @@ -12343,6 +12347,7 @@ class PipelineState final leonida::cached_pso::Key order_key_; // see set_order_key; empty: cache_key_ std::uint64_t order_hash_ = 0; // 0: this pipeline is not in the order log char order_kind_ = 'c'; + std::uint64_t order_name_hash_ = 0; // compute: the hash of its library entry's name (E line); 0: none std::uint32_t order_created_ms_ = device_.order_log ? DeviceState::order_now_ms() : 0; std::atomic order_build_ms_{leonida::pipeline_order::unknown_ms}; // variant 0, once built }; diff --git a/runtime/src/pipeline_order.h b/runtime/src/pipeline_order.h index 1ee4f7bd97..c7d8b3b0fd 100644 --- a/runtime/src/pipeline_order.h +++ b/runtime/src/pipeline_order.h @@ -17,9 +17,13 @@ // S 1 a run starts here // P * // B * the build of a P line whose time was not known yet +// E * which library entry a compute P line is (right after it) // // c = compute, g = graphics, m = mesh. The checksum is FNV-1a over the line before " *". No game data is in the file: -// the key is a SHA-256 of the title's own description of the pipeline (cached_pso.h), the rest are numbers. +// the key is a SHA-256 of the title's own description of the pipeline (cached_pso.h), the rest are numbers. The name +// hash of an E line is 16 hex digits of FNV-1a 64 over the name of the library entry the pipeline was made from (the +// name itself is not written). A reader from before E lines skips them (counted as lines not read); +// parse() below reads them. #pragma once #include @@ -40,6 +44,7 @@ #include #include #include +#include #include namespace leonida::pipeline_order { @@ -64,6 +69,14 @@ struct Record { bool operator==(const Record&) const = default; }; +// An E line: the library entry (by the hash of its name) behind a pipeline and variant. +struct EntryName { + std::string key; + std::uint32_t variant = 0; + std::uint64_t name_hash = 0; + bool operator==(const EntryName&) const = default; +}; + struct Session { std::uint32_t vendor = 0; std::uint32_t device = 0; @@ -72,6 +85,7 @@ struct Session { struct ReadResult { std::vector sessions; + std::vector entries; // the E lines of the whole file, in file order std::size_t bad_lines = 0; // complete lines that could not be read: skipped bool cut_tail = false; // the last line had no newline: a write that did not finish, skipped }; @@ -88,6 +102,9 @@ inline std::uint64_t key_hash(std::string_view key) { return h ? h : 1; } +// The hash an E line carries for the name of a library entry. +inline std::uint64_t entry_name_hash(std::string_view name) { return key_hash(name); } + namespace detail { inline std::uint64_t mix(std::uint64_t key, std::uint32_t variant) { @@ -122,6 +139,21 @@ inline bool parse_u32(std::string_view s, int base, std::uint32_t& out) { return true; } +// Exactly 16 lowercase hex digits. +inline bool parse_hash64(std::string_view s, std::uint64_t& out) { + if (s.size() != 16) return false; + std::uint64_t v = 0; + for (const char c : s) { + int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; + else return false; + v = (v << 4) | std::uint64_t(d); + } + out = v; + return true; +} + inline std::vector split(std::string_view s) { std::vector out; std::size_t i = 0; @@ -176,6 +208,17 @@ inline std::string format_build(std::string_view key, std::uint32_t variant, std return out; } +inline std::string format_entry(std::string_view key, std::uint32_t variant, std::uint64_t name_hash) { + char numbers[48]; + std::snprintf(numbers, sizeof(numbers), " %x %016llx", variant, static_cast(name_hash)); + std::string body = "E "; + body += key; + body += numbers; + std::string out; + detail::append_line(out, std::move(body)); + return out; +} + // Reads what a file holds: whole sessions in file order, a record per P line (its B line merged in), every damaged line // skipped. Never throws on any input. inline ReadResult parse(std::string_view text) { @@ -235,6 +278,14 @@ inline ReadResult parse(std::string_view text) { break; } } + } else if (f.size() == 4 && f[0] == "E") { + EntryName e; + ok = !f[1].empty() && f[1].size() <= key_chars && detail::parse_u32(f[2], 16, e.variant) && + detail::parse_hash64(f[3], e.name_hash); + if (ok) { + e.key = std::string(f[1]); + result.entries.push_back(std::move(e)); + } } if (!ok) ++result.bad_lines; } @@ -313,11 +364,13 @@ class Recorder { } // Fills the claimed record and makes it visible to the writer. `key` is cut at key_chars. `build_ms` is what is - // known of the build now, or unknown_ms. + // known of the build now, or unknown_ms. `name_hash` is entry_name_hash() of the library entry of a compute + // pipeline (an E line follows its P line), 0 when there is none. void publish(Claim claim, std::string_view key, char kind, bool ready, std::uint32_t created_ms, - std::uint32_t build_ms) noexcept { + std::uint32_t build_ms, std::uint64_t name_hash = 0) noexcept { if (!claim.first) return; Slot& s = slots_[claim.index]; + s.name_hash = name_hash; s.key_len = std::uint8_t(std::min(key.size(), key_chars)); for (std::size_t i = 0; i < s.key_len; ++i) { // a key is one word of the line: no space, no newline const char c = key[i]; @@ -338,11 +391,11 @@ class Recorder { // Returns true when this call made the record. template bool request(std::uint64_t hash, std::string_view key, std::uint32_t variant, char kind, std::uint32_t created_ms, - Ready&& ready, Build&& build_ms) noexcept { + Ready&& ready, Build&& build_ms, std::uint64_t name_hash = 0) noexcept { const Claim c = claim(hash, variant); if (!c) return false; const bool is_ready = ready(); - publish(c, key, kind, is_ready, created_ms, build_ms()); + publish(c, key, kind, is_ready, created_ms, build_ms(), name_hash); return true; } @@ -449,6 +502,7 @@ class Recorder { std::uint32_t variant = 0; std::uint32_t created_ms = 0; std::uint32_t first_ms = 0; + std::uint64_t name_hash = 0; // 0: no E line std::uint8_t key_len = 0; char kind = 'c'; bool ready = false; @@ -487,6 +541,10 @@ class Recorder { r.ready = s.ready; out += format_record(r); ++lines; + if (s.name_hash) { + out += format_entry(r.key, r.variant, s.name_hash); + ++lines; + } if (r.build_ms == unknown_ms) waiting_.push_back(cursor_); ++cursor_; } diff --git a/runtime/test/pipeline_order_test.cpp b/runtime/test/pipeline_order_test.cpp index 2d0d4e09a8..a1fb74bd63 100644 --- a/runtime/test/pipeline_order_test.cpp +++ b/runtime/test/pipeline_order_test.cpp @@ -573,6 +573,110 @@ void test_unknown_session_version() { CHECK(read.bad_lines == 1); } +// --- E lines (the names are made up) --- + +std::uint64_t hash_of(const char* name) { return po::entry_name_hash(name); } + +// A log as the recorder writes it for compute pipelines: a P line and its E line for each name, in this order. +std::string log_of(const std::vector& names) { + std::string text = po::format_header() + po::format_session(0x10de, 0x2504); + int n = 0; + for (const char* name : names) { + po::Record r; + r.key = key_of(++n); + r.first_ms = std::uint32_t(n); + text += po::format_record(r); + text += po::format_entry(r.key, 0, hash_of(name)); + } + return text; +} + +void test_entry_line_format() { + // "E <16 hex digits> *", the checksum over the text before " *". + const std::string line = po::format_entry(key_of(1), 0x1f, 0x0123456789abcdefull); + const std::string body = "E " + key_of(1) + " 1f 0123456789abcdef"; + char sum[16]; + std::snprintf(sum, sizeof(sum), " *%08x\n", po::checksum(body)); + CHECK(line == body + sum); + const auto read = po::parse(line); + CHECK(read.bad_lines == 0 && read.sessions.empty()); + CHECK(read.entries.size() == 1); + CHECK(read.entries[0].key == key_of(1) && read.entries[0].variant == 0x1f && + read.entries[0].name_hash == 0x0123456789abcdefull); + // The hash is a stable function of the name, and always 16 digits. + CHECK(hash_of("blur_a") == hash_of("blur_a") && hash_of("blur_a") != hash_of("blur_b")); + // The disk format: FNV-1a 64 of the name, so the hash never changes under old logs. + CHECK(po::entry_name_hash("a") == 0xaf63dc4c8601ec8cull); + CHECK(po::format_entry(key_of(1), 0, 1).find(" 0000000000000001 ") != std::string::npos); +} + +// A reader from before E lines skips them (counted as lines not read) and keeps the same sessions and records; this +// reader reads them and counts no damaged line. +void test_entry_lines_are_skipped_by_the_record_reader() { + const auto with = po::parse(log_of({"blur_a", "sky_c", "tile_d"})); + std::string without = po::format_header() + po::format_session(0x10de, 0x2504); + for (int n = 1; n <= 3; ++n) { + po::Record r; + r.key = key_of(n); + r.first_ms = std::uint32_t(n); + without += po::format_record(r); + } + const auto plain = po::parse(without); + CHECK(with.bad_lines == 0 && !with.cut_tail); + CHECK(with.sessions.size() == 1 && plain.sessions.size() == 1); + CHECK(with.sessions[0].records == plain.sessions[0].records); + CHECK(with.sessions[0].records.size() == 3); + CHECK(with.entries.size() == 3); +} + +void test_malformed_entry_lines() { + const auto bad = [](const std::string& body) { + char sum[16]; + std::snprintf(sum, sizeof(sum), " *%08x\n", po::checksum(body)); + const auto read = po::parse(body + sum); + return read.entries.empty() && read.bad_lines == 1; + }; + const std::string k = key_of(1); + CHECK(bad("E " + k + " 0 0123456789abcde")); // 15 digits + CHECK(bad("E " + k + " 0 0123456789abcdef0")); // 17 digits + CHECK(bad("E " + k + " 0 0123456789ABCDEF")); // upper case + CHECK(bad("E " + k + " 0 0123456789abcdeg")); // not hex + CHECK(bad("E " + k + " zz 0123456789abcdef")); // the variant + CHECK(bad("E " + k + " 0")); // no hash + CHECK(bad("E " + k + " 0 0123456789abcdef x")); // an extra field + CHECK(bad("E 0 0123456789abcdef")); // no key + CHECK(!bad("E " + k + " 0 0123456789abcdef")); // the good one + // A good line with a wrong checksum is damaged too. + std::string line = po::format_entry(k, 0, 5); + char& last_digit = line[line.size() - 2]; + last_digit = last_digit == '0' ? '1' : '0'; + const auto read = po::parse(line); + CHECK(read.entries.empty() && read.bad_lines == 1); +} + +// The recorder writes the E line right after the P line of a compute pipeline, and none for a pipeline without a name. +void test_recorder_writes_entry_lines() { + const auto path = scratch("entry.log"); + { + po::Recorder r(config(path)); + const std::string k1 = key_of(1), k2 = key_of(2); + r.publish(r.claim(po::key_hash(k1), 0), k1, 'c', false, 0, po::unknown_ms, hash_of("blur_a")); + r.publish(r.claim(po::key_hash(k2), 5), k2, 'g', false, 0, po::unknown_ms); + CHECK(r.flush() == 3); // P, E, P + } + const std::string text = slurp(path); + const auto read = po::parse(text); + CHECK(read.bad_lines == 0); + CHECK(read.sessions.size() == 1 && read.sessions[0].records.size() == 2); + CHECK(read.entries.size() == 1); + CHECK(read.entries[0].key == key_of(1) && read.entries[0].name_hash == hash_of("blur_a")); + CHECK(text.find("\nE " + key_of(1)) != std::string::npos); + CHECK(text.find("\nE " + key_of(2)) == std::string::npos); + // The E line comes after the P line of its key and before the next P line. + CHECK(text.find("\nP c " + key_of(1)) < text.find("\nE " + key_of(1))); + CHECK(text.find("\nE " + key_of(1)) < text.find("\nP g " + key_of(2))); +} + } // namespace int main() { @@ -597,6 +701,10 @@ int main() { test_cut_file_then_new_session(); test_flush_stops_at_unpublished(); test_unknown_session_version(); + test_entry_line_format(); + test_entry_lines_are_skipped_by_the_record_reader(); + test_malformed_entry_lines(); + test_recorder_writes_entry_lines(); if (failures) { std::fprintf(stderr, "%d failure(s)\n", failures); return 1;