From ec95c3c0b451ae10e84da2f9f0150aec5a7ee56f Mon Sep 17 00:00:00 2001 From: IlyassRS Date: Wed, 25 Nov 2026 17:45:11 +0100 Subject: [PATCH 1/2] runtime: pause list value wait timeouts while submitted or held work can still satisfy them --- runtime/CMakeLists.txt | 2 + runtime/shims/d3d12_xs_list_values.h | 166 ++++++++++--- runtime/src/list_value_wait_budget.h | 214 +++++++++++++++++ runtime/test/list_value_wait_budget_test.cpp | 237 +++++++++++++++++++ 4 files changed, 586 insertions(+), 33 deletions(-) create mode 100644 runtime/src/list_value_wait_budget.h create mode 100644 runtime/test/list_value_wait_budget_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index c1d0e7cb53..3b95c403aa 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1380,6 +1380,8 @@ if(BUILD_TESTING) # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. add_executable(spirv_stores_test test/spirv_stores_test.cpp) add_test(NAME spirv_stores COMMAND spirv_stores_test) + add_executable(list_value_wait_budget_test test/list_value_wait_budget_test.cpp) + add_test(NAME list_value_wait_budget COMMAND list_value_wait_budget_test) add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) add_executable(resource_tiling_test test/resource_tiling_test.cpp) diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index 2a30b4b964..2619edfaff 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -31,8 +31,10 @@ // - The thread that signals a gate runs the work the layer held behind it (QueueHolds: the held lists' submission, // the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so // writes keep landing and other gates keep timing out while held work runs. -// Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) whatever memory holds, counted -// from when the gates before it on its queue opened, and logged once per address. Short timeouts (4 ms) go to an +// Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) of idle wait time, counted from +// when the gates before it on its queue opened and paused while the releaser is running held work, while an acyclic +// matching producer write is in flight, or (up to a cap) while unrelated unblocked GPU work is running +// (src/list_value_wait_budget.h); logged once per address. Short timeouts (4 ms) go to an // address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values // no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays // a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full @@ -56,10 +58,12 @@ #include #include #include +#include #include #include #include "d3d12_xs_device.h" // console_value_met, ListValueStats +#include "../src/list_value_wait_budget.h" // leonida::list_value_wait: work-aware timeout clock & producer graph #include "../src/title_page_watch.h" // leonida::kernel_writes::store #include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages @@ -362,7 +366,8 @@ class Pump { if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there { std::lock_guard lock(mutex_); - writes_.push_back({std::move(queue), value, std::move(writes)}); + const std::uint64_t after_gate = max_pending_gate_locked(queue.get()); + writes_.push_back({std::move(queue), value, std::move(writes), after_gate}); } start_or_settle(); } @@ -396,7 +401,7 @@ class Pump { gate.value = value; gate.started = true; gate.since = Clock::now(); - gate.deadline = Clock::time_point::max(); + gate.last_tick = gate.since; gate.after = after; gate.action = std::move(action); gates_.push_back(std::move(gate)); @@ -502,13 +507,15 @@ class Pump { std::shared_ptr queue; std::uint64_t value; std::vector writes; + std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this write group }; struct Gate { std::shared_ptr queue; std::uint64_t value = 0; std::vector waits; - Clock::time_point deadline; // set by start_gate - Clock::time_point since; + leonida::list_value_wait::GateTimeoutState timeout{}; // work-aware timeout clock (set by start_gate) + Clock::time_point last_tick{}; + Clock::time_point since{}; bool started = false; // the gates before it on its queue have opened: its time runs bool cut_short = false; // given the short timeout std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind @@ -630,12 +637,21 @@ class Pump { releasing_ = true; } SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on + struct PendingReleaseGuard { + std::atomic* count; + std::size_t remaining; + ~PendingReleaseGuard() { + if (remaining) count->fetch_sub(remaining, std::memory_order_release); + } + } pending_guard{&pending_releases_, batch.size()}; for (Release& release : batch) { if (stop_.load(std::memory_order_relaxed)) break; signal_value_.store(release.value, std::memory_order_relaxed); signal_since_ms_.store(GetTickCount64() | 1, std::memory_order_relaxed); // never 0 while inside signal(release); signal_since_ms_.store(0, std::memory_order_relaxed); + pending_releases_.fetch_sub(1, std::memory_order_release); + --pending_guard.remaining; } std::lock_guard lock(release_mutex_); releasing_ = false; @@ -719,36 +735,114 @@ class Pump { writes_.swap(rest); } - // The gates whose waits are met, whose time is up or whose action's turn has come, taken off the list in each + // Highest pending gate value currently in `gates_` for `queue` (0 if none). Called with mutex_ held. + std::uint64_t max_pending_gate_locked(const QueueValues* queue) const { + std::uint64_t highest = 0; + for (const Gate& g : gates_) + if (g.queue.get() == queue && g.value > highest) highest = g.value; + return highest; + } + + // The gates whose waits are met, whose idle time is up or whose action's turn has come, taken off the list in each // queue's order (a queue's gate values rise in submission order, so a later one must not be signalled first: it - // would open the earlier one too). `force` (no threads): every gate, now. Called with mutex_ held. - void take_open(bool force, std::vector& opening) { - std::vector blocked; + // would open the earlier one too). A memory gate's timeout clock pauses while held work is being released, while + // an acyclic matching producer write is in flight, or (up to a cap) while unrelated unblocked GPU work is running + // (src/list_value_wait_budget.h). `force` (no threads): every gate, now. Called with mutex_ held. + void take_open(bool force, bool landed_any, std::vector& opening) { + if (gates_.empty()) return; const auto now = Clock::now(); - for (auto it = gates_.begin(); it != gates_.end();) { - const QueueValues* queue = it->queue.get(); - if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) { - ++it; - continue; + namespace lvw = leonida::list_value_wait; + + // Build the lightweight producer/gate dependency view lazily only if a started memory gate is still unmet. + bool graph_built = false; + std::vector flat_writes; + std::vector view_writes; + std::vector flat_waits; + std::vector view_gates; + std::vector> gate_wait_ranges; // (offset, count) into flat_waits + const auto ensure_graph = [&] { + if (graph_built) return; + graph_built = true; + std::size_t total_writes = 0; + for (const WriteGroup& wg : writes_) total_writes += wg.writes.size(); + flat_writes.reserve(total_writes); + view_writes.reserve(writes_.size()); + for (const WriteGroup& wg : writes_) { + const std::size_t start = flat_writes.size(); + for (const Write& w : wg.writes) + flat_writes.push_back({w.address, w.value, w.bytes, w.kind != WriteKind::value}); + view_writes.push_back({wg.queue.get(), wg.after_gate, + std::span(flat_writes).subspan(start, wg.writes.size())}); + } + std::size_t total_waits = 0; + for (const Gate& g : gates_) + if (!g.action) total_waits += g.waits.size(); + flat_waits.reserve(total_waits); + gate_wait_ranges.reserve(gates_.size()); + for (const Gate& g : gates_) { + const std::size_t start = flat_waits.size(); + if (!g.action) { + for (const Wait& w : g.waits) + if (!met_now(w)) flat_waits.push_back({w.address, w.reference, w.comparison, w.wide}); + } + gate_wait_ranges.emplace_back(start, flat_waits.size() - start); + } + view_gates.reserve(gates_.size()); + for (std::size_t i = 0; i < gates_.size(); ++i) { + const auto [off, cnt] = gate_wait_ranges[i]; + view_gates.push_back({gates_[i].queue.get(), gates_[i].value, static_cast(gates_[i].action), + std::span(flat_waits).subspan(off, cnt)}); } + }; + + std::vector blocked; + std::vector opened(gates_.size(), false); + for (std::size_t idx = 0; idx < gates_.size(); ++idx) { + Gate& gate = gates_[idx]; + const QueueValues* queue = gate.queue.get(); + if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) continue; bool open = force; - if (it->action) { - open = open || queue->written->GetCompletedValue() >= it->after; + if (gate.action) { + open = open || queue->written->GetCompletedValue() >= gate.after; } else { - if (!it->started) start_gate(*it, now); + if (!gate.started) start_gate(gate, now); bool met = true; - for (const Wait& wait : it->waits) met = met && met_now(wait); - open = open || met || now >= it->deadline; - if (open) note_outcome(*it, met || force); + for (const Wait& wait : gate.waits) met = met && met_now(wait); + bool timed_out = false; + if (!open && !met) { + const std::uint64_t dt_us = + now > gate.last_tick + ? static_cast( + std::chrono::duration_cast(now - gate.last_tick).count()) + : 0u; + gate.last_tick = now; + const bool releaser_busy = + landed_any || !opening.empty() || pending_releases_.load(std::memory_order_acquire) != 0; + lvw::PauseReason reason = lvw::PauseReason::releaser_busy; + if (!releaser_busy) { + ensure_graph(); + reason = lvw::pause_reason(false, view_writes, view_gates, idx, console_value_met); + } + timed_out = gate.timeout.advance(dt_us, reason); + } else { + gate.last_tick = now; + } + open = open || met || timed_out; + if (open) note_outcome(gate, met || force, now); } if (open) { - opening.push_back({std::move(it->queue), it->value, std::move(it->action)}); - it = gates_.erase(it); + opening.push_back({std::move(gate.queue), gate.value, std::move(gate.action)}); + opened[idx] = true; } else { blocked.push_back(queue); - ++it; } } + if (!opening.empty()) { + std::deque rest; + for (std::size_t idx = 0; idx < gates_.size(); ++idx) + if (!opened[idx]) rest.push_back(std::move(gates_[idx])); + gates_.swap(rest); + } } // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do @@ -761,12 +855,15 @@ class Pump { busy_ = true; take_landed(force, landing); } + const bool landed_any = !landing.empty(); for (const WriteGroup& group : landing) land(group); std::vector opening; { std::lock_guard lock(mutex_); watch_late(); - take_open(force, opening); + take_open(force, landed_any, opening); + if (!force && !opening.empty()) + pending_releases_.fetch_add(opening.size(), std::memory_order_release); } if (!opening.empty()) { if (force) { @@ -917,7 +1014,9 @@ class Pump { gate.started = true; gate.cut_short = cut_short; gate.since = now; - gate.deadline = now + std::chrono::milliseconds(cut_short ? kDemotedTimeoutMs : full); + gate.last_tick = now; + gate.timeout.reset(static_cast(cut_short ? kDemotedTimeoutMs : full) * 1000u, + leonida::list_value_wait::default_active_pause_cap_us(full)); } // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end. @@ -959,15 +1058,15 @@ class Pump { } // Called with mutex_ held. - void note_outcome(const Gate& gate, bool met) { + void note_outcome(const Gate& gate, bool met, Clock::time_point now) { if (met) { bump(counters().gates_met); timeouts_in_a_row_ = 0; for (const Wait& wait : gate.waits) note_met(wait.address); if (gate.cut_short && !gate.waits.empty()) lift_demotion(gate.waits.front().address); - if (logged_met_ < 4) { // the first few, to show the model at work in a boot log + if (logged_met_ < 4 && !gate.waits.empty()) { // the first few, to show the model at work in a boot log ++logged_met_; - const double ms = std::chrono::duration(Clock::now() - gate.since).count(); + const double ms = std::chrono::duration(now - gate.since).count(); std::fprintf(stderr, "[rt] d3d12_xs: a queue's wait for 0x%llx was met after %.2f ms\n", static_cast(gate.waits.front().address), ms); } @@ -988,14 +1087,14 @@ class Pump { for (const Wait& wait : gate.waits) { if (met_now(wait)) continue; if (gate.cut_short && !watched && late_.size() < kMaxLate) { - late_.push_back({wait, gate.since + std::chrono::milliseconds(full)}); + late_.push_back({wait, now + std::chrono::milliseconds(full)}); watched = true; } Streak* streak = find_streak(wait.address); if (!streak) streak = add_streak(wait.address); ++streak->timeouts; - std::uint64_t now = 0; - read_value(wait.address, wait.wide, now); + std::uint64_t current = 0; + read_value(wait.address, wait.wide, current); if (!streak->logged) { streak->logged = true; static std::atomic addresses{0}; @@ -1006,7 +1105,7 @@ class Pump { gate.cut_short ? kDemotedTimeoutMs : full, static_cast(wait.address), wait.wide ? 64u : 32u, wait.comparison, static_cast(wait.reference), - static_cast(now)); + static_cast(current)); } if (streak->timeouts == kDemoteAfter) { static std::atomic demoted{0}; @@ -1039,6 +1138,7 @@ class Pump { std::condition_variable release_ready_; std::deque releases_; bool releasing_ = false; + std::atomic pending_releases_{0}; // queued + active releases, read lock-free in take_open() std::atomic signal_since_ms_{0}; // GetTickCount64 when the releaser's current Signal began, or 0 std::atomic signal_value_{0}; std::atomic releaser_tid_{0}; diff --git a/runtime/src/list_value_wait_budget.h b/runtime/src/list_value_wait_budget.h new file mode 100644 index 0000000000..625e6c1f3e --- /dev/null +++ b/runtime/src/list_value_wait_budget.h @@ -0,0 +1,214 @@ +#pragma once +// Work-aware timeout clock and cycle-safe producer dependency analysis for console command-list memory waits +// (runtime/shims/d3d12_xs_list_values.h, docs/d3d12_xs_console_abi.md ยง5.5). +// +// A memory wait gate needs a bounded timeout so an unmodelled write (one the runtime never lands) cannot hang a queue +// forever. Counting wall-clock time blindly cuts waits short whenever the runtime is busy running held work (e.g. +// multi-second CPU shadow/texture copies inside the releaser) or while an in-flight producer write has not finished on +// the GPU yet, running dependent queues out of order. +// +// This header separates the policy from Windows/D3D12 handles so it can be verified portably under sanitizers: +// - `pause_reason()` decides whether submitted or held work can still satisfy a gate without creating a deadlock cycle: +// 1. `releaser_busy`: held work from an already-opened gate is currently being released/submitted; +// 2. `matching_producer`: an in-flight WriteGroup whose final write to a waited address can satisfy an unmet wait, and +// every pending gate preceding that WriteGroup is cycle-free with respect to the waiting queue; +// 3. `active_work`: unrelated unblocked GPU work (a WriteGroup or action gate with no pending gate ahead of it) is +// still executing, paused only up to a finite cap so a continuously streaming queue cannot starve an unmodelled wait. +// - `GateTimeoutState` tracks idle wait time (`elapsed_us`) separately from paused time, expiring only once `elapsed_us` +// reaches `budget_us`. +// +// Pure C++20 standard library only. + +#include +#include +#include +#include +#include + +namespace leonida::list_value_wait { + +enum class PauseReason : std::uint8_t { + none = 0, // no submitted or held work can still satisfy this gate -> timeout clock ticks + releaser_busy = 1, // releaser thread is executing or draining opened gates + matching_producer = 2, // an acyclic in-flight WriteGroup can satisfy an unmet wait of this gate + active_work = 3, // unrelated unblocked submitted work is still executing (bounded by active_pause_cap_us) +}; + +struct WaitPredicate { + std::uint64_t address = 0; + std::uint64_t reference = 0; + std::uint32_t comparison = 0; + bool wide = false; +}; + +struct PendingWrite { + std::uint64_t address = 0; + std::uint64_t value = 0; + std::uint8_t bytes = 0; + bool timestamp = false; // GPU/system timestamp: final value is unknown until landing +}; + +struct PendingWriteGroup { + const void* queue = nullptr; + std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this group when submitted (0: none) + std::span writes; +}; + +struct PendingGate { + const void* queue = nullptr; + std::uint64_t value = 0; + bool is_action = false; // waits only on earlier GPU work on `queue`, never on memory + std::span unmet_waits; // waits not currently satisfied in memory (empty for action gates) +}; + +// Default cap on pausing solely for unrelated unblocked GPU work: 300x the idle timeout, clamped to [1 s, 10 min]. +// At the default 200 ms timeout this allows up to 60 s for slow world-phase frames while preventing an unrelated +// continuously streaming queue from starving an unmodelled wait indefinitely. +inline constexpr std::uint64_t default_active_pause_cap_us(unsigned full_timeout_ms) { + const std::uint64_t base_ms = full_timeout_ms ? std::uint64_t{full_timeout_ms} : 1u; + const std::uint64_t scaled_ms = base_ms > 2000u ? 600000u : base_ms * 300u; + const std::uint64_t clamped_ms = scaled_ms < 1000u ? 1000u : (scaled_ms > 600000u ? 600000u : scaled_ms); + return clamped_ms * 1000u; +} + +struct GateTimeoutState { + std::uint64_t budget_us = 0; + std::uint64_t elapsed_us = 0; + std::uint64_t active_paused_us = 0; + std::uint64_t active_pause_cap_us = 0; + bool paused_ever = false; + + void reset(std::uint64_t budget, std::uint64_t active_cap) { + budget_us = budget; + elapsed_us = 0; + active_paused_us = 0; + active_pause_cap_us = active_cap; + paused_ever = false; + } + + // Advances the gate by `dt_us` under `reason`. Returns true once the idle timeout budget is exhausted. + bool advance(std::uint64_t dt_us, PauseReason reason) { + if (reason == PauseReason::releaser_busy || reason == PauseReason::matching_producer) { + paused_ever = true; + return false; + } + if (reason == PauseReason::active_work && active_paused_us < active_pause_cap_us) { + paused_ever = true; + const std::uint64_t room = active_pause_cap_us - active_paused_us; + const std::uint64_t absorb = dt_us < room ? dt_us : room; + active_paused_us += absorb; + dt_us -= absorb; + } + if (dt_us > UINT64_MAX - elapsed_us) + elapsed_us = UINT64_MAX; + else + elapsed_us += dt_us; + return elapsed_us >= budget_us; + } +}; + +namespace detail { + +// True when `group`'s final write touching [wait.address, wait.address + need) lands a value that meets `wait` +// (or is a timestamp write to the exact address whose runtime value is unknown until landing). +template +inline bool write_group_matches_wait(const PendingWriteGroup& group, const WaitPredicate& wait, MetFn&& met) { + const std::uint64_t need = wait.wide ? 8u : 4u; + if (!wait.address || wait.address > UINT64_MAX - need) return false; + const std::uint64_t wait_end = wait.address + need; + for (std::size_t i = group.writes.size(); i-- > 0;) { + const PendingWrite& w = group.writes[i]; + if (!w.bytes || w.address > UINT64_MAX - w.bytes) continue; + const std::uint64_t write_end = w.address + w.bytes; + if (w.address >= wait_end || wait.address >= write_end) continue; + if (w.address == wait.address && w.bytes >= need && + (w.timestamp || met(wait.comparison, w.value, wait.reference, wait.wide))) + return true; + // A later write in the same group overwrote or partially overlapped the waited range with a non-matching value. + return false; + } + return false; +} + +// True when no pending gate in `gates` precedes `(queue, after_gate)`. +inline bool is_unblocked(std::span gates, const void* queue, std::uint64_t after_gate) { + if (!after_gate) return true; + for (const PendingGate& g : gates) + if (g.queue == queue && g.value <= after_gate) return false; + return true; +} + +// True when `gate_idx` (directly or transitively via matching in-flight writes) depends on a gate on `target_queue`. +template +inline bool gate_can_reach_queue(std::size_t gate_idx, const void* target_queue, + std::span writes, std::span gates, + MetFn&& met, std::vector& visiting) { + const PendingGate& g = gates[gate_idx]; + if (g.queue == target_queue) return true; + if (g.is_action) return false; + if (std::find(visiting.begin(), visiting.end(), gate_idx) != visiting.end()) return false; + visiting.push_back(gate_idx); + for (const WaitPredicate& wait : g.unmet_waits) { + for (const PendingWriteGroup& w : writes) { + if (!write_group_matches_wait(w, wait, met)) continue; + if (!w.after_gate) continue; + for (std::size_t b = 0; b < gates.size(); ++b) { + if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; + if (gates[b].queue == target_queue || + gate_can_reach_queue(b, target_queue, writes, gates, met, visiting)) { + visiting.pop_back(); + return true; + } + } + } + } + visiting.pop_back(); + return false; +} + +} // namespace detail + +// Decides whether the timeout clock of `gates[target_idx]` should pause on this pump pass. +// `met(comparison, value, reference, wide)` must implement the same predicate as `console_value_met`. +template +inline PauseReason pause_reason(bool releaser_busy, std::span writes, + std::span gates, std::size_t target_idx, MetFn&& met) { + if (releaser_busy) return PauseReason::releaser_busy; + if (target_idx >= gates.size()) return PauseReason::none; + const PendingGate& target = gates[target_idx]; + if (target.is_action) return PauseReason::none; + + // 1. A matching in-flight WriteGroup whose preceding gates (if any) do not cycle back to `target.queue`. + std::vector visiting; + for (const WaitPredicate& wait : target.unmet_waits) { + for (const PendingWriteGroup& w : writes) { + if (!detail::write_group_matches_wait(w, wait, met)) continue; + bool cyclic = false; + if (w.after_gate) { + for (std::size_t b = 0; b < gates.size(); ++b) { + if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; + visiting.clear(); + if (gates[b].queue == target.queue || + detail::gate_can_reach_queue(b, target.queue, writes, gates, met, visiting)) { + cyclic = true; + break; + } + } + } + if (!cyclic) return PauseReason::matching_producer; + } + } + + // 2. Unrelated unblocked submitted GPU work (an unblocked WriteGroup on any queue, or an unblocked action gate on + // another queue) that could still write memory via a shader/copy or unblock a CPU producer. + for (const PendingWriteGroup& w : writes) { + if (detail::is_unblocked(gates, w.queue, w.after_gate)) return PauseReason::active_work; + } + for (const PendingGate& g : gates) { + if (!g.is_action || g.queue == target.queue) continue; + if (g.value == 0 || detail::is_unblocked(gates, g.queue, g.value - 1)) return PauseReason::active_work; + } + return PauseReason::none; +} + +} // namespace leonida::list_value_wait diff --git a/runtime/test/list_value_wait_budget_test.cpp b/runtime/test/list_value_wait_budget_test.cpp new file mode 100644 index 0000000000..e607527170 --- /dev/null +++ b/runtime/test/list_value_wait_budget_test.cpp @@ -0,0 +1,237 @@ +// Portable CPU-only unit tests for runtime/src/list_value_wait_budget.h (RT-LIST-VALUE-WAIT-WORK-AWARE-TIMEOUT): +// work-aware timeout pausing, cycle detection across multi-queue write/gate chains, overwrite-aware write matching, +// action gates, and bounded unrelated-work pausing. No Windows, D3D12, or Vulkan headers; no game files. +#include "../src/list_value_wait_budget.h" + +#include +#include + +#define CHECK(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \ + return 1; \ + } \ +} while (0) + +namespace { + +constexpr bool test_met(std::uint32_t comparison, std::uint64_t value, std::uint64_t reference, bool wide) { + if (!wide) { + value &= 0xffffffffu; + reference &= 0xffffffffu; + } + switch (comparison) { + case 2: return value < reference; + case 3: return value == reference; + case 4: return value <= reference; + case 5: return value > reference; + case 6: return value != reference; + case 7: return value >= reference; + default: return true; + } +} + +} // namespace + +int main() { + using namespace leonida::list_value_wait; + + int q1_tag = 0, q2_tag = 0, q3_tag = 0; + const void* const q1 = &q1_tag; + const void* const q2 = &q2_tag; + const void* const q3 = &q3_tag; + + // 1. Idle unmodelled wait: PauseReason::none -> expires at exact budget_us. + { + const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; // >= 5 + const PendingGate gates[] = {{q1, 1, false, waits}}; + CHECK(pause_reason(false, {}, gates, 0, test_met) == PauseReason::none); + + GateTimeoutState t; + t.reset(200'000, default_active_pause_cap_us(200)); + CHECK(!t.advance(100'000, PauseReason::none)); + CHECK(t.elapsed_us == 100'000 && !t.paused_ever); + CHECK(!t.advance(99'999, PauseReason::none)); + CHECK(t.advance(1, PauseReason::none)); + CHECK(t.elapsed_us == 200'000); + } + + // 2. Releaser actively executing held work pauses the timeout clock indefinitely without burning idle budget. + { + const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; + const PendingGate gates[] = {{q1, 1, false, waits}}; + CHECK(pause_reason(true, {}, gates, 0, test_met) == PauseReason::releaser_busy); + + GateTimeoutState t; + t.reset(200'000, default_active_pause_cap_us(200)); + // 30 seconds of releaser executing shadow/texture copies burns 0 us of idle timeout budget. + for (int i = 0; i < 30; ++i) CHECK(!t.advance(1'000'000, PauseReason::releaser_busy)); + CHECK(t.elapsed_us == 0 && t.paused_ever); + // Once idle again, still gets its full 200 ms budget before expiring. + CHECK(!t.advance(199'000, PauseReason::none)); + CHECK(t.advance(1'000, PauseReason::none)); + } + + // 3. Matching unblocked producer write on another queue (Wait-before-Signal) -> PauseReason::matching_producer. + { + const WaitPredicate waits[] = {{0x2000, 10, 7, true}}; // >= 10 + const PendingWrite w_ok[] = {{0x2000, 12, 8, false}}; + const PendingWriteGroup groups[] = {{q2, 0, w_ok}}; + const PendingGate gates[] = {{q1, 1, false, waits}}; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer); + + // Timestamp write to the same address also matches (final value unknown until landing). + const PendingWrite w_ts[] = {{0x2000, 0, 8, true}}; + const PendingWriteGroup ts_groups[] = {{q2, 0, w_ts}}; + CHECK(pause_reason(false, ts_groups, gates, 0, test_met) == PauseReason::matching_producer); + + // Matching write overwritten later in the same WriteGroup by a non-matching value does NOT match, + // falling back to active_work (since q2's group is unblocked). + const PendingWrite w_overwritten[] = {{0x2000, 12, 8, false}, {0x2000, 3, 8, false}}; + const PendingWriteGroup ow_groups[] = {{q2, 0, w_overwritten}}; + CHECK(pause_reason(false, ow_groups, gates, 0, test_met) == PauseReason::active_work); + + // Partial overlap by a later write in the same group invalidates the earlier matching write. + const PendingWrite w_partial[] = {{0x2000, 12, 8, false}, {0x2004, 0, 4, false}}; + const PendingWriteGroup part_groups[] = {{q2, 0, w_partial}}; + CHECK(pause_reason(false, part_groups, gates, 0, test_met) == PauseReason::active_work); + + // 4-byte write cannot satisfy an 8-byte (wide) wait. + const PendingWrite w_narrow[] = {{0x2000, 12, 4, false}}; + const PendingWriteGroup nar_groups[] = {{q2, 0, w_narrow}}; + CHECK(pause_reason(false, nar_groups, gates, 0, test_met) == PauseReason::active_work); + + // 8-byte write CAN satisfy a 4-byte wait (low 32 bits compared). + const WaitPredicate wait32[] = {{0x2000, 10, 7, false}}; + const PendingWrite w_hi_lo[] = {{0x2000, 0x100000000ull | 12ull, 8, false}}; + const PendingWriteGroup hilo_groups[] = {{q2, 0, w_hi_lo}}; + const PendingGate gates32[] = {{q1, 1, false, wait32}}; + CHECK(pause_reason(false, hilo_groups, gates32, 0, test_met) == PauseReason::matching_producer); + } + + // 4. Same-queue ordering: a write submitted BEFORE the gate (after_gate < gate.value) IS a live producer; + // a write submitted AFTER the gate (after_gate >= gate.value) is a self-deadlock and MUST NOT pause the gate. + { + const WaitPredicate waits[] = {{0x3000, 1, 7, true}}; + const PendingWrite w[] = {{0x3000, 1, 8, false}}; + const PendingGate gates[] = {{q1, 2, false, waits}}; + + const PendingWriteGroup before_gate[] = {{q1, 1, w}}; // after_gate 1 < gate.value 2 (unblocked!) + CHECK(pause_reason(false, before_gate, gates, 0, test_met) == PauseReason::matching_producer); + + const PendingWriteGroup behind_gate[] = {{q1, 2, w}}; // after_gate 2 == gate.value 2 (held by itself!) + CHECK(pause_reason(false, behind_gate, gates, 0, test_met) == PauseReason::none); + } + + // 5. Mutual 2-queue cycle (Q1 waits on Q2's write behind G2; Q2 waits on Q1's write behind G1): + // NEITHER gate pauses, so the cycle breaks cleanly instead of deadlocking. + { + const WaitPredicate w1[] = {{0x4000, 1, 7, true}}; + const WaitPredicate w2[] = {{0x5000, 1, 7, true}}; + const PendingWrite pw1[] = {{0x5000, 1, 8, false}}; // Q1 writes what Q2 waits for, behind Q1's gate 1 + const PendingWrite pw2[] = {{0x4000, 1, 8, false}}; // Q2 writes what Q1 waits for, behind Q2's gate 1 + const PendingWriteGroup groups[] = {{q1, 1, pw1}, {q2, 1, pw2}}; + const PendingGate gates[] = {{q1, 1, false, w1}, {q2, 1, false, w2}}; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none); + CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::none); + } + + // 6. 3-queue cycle involving a SECOND (non-front) gate on Q2: + // Q1 gate 1 waits on W2 (behind Q2 gates 1 & 2); Q2 gate 2 waits on W1 (behind Q1 gate 1). + // Checking all gates <= after_gate catches this indirect cycle! + { + const WaitPredicate w_q1[] = {{0x6000, 1, 7, true}}; + const WaitPredicate w_q2_g1[] = {{0x6100, 1, 7, true}}; // unrelated front gate on Q2 + const WaitPredicate w_q2_g2[] = {{0x6200, 1, 7, true}}; // second gate on Q2 waits on Q1 + const PendingWrite pw_q1[] = {{0x6200, 1, 8, false}}; // behind Q1 gate 1 + const PendingWrite pw_q2[] = {{0x6000, 1, 8, false}}; // behind Q2 gate 2 (after_gate = 2) + const PendingWriteGroup groups[] = {{q1, 1, pw_q1}, {q2, 2, pw_q2}}; + const PendingGate gates[] = { + {q1, 1, false, w_q1}, + {q2, 1, false, w_q2_g1}, + {q2, 2, false, w_q2_g2}, + }; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none); + CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none); + } + + // 7. Acyclic 3-queue chain (Q1 -> Q2 -> Q3 where Q3's gate has no producer): + // Q3 does NOT pause (times out first), while Q2 and Q1 wait for their upstream producers to run in order! + { + const WaitPredicate w_q1[] = {{0x7000, 1, 7, true}}; + const WaitPredicate w_q2[] = {{0x7100, 1, 7, true}}; + const WaitPredicate w_q3[] = {{0x7200, 1, 7, true}}; // unmodelled wait on Q3 + const PendingWrite pw_q2[] = {{0x7000, 1, 8, false}}; // Q2 feeds Q1 (behind Q2 gate 1) + const PendingWrite pw_q3[] = {{0x7100, 1, 8, false}}; // Q3 feeds Q2 (behind Q3 gate 1) + const PendingWriteGroup groups[] = {{q2, 1, pw_q2}, {q3, 1, pw_q3}}; + const PendingGate gates[] = { + {q1, 1, false, w_q1}, + {q2, 1, false, w_q2}, + {q3, 1, false, w_q3}, + }; + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer); + CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::matching_producer); + CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none); + } + + // 8. Action gate on another queue counts as active_work when unblocked, and does NOT count when blocked behind a + // memory gate on its own queue. + { + const WaitPredicate w_q1[] = {{0x8000, 1, 7, true}}; + const WaitPredicate w_q2[] = {{0x8100, 1, 7, true}}; + const PendingGate unblocked_action[] = { + {q1, 1, false, w_q1}, + {q2, 1, true, {}}, // unblocked action gate on Q2 + }; + CHECK(pause_reason(false, {}, unblocked_action, 0, test_met) == PauseReason::active_work); + + const PendingGate blocked_action[] = { + {q1, 1, false, w_q1}, + {q2, 1, false, w_q2}, // memory gate blocking Q2 + {q2, 2, true, {}}, // action gate behind Q2's memory gate + }; + CHECK(pause_reason(false, {}, blocked_action, 0, test_met) == PauseReason::none); + } + + // 9. Bounded unrelated active_work pause: pauses up to active_pause_cap_us, then drains idle budget_us cleanly. + { + CHECK(default_active_pause_cap_us(200) == 60'000'000ull); // 60 s at default 200 ms + CHECK(default_active_pause_cap_us(1) == 1'000'000ull); // 1 s floor + CHECK(default_active_pause_cap_us(30000) == 600'000'000ull); // 10 min ceiling + + GateTimeoutState t; + t.reset(200'000, 5'000'000); // 200 ms budget, 5 s unrelated-work cap + // 5 full seconds of unrelated active work exhausts the pause cap, leaving 0 elapsed. + for (int i = 0; i < 5; ++i) CHECK(!t.advance(1'000'000, PauseReason::active_work)); + CHECK(t.active_paused_us == 5'000'000 && t.elapsed_us == 0 && t.paused_ever); + // Next 200 ms of unrelated work now counts against idle budget and expires the gate. + CHECK(!t.advance(199'000, PauseReason::active_work)); + CHECK(t.advance(1'000, PauseReason::active_work)); + CHECK(t.elapsed_us == 200'000); + + // Partial step straddling the cap splits cleanly between active_paused_us and elapsed_us. + GateTimeoutState t2; + t2.reset(200'000, 500'000); + CHECK(!t2.advance(600'000, PauseReason::active_work)); // 500k paused, 100k elapsed + CHECK(t2.active_paused_us == 500'000 && t2.elapsed_us == 100'000); + CHECK(t2.advance(100'000, PauseReason::active_work)); + } + + // 10. Overflow-safe address / dt_us guards. + { + const WaitPredicate overflow_wait[] = {{UINT64_MAX - 2, 1, 7, true}}; + const PendingWrite overflow_write[] = {{UINT64_MAX - 2, 1, 8, false}}; + const PendingWriteGroup groups[] = {{q2, 0, overflow_write}}; + const PendingGate gates[] = {{q1, 1, false, overflow_wait}}; + // Write doesn't match due to address wrap guard, falls back to active_work for the unblocked group. + CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::active_work); + + GateTimeoutState t; + t.reset(1000, 0); + CHECK(t.advance(UINT64_MAX, PauseReason::none)); + CHECK(t.elapsed_us == UINT64_MAX); + } + + std::printf("list_value_wait_budget_test: all checks passed\n"); + return 0; +} From 9520db518779080a5a7a9a1b7cc1d4c42fe3b41a Mon Sep 17 00:00:00 2001 From: IlyassRS Date: Wed, 25 Nov 2026 18:52:28 +0100 Subject: [PATCH 2/2] runtime: cap all list-value wait pauses, scale demoted caps, and test Pump --- runtime/shims/d3d12_xs_list_values.h | 11 +- runtime/src/list_value_wait_budget.h | 73 ++++++--- runtime/test/list_value_wait_budget_test.cpp | 153 ++++++++++++++++--- runtime/test/xs_proxy_mock_test.cpp | 79 ++++++++++ 4 files changed, 272 insertions(+), 44 deletions(-) diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index 2619edfaff..29ffc3abca 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h @@ -32,9 +32,9 @@ // the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so // writes keep landing and other gates keep timing out while held work runs. // Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) of idle wait time, counted from -// when the gates before it on its queue opened and paused while the releaser is running held work, while an acyclic -// matching producer write is in flight, or (up to a cap) while unrelated unblocked GPU work is running -// (src/list_value_wait_budget.h); logged once per address. Short timeouts (4 ms) go to an +// when the gates before it on its queue opened and paused (up to a finite cap scaled with the gate's own budget) while +// the releaser is running held work, while an acyclic matching producer write is in flight, or while unrelated +// unblocked GPU work is running (src/list_value_wait_budget.h); logged once per address. Short timeouts (4 ms) go to an // address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values // no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays // a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full @@ -1015,8 +1015,9 @@ class Pump { gate.cut_short = cut_short; gate.since = now; gate.last_tick = now; - gate.timeout.reset(static_cast(cut_short ? kDemotedTimeoutMs : full) * 1000u, - leonida::list_value_wait::default_active_pause_cap_us(full)); + const unsigned gate_ms = cut_short ? kDemotedTimeoutMs : full; + const auto caps = leonida::list_value_wait::default_pause_caps(gate_ms, cut_short); + gate.timeout.reset(static_cast(gate_ms) * 1000u, caps.active_us, caps.max_us); } // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end. diff --git a/runtime/src/list_value_wait_budget.h b/runtime/src/list_value_wait_budget.h index 625e6c1f3e..8e1fd52190 100644 --- a/runtime/src/list_value_wait_budget.h +++ b/runtime/src/list_value_wait_budget.h @@ -13,9 +13,12 @@ // 2. `matching_producer`: an in-flight WriteGroup whose final write to a waited address can satisfy an unmet wait, and // every pending gate preceding that WriteGroup is cycle-free with respect to the waiting queue; // 3. `active_work`: unrelated unblocked GPU work (a WriteGroup or action gate with no pending gate ahead of it) is -// still executing, paused only up to a finite cap so a continuously streaming queue cannot starve an unmodelled wait. -// - `GateTimeoutState` tracks idle wait time (`elapsed_us`) separately from paused time, expiring only once `elapsed_us` -// reaches `budget_us`. +// still executing, paused only up to `active_pause_cap_us` so a continuously streaming queue cannot starve an +// unmodelled wait. +// - `GateTimeoutState` tracks idle wait time (`elapsed_us`) separately from paused time, expiring once `elapsed_us` +// reaches `budget_us`. Every pause reason (`releaser_busy` and `matching_producer` included) is bounded by a finite +// `max_pause_cap_us` so a producer stuck behind an untracked dependency (e.g. a title fence wait or a hung Signal) +// still expires instead of hanging forever, and demoted (`cut_short`) gates scale both caps with their short budget. // // Pure C++20 standard library only. @@ -61,14 +64,35 @@ struct PendingGate { std::span unmet_waits; // waits not currently satisfied in memory (empty for action gates) }; -// Default cap on pausing solely for unrelated unblocked GPU work: 300x the idle timeout, clamped to [1 s, 10 min]. -// At the default 200 ms timeout this allows up to 60 s for slow world-phase frames while preventing an unrelated -// continuously streaming queue from starving an unmodelled wait indefinitely. -inline constexpr std::uint64_t default_active_pause_cap_us(unsigned full_timeout_ms) { - const std::uint64_t base_ms = full_timeout_ms ? std::uint64_t{full_timeout_ms} : 1u; - const std::uint64_t scaled_ms = base_ms > 2000u ? 600000u : base_ms * 300u; - const std::uint64_t clamped_ms = scaled_ms < 1000u ? 1000u : (scaled_ms > 600000u ? 600000u : scaled_ms); - return clamped_ms * 1000u; +struct PauseCaps { + std::uint64_t active_us = 0; // cap on pausing solely for unrelated active_work + std::uint64_t max_us = 0; // hard finite cap across ALL pause reasons (releaser_busy, matching_producer, active_work) +}; + +// Pause caps scaled with the gate's own timeout budget (`gate_timeout_ms`) and demotion state (`cut_short`): +// - Normal gates: `active_us = 300x` and `max_us = 1500x` of `gate_timeout_ms`, capped at 10 min. At the default +// 200 ms timeout this allows up to 60 s for unrelated GPU work and up to 300 s (5 min) while the releaser or an +// acyclic matching producer is working (covering multi-minute world-phase pipeline builds), while guaranteeing a +// finite exit if a producer is held behind an untracked dependency (title fence wait or stuck Signal). +// - Demoted (`cut_short`) gates: `active_us = 1x` and `max_us = 4x` of `gate_timeout_ms` (4 ms / 16 ms at the 4 ms +// demoted budget), so an unmodelled wait only pays a few milliseconds instead of inheriting the full timeout's cap. +inline constexpr PauseCaps default_pause_caps(unsigned gate_timeout_ms, bool cut_short = false) { + constexpr std::uint64_t kMaxCapMs = 600000u; // 10 min hard ceiling + const std::uint64_t base_ms = gate_timeout_ms ? std::uint64_t{gate_timeout_ms} : 1u; + const auto scale_ms = [base_ms](std::uint64_t mult) -> std::uint64_t { + return base_ms > kMaxCapMs / mult ? kMaxCapMs : base_ms * mult; + }; + const std::uint64_t active_ms = cut_short ? (base_ms < kMaxCapMs ? base_ms : kMaxCapMs) : scale_ms(300u); + const std::uint64_t max_ms = cut_short ? scale_ms(4u) : scale_ms(1500u); + return {active_ms * 1000u, max_ms * 1000u}; +} + +inline constexpr std::uint64_t default_active_pause_cap_us(unsigned gate_timeout_ms, bool cut_short = false) { + return default_pause_caps(gate_timeout_ms, cut_short).active_us; +} + +inline constexpr std::uint64_t default_max_pause_cap_us(unsigned gate_timeout_ms, bool cut_short = false) { + return default_pause_caps(gate_timeout_ms, cut_short).max_us; } struct GateTimeoutState { @@ -76,27 +100,40 @@ struct GateTimeoutState { std::uint64_t elapsed_us = 0; std::uint64_t active_paused_us = 0; std::uint64_t active_pause_cap_us = 0; + std::uint64_t total_paused_us = 0; + std::uint64_t max_pause_cap_us = 0; bool paused_ever = false; - void reset(std::uint64_t budget, std::uint64_t active_cap) { + void reset(std::uint64_t budget, std::uint64_t active_cap, std::uint64_t max_cap) { budget_us = budget; elapsed_us = 0; active_paused_us = 0; - active_pause_cap_us = active_cap; + total_paused_us = 0; + max_pause_cap_us = max_cap; + active_pause_cap_us = active_cap < max_cap ? active_cap : max_cap; paused_ever = false; } // Advances the gate by `dt_us` under `reason`. Returns true once the idle timeout budget is exhausted. + // Every pause reason is bounded by `max_pause_cap_us`; unrelated `active_work` is additionally bounded by + // `active_pause_cap_us`. bool advance(std::uint64_t dt_us, PauseReason reason) { + std::uint64_t room = 0; if (reason == PauseReason::releaser_busy || reason == PauseReason::matching_producer) { - paused_ever = true; - return false; + room = total_paused_us < max_pause_cap_us ? max_pause_cap_us - total_paused_us : 0u; + } else if (reason == PauseReason::active_work) { + const std::uint64_t total_room = + total_paused_us < max_pause_cap_us ? max_pause_cap_us - total_paused_us : 0u; + const std::uint64_t active_room = + active_paused_us < active_pause_cap_us ? active_pause_cap_us - active_paused_us : 0u; + room = total_room < active_room ? total_room : active_room; } - if (reason == PauseReason::active_work && active_paused_us < active_pause_cap_us) { + if (room > 0) { + if (dt_us == 0) return false; paused_ever = true; - const std::uint64_t room = active_pause_cap_us - active_paused_us; const std::uint64_t absorb = dt_us < room ? dt_us : room; - active_paused_us += absorb; + total_paused_us += absorb; + if (reason == PauseReason::active_work) active_paused_us += absorb; dt_us -= absorb; } if (dt_us > UINT64_MAX - elapsed_us) diff --git a/runtime/test/list_value_wait_budget_test.cpp b/runtime/test/list_value_wait_budget_test.cpp index e607527170..6bf9bfbf53 100644 --- a/runtime/test/list_value_wait_budget_test.cpp +++ b/runtime/test/list_value_wait_budget_test.cpp @@ -1,8 +1,10 @@ // Portable CPU-only unit tests for runtime/src/list_value_wait_budget.h (RT-LIST-VALUE-WAIT-WORK-AWARE-TIMEOUT): -// work-aware timeout pausing, cycle detection across multi-queue write/gate chains, overwrite-aware write matching, -// action gates, and bounded unrelated-work pausing. No Windows, D3D12, or Vulkan headers; no game files. +// work-aware timeout pausing, finite pause caps across all pause reasons (including releaser_busy and +// matching_producer), demoted-gate cap scaling, cycle detection across multi-queue write/gate chains, overwrite-aware +// write matching, action gates, and a mock Pump tick driver. No Windows, D3D12, or Vulkan headers; no game files. #include "../src/list_value_wait_budget.h" +#include #include #include @@ -48,7 +50,8 @@ int main() { CHECK(pause_reason(false, {}, gates, 0, test_met) == PauseReason::none); GateTimeoutState t; - t.reset(200'000, default_active_pause_cap_us(200)); + const PauseCaps caps = default_pause_caps(200, false); + t.reset(200'000, caps.active_us, caps.max_us); CHECK(!t.advance(100'000, PauseReason::none)); CHECK(t.elapsed_us == 100'000 && !t.paused_ever); CHECK(!t.advance(99'999, PauseReason::none)); @@ -56,20 +59,32 @@ int main() { CHECK(t.elapsed_us == 200'000); } - // 2. Releaser actively executing held work pauses the timeout clock indefinitely without burning idle budget. + // 2. Releaser actively executing held work pauses the timeout clock (covering multi-minute world-phase pipeline + // builds without burning idle budget), yet still expires at the finite max_pause_cap_us if a Signal hangs. { const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; const PendingGate gates[] = {{q1, 1, false, waits}}; CHECK(pause_reason(true, {}, gates, 0, test_met) == PauseReason::releaser_busy); GateTimeoutState t; - t.reset(200'000, default_active_pause_cap_us(200)); - // 30 seconds of releaser executing shadow/texture copies burns 0 us of idle timeout budget. - for (int i = 0; i < 30; ++i) CHECK(!t.advance(1'000'000, PauseReason::releaser_busy)); - CHECK(t.elapsed_us == 0 && t.paused_ever); + const PauseCaps caps = default_pause_caps(200, false); + CHECK(caps.active_us == 60'000'000ull && caps.max_us == 300'000'000ull); + t.reset(200'000, caps.active_us, caps.max_us); + // 120 seconds of releaser executing pipeline builds/copies burns 0 us of idle timeout budget. + for (int i = 0; i < 120; ++i) CHECK(!t.advance(1'000'000, PauseReason::releaser_busy)); + CHECK(t.elapsed_us == 0 && t.total_paused_us == 120'000'000ull && t.paused_ever); // Once idle again, still gets its full 200 ms budget before expiring. CHECK(!t.advance(199'000, PauseReason::none)); CHECK(t.advance(1'000, PauseReason::none)); + + // Hung Signal (releaser_busy forever) hits the finite max_pause_cap_us and then drains budget_us. + GateTimeoutState hung; + hung.reset(200'000, caps.active_us, caps.max_us); + for (int i = 0; i < 300; ++i) CHECK(!hung.advance(1'000'000, PauseReason::releaser_busy)); + CHECK(hung.total_paused_us == 300'000'000ull && hung.elapsed_us == 0); + CHECK(!hung.advance(199'000, PauseReason::releaser_busy)); + CHECK(hung.advance(1'000, PauseReason::releaser_busy)); + CHECK(hung.elapsed_us == 200'000); } // 3. Matching unblocked producer write on another queue (Wait-before-Signal) -> PauseReason::matching_producer. @@ -193,31 +208,70 @@ int main() { CHECK(pause_reason(false, {}, blocked_action, 0, test_met) == PauseReason::none); } - // 9. Bounded unrelated active_work pause: pauses up to active_pause_cap_us, then drains idle budget_us cleanly. + // 9. Bounded pause caps: active_work, matching_producer, releaser_busy, combined alternating reasons, and + // demoted-gate cap scaling. { - CHECK(default_active_pause_cap_us(200) == 60'000'000ull); // 60 s at default 200 ms - CHECK(default_active_pause_cap_us(1) == 1'000'000ull); // 1 s floor - CHECK(default_active_pause_cap_us(30000) == 600'000'000ull); // 10 min ceiling + CHECK(default_active_pause_cap_us(200) == 60'000'000ull); + CHECK(default_max_pause_cap_us(200) == 300'000'000ull); + CHECK(default_active_pause_cap_us(30) == 9'000'000ull); + CHECK(default_max_pause_cap_us(30) == 45'000'000ull); + CHECK(default_active_pause_cap_us(1) == 300'000ull); + CHECK(default_max_pause_cap_us(1) == 1'500'000ull); + CHECK(default_active_pause_cap_us(30000) == 600'000'000ull); + CHECK(default_max_pause_cap_us(30000) == 600'000'000ull); + CHECK(default_active_pause_cap_us(UINT_MAX) == 600'000'000ull); + CHECK(default_max_pause_cap_us(UINT_MAX) == 600'000'000ull); + + // Demoted (cut_short) gates scale caps with their short 4 ms budget instead of inheriting 60 s / 300 s. + const PauseCaps dem = default_pause_caps(4, true); + CHECK(dem.active_us == 4'000ull && dem.max_us == 16'000ull); + GateTimeoutState dem_active; + dem_active.reset(4'000, dem.active_us, dem.max_us); + CHECK(!dem_active.advance(4'000, PauseReason::active_work)); // absorbs 4 ms cap + CHECK(dem_active.active_paused_us == 4'000 && dem_active.elapsed_us == 0); + CHECK(!dem_active.advance(3'999, PauseReason::active_work)); + CHECK(dem_active.advance(1, PauseReason::active_work)); // expires at 8 ms total, not 60 s! + GateTimeoutState dem_prod; + dem_prod.reset(4'000, dem.active_us, dem.max_us); + CHECK(!dem_prod.advance(16'000, PauseReason::matching_producer)); + CHECK(dem_prod.total_paused_us == 16'000 && dem_prod.elapsed_us == 0); + CHECK(dem_prod.advance(4'000, PauseReason::matching_producer)); // expires at 20 ms total + + // Normal gate active_work cap (5 s) vs larger max cap (20 s). GateTimeoutState t; - t.reset(200'000, 5'000'000); // 200 ms budget, 5 s unrelated-work cap - // 5 full seconds of unrelated active work exhausts the pause cap, leaving 0 elapsed. + t.reset(200'000, 5'000'000, 20'000'000); for (int i = 0; i < 5; ++i) CHECK(!t.advance(1'000'000, PauseReason::active_work)); - CHECK(t.active_paused_us == 5'000'000 && t.elapsed_us == 0 && t.paused_ever); - // Next 200 ms of unrelated work now counts against idle budget and expires the gate. + CHECK(t.active_paused_us == 5'000'000 && t.total_paused_us == 5'000'000 && t.elapsed_us == 0 && t.paused_ever); CHECK(!t.advance(199'000, PauseReason::active_work)); CHECK(t.advance(1'000, PauseReason::active_work)); CHECK(t.elapsed_us == 200'000); - // Partial step straddling the cap splits cleanly between active_paused_us and elapsed_us. + // Stuck matching_producer + alternating releaser_busy share total_paused_us <= max_pause_cap_us. + GateTimeoutState stuck; + stuck.reset(200'000, 2'000'000, 10'000'000); + CHECK(!stuck.advance(2'000'000, PauseReason::active_work)); // total = 2 s + CHECK(!stuck.advance(5'000'000, PauseReason::matching_producer)); // total = 7 s + CHECK(!stuck.advance(3'100'000, PauseReason::releaser_busy)); // 3 s paused (hits 10 s cap), 100 ms elapsed + CHECK(stuck.total_paused_us == 10'000'000 && stuck.elapsed_us == 100'000); + CHECK(!stuck.advance(99'999, PauseReason::matching_producer)); + CHECK(stuck.advance(1, PauseReason::matching_producer)); + CHECK(stuck.elapsed_us == 200'000); + + // Partial step straddling active_pause_cap_us splits cleanly between active_paused_us and elapsed_us. GateTimeoutState t2; - t2.reset(200'000, 500'000); + t2.reset(200'000, 500'000, 1'000'000); CHECK(!t2.advance(600'000, PauseReason::active_work)); // 500k paused, 100k elapsed - CHECK(t2.active_paused_us == 500'000 && t2.elapsed_us == 100'000); + CHECK(t2.active_paused_us == 500'000 && t2.total_paused_us == 500'000 && t2.elapsed_us == 100'000); CHECK(t2.advance(100'000, PauseReason::active_work)); + + // active_cap > max_cap is clamped to max_cap by reset(). + GateTimeoutState clamped; + clamped.reset(100'000, 9'000'000, 3'000'000); + CHECK(clamped.active_pause_cap_us == 3'000'000 && clamped.max_pause_cap_us == 3'000'000); } - // 10. Overflow-safe address / dt_us guards. + // 10. Overflow-safe address / dt_us guards and zero-dt paused tick. { const WaitPredicate overflow_wait[] = {{UINT64_MAX - 2, 1, 7, true}}; const PendingWrite overflow_write[] = {{UINT64_MAX - 2, 1, 8, false}}; @@ -227,9 +281,66 @@ int main() { CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::active_work); GateTimeoutState t; - t.reset(1000, 0); + t.reset(1000, 0, 0); CHECK(t.advance(UINT64_MAX, PauseReason::none)); CHECK(t.elapsed_us == UINT64_MAX); + + GateTimeoutState z; + z.reset(0, 1000, 1000); + CHECK(!z.advance(0, PauseReason::releaser_busy)); + CHECK(!z.paused_ever); + } + + // 11. Mock Pump tick loop driving start_gate + pause_reason + GateTimeoutState end-to-end across 1 ms steps. + { + // (a) 200 ms gate held while releaser runs a 110 s pipeline build, then producer lands at 110.5 s: met! + const WaitPredicate waits[] = {{0x9000, 7, 7, true}}; + const PendingWrite prod_write[] = {{0x9000, 7, 8, false}}; + const PendingWriteGroup prod_groups[] = {{q2, 0, prod_write}}; + const PendingGate gates[] = {{q1, 1, false, waits}}; + + GateTimeoutState gate; + const PauseCaps full_caps = default_pause_caps(200, false); + gate.reset(200'000, full_caps.active_us, full_caps.max_us); + for (int ms = 0; ms < 110'000; ++ms) { + const PauseReason r = pause_reason(true, prod_groups, gates, 0, test_met); + CHECK(r == PauseReason::releaser_busy && !gate.advance(1'000, r)); + } + for (int ms = 0; ms < 500; ++ms) { + const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met); + CHECK(r == PauseReason::matching_producer && !gate.advance(1'000, r)); + } + CHECK(gate.elapsed_us == 0 && gate.total_paused_us == 110'500'000ull); + + // (b) Same gate with a matching producer stuck behind an untracked title fence wait: expires at 300.2 s! + GateTimeoutState stuck_gate; + stuck_gate.reset(200'000, full_caps.active_us, full_caps.max_us); + int expired_at_ms = -1; + for (int ms = 1; ms <= 305'000; ++ms) { + const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met); + if (stuck_gate.advance(1'000, r)) { + expired_at_ms = ms; + break; + } + } + CHECK(expired_at_ms == 300'200); + + // (c) Demoted gate (4 ms budget) with continuous unrelated GPU work on q2: expires at 8 ms! + const PendingWrite unrelated[] = {{0xA000, 1, 8, false}}; + const PendingWriteGroup unrel_groups[] = {{q2, 0, unrelated}}; + GateTimeoutState dem_gate; + const PauseCaps dem_caps = default_pause_caps(4, true); + dem_gate.reset(4'000, dem_caps.active_us, dem_caps.max_us); + int dem_expired_ms = -1; + for (int ms = 1; ms <= 100; ++ms) { + const PauseReason r = pause_reason(false, unrel_groups, gates, 0, test_met); + CHECK(r == PauseReason::active_work); + if (dem_gate.advance(1'000, r)) { + dem_expired_ms = ms; + break; + } + } + CHECK(dem_expired_ms == 8); } std::printf("list_value_wait_budget_test: all checks passed\n"); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 27af09aec3..4a169e81b5 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -4556,6 +4556,85 @@ int check_list_values_more() { WaitForSingleObject(job, INFINITE); CloseHandle(job); + // 11. Work-aware timeout in Pump (src/list_value_wait_budget.h): + // a) a matching in-flight producer pauses a held memory gate past the idle timeout until the producer lands; + // b) a busy releaser executing an action gate pauses a concurrent memory gate past the idle timeout; + // c) a demoted gate (4 ms budget) scales its pause caps with its short budget so unrelated active work does not + // hold it for the full timeout's cap; + // d) a matching producer stuck behind an unsignalled fence still hits a finite pause cap instead of hanging. + const auto write_on_a = [&](int index, std::uint64_t value, std::uint64_t& signal_value) -> bool { + if (FAILED(hr_of(raw(direct, 139, word(allocator), 0)))) return false; + raw(direct, 14, 1, 1, 1); // Dispatch + raw(direct, 72, word(&g_cells2[index]), value, 0, 0); // write64 + if (FAILED(hr_of(raw(direct, 9)))) return false; + g_queue_call_count = 0; + if (submit(qa, direct) != 0) return false; + signal_value = logged_signal(qa_mock, a_written); + return signal_value != 0; + }; + xs::set_list_value_wait_timeout_ms(40); + xs::reset_list_value_stats(); + // 11a. Wait on qb before qa submits its matching write (so relay() misses it and Pump holds a gate). + EXPECT(hold_on(qb, 27, 1)); + std::uint64_t producer_sig = 0; + EXPECT(write_on_a(27, 1, producer_sig)); + EXPECT(!xs::list_values_idle(150)); // >3x the 40 ms idle timeout: pauses while producer is in flight + stats = xs::list_value_stats(); + EXPECT(stats.gates_timed_out == 0 && stats.gates_met == 0 && cell2(27) == 0); + fence_signal(a_written, producer_sig); + EXPECT(xs::list_values_idle(3000) && cell2(27) == 1); + stats = xs::list_value_stats(); + EXPECT(stats.gates_met == 1 && stats.gates_timed_out == 0); + + // 11b. Releaser inside a 150 ms action gate pauses a concurrent memory gate past the 40 ms idle timeout. + xs::set_copy_page_mappings_hook([](std::uint32_t, const rt::xmem::PageBatch*, std::uintptr_t, std::uint32_t, + std::uint32_t) -> bool { + Sleep(150); + InterlockedExchange64(reinterpret_cast(&g_cells2[28]), 1); + return true; + }); + g_queue_call_count = 0; + EXPECT(hr_of(raw(qc, 31, 1, word(remap), 0x7000000000, 16, 0)) == S_OK); + const std::uint64_t action_sig = logged_signal(qc_mock, c_written); + EXPECT(action_sig != 0); + const std::uint64_t met_before_rel = xs::list_value_stats().gates_met; + const std::uint64_t to_before_rel = xs::list_value_stats().gates_timed_out; + EXPECT(hold_on(qb, 28, 1)); + fence_signal(c_written, action_sig); + EXPECT(xs::list_values_idle(3000) && cell2(28) == 1); + xs::set_copy_page_mappings_hook(nullptr); + stats = xs::list_value_stats(); + EXPECT(stats.gates_met == met_before_rel + 1 && stats.gates_timed_out == to_before_rel); + + // 11c. Demoted gate (3 timeouts -> 4 ms budget) with unrelated in-flight work on qa times out in a few ms, not + // the 12 s active-work cap of the 40 ms full timeout. + for (int i = 0; i < 3; ++i) EXPECT(hold_on(qb, 29, 1) && xs::list_values_idle(3000)); + std::uint64_t unrelated_sig = 0; + EXPECT(write_on_a(30, 1, unrelated_sig)); + const std::uint64_t short_before_dem = xs::list_value_stats().gates_short; + const std::uint64_t to_before_dem = xs::list_value_stats().gates_timed_out; + started = Clock::now(); + EXPECT(hold_on(qb, 29, 1)); + for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_dem; ++i) Sleep(1); + const auto demoted_active_ms = ms_since(started); + EXPECT(xs::list_value_stats().gates_timed_out == to_before_dem + 1 && + xs::list_value_stats().gates_short == short_before_dem + 1 && demoted_active_ms < 500); + fence_signal(a_written, unrelated_sig); + EXPECT(xs::list_values_idle(3000)); + + // 11d. Stuck matching producer (fence never signals) still hits the finite max pause cap instead of hanging. + const std::uint64_t to_before_stuck = xs::list_value_stats().gates_timed_out; + started = Clock::now(); + EXPECT(hold_on(qb, 29, 1)); + std::uint64_t stuck_sig = 0; + EXPECT(write_on_a(29, 1, stuck_sig)); + for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_stuck; ++i) Sleep(1); + const auto stuck_producer_ms = ms_since(started); + EXPECT(xs::list_value_stats().gates_timed_out == to_before_stuck + 1 && stuck_producer_ms < 500); + fence_signal(a_written, stuck_sig); + EXPECT(xs::list_values_idle(3000)); + xs::set_list_value_wait_timeout_ms(5000); + // 8. stop() ends both threads. Afterwards nothing new is landed or opened (the process is ending: a gate // signalled from another thread could open one whose remap was skipped, or go below one still to come), and // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut.