From 0ba2e34af0e00e7d052dc9de51e94f4be4f02f6e Mon Sep 17 00:00:00 2001 From: AlenHay <82121826+AlenHay@users.noreply.github.com> Date: Wed, 7 Oct 2026 07:05:07 +0200 Subject: [PATCH 1/3] Make timer shutdown and callback enqueue stop-safe --- src/core/timer_queue.cpp | 166 ++++++++++++++-- tests/CMakeLists.txt | 21 ++ tests/regression/test_timer_lifecycle.py | 237 +++++++++++++++++++++++ tests/regression/test_timer_wait.py | 232 ++++++++++++++++++++++ 4 files changed, 643 insertions(+), 13 deletions(-) create mode 100644 tests/regression/test_timer_lifecycle.py create mode 100644 tests/regression/test_timer_wait.py diff --git a/src/core/timer_queue.cpp b/src/core/timer_queue.cpp index 5cfea05..2b6cd6a 100644 --- a/src/core/timer_queue.cpp +++ b/src/core/timer_queue.cpp @@ -10,7 +10,10 @@ */ #include +#include +#include #include +#include #include #include @@ -27,6 +30,121 @@ namespace rex::thread { using WaitItem = TimerQueueWaitItem; +// Snapshot the opt-in before starting this queue's thread. Blocking preserves +// deadlines, but OS wakeup jitter can differ from the default phased spin wait. +// Keep this private so timer and runtime ABI layouts do not change. +class TimerWaitStrategy { + public: + // Closure is distinct from a timeout or a published sequence. In particular, + // waking a stopped consumer must never make an uninitialized ring slot valid. + struct Stopped {}; + + TimerWaitStrategy() : blocking_(std::getenv("REX_TIMER_WAIT_BLOCKING") != nullptr) {} + + bool stopped() const { return stopped_.load(std::memory_order_acquire); } + + void Stop() { + // Use the publication handshake for closure too, so stop cannot be lost + // between a blocking wait's predicate check and release of the mutex. + std::lock_guard lock(mutex_); + stopped_.store(true, std::memory_order_release); + cv_.notify_all(); + } + + dp::sequence_t wait_until_published( + dp::sequence_t sequence, size_t count, + const std::atomic* const sequences[]) { + if (!blocking_) { + ThrowIfStopped(); + dp::spin_wait spinner; + auto result = dp::minimum_sequence_after(sequence, count, sequences); + while (dp::difference(result, sequence) < 0) { + ThrowIfStopped(); + spinner.spin_once(); + result = dp::minimum_sequence_after(sequence, count, sequences); + } + ThrowIfStopped(); + return result; + } + dp::sequence_t result; + std::unique_lock lock(mutex_); + cv_.wait(lock, [&] { + result = dp::minimum_sequence_after(sequence, count, sequences); + return stopped() || dp::difference(result, sequence) >= 0; + }); + ThrowIfStopped(); + return result; + } + + template + dp::sequence_t wait_until_published( + dp::sequence_t sequence, size_t count, + const std::atomic* const sequences[], + const std::chrono::duration& timeout) { + if (!blocking_) { + return wait_until_published(sequence, count, sequences, + std::chrono::high_resolution_clock::now() + timeout); + } + return wait_until_published(sequence, count, sequences, + std::chrono::steady_clock::now() + timeout); + } + + template + dp::sequence_t wait_until_published( + dp::sequence_t sequence, size_t count, + const std::atomic* const sequences[], + const std::chrono::time_point& deadline) { + if (!blocking_) { + ThrowIfStopped(); + dp::spin_wait spinner; + auto result = dp::minimum_sequence_after(sequence, count, sequences); + while (dp::difference(result, sequence) < 0) { + ThrowIfStopped(); + if (spinner.next_spin_will_yield() && deadline < Clock::now()) return result; + spinner.spin_once(); + result = dp::minimum_sequence_after(sequence, count, sequences); + } + ThrowIfStopped(); + return result; + } + dp::sequence_t result; + std::unique_lock lock(mutex_); + const auto ready = [&] { + result = dp::minimum_sequence_after(sequence, count, sequences); + return stopped() || dp::difference(result, sequence) >= 0; + }; + // The empty queue has no deadline. Avoid converting time_point::max() to + // a platform timeout, which may overflow and turn an idle wait into a poll. + if (deadline == std::chrono::time_point::max()) { + cv_.wait(lock, ready); + } else { + cv_.wait_until(lock, deadline, ready); + } + ThrowIfStopped(); + return result; + } + + void signal_all_when_blocking() { + if (!blocking_) { + return; + } + // Publishers store their sequence before entering this lock. Taking the + // same lock as the predicate prevents a lost wake between check and wait. + std::lock_guard lock(mutex_); + cv_.notify_all(); + } + + private: + void ThrowIfStopped() const { + if (stopped()) throw Stopped{}; + } + + const bool blocking_; + std::atomic stopped_{false}; + std::mutex mutex_; + std::condition_variable cv_; +}; + class TimerQueue { public: using clock = WaitItem::clock; @@ -45,12 +163,9 @@ class TimerQueue { ~TimerQueue() { dispatch_thread_.request_stop(); - - // Kick dispatch thread to check stop token - auto wait_item = std::make_shared(nullptr, nullptr, this, clock::time_point::min(), - clock::duration::zero()); - wait_item->Disarm(); - QueueTimer(std::move(wait_item)); + // Shutdown cannot depend on spare capacity in the producer ring. An active + // callback completes normally; an idle consumer leaves its publication wait. + wait_strategy_.Stop(); // std::jthread auto-joins on destruction } @@ -65,11 +180,20 @@ class TimerQueue { set_current_thread_name("rex::thread::TimerQueue"); while (!stop_token.stop_requested()) { + // Callback ingress belongs only to this consumer. Defer it to the next + // iteration, rather than waiting for this same thread to free ring space. + deferred_wait_items_.sort(comp); + wait_queue_.merge(deferred_wait_items_, comp); { // Consume new wait items and add them to sorted wait queue - dp::sequence_t available = claim_strategy_.wait_until_published( - next_sequence, next_sequence - 1, - wait_queue_.empty() ? clock::time_point::max() : wait_queue_.front()->due_); + dp::sequence_t available; + try { + available = claim_strategy_.wait_until_published( + next_sequence, next_sequence - 1, + wait_queue_.empty() ? clock::time_point::max() : wait_queue_.front()->due_); + } catch (const TimerWaitStrategy::Stopped&) { + break; + } // Check for timeout if (available != next_sequence - 1) { @@ -124,12 +248,27 @@ class TimerQueue { } std::weak_ptr QueueTimer(std::shared_ptr wait_item) { + // The queue is permanently closed during teardown. Callers must still keep + // the queue alive for the whole call; closure does not extend its lifetime. + if (wait_strategy_.stopped()) return {}; auto wait_item_weak = std::weak_ptr(wait_item); // Mitigate callback flooding wait_item->due_ = std::max(clock::now() - wait_item->interval_, wait_item->due_); - auto sequence = claim_strategy_.claim_one(); + if (std::this_thread::get_id() == dispatch_thread_id()) { + deferred_wait_items_.push_front(std::move(wait_item)); + return wait_item_weak; + } + + dp::sequence_t sequence; + try { + sequence = claim_strategy_.claim_one(); + } catch (const TimerWaitStrategy::Stopped&) { + // A stopped claim is never published. The ring is permanently closed, + // so the reserved sequence cannot leave a hole in a running queue. + return {}; + } buffer_[sequence] = std::move(wait_item); claim_strategy_.publish(sequence); @@ -142,13 +281,14 @@ class TimerQueue { // This ring buffer will be used to introduce timers queued by the public API static constexpr size_t kWaitCount = 512; dp::ring_buffer> buffer_; - dp::spin_wait_strategy wait_strategy_; - dp::multi_threaded_claim_strategy claim_strategy_; - dp::sequence_barrier consumed_; + TimerWaitStrategy wait_strategy_; + dp::multi_threaded_claim_strategy claim_strategy_; + dp::sequence_barrier consumed_; // This is a _sorted_ (ascending due_) list of active timers managed by a // dedicated thread std::forward_list> wait_queue_; + std::forward_list> deferred_wait_items_; std::jthread dispatch_thread_; }; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3e67044..c8ada59 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -6,3 +6,24 @@ add_subdirectory(unit) # PPC instruction tests (requires PPC toolchain) add_subdirectory(ppc) + +# Timer publication/lifecycle fixtures compile the actual production queue and +# Disruptor with runtime-independent assert/thread-name facilities only. +# POSIX runner/process limits require Linux and GNU-style compiler drivers. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" + AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU") + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_Interpreter_FOUND) + foreach(check IN ITEMS timer_wait timer_lifecycle) + add_test(NAME regression_${check} + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/regression/test_${check}.py + ${CMAKE_CURRENT_BINARY_DIR}/regression/${check} + --compiler ${CMAKE_CXX_COMPILER}) + set_tests_properties(regression_${check} PROPERTIES + TIMEOUT 100 LABELS "regression;asset_free") + endforeach() + else() + message(STATUS "Python3 unavailable: timer regression fixtures are disabled") + endif() +endif() diff --git a/tests/regression/test_timer_lifecycle.py b/tests/regression/test_timer_lifecycle.py new file mode 100644 index 0000000..7887db2 --- /dev/null +++ b/tests/regression/test_timer_lifecycle.py @@ -0,0 +1,237 @@ +"""Exercise actual TimerQueue closure, callback ingress and lifetime boundaries.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import resource +import signal +import subprocess + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('output', type=Path) +p.add_argument('--compiler', default='clang++') +p.add_argument('--sdk', type=Path) +p.add_argument('--legacy-source', type=Path, + help='Also require exact old full-ring deadlocks from this saved source') +a = p.parse_args() +sdk = (a.sdk or Path(__file__).resolve().parents[2]).resolve() +a.output.mkdir(parents=True, exist_ok=True) +# Visibility only: observe the real claim reservation before closing the +# full queue, proving that the producer reached Disruptor's blocking barrier. +# All claim/publish implementation bytes remain unchanged. +claim_header = sdk/'thirdparty/disruptorplus/include/disruptorplus/multi_threaded_claim_strategy.hpp' +claim_original = claim_header.read_text() +claim_overlay = a.output/'visibility/disruptorplus/multi_threaded_claim_strategy.hpp' +claim_overlay.parent.mkdir(parents=True, exist_ok=True) +assert 'private:' in claim_original +claim_overlay.write_text(claim_original.replace('private:', 'public:')) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) +soft_as, hard_as = resource.getrlimit(resource.RLIMIT_AS) +limit = min(3 * 1024**3, soft_as) if soft_as != resource.RLIM_INFINITY else 3 * 1024**3 +resource.setrlimit(resource.RLIMIT_AS, (limit, hard_as)) +fixture = r''' +using namespace rex::thread;using namespace std::chrono_literals; +using Clock=TimerQueueWaitItem::clock; +void Mark(const char* text){std::cout<void Ready(Future& f){if(f.wait_for(2s)!=std::future_status::ready){Mark("SETUP_FAILED: future deadline");std::abort();}f.get();} +struct Gate{std::mutex mutex;std::condition_variable cv;bool open=false; + void Wait(){std::unique_lock lock(mutex);assert(cv.wait_for(lock,3s,[&]{return open;}));} + void Open(){std::lock_guard lock(mutex);open=true;cv.notify_all();}}; +auto Item(TimerQueue& q,std::function cb,Clock::time_point due,Clock::duration interval={}){ + return std::make_shared(std::move(cb),nullptr,&q,due,interval);} +int main(int argc,char** argv){assert(argc==2);const std::string_view test=argv[1]; + if(test=="shutdown-full"){ + auto queue=std::make_unique();Gate release;std::promise entered,left; + auto entry=entered.get_future(),exit=left.get_future(); + queue->QueueTimer(Item(*queue,[&](void*){entered.set_value();release.Wait();Mark("CALLBACK_EXITED");left.set_value();},Clock::now())); + Ready(entry);assert(queue->consumed_.last_published()==0); + for(int i=0;i<512;++i)queue->QueueTimer(Item(*queue,[](void*){},Clock::now()+1h)); + assert(queue->consumed_.last_published()==0);Mark("FULL_RING: 512 published, consumed=0, no producers active"); + const auto stop=queue->dispatch_thread_.get_stop_token(); + std::thread destroyer([q=std::move(queue)]()mutable{Mark("DESTRUCTOR_ENTERED");q.reset();Mark("DESTRUCTOR_RETURNED");}); + const auto deadline=Clock::now()+1s;while(!stop.stop_requested()&&Clock::now(),count> calls{}; + std::atomic total=0;std::promise finished;auto done=finished.get_future(); + queue.QueueTimer(Item(queue,[&](void*){ + assert(queue.consumed_.last_published()==0);Mark("CALLBACK_ENTERED"); + for(int i=0;i=due);assert(++calls[i]==1);if(++total==count)finished.set_value(); + },due));assert(!handle.expired()); + } + Mark("REENTRANT_CLAIMS_RETURNED"); + },Clock::now())); + Ready(done);assert(total==count);for(auto& n:calls)assert(n==1); + Mark("PASS: reentrant-full");return 0; + } + if(test=="mixed"){ + TimerQueue queue;Gate release;std::promise entered,finished,full; + auto entry=entered.get_future(),done=finished.get_future(),filled=full.get_future(); + constexpr int externalCount=600,nestedCount=1100;std::array,externalCount+nestedCount> calls{}; + std::atomic total=0,published=0;std::vector> canceled; + queue.QueueTimer(Item(queue,[&](void*){ + entered.set_value();release.Wait(); + for(int i=0;iDisarm();canceled.push_back(h);} + },Clock::now()));Ready(entry); + auto producer=std::async(std::launch::async,[&]{ + for(int i=0;i barrier;auto ended=barrier.get_future();queue.QueueTimer(Item(queue,[&](void*){barrier.set_value();},Clock::now()));Ready(ended); + for(auto& h:canceled)assert(h.expired()); + // A recurring callback may enqueue new work, then self-disarm without a lock cycle. + Gate ready;std::promise recurringDone;auto recurDone=recurringDone.get_future(); + std::shared_ptr recurring;std::atomic repeats=0,nested=0; + const auto firstDue=Clock::now();recurring=Item(queue,[&](void*){ + ready.Wait();const int n=++repeats;assert(Clock::now()>=firstDue+1ms*(n-1)); + queue.QueueTimer(Item(queue,[&](void*){if(++nested==3)recurringDone.set_value();},Clock::now())); + if(n==3)recurring->Disarm(); + },firstDue,1ms);queue.QueueTimer(recurring);ready.Open();Ready(recurDone);recurring->Disarm();assert(repeats==3&&nested==3); + Mark("PASS: mixed");return 0; + } + if(test=="closure"){ + // Stop must wake both consumer-publication and producer-claim waits without + // manufacturing sequence availability. Keep the queue alive until callers exit. + TimerWaitStrategy strategy;std::atomic sequence{dp::sequence_t(-1)}; + const std::atomic* seqs[]{&sequence}; + std::promise waiting;auto started=waiting.get_future(); + auto wait=std::async(std::launch::async,[&]{waiting.set_value();try{strategy.wait_until_published(0,1,seqs);assert(false);}catch(const TimerWaitStrategy::Stopped&){}}); + Ready(started);assert(wait.wait_for(10ms)==std::future_status::timeout); + strategy.Stop();Ready(wait);assert(sequence==dp::sequence_t(-1)); + for(int kind=0;kind<3;++kind){bool stopped=false;try{ + if(kind==0)strategy.wait_until_published(0,1,seqs); + else if(kind==1)strategy.wait_until_published(0,1,seqs,1ms); + else strategy.wait_until_published(0,1,seqs,Clock::time_point::max()); + }catch(const TimerWaitStrategy::Stopped&){stopped=true;}assert(stopped);} + TimerQueue queue;Gate release;std::promise entered,published; + auto entry=entered.get_future(),full=published.get_future(); + queue.QueueTimer(Item(queue,[&](void*){entered.set_value();release.Wait();},Clock::now()));Ready(entry); + for(int i=0;i<512;++i)queue.QueueTimer(Item(queue,[](void*){assert(false);},Clock::now()+1h)); + auto producer=std::async(std::launch::async,[&]{published.set_value();return queue.QueueTimer(Item(queue,[](void*){assert(false);},Clock::now()+1h));}); + Ready(full); + const auto claimDeadline=Clock::now()+1s; + while(queue.claim_strategy_.m_nextClaimable.load(std::memory_order_acquire)!=514&&Clock::now(),count> calls{}; + std::atomic total=0;std::promise finished;auto done=finished.get_future(); + std::array,4> producers; + for(int p=0;p<4;++p)producers[p]=std::async(std::launch::async,[&,p]{ + for(int j=0;j', ''' +#include +#include +#include +#include +#include +#include +#include +#define assert_not_null(value) assert(value) +#define assert_true(value) assert(value) +namespace rex::thread { inline void set_current_thread_name(const char*) {} } +''').replace('#include ', '') + begin = source.index('class TimerQueue {') + end = source.index('rex::thread::TimerQueue timer_queue_;', begin) + body = source[begin:end] + assert body.count('\n private:') == 1 + source = source[:begin]+body.replace('\n private:', '\n public:')+source[end:] + test = fixture + if legacy: + # Only remove the NEW-API-specific closure case; both red oracles compile + # the exact same legacy/new consumer, destructor and reentrant bodies. + start = test.index(' if(test=="closure")') + end = test.index(' if(test=="idle-shutdown")', start) + test = test[:start]+test[end:] + # The negative child is killed at2s; its own setup deadline must be + # later, so a correct legacy deadlock cannot race a setup-timeout abort. + test = test.replace('wait_for(2s)', 'wait_for(5s)') + cpp = a.output / (label+'.cpp') + cpp.write_text(source+'\n'+test) + exe = (a.output / label).resolve() + rc, stdout, stderr, timeout = group_run([a.compiler, '-std=c++20', '-O2', '-UNDEBUG', '-pthread', + '-I'+str(sdk/'include'), '-I'+str(a.output/'visibility'), + '-I'+str(sdk/'thirdparty/disruptorplus/include'), + '-I'+str(sdk/'thirdparty/disruptorplus/include/disruptorplus'), str(cpp), '-o', str(exe)], 45) + (a.output/(label+'-compile.log')).write_text(stdout+stderr) + if timeout or rc != 0: + raise RuntimeError(f'{label}: compile/setup failed, no behavioral result claimed') + return exe, hashlib.sha256(path.read_bytes()).hexdigest() + +exe, sha = compile_source(sdk/'src/core/timer_queue.cpp', 'timer-lifecycle') +records=[] +for mode in ('spin', 'blocking'): + env=os.environ.copy();env.pop('REX_TIMER_WAIT_BLOCKING',None) + if mode=='blocking':env['REX_TIMER_WAIT_BLOCKING']='1' + for case in ('shutdown-full','reentrant-full','mixed','closure','idle-shutdown','multi-producer'): + rc,stdout,stderr,timeout=group_run([str(exe),case], 8, env) + (a.output/(mode+'-'+case+'.log')).write_text(stdout+stderr) + if timeout or rc or 'PASS: '+case not in stdout: + raise RuntimeError(f'{mode}/{case}: expected real accounting/termination, inspect log') + records.append({'mode':mode,'case':case,'passed':True,'stdout':stdout}) +negative=[] +if a.legacy_source: + old,old_sha=compile_source(a.legacy_source.resolve(),'timer-lifecycle-legacy',True) + for mode in ('spin','blocking'): + env=os.environ.copy();env.pop('REX_TIMER_WAIT_BLOCKING',None) + if mode=='blocking':env['REX_TIMER_WAIT_BLOCKING']='1' + for case in ('shutdown-full','reentrant-full'): + rc,stdout,stderr,timeout=group_run([str(old),case],2,env) + (a.output/('legacy-'+mode+'-'+case+'.log')).write_text(stdout+stderr) + markers=(['FULL_RING: 512 published, consumed=0, no producers active','DESTRUCTOR_ENTERED','STOP_REQUESTED','CALLBACK_EXITED','CASE_ARMED: shutdown-full'] if case=='shutdown-full' else ['CALLBACK_ENTERED','REENTRANT_FULL_RING_BOUNDARY: 512 enqueued, consumed=0','CASE_ARMED: reentrant-full']) + if not timeout or not all(s in stdout for s in markers) or 'SETUP_FAILED' in stdout or 'PASS:' in stdout or 'DESTRUCTOR_RETURNED' in stdout or 'REENTRANT_CLAIMS_RETURNED' in stdout: + raise RuntimeError(f'legacy {mode}/{case}: not exact expected deadlock; timeout alone is not proof') + negative.append({'mode':mode,'case':case,'expected_deadlock_confirmed':True,'killed_and_reaped':True,'source_sha256':old_sha,'stdout':stdout}) +report={'production_sha256':sha,'public_header_sha256':hashlib.sha256((sdk/'include/rex/thread/timer_queue.h').read_bytes()).hexdigest(),'disruptor_claim_header_sha256':hashlib.sha256(claim_header.read_bytes()).hexdigest(),'fixture_sha256':hashlib.sha256(exe.read_bytes()).hexdigest(),'positive_cases':records,'legacy_negative_controls':negative,'limits':['Actual production TU, public header and Disruptor; assert/thread-name facilities shimmed; TimerQueue and real Disruptor reservation visibility changed only.','No callback drops during running queue; permanent closure returns expired weak handle. Producer callers retain queue lifetime until their calls exit.','Each compiler45s/group kill and reap; positive children8s, legacy children2s;3GiB AS/core0.','Does not prove guest1ms clock freshness, OS wake precision or default promotion.']} +(a.output/'verification.json').write_text(json.dumps(report,indent=2)+'\n') +print(f'PASS: {len(records)} actual timer lifecycle cases; {len(negative)} exact legacy deadlock controls') diff --git a/tests/regression/test_timer_wait.py b/tests/regression/test_timer_wait.py new file mode 100644 index 0000000..9b48710 --- /dev/null +++ b/tests/regression/test_timer_wait.py @@ -0,0 +1,232 @@ +"""Run the actual SDK timer queue and publication strategy without a runtime.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import subprocess + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('output', type=Path) +p.add_argument('--compiler', default='clang++') +p.add_argument('--sdk', type=Path) +p.add_argument('--latency', action='store_true', + help='Also report idle host 1ms recurring deadline lateness and CPU cost') +a = p.parse_args() +sdk = (a.sdk or Path(__file__).resolve().parents[2]).resolve() +a.output.mkdir(parents=True, exist_ok=True) +source = (sdk / 'src/core/timer_queue.cpp').read_text() +# Compile the complete production translation unit, actual public wait-item +# header and actual DisruptorPlus implementation. Only runtime-independent +# assertion/thread-name facilities are shimmed; no queue logic is copied. +source = source.replace('#include ', ''' +#include +#include +#include +#include +#include +#include +#include +#define assert_not_null(value) assert(value) +#define assert_true(value) assert(value) +namespace rex::thread { inline void set_current_thread_name(const char*) {} } +''').replace('#include ', '') +fixture = r''' +using namespace rex::thread; +using namespace std::chrono_literals; +struct Gate { + std::mutex mutex;std::condition_variable cv;bool open=false; + void Wait(){std::unique_lock lock(mutex);assert(cv.wait_for(lock,5s,[&]{return open;}));} + void Open(){std::lock_guard lock(mutex);open=true;cv.notify_all();} +}; +template void Complete(Future& f){ + assert(f.wait_for(5s)==std::future_status::ready);f.get(); +} +std::shared_ptr Item(TimerQueue& queue, + std::function callback,TimerQueueWaitItem::clock::time_point due, + TimerQueueWaitItem::clock::duration interval={}){ + return std::make_shared(std::move(callback),nullptr,&queue,due,interval); +} +int MeasureLatency(){ + using Clock=TimerQueueWaitItem::clock; + constexpr size_t sampleCount=1000; + const auto cpuNs=[](clockid_t clock){timespec t{};assert(clock_gettime(clock,&t)==0); + return int64_t(t.tv_sec)*1000000000+t.tv_nsec;}; + timespec resolution{};assert(clock_getres(CLOCK_MONOTONIC,&resolution)==0); + const int64_t processStart=cpuNs(CLOCK_PROCESS_CPUTIME_ID); + const auto wallStart=Clock::now(); + int64_t threadStart=0,threadEnd=0;Clock::time_point first{},last{}; + std::vector lateness; lateness.reserve(sampleCount); + TimerQueue queue;std::promise finished;auto done=finished.get_future(); + const auto firstDue=Clock::now()+20ms; + std::shared_ptr item; + Gate ready; + item=Item(queue,[&](void*){ + ready.Wait();const auto now=Clock::now(); + const auto deadline=firstDue+1ms*int64_t(lateness.size());assert(now>=deadline); + if(lateness.empty()){threadStart=cpuNs(CLOCK_THREAD_CPUTIME_ID);first=now;} + lateness.push_back(std::chrono::duration_cast(now-deadline).count()); + if(lateness.size()==sampleCount){ + threadEnd=cpuNs(CLOCK_THREAD_CPUTIME_ID);last=now; + item->Disarm();finished.set_value(); + } + },firstDue,1ms); + queue.QueueTimer(item);ready.Open();Complete(done);item->Disarm(); + const int64_t processElapsed=cpuNs(CLOCK_PROCESS_CPUTIME_ID)-processStart; + const auto elapsed=std::chrono::duration_cast(Clock::now()-wallStart).count(); + const auto sampleElapsed=std::chrono::duration_cast(last-first).count(); + std::cout<<"{\"interval_ns\":1000000,\"samples\":"< sequence{dp::sequence_t(-1)}; + const std::atomic* sequences[]{&sequence}; + assert(dp::difference(strategy.wait_until_published(0,1,sequences,Clock::now()-1s),0)<0); + assert(dp::difference(strategy.wait_until_published(0,1,sequences,0ms),0)<0); + sequence.store(0,std::memory_order_release); + assert(strategy.wait_until_published(0,1,sequences)==0); + assert(strategy.wait_until_published(0,1,sequences,Clock::now()-1s)==0); + // Publication can happen before or after predicate entry. Neither may lose + // its notification; a spurious notification may not satisfy the predicate. + for(int i=1;i<=100;++i){ + auto waiter=std::async(std::launch::async,[&]{ + return strategy.wait_until_published(i,1,sequences,Clock::time_point::max()); + }); + strategy.signal_all_when_blocking(); + sequence.store(i,std::memory_order_release);strategy.signal_all_when_blocking(); + assert(waiter.wait_for(5s)==std::future_status::ready);assert(waiter.get()==dp::sequence_t(i)); + } + // Empty-queue shutdown must wake an indefinite publication wait. + {TimerQueue empty;} + // A newly queued earlier timer interrupts the existing far-future wait. + { + TimerQueue queue;std::atomic farCalls=0;std::promise arrived; + auto far=Item(queue,[&](void*){++farCalls;},Clock::now()+1h); + queue.QueueTimer(far); + auto done=arrived.get_future();const auto due=Clock::now()+5ms; + queue.QueueTimer(Item(queue,[&](void*){assert(Clock::now()>=due);arrived.set_value();},due)); + Complete(done);far->Disarm();assert(farCalls==0); + } + // Callbacks are never invoked early, even when the ring wait times out. + { + TimerQueue queue;std::promise arrived;auto done=arrived.get_future(); + const auto due=Clock::now()+10ms; + queue.QueueTimer(Item(queue,[&](void*){assert(Clock::now()>=due);arrived.set_value();},due)); + Complete(done); + } + // A disarmed pending item cannot call back; later live items still complete. + { + TimerQueue queue;Gate gate;std::promise entered,finished; + auto entry=entered.get_future(),done=finished.get_future();std::atomic canceledCalls=0; + queue.QueueTimer(Item(queue,[&](void*){entered.set_value();gate.Wait();},Clock::now())); + Complete(entry); + auto canceled=Item(queue,[&](void*){++canceledCalls;},Clock::now());canceled->Disarm(); + queue.QueueTimer(canceled); + queue.QueueTimer(Item(queue,[&](void*){finished.set_value();},Clock::now())); + gate.Open();Complete(done);assert(canceledCalls==0); + } + // Full producer ring: hold the consumer in a real callback, publish exactly + // 512 more items, then release it. All 600 callbacks must arrive exactly once. + { + TimerQueue queue;Gate gate;std::promise entered,full,finished; + auto entry=entered.get_future(),filled=full.get_future(),done=finished.get_future(); + std::atomic calls=0,published=0; + queue.QueueTimer(Item(queue,[&](void*){entered.set_value();gate.Wait();},Clock::now())); + Complete(entry); + auto producer=std::async(std::launch::async,[&]{ + for(int i=0;i<600;++i){ + queue.QueueTimer(Item(queue,[&](void*){if(++calls==600)finished.set_value();},Clock::now())); + ++published;if(i==511)full.set_value(); + } + }); + Complete(filled);assert(published==512);assert(calls==0); + gate.Open();Complete(producer);Complete(done);assert(calls==600&&published==600); + } + // Recurrence keeps its due-time sequence and self-disarm ends the callback + // without deadlocking. The gate safely publishes the weak handle first. + { + Gate ready;std::promise finished;auto done=finished.get_future(); + std::weak_ptr recurring;std::atomic calls=0; + const auto firstDue=Clock::now(); + recurring=QueueTimerRecurring([&](void*){ + ready.Wait();const int n=++calls;assert(Clock::now()>=firstDue+2ms*(n-1)); + if(n==3){auto item=recurring.lock();assert(item);item->Disarm();finished.set_value();} + },nullptr,firstDue,2ms); + ready.Open();Complete(done); + if(auto item=recurring.lock())item->Disarm();assert(calls==3); + } + // External Disarm blocks until the callback exits, preserving owner lifetime. + { + Gate release;std::promise entered,started;auto entry=entered.get_future(),start=started.get_future(); + auto handle=QueueTimerOnce([&](void*){entered.set_value();release.Wait();},nullptr,Clock::now()); + Complete(entry);auto item=handle.lock();assert(item); + auto canceled=std::async(std::launch::async,[&]{started.set_value();item->Disarm();}); + Complete(start);assert(canceled.wait_for(0ms)==std::future_status::timeout); + release.Open();Complete(canceled); + } +} +''' +cpp = a.output / 'timer-wait.cpp' +cpp.write_text(source + '\n' + fixture) +exe = (a.output / 'timer-wait').resolve() +subprocess.run([a.compiler, '-std=c++20', '-O2', '-pthread', + '-I'+str(sdk/'include'), + '-I'+str(sdk/'thirdparty/disruptorplus/include'), + str(cpp), '-o', str(exe)], check=True, timeout=45) +for value in (None, '0', ''): + env = os.environ.copy() + env.pop('REX_TIMER_WAIT_BLOCKING', None) + if value is not None: + env['REX_TIMER_WAIT_BLOCKING'] = value + subprocess.run([str(exe)], env=env, check=True, timeout=15) + print(f'PASS: actual timer queue with REX_TIMER_WAIT_BLOCKING={value!r}') +print('PASS: publication, deadlines, empty shutdown, earlier insertion, backpressure, recurrence, disarm and completion') +if a.latency: + modes = {} + for mode, value in [('spin', None), ('blocking', '1')]: + env = os.environ.copy() + env.pop('REX_TIMER_WAIT_BLOCKING', None) + if value is not None: + env['REX_TIMER_WAIT_BLOCKING'] = value + record = json.loads(subprocess.check_output( + [str(exe), '--latency'], env=env, text=True, timeout=5)) + samples = sorted(record['lateness_ns']) + assert len(samples) == 1000 and samples[0] >= 0 + record['lateness_us'] = { + 'min': samples[0]/1000, 'mean': sum(samples)/len(samples)/1000, + 'p50': samples[(len(samples)-1)//2]/1000, + 'p95': samples[int((len(samples)-1)*.95)]/1000, + 'p99': samples[int((len(samples)-1)*.99)]/1000, + 'max': samples[-1]/1000, + } + record['late_over_1ms_count'] = sum(n > 1000000 for n in samples) + record['timer_thread_cpu_percent'] = 100*record['timer_thread_cpu_ns']/record['sample_elapsed_ns'] + record['process_cpu_percent'] = 100*record['process_cpu_ns']/record['wall_elapsed_ns'] + modes[mode] = record + print(json.dumps({'mode': mode, 'lateness_us': record['lateness_us'], + 'timer_thread_cpu_percent': record['timer_thread_cpu_percent'], + 'late_over_1ms_count': record['late_over_1ms_count']})) + report = {'status': 'measured_actual_production_timer_queue', + 'platform': platform.platform(), 'nice': os.getpriority(os.PRIO_PROCESS, 0), + 'cpu_affinity': sorted(os.sched_getaffinity(0)), + 'production_source_sha256': hashlib.sha256((sdk/'src/core/timer_queue.cpp').read_bytes()).hexdigest(), + 'fixture_exe_sha256': hashlib.sha256(exe.read_bytes()).hexdigest(), + 'percentile_method': 'lower order statistic: floor((n-1)*q)', + 'limits': ['Idle native Linux host fixture; Windows UCRT/Proton CV behavior unmeasured', + 'One 1000-callback run per mode, pinned to one CPU at nice10; not a gameplay/FPS benchmark', + 'Clock resolution is nominal clock_getres precision, not scheduler wakeup resolution', + 'Timer CPU spans first-to-last callback; process CPU also includes the production global empty queue'], + 'modes': modes} + path = a.output / 'timer-latency.json' + path.write_text(json.dumps(report, indent=2)+'\n') + print('Latency report:', path) From 13137ae21fb3ca6ee667783299a9c6d8eb5db747 Mon Sep 17 00:00:00 2001 From: AlenHay <82121826+AlenHay@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:40:08 +0200 Subject: [PATCH 2/3] Fix GPU interrupt publication, cache bounds, and shutdown ordering Publish callback address/data coherently, synchronize the shared frame counter, preserve TLS after a failed interrupt lookup, validate shader-cache lengths, and stop vblank before destroying its command processor. Abort deferred module launch when its prelaunch hook requests UI shutdown. Validate production bodies with bounded concurrent, storage, dispatch, and launch fixtures. Gate host-executed regressions out of cross builds. Public atomic storage changes require rebuilding the runtime and every consumer together; this does not establish full runtime teardown safety. --- include/rex/graphics/command_processor.h | 7 +- include/rex/graphics/graphics_system.h | 5 +- src/graphics/command_processor.cpp | 4 +- src/graphics/d3d12/pipeline_cache.cpp | 26 ++- src/graphics/graphics_system.cpp | 38 +-- src/graphics/vulkan/pipeline_cache.cpp | 39 +++- src/system/function_dispatcher.cpp | 10 +- src/ui/rex_app.cpp | 3 + tests/CMakeLists.txt | 19 +- tests/regression/test_app_launch.py | 160 +++++++++++++ .../test_graphics_interrupt_concurrency.py | 166 ++++++++++++++ tests/regression/test_graphics_shutdown.py | 216 ++++++++++++++++++ tests/regression/test_interrupt_tls.py | 99 ++++++++ tests/regression/test_shader_cache_bounds.py | 163 +++++++++++++ .../test_vulkan_pipeline_storage.py | 152 ++++++++++++ 15 files changed, 1067 insertions(+), 40 deletions(-) create mode 100644 tests/regression/test_app_launch.py create mode 100644 tests/regression/test_graphics_interrupt_concurrency.py create mode 100644 tests/regression/test_graphics_shutdown.py create mode 100644 tests/regression/test_interrupt_tls.py create mode 100644 tests/regression/test_shader_cache_bounds.py create mode 100644 tests/regression/test_vulkan_pipeline_storage.py diff --git a/include/rex/graphics/command_processor.h b/include/rex/graphics/command_processor.h index 89f42a5..5a8d2f2 100644 --- a/include/rex/graphics/command_processor.h +++ b/include/rex/graphics/command_processor.h @@ -84,8 +84,8 @@ class CommandProcessor { CommandProcessor(GraphicsSystem* graphics_system, system::KernelState* kernel_state); virtual ~CommandProcessor(); - uint32_t counter() const { return counter_; } - void increment_counter() { counter_++; } + uint32_t counter() const { return counter_.load(std::memory_order_relaxed); } + void increment_counter() { counter_.fetch_add(1, std::memory_order_relaxed); } // What the GPU thread is doing right now, for hang reports. Any thread. std::string DescribeState() const; @@ -259,7 +259,8 @@ class CommandProcessor { // MicroEngine binary from PM4_ME_INIT std::vector me_bin_; - uint32_t counter_ = 0; + // Both the vblank worker and command processor increment this counter. + std::atomic counter_{0}; uint32_t primary_buffer_ptr_ = 0; uint32_t primary_buffer_size_ = 0; diff --git a/include/rex/graphics/graphics_system.h b/include/rex/graphics/graphics_system.h index bd3339b..6cf9a38 100644 --- a/include/rex/graphics/graphics_system.h +++ b/include/rex/graphics/graphics_system.h @@ -118,8 +118,9 @@ class GraphicsSystem : public system::IGraphicsSystem { std::unique_ptr<::rex::ui::GraphicsProvider> provider_; bool provider_supports_presentation_ = false; - uint32_t interrupt_callback_ = 0; - uint32_t interrupt_callback_data_ = 0; + // Publish callback address and its user data together. Interrupts may run on + // the vblank/GPU workers while the guest replaces this pair. + std::atomic interrupt_callback_state_{0}; std::atomic vsync_worker_running_; system::object_ref vsync_worker_thread_; diff --git a/src/graphics/command_processor.cpp b/src/graphics/command_processor.cpp index de2e472..4fec70b 100644 --- a/src/graphics/command_processor.cpp +++ b/src/graphics/command_processor.cpp @@ -1086,7 +1086,7 @@ bool CommandProcessor::ExecutePacketType3_XE_SWAP(memory::RingBuffer* reader, ui // rather than delaying the frame itself. LimitFramerate(); - ++counter_; + increment_counter(); return true; } @@ -1404,7 +1404,7 @@ bool CommandProcessor::ExecutePacketType3_EVENT_WRITE_SHD(memory::RingBuffer* re uint32_t data_value; if ((initiator >> 31) & 0x1) { // Write counter (GPU vblank counter?). - data_value = counter_; + data_value = counter(); } else { // Write value. data_value = value; diff --git a/src/graphics/d3d12/pipeline_cache.cpp b/src/graphics/d3d12/pipeline_cache.cpp index db6571a..234c83f 100644 --- a/src/graphics/d3d12/pipeline_cache.cpp +++ b/src/graphics/d3d12/pipeline_cache.cpp @@ -356,6 +356,16 @@ void PipelineCache::InitializeShaderStorage(const std::filesystem::path& cache_r shader_storage_file_header.magic == shader_storage_magic && rex::byte_swap(shader_storage_file_header.version_swapped) == ShaderStoredHeader::kVersion) { uint64_t shader_storage_valid_bytes = sizeof(shader_storage_file_header); + const bool shader_storage_end_seeked = + rex::filesystem::Seek(shader_storage_file_, 0, SEEK_END); + const int64_t shader_storage_file_end = + shader_storage_end_seeked ? rex::filesystem::Tell(shader_storage_file_) : -1; + const bool shader_storage_size_valid = + shader_storage_file_end >= int64_t(shader_storage_valid_bytes) && + rex::filesystem::Seek(shader_storage_file_, int64_t(shader_storage_valid_bytes), SEEK_SET); + if (!shader_storage_size_valid) { + REXGPU_WARN("Shader storage: unable to determine readable file size; skipping cache load"); + } // Load and translate shaders written by previous Xenia executions until the // end of the file or until a corrupted one is detected. ShaderStoredHeader shader_header; @@ -447,11 +457,21 @@ void PipelineCache::InitializeShaderStorage(const std::filesystem::path& cache_r }; std::vector> shader_translation_threads; - while (true) { + while (shader_storage_size_valid) { if (!fread(&shader_header, sizeof(shader_header), 1, shader_storage_file_)) { break; } size_t ucode_byte_count = shader_header.ucode_dword_count * sizeof(uint32_t); + const uint64_t payload_offset = shader_storage_valid_bytes + sizeof(shader_header); + // A corrupt 31-bit count must not allocate gigabytes before fread can + // discover the truncated payload. Validate against this open file first. + if (payload_offset > uint64_t(shader_storage_file_end) || + shader_header.ucode_dword_count > + (uint64_t(shader_storage_file_end) - payload_offset) / sizeof(uint32_t)) { + REXGPU_WARN("Shader storage: truncated payload at byte {}; discarding corrupt suffix", + shader_storage_valid_bytes); + break; + } ucode_dwords.resize(shader_header.ucode_dword_count); if (shader_header.ucode_dword_count && !fread(ucode_dwords.data(), ucode_byte_count, 1, shader_storage_file_)) { @@ -520,7 +540,9 @@ void PipelineCache::InitializeShaderStorage(const std::filesystem::path& cache_r REXGPU_INFO("Translated {} shaders from the storage in {} milliseconds", shaders_translated, (rex::chrono::Clock::QueryHostTickCount() - shader_storage_initialization_start) * 1000 / rex::chrono::Clock::QueryHostTickFrequency()); - rex::filesystem::TruncateStdioFile(shader_storage_file_, shader_storage_valid_bytes); + if (shader_storage_size_valid) { + rex::filesystem::TruncateStdioFile(shader_storage_file_, shader_storage_valid_bytes); + } } else { rex::filesystem::TruncateStdioFile(shader_storage_file_, 0); shader_storage_file_header.magic = shader_storage_magic; diff --git a/src/graphics/graphics_system.cpp b/src/graphics/graphics_system.cpp index a794e71..64860de 100644 --- a/src/graphics/graphics_system.cpp +++ b/src/graphics/graphics_system.cpp @@ -197,17 +197,19 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis } void GraphicsSystem::Shutdown() { - if (command_processor_) { - command_processor_->Shutdown(); - command_processor_.reset(); - } - + // MarkVblank and its guest interrupt callback may still use the command + // processor. Keep it running until the vblank worker has finished. if (vsync_worker_thread_) { vsync_worker_running_ = false; vsync_worker_thread_->Wait(0, 0, 0, nullptr); vsync_worker_thread_.reset(); } + if (command_processor_) { + command_processor_->Shutdown(); + command_processor_.reset(); + } + if (presenter_) { if (app_context_) { app_context_->CallInUIThreadSynchronous([this]() { presenter_.reset(); }); @@ -307,13 +309,16 @@ void GraphicsSystem::EnableReadPointerWriteBack(uint32_t ptr, uint32_t block_siz } void GraphicsSystem::SetInterruptCallback(uint32_t callback, uint32_t user_data) { - interrupt_callback_ = callback; - interrupt_callback_data_ = user_data; + interrupt_callback_state_.store((uint64_t(callback) << 32) | user_data, + std::memory_order_release); REXGPU_INFO("SetInterruptCallback({:08X}, {:08X})", callback, user_data); } void GraphicsSystem::DispatchInterruptCallback(uint32_t source, uint32_t cpu) { - if (!interrupt_callback_) { + const uint64_t callback_state = interrupt_callback_state_.load(std::memory_order_acquire); + const uint32_t callback = uint32_t(callback_state >> 32); + const uint32_t callback_data = uint32_t(callback_state); + if (!callback) { return; } @@ -327,10 +332,10 @@ void GraphicsSystem::DispatchInterruptCallback(uint32_t source, uint32_t cpu) { thread->SetActiveCpu(cpu); // REXGPU_INFO("Dispatching GPU interrupt at {:08X} w/ mode {} on cpu {}", - // interrupt_callback_, source, cpu); + // callback, source, cpu); - uint64_t args[] = {source, interrupt_callback_data_}; - function_dispatcher_->ExecuteInterrupt(thread->thread_state(), interrupt_callback_, args, + uint64_t args[] = {source, callback_data}; + function_dispatcher_->ExecuteInterrupt(thread->thread_state(), callback, args, rex::countof(args)); } @@ -401,14 +406,17 @@ void GraphicsSystem::Resume() { } bool GraphicsSystem::Save(::rex::stream::ByteStream* stream) { - stream->Write(interrupt_callback_); - stream->Write(interrupt_callback_data_); + const uint64_t callback_state = interrupt_callback_state_.load(std::memory_order_acquire); + stream->Write(uint32_t(callback_state >> 32)); + stream->Write(uint32_t(callback_state)); return command_processor_->Save(stream); } bool GraphicsSystem::Restore(::rex::stream::ByteStream* stream) { - interrupt_callback_ = stream->Read(); - interrupt_callback_data_ = stream->Read(); + const uint32_t callback = stream->Read(); + const uint32_t callback_data = stream->Read(); + interrupt_callback_state_.store((uint64_t(callback) << 32) | callback_data, + std::memory_order_release); return command_processor_->Restore(stream); } diff --git a/src/graphics/vulkan/pipeline_cache.cpp b/src/graphics/vulkan/pipeline_cache.cpp index 99a22b9..23da01a 100644 --- a/src/graphics/vulkan/pipeline_cache.cpp +++ b/src/graphics/vulkan/pipeline_cache.cpp @@ -414,6 +414,7 @@ void VulkanPipelineCache::InitializeShaderStorage(const std::filesystem::path& c // Initialize the pipeline storage stream - read pipeline descriptions and // collect used shader modifications to translate. std::vector pipeline_stored_descriptions; + size_t pipeline_storage_valid_count = 0; // . std::set> shader_translations_needed; auto pipeline_storage_file_path = @@ -473,6 +474,10 @@ void VulkanPipelineCache::InitializeShaderStorage(const std::filesystem::path& c pipeline_storage_read_count = i; break; } + // Unsupported pipelines are omitted from startup creation, but their + // valid disk records remain useful on another device. The in-memory + // compaction below does not rewrite the storage stream. + pipeline_storage_valid_count = i + 1; if (!ArePipelineRequirementsMet(pipeline_stored_description.description)) { ++pipeline_storage_skipped_unsupported_count; continue; @@ -525,16 +530,36 @@ void VulkanPipelineCache::InitializeShaderStorage(const std::filesystem::path& c shader_storage_file_header.magic == shader_storage_magic && rex::byte_swap(shader_storage_file_header.version_swapped) == ShaderStoredHeader::kVersion) { uint64_t shader_storage_valid_bytes = sizeof(shader_storage_file_header); + const bool shader_storage_end_seeked = + rex::filesystem::Seek(shader_storage_file_, 0, SEEK_END); + const int64_t shader_storage_file_end = + shader_storage_end_seeked ? rex::filesystem::Tell(shader_storage_file_) : -1; + const bool shader_storage_size_valid = + shader_storage_file_end >= int64_t(shader_storage_valid_bytes) && + rex::filesystem::Seek(shader_storage_file_, int64_t(shader_storage_valid_bytes), SEEK_SET); + if (!shader_storage_size_valid) { + REXGPU_WARN("Shader storage: unable to determine readable file size; skipping cache load"); + } // Load shaders written by previous runs until the end of the file or until // a corrupted one is detected. ShaderStoredHeader shader_header; std::vector ucode_dwords; ucode_dwords.reserve(0xFFFF); - while (true) { + while (shader_storage_size_valid) { if (!fread(&shader_header, sizeof(shader_header), 1, shader_storage_file_)) { break; } size_t ucode_byte_count = shader_header.ucode_dword_count * sizeof(uint32_t); + const uint64_t payload_offset = shader_storage_valid_bytes + sizeof(shader_header); + // A corrupt 31-bit count must not allocate gigabytes before fread can + // discover the truncated payload. Validate against this open file first. + if (payload_offset > uint64_t(shader_storage_file_end) || + shader_header.ucode_dword_count > + (uint64_t(shader_storage_file_end) - payload_offset) / sizeof(uint32_t)) { + REXGPU_WARN("Shader storage: truncated payload at byte {}; discarding corrupt suffix", + shader_storage_valid_bytes); + break; + } ucode_dwords.resize(shader_header.ucode_dword_count); if (shader_header.ucode_dword_count && !fread(ucode_dwords.data(), ucode_byte_count, 1, shader_storage_file_)) { @@ -555,7 +580,9 @@ void VulkanPipelineCache::InitializeShaderStorage(const std::filesystem::path& c // Loaded from the current storage - don't write again. shader->set_ucode_storage_index(shader_storage_index_); } - rex::filesystem::TruncateStdioFile(shader_storage_file_, shader_storage_valid_bytes); + if (shader_storage_size_valid) { + rex::filesystem::TruncateStdioFile(shader_storage_file_, shader_storage_valid_bytes); + } } else { rex::filesystem::TruncateStdioFile(shader_storage_file_, 0); shader_storage_file_header.magic = shader_storage_magic; @@ -687,13 +714,13 @@ void VulkanPipelineCache::InitializeShaderStorage(const std::filesystem::path& c } } - // If any pipeline descriptions were corrupted (or the whole file has excess - // bytes in the end), truncate to the last valid pipeline description. + // Truncate only the corrupt or incomplete suffix. Using the compacted + // supported count would discard valid records without rewriting their order. rex::filesystem::TruncateStdioFile( pipeline_storage_file_, uint64_t(sizeof(pipeline_storage_file_header) + - sizeof(PipelineStoredDescription) * pipeline_stored_descriptions.size())); - if (pipeline_stored_descriptions.empty()) { + sizeof(PipelineStoredDescription) * pipeline_storage_valid_count)); + if (!pipeline_storage_valid_count) { rex::filesystem::TruncateStdioFile(pipeline_storage_file_, 0); pipeline_storage_file_header.magic = pipeline_storage_magic; pipeline_storage_file_header.magic_api = pipeline_storage_magic_api; diff --git a/src/system/function_dispatcher.cpp b/src/system/function_dispatcher.cpp index c69e2a2..44ecec6 100644 --- a/src/system/function_dispatcher.cpp +++ b/src/system/function_dispatcher.cpp @@ -212,13 +212,15 @@ uint64_t FunctionDispatcher::ExecuteInterrupt(ThreadState* thread_state, uint32_ uint32_t old_tls_ptr = memory::load_and_swap(pcr_address); memory::store_and_swap(pcr_address, 0); - if (!Execute(thread_state, address)) { - return 0xDEADBABE; - } + const bool executed = Execute(thread_state, address); - // Restore TLS ptr. + // Restore TLS even when dispatch fails (for example, a missing function). memory::store_and_swap(pcr_address, old_tls_ptr); + if (!executed) { + return 0xDEADBABE; + } + return ctx->r3.u64; } diff --git a/src/ui/rex_app.cpp b/src/ui/rex_app.cpp index cc91fda..822580c 100644 --- a/src/ui/rex_app.cpp +++ b/src/ui/rex_app.cpp @@ -536,6 +536,9 @@ void ReXApp::LaunchModule() { } OnPreLaunchModule(); + if (app_context().HasQuitFromUIThread()) { + return; + } auto main_thread = runtime_->PrepareModuleLaunch(); if (!main_thread) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c8ada59..a482a21 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,23 +7,30 @@ add_subdirectory(unit) # PPC instruction tests (requires PPC toolchain) add_subdirectory(ppc) -# Timer publication/lifecycle fixtures compile the actual production queue and -# Disruptor with runtime-independent assert/thread-name facilities only. -# POSIX runner/process limits require Linux and GNU-style compiler drivers. +# Compile small production-body fixtures with fake guest threads and graphics +# objects. These tests do not require game assets or a graphics device. The +# cache-storage fixtures use POSIX stdio/file APIs, so register them on Linux +# with GNU-style compiler drivers only. if(CMAKE_SYSTEM_NAME STREQUAL "Linux" + AND NOT CMAKE_CROSSCOMPILING AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU") find_package(Python3 COMPONENTS Interpreter QUIET) if(Python3_Interpreter_FOUND) - foreach(check IN ITEMS timer_wait timer_lifecycle) + set(REXGLUE_REGRESSION_CHECKS app_launch timer_wait timer_lifecycle interrupt_tls graphics_interrupt_concurrency graphics_shutdown + vulkan_pipeline_storage shader_cache_bounds) + foreach(check IN LISTS REXGLUE_REGRESSION_CHECKS) add_test(NAME regression_${check} COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/regression/test_${check}.py ${CMAKE_CURRENT_BINARY_DIR}/regression/${check} --compiler ${CMAKE_CXX_COMPILER}) set_tests_properties(regression_${check} PROPERTIES - TIMEOUT 100 LABELS "regression;asset_free") + TIMEOUT 60 LABELS "regression;asset_free") + if(check STREQUAL "timer_wait") + set_tests_properties(regression_${check} PROPERTIES TIMEOUT 100) + endif() endforeach() else() - message(STATUS "Python3 unavailable: timer regression fixtures are disabled") + message(STATUS "Python3 unavailable: production-body regression fixtures are disabled") endif() endif() diff --git a/tests/regression/test_app_launch.py b/tests/regression/test_app_launch.py new file mode 100644 index 0000000..411ba8c --- /dev/null +++ b/tests/regression/test_app_launch.py @@ -0,0 +1,160 @@ +"""Execute the production LaunchModule body with deferred UI and guest-thread fixtures.""" +import argparse +from pathlib import Path +import subprocess + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('output', type=Path) +parser.add_argument('--compiler', default='clang++') +parser.add_argument('--source', type=Path) +args = parser.parse_args() +sdk = Path(__file__).resolve().parents[2] +source = (args.source or sdk / 'src/ui/rex_app.cpp').read_text() +start = source.index('void ReXApp::LaunchModule() {') +opening = source.index('{', start) +depth, end = 1, opening + 1 +while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 +body = source[start:end] + +code = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#define REXLOG_INFO(...) ((void)0) +#define REXLOG_ERROR(...) ((void)0) +namespace rex::system { struct AchievementEvent {}; } +namespace ui { +struct AchievementNotificationDialog { + void Push(const rex::system::AchievementEvent&) {} +}; +struct ShaderCompileNoticeDialog { + template ShaderCompileNoticeDialog(void*, Callback) {} +}; +} +struct UIContext { + std::thread::id ui_thread = std::this_thread::get_id(); + std::function pending; + bool quit = false; + bool CallInUIThreadDeferred(std::function callback) { + assert(!pending); pending = std::move(callback); return true; + } + void RunPending() { + assert(std::this_thread::get_id() == ui_thread && pending); + auto callback = std::move(pending); pending = {}; callback(); + } + bool HasQuitFromUIThread() const { + assert(std::this_thread::get_id() == ui_thread); return quit; + } + void QuitFromUIThread() { + assert(std::this_thread::get_id() == ui_thread); quit = true; + } + bool CallInUIThread(std::function callback) { + assert(std::this_thread::get_id() == ui_thread); callback(); return true; + } +}; +struct GuestThread { + unsigned resumed = 0, waited = 0; + void Resume() { ++resumed; } + void Wait(int, int, int, void*) { ++waited; } +}; +struct KernelState { uint32_t title_id() { return 0x5752084B; } }; +struct Graphics { + unsigned storage_initialized = 0; + bool GetCompileProgress(uint32_t&, uint32_t&) { return false; } + void InitializeShaderStorage(const std::string& root, uint32_t title, bool blocking) { + assert(root == "cache" && title == 0x5752084B && blocking); + ++storage_initialized; + } +}; +struct Runtime { + unsigned prepared = 0; + bool preparation_fails = false; + KernelState kernel; + Graphics graphics; + std::shared_ptr thread = std::make_shared(); + std::shared_ptr PrepareModuleLaunch() { + ++prepared; return preparation_fails ? nullptr : thread; + } + KernelState* kernel_state() { return &kernel; } + Graphics* graphics_system() { return &graphics; } + std::string cache_root() { return "cache"; } +}; +struct Achievements { + unsigned registered = 0; + unsigned RegisterNotificationCallback( + std::function) { + return ++registered; + } +}; +struct ReXApp { + UIContext context; + Achievements achievement_manager; + std::shared_ptr achievement_notification_; + unsigned achievement_notification_listener_ = 0; + std::unique_ptr shader_compile_notice_; + std::unique_ptr imgui_drawer_ = std::make_unique(1); + std::unique_ptr runtime_ = std::make_unique(); + std::atomic shutting_down_{true}; + std::thread module_thread_; + bool hook_quits = false; + unsigned pre_launch = 0, post_launch = 0, guest_exits = 0; + ~ReXApp() { Join(); } + void Join() { if (module_thread_.joinable()) module_thread_.join(); } + UIContext& app_context() { return context; } + Achievements& achievements() { return achievement_manager; } + ui::AchievementNotificationDialog* CreateAchievementNotificationDialog() { + return new ui::AchievementNotificationDialog; + } + void OnPreLaunchModule() { + ++pre_launch; if (hook_quits) context.QuitFromUIThread(); + } + void OnPostLaunchModule(GuestThread* thread) { + assert(thread == runtime_->thread.get()); ++post_launch; + } + void OnGuestThreadExit(GuestThread* thread) { + assert(thread == runtime_->thread.get()); ++guest_exits; + } + void LaunchModule(); +}; +''' + body + r''' +int main() { + for (unsigned scenario = 0; scenario < 3; ++scenario) { + ReXApp app; + app.hook_quits = scenario == 1; + app.runtime_->preparation_fails = scenario == 2; + app.LaunchModule(); + assert(app.context.pending && app.pre_launch == 0 && app.runtime_->prepared == 0); + app.context.RunPending(); + app.Join(); + assert(app.pre_launch == 1 && app.achievement_manager.registered == 1); + assert(app.achievement_notification_ && app.shader_compile_notice_); + if (scenario == 0) { + assert(!app.context.quit && app.runtime_->prepared == 1); + assert(app.runtime_->graphics.storage_initialized == 1); + assert(app.post_launch == 1 && app.guest_exits == 1); + assert(app.runtime_->thread->resumed == 1 && app.runtime_->thread->waited == 1); + } else { + assert(app.context.quit && app.runtime_->prepared == (scenario == 2 ? 1u : 0u)); + assert(app.runtime_->graphics.storage_initialized == 0); + assert(app.post_launch == 0 && app.guest_exits == 0); + assert(app.runtime_->thread->resumed == 0 && app.runtime_->thread->waited == 0); + } + } +} +''' +args.output.mkdir(parents=True, exist_ok=True) +cpp = args.output.resolve() / 'app-launch.cpp' +binary = args.output.resolve() / 'app-launch.exe' +cpp.write_text(code) +subprocess.run([args.compiler, '-std=c++20', '-UNDEBUG', '-pthread', str(cpp), + '-o', str(binary)], check=True, timeout=45) +subprocess.run([str(binary)], check=True, timeout=10) +print('PASS: production LaunchModule preserves successful deferred launch and ' + 'preparation failure; prelaunch UI quit skips preparation, storage, hooks and resume') diff --git a/tests/regression/test_graphics_interrupt_concurrency.py b/tests/regression/test_graphics_interrupt_concurrency.py new file mode 100644 index 0000000..e4125fb --- /dev/null +++ b/tests/regression/test_graphics_interrupt_concurrency.py @@ -0,0 +1,166 @@ +"""Run production counter/publication/dispatch/save bodies with bounded threads.""" +import argparse +from pathlib import Path +import re +import subprocess + + +def function(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('output', type=Path) +p.add_argument('--compiler', default='clang++') +p.add_argument('--sdk', type=Path) +p.add_argument('--tsan', action='store_true') +a = p.parse_args() +root = Path(__file__).resolve().parents[2] +sdk = a.sdk or root +graphics = (sdk / 'src/graphics/graphics_system.cpp').read_text() +graphics_header = (sdk / 'include/rex/graphics/graphics_system.h').read_text() +processor_header = (sdk / 'include/rex/graphics/command_processor.h').read_text() +processor = (sdk / 'src/graphics/command_processor.cpp').read_text() +fields = '\n'.join(re.findall( + r' (?:std::atomic interrupt_callback_state_\{0\};|' + r'uint32_t interrupt_callback_ = 0;|uint32_t interrupt_callback_data_ = 0;)', graphics_header)) +counter_field = re.search( + r' (?:std::atomic counter_\{0\};|uint32_t counter_ = 0;)', processor_header).group(0) +counter_methods = '\n'.join(function(processor_header, signature) for signature in ( + 'uint32_t counter() const', 'void increment_counter()')) +# Both production command-thread accesses must use the same synchronized +# primitive as the vblank thread. Do not silently test only the public getter. +if 'std::atomic' in counter_field: + assert '++counter_;' not in processor + assert 'data_value = counter();' in processor + assert 'increment_counter();' in processor +bodies = '\n'.join(function(graphics, signature) for signature in ( + 'void GraphicsSystem::SetInterruptCallback(', 'void GraphicsSystem::DispatchInterruptCallback(', + 'bool GraphicsSystem::Save(', 'bool GraphicsSystem::Restore(')) +code = r''' +#include +#include +#include +#include +#include +#include +#include +#define REXGPU_INFO(...) ((void)0) +#define assert_not_null(value) assert(value) +namespace rex { +templateconstexpr size_t countof(T (&)[N]){return N;} +namespace stream { +struct ByteStream { + std::vector words;size_t next=0; + templatevoid Write(T word){static_assert(sizeof(T)==4);words.push_back(uint32_t(word));} + templateT Read(){static_assert(sizeof(T)==4);return T(words.at(next++));} +}; +} +} +namespace rex::system { +struct XThread { + uint32_t cpu=0; + void SetActiveCpu(uint32_t active){cpu=active;} + void* thread_state(){return this;} + static XThread* GetCurrentThread(){static thread_local XThread thread;return &thread;} +}; +} +namespace rex::graphics { +struct Processor { +''' + counter_field + '\n' + counter_methods + r''' + bool Save(rex::stream::ByteStream*){return true;} + bool Restore(rex::stream::ByteStream*){return true;} +}; +struct GraphicsSystem; +struct Dispatcher { + std::atomic calls{0};bool reentrant=false;GraphicsSystem* owner=nullptr; + void ExecuteInterrupt(void* thread,uint32_t callback,uint64_t args[],size_t count); +}; +struct GraphicsSystem { +''' + fields + r''' + Processor processor;Processor* command_processor_=&processor; + Dispatcher dispatcher;Dispatcher* function_dispatcher_=&dispatcher; + GraphicsSystem(){dispatcher.owner=this;} + void SetInterruptCallback(uint32_t,uint32_t); + void DispatchInterruptCallback(uint32_t,uint32_t); + bool Save(rex::stream::ByteStream*); + bool Restore(rex::stream::ByteStream*); +}; +''' + bodies + r''' +constexpr uint32_t callback_a=0x83FBF508,callback_b=0x82012340; +constexpr uint32_t data_a=0x40009A00,data_b=0x1234ABCD; +void Dispatcher::ExecuteInterrupt(void* thread,uint32_t callback,uint64_t args[],size_t count){ + assert(thread&&count==2&&args[0]==7); + assert((callback==callback_a&&args[1]==data_a)||(callback==callback_b&&args[1]==data_b)); + assert(static_cast(thread)->cpu==2); + calls.fetch_add(1,std::memory_order_relaxed); + if(reentrant)owner->SetInterruptCallback(callback_b,data_b); +} +void CheckSaved(const rex::stream::ByteStream& saved){ + assert(saved.words.size()==2); + const auto callback=saved.words[0],data=saved.words[1]; + assert((callback==callback_a&&data==data_a)||(callback==callback_b&&data==data_b)|| + (callback==0&&data==0xDEADBEEF)); +} +} // namespace rex::graphics +using namespace rex::graphics; +int main(){ + constexpr uint32_t count=200000; + Processor processor; + std::atomic start{false}; + const auto writer=[&]{while(!start.load(std::memory_order_acquire))std::this_thread::yield(); + for(uint32_t i=0;i0); + graphics.SetInterruptCallback(0,0xDEADBEEF); + const auto calls=graphics.dispatcher.calls.load();graphics.DispatchInterruptCallback(7,2); + assert(graphics.dispatcher.calls.load()==calls); + rex::stream::ByteStream saved;saved.words={callback_b,data_b}; + assert(graphics.Restore(&saved));rex::stream::ByteStream restored; + assert(graphics.Save(&restored));assert(restored.words==saved.words); + graphics.SetInterruptCallback(callback_a,data_a);graphics.dispatcher.reentrant=true; + graphics.DispatchInterruptCallback(7,2);rex::stream::ByteStream after; + assert(graphics.Save(&after));assert(after.words==std::vector({callback_b,data_b})); +} +''' +a.output.mkdir(parents=True, exist_ok=True) +cpp = a.output.resolve() / 'graphics-interrupt-concurrency.cpp' +exe = a.output.resolve() / 'graphics-interrupt-concurrency.exe' +cpp.write_text(code) +flags = ['-fsanitize=thread', '-g', '-O1'] if a.tsan else [] +subprocess.run([a.compiler, '-std=c++20', '-UNDEBUG', '-pthread', *flags, + str(cpp), '-o', str(exe)], check=True, timeout=45) +subprocess.run([str(exe)], check=True, timeout=15) +print('PASS: production counter and callback publication/dispatch/save/restore ' + 'bodies under bounded concurrency; no lost increments or mixed callback pairs') diff --git a/tests/regression/test_graphics_shutdown.py b/tests/regression/test_graphics_shutdown.py new file mode 100644 index 0000000..b5ecd0f --- /dev/null +++ b/tests/regression/test_graphics_shutdown.py @@ -0,0 +1,216 @@ +"""Exercise graphics teardown with a real worker inside production vblank bodies.""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + + +def function(source, signature): + start = source.index(signature) + opening = source.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--compiler", default="clang++") + parser.add_argument("--source", type=Path) + parser.add_argument("--legacy-order", action="store_true") + args = parser.parse_args() + sdk = Path(__file__).resolve().parents[2] + path = args.source or sdk / "src/graphics/graphics_system.cpp" + source = path.read_text() + shutdown = function(source, "void GraphicsSystem::Shutdown()") + if args.legacy_order: + # Reverse only the two actual production teardown blocks. Detect the + # lifetime violation before allowing a destructor or stale dereference. + worker = function(shutdown, "if (vsync_worker_thread_)") + processor = function(shutdown, "if (command_processor_)") + assert shutdown.index(worker) < shutdown.index(processor) + shutdown = shutdown.replace(worker, "WORKER_BLOCK", 1) + shutdown = shutdown.replace(processor, worker, 1) + shutdown = shutdown.replace("WORKER_BLOCK", processor, 1) + bodies = shutdown + "\n" + "\n".join(function(source, signature) for signature in ( + "void GraphicsSystem::MarkVblank()", + "void GraphicsSystem::DispatchInterruptCallback(")) + code = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define assert_not_null(x) assert(x) +namespace rex { +template constexpr size_t countof(T (&)[N]) { return N; } +} +namespace rex::system { +struct XThread { + uint32_t cpu=0; + static XThread* GetCurrentThread() { static thread_local XThread thread; return &thread; } + void SetActiveCpu(uint32_t value) { cpu=value; } + void* thread_state() { return this; } +}; +} +namespace rex::graphics { +struct State { + std::mutex mutex; + std::condition_variable cv; + bool active=false, entered=false, permit=false, block_counter=false; + bool cp_stopped=false, cp_destroyed=false, worker_joined=false; + unsigned counter=0, callbacks=0, waits=0, ui_calls=0; + std::vector order; + void Park() { + std::unique_lock lock(mutex); entered=true; cv.notify_all(); + assert(cv.wait_for(lock,std::chrono::seconds(2),[&]{return permit;})); + } + void AwaitEntered() { + std::unique_lock lock(mutex); + assert(cv.wait_for(lock,std::chrono::seconds(2),[&]{return entered;})); + } + void Permit() { + { std::lock_guard lock(mutex); permit=true; } cv.notify_all(); + } +}; +struct Processor { + State& state; + explicit Processor(State& s):state(s){} + void increment_counter() { + assert(!state.cp_stopped && !state.cp_destroyed); + if(state.block_counter)state.Park(); + assert(!state.cp_stopped && !state.cp_destroyed); ++state.counter; + } + void Shutdown() { + if(state.active)throw std::runtime_error("vblank_processor_lifetime"); + assert(!state.cp_stopped); state.cp_stopped=true; state.order.push_back("cp_stop"); + } + ~Processor() { state.cp_destroyed=true; state.order.push_back("cp_destroy"); } +}; +struct Worker { + State& state; std::atomic& running; std::thread thread; + Worker(State& s,std::atomic& r,std::function body):state(s),running(r) { + { std::lock_guard lock(state.mutex); state.active=true; } + thread=std::thread([this,body]{ + body(); assert(!running.load()); + { std::lock_guard lock(state.mutex); state.active=false; } state.cv.notify_all(); + }); + } + void Wait(int a,int b,int c,void* timeout) { + assert(a==0 && b==0 && c==0 && !timeout && !running.load()); + ++state.waits; state.Permit(); thread.join(); state.worker_joined=true; + state.order.push_back("worker_join"); + } + ~Worker() { + // Also clean up the deliberate legacy failure without leaving a test + // worker behind; this path is not a replacement production teardown. + if(thread.joinable()){running=false;state.Permit();thread.join();} + state.order.push_back("worker_destroy"); + } +}; +struct Resource { + State& state; const char* name; + Resource(State& s,const char* n):state(s),name(n){} + ~Resource(){state.order.push_back(name);} +}; +struct Context { + State& state; + templatevoid CallInUIThreadSynchronous(Callback cb) { + ++state.ui_calls; cb(); + } +}; +struct GraphicsSystem; +struct Dispatcher { + State& state; GraphicsSystem* owner=nullptr; + void ExecuteInterrupt(void*,uint32_t,uint64_t[],size_t); +}; +struct GraphicsSystem { + State& state; + std::unique_ptr command_processor_; + std::atomic vsync_worker_running_{false}; + std::unique_ptr vsync_worker_thread_; + std::unique_ptr presenter_,provider_; + Context* app_context_=nullptr; + std::atomic interrupt_callback_state_{(uint64_t(0x82000000)<<32)|0x12345678}; + Dispatcher* function_dispatcher_; + GraphicsSystem(State& s,Dispatcher& d):state(s),function_dispatcher_(&d){d.owner=this;} + void Shutdown(); void MarkVblank(); void DispatchInterruptCallback(uint32_t,uint32_t); +}; +void Dispatcher::ExecuteInterrupt(void* thread,uint32_t callback,uint64_t args[],size_t count) { + assert(thread && callback==0x82000000 && count==2 && args[0]==0 && args[1]==0x12345678); + assert(static_cast(thread)->cpu==2); + if(!state.block_counter)state.Park(); + assert(owner->command_processor_ && !state.cp_stopped && !state.cp_destroyed); + // A final callback can need the command processor to remain operational. + owner->command_processor_->increment_counter(); ++state.callbacks; +} +''' + bodies + r''' +} // namespace rex::graphics +using namespace rex::graphics; +int main() { + try { + for(bool block_counter:{true,false})for(bool use_ui:{true,false}) { + State state;state.block_counter=block_counter;Dispatcher dispatcher{state}; + GraphicsSystem graphics(state,dispatcher);Context context{state}; + graphics.app_context_=use_ui?&context:nullptr; + graphics.command_processor_=std::make_unique(state); + graphics.presenter_=std::make_unique(state,"presenter_destroy"); + graphics.provider_=std::make_unique(state,"provider_destroy"); + graphics.vsync_worker_running_=true; + graphics.vsync_worker_thread_=std::make_unique(state,graphics.vsync_worker_running_, + [&]{graphics.MarkVblank();}); + state.AwaitEntered(); graphics.Shutdown(); + assert(state.counter==2 && state.callbacks==1 && state.waits==1 && state.worker_joined); + assert(state.ui_calls==unsigned(use_ui) && !graphics.vsync_worker_running_); + assert((state.order==std::vector{"worker_join","worker_destroy","cp_stop", + "cp_destroy","presenter_destroy","provider_destroy"})); + const auto order=state.order;graphics.Shutdown();assert(state.order==order && state.waits==1); + } + // Empty and partial setup remain safe; a missing worker does not require a wait. + for(bool cp:{false,true}) { + State state;Dispatcher dispatcher{state};GraphicsSystem graphics(state,dispatcher); + if(cp)graphics.command_processor_=std::make_unique(state); + graphics.Shutdown();graphics.Shutdown();assert(!state.waits); + assert(state.cp_stopped==cp && state.cp_destroyed==cp); + } + std::cout<<"PASS: in-flight vblank/callback joins before processor teardown; partial and repeated shutdown\n"; + } catch(const std::exception& error) { + std::cerr< +#include +#include +#include +#include +#define SCOPE_profile_cpu_f(...) ((void)0) +#define PROFILE_INTERRUPT_DISPATCHED() ((void)0) +#define assert_true(value) assert(value) +namespace memory { +templateT load_and_swap(const uint8_t* bytes){ + static_assert(sizeof(T)==4);T word=0; + for(unsigned i=0;i<4;++i)word=(word<<8)|bytes[i];return word; +} +templatevoid store_and_swap(uint8_t* bytes,T word){ + static_assert(sizeof(T)==4); + for(unsigned i=0;i<4;++i)bytes[i]=uint8_t(word>>(24-8*i)); +} +} +struct FixtureMemory { + std::array pcr{}; + uint8_t* TranslateVirtual(uint32_t address){assert(address==0x1000);return pcr.data();} +}; +struct Register {uint64_t u64=0;}; +struct Context {Register r3,r4,r5,r6,r7,r13;}; +struct ThreadState {Context ctx;Context* context(){return &ctx;}}; +struct CriticalRegion { + bool held=false; + struct Guard {CriticalRegion& owner;~Guard(){owner.held=false;}}; + Guard Acquire(){assert(!held);held=true;return Guard{*this};} +}; +struct FunctionDispatcher { + FixtureMemory* memory_; + CriticalRegion global_critical_region_; + std::array observed{}; + unsigned calls=0; + explicit FunctionDispatcher(FixtureMemory* memory):memory_(memory){} + bool Execute(ThreadState* thread,uint32_t address){ + ++calls;assert(global_critical_region_.held); + assert(memory::load_and_swap(memory_->pcr.data())==0); + auto* ctx=thread->context();observed={ctx->r3.u64,ctx->r4.u64,ctx->r5.u64,ctx->r6.u64,ctx->r7.u64}; + if(address==0xDEAD)return false; + assert(address==0x82000000);ctx->r3.u64=0x123456789ABCDEF0ull;return true; + } + uint64_t ExecuteInterrupt(ThreadState*,uint32_t,uint64_t[],size_t); +}; +''' + body + r''' +int main(){ + FixtureMemory memory_space;FunctionDispatcher dispatcher(&memory_space); + uint64_t args[]={0x1111222233334444ull,0x2222333344445555ull, + 0x3333444455556666ull,0x4444555566667777ull,0x5555666677778888ull}; + for(uint32_t tls:{0u,0x10203040u,0xFFFFFFFFu}){ + for(unsigned count=0;count<=5;++count){ + for(bool success:{false,true}){ + ThreadState thread;thread.ctx.r13.u64=0x1000; + thread.ctx.r3.u64=3;thread.ctx.r4.u64=4;thread.ctx.r5.u64=5; + thread.ctx.r6.u64=6;thread.ctx.r7.u64=7; + memory::store_and_swap(memory_space.pcr.data(),tls); + const auto result=dispatcher.ExecuteInterrupt(&thread, + success?0x82000000u:0xDEADu,args,count); + assert(result==(success?0x123456789ABCDEF0ull:0xDEADBABEull)); + assert(memory::load_and_swap(memory_space.pcr.data())==tls); + assert(!dispatcher.global_critical_region_.held); + for(unsigned i=0;i<5;++i)assert(dispatcher.observed[i]==(i= 0: + truncate = block(source, condition) + else: + truncate = source[truncate_start:source.index(";", truncate_start) + 1] + return prefix, loop, truncate + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--compiler", default="clang++") + parser.add_argument("--d3d-source", type=Path) + parser.add_argument("--vulkan-source", type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + sdk = root + paths = [args.d3d_source or sdk / "src/graphics/d3d12/pipeline_cache.cpp", + args.vulkan_source or sdk / "src/graphics/vulkan/pipeline_cache.cpp"] + harness = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define XXH_INLINE_ALL +#include +#define REXGPU_WARN(...) ((void)0) +bool fail_size_query=false; +namespace rex {namespace filesystem { +bool Seek(FILE* file,int64_t offset,int origin){ + if(fail_size_query&&origin==SEEK_END)return false;return fseeko(file,offset,origin)==0; +} +int64_t Tell(FILE* file){return ftello(file);} +bool TruncateStdioFile(FILE* file,uint64_t length){ + return !fflush(file)&&!ftruncate(fileno(file),off_t(length))&&fseeko(file,0,SEEK_END)==0; +} +}} +#pragma pack(push,1) +struct ShaderStoredHeader {uint64_t ucode_data_hash;uint32_t ucode_dword_count:31;uint32_t type:1;}; +#pragma pack(pop) +struct FileHeader {uint32_t magic=0x48534558,version=0x19122020;}; +static_assert(sizeof(ShaderStoredHeader)==12); +uint32_t resize_calls=0,max_resize=0; +struct CheckedWords:std::vector { + void resize(size_t count){ + ++resize_calls;max_resize=std::max(max_resize,uint32_t(count)); + // Old production code trips this assertion, rather than allocating gigabytes. + assert(count<=4096);std::vector::resize(count); + } +}; +''' + for name, path in zip(("D3D", "Vulkan"), paths): + prefix, loop, truncate = reader(path.read_text()) + harness += "std::vector> Load" + name + r'''(const std::filesystem::path& path){ + FILE* shader_storage_file_=fopen(path.c_str(),"a+b");assert(shader_storage_file_); + assert(fseeko(shader_storage_file_,0,SEEK_SET)==0); + FileHeader shader_storage_file_header; + assert(fread(&shader_storage_file_header,sizeof(shader_storage_file_header),1,shader_storage_file_)==1); + std::vector> loaded; + ShaderStoredHeader shader_header;CheckedWords ucode_dwords; +''' + harness += prefix + loop + r''' + loaded.push_back(ucode_dwords); + } +''' + truncate + r''' + assert(!fclose(shader_storage_file_));return loaded; +} +''' + harness += r''' +using Payload=std::vector; +using Reader=std::vector(*)(const std::filesystem::path&); +void Write(const std::filesystem::path& path,const std::vector& payloads, + uint32_t corrupt_count=0,bool torn_header=false,bool bad_hash=false){ + FILE* file=fopen(path.c_str(),"wb");assert(file);FileHeader header; + assert(fwrite(&header,sizeof(header),1,file)==1); + for(const auto& payload:payloads){ + ShaderStoredHeader record{};record.ucode_dword_count=uint32_t(payload.size()); + record.ucode_data_hash=XXH3_64bits(payload.data(),payload.size()*4); + if(bad_hash)record.ucode_data_hash^=1; + assert(fwrite(&record,sizeof(record),1,file)==1); + if(!payload.empty())assert(fwrite(payload.data(),payload.size()*4,1,file)==1); + } + if(corrupt_count||torn_header){ + ShaderStoredHeader record{};record.ucode_dword_count=corrupt_count; + assert(fwrite(&record,torn_header?5:sizeof(record),1,file)==1); + } + assert(!fclose(file)); +} +std::vector Bytes(const std::filesystem::path& path){ + std::ifstream input(path,std::ios::binary);return {std::istreambuf_iterator(input),{}}; +} +int main(int argc,char** argv){ + assert(argc==2);const std::filesystem::path directory=argv[1]; + const auto path=directory/"shader.xsh",expected=directory/"expected.xsh"; + const std::vector valid{{1,2,3},Payload(300,0x12345678),{9}}; + for(Reader load:{&LoadD3D,&LoadVulkan}){ + Write(path,valid);const auto original=Bytes(path);resize_calls=max_resize=0; + assert(load(path)==valid&&resize_calls==3&&max_resize==300); + assert(Bytes(path)==original&&load(path)==valid); + for(uint32_t count:{1u,4097u,0x7FFFFFFFu}){ + // The corrupt suffix advertises up to8GiB but has no payload bytes. + Write(path,valid,count);Write(expected,valid);resize_calls=max_resize=0; + assert(load(path)==valid&&resize_calls==3&&max_resize==300); + assert(Bytes(path)==Bytes(expected)&&load(path)==valid); + Write(path,{},count);Write(expected,{});resize_calls=0; + assert(load(path).empty()&&resize_calls==0&&Bytes(path)==Bytes(expected)); + } + Write(path,valid,0,true);Write(expected,valid);resize_calls=0; + assert(load(path)==valid&&resize_calls==3&&Bytes(path)==Bytes(expected)); + Write(path,{},0,true);Write(expected,{});resize_calls=0; + assert(load(path).empty()&&resize_calls==0&&Bytes(path)==Bytes(expected)); + Write(path,{{1,2}},0,false,true);Write(expected,{});resize_calls=0; + assert(load(path).empty()&&resize_calls==1&&Bytes(path)==Bytes(expected)); + // Failure to size a readable file must not destructively truncate its cache. + Write(path,valid);const auto intact=Bytes(path);fail_size_query=true;resize_calls=0; + assert(load(path).empty()&&resize_calls==0&&Bytes(path)==intact); + fail_size_query=false;assert(load(path)==valid); + } + std::cout<<"PASS: D3D/Vulkan shader-cache counts bounded before allocation; valid prefix preserved.\n"; +} +''' + args.output.mkdir(parents=True, exist_ok=True) + source = args.output.resolve() / "shader-cache-bounds.cpp" + exe = args.output.resolve() / "shader-cache-bounds" + source.write_text(harness) + subprocess.run([args.compiler, "-std=c++20", "-UNDEBUG", + "-I" + str(sdk / "thirdparty/xxHash"), str(source), "-o", str(exe)], + check=True, timeout=45) + subprocess.run([str(exe), str(args.output.resolve())], check=True, timeout=10) + + +if __name__ == "__main__": + main() diff --git a/tests/regression/test_vulkan_pipeline_storage.py b/tests/regression/test_vulkan_pipeline_storage.py new file mode 100644 index 0000000..081f458 --- /dev/null +++ b/tests/regression/test_vulkan_pipeline_storage.py @@ -0,0 +1,152 @@ +"""Run production Vulkan cache load/truncation blocks against real temporary files.""" +import argparse +from pathlib import Path +import subprocess + + +def block(source, start): + end = source.index("{", start) + 1 + depth = 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--compiler", default="clang++") + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + production = (root / "src/graphics/vulkan/pipeline_cache.cpp").read_text() + declaration_start = production.index(" std::vector pipeline_stored_descriptions;") + declarations = production[declaration_start:production.index(" // > shader_translations_needed; +''' + harness += declarations + header_and_load + truncation + r''' + std::vector kept; + for(const auto& record:pipeline_stored_descriptions)kept.push_back(record.description.vertex_shader_hash); + assert(!fclose(pipeline_storage_file_));return kept; +} +struct Header {uint32_t magic=0x53504558,api=0,version=rex::byte_swap(1);}; +PipelineStoredDescription Record(uint64_t id,bool unsupported=false,bool corrupt=false){ + PipelineStoredDescription record{};record.description.vertex_shader_hash=id; + record.description.vertex_shader_modification=unsupported?1:0; + record.description_hash=XXH3_64bits(&record.description,sizeof(record.description)); + if(corrupt)record.description_hash^=1;return record; +} +void Write(const std::filesystem::path& path,const std::vector& records,bool torn=false){ + FILE* file=fopen(path.c_str(),"wb");assert(file);Header header; + assert(fwrite(&header,sizeof(header),1,file)==1); + for(const auto& record:records)assert(fwrite(&record,sizeof(record),1,file)==1); + if(torn){auto record=Record(99);assert(fwrite(&record,7,1,file)==1);} + assert(!fclose(file)); +} +std::vector Bytes(const std::filesystem::path& path){ + std::ifstream input(path,std::ios::binary);return {std::istreambuf_iterator(input),{}}; +} +void AssertDisk(const std::filesystem::path& actual,const std::filesystem::path& expected, + const std::vector& records){ + Write(expected,records);assert(Bytes(actual)==Bytes(expected)); +} +int main(int argc,char** argv){ + assert(argc==2);const std::filesystem::path directory=argv[1]; + const auto file=directory/"cache.xpso",expected=directory/"expected.xpso"; + { + const auto a=Record(1,true),b=Record(2),c=Record(3); + Write(file,{a,b,c});assert((Load(file,false)==std::vector{2,3})); + AssertDisk(file,expected,{a,b,c}); + assert((Load(file,false)==std::vector{2,3}));AssertDisk(file,expected,{a,b,c}); + assert((Load(file,true)==std::vector{1,2,3})); + } + { + const auto a=Record(4,true),b=Record(5,true); + Write(file,{a,b});assert(Load(file,false).empty());AssertDisk(file,expected,{a,b}); + assert(Load(file,false).empty());AssertDisk(file,expected,{a,b}); + assert((Load(file,true)==std::vector{4,5})); + } + { + const auto a=Record(6),b=Record(7,true),c=Record(8,false,true),d=Record(9); + Write(file,{a,b,c,d});assert((Load(file,false)==std::vector{6})); + AssertDisk(file,expected,{a,b});assert((Load(file,false)==std::vector{6})); + assert((Load(file,true)==std::vector{6,7})); + } + { + const auto a=Record(10,true),b=Record(11); + Write(file,{a,b},true);assert((Load(file,false)==std::vector{11})); + AssertDisk(file,expected,{a,b});assert((Load(file,true)==std::vector{10,11})); + } + { + Write(file,{Record(12,false,true),Record(13)});assert(Load(file,false).empty()); + AssertDisk(file,expected,{});assert(Load(file,true).empty()); + } + { + const auto unsupported=Record(14,true),appended=Record(15); + Write(file,{unsupported});assert(Load(file,false).empty()); + FILE* stream=fopen(file.c_str(),"ab");assert(stream); + assert(fwrite(&appended,sizeof(appended),1,stream)==1);assert(!fclose(stream)); + assert((Load(file,false)==std::vector{15})); + AssertDisk(file,expected,{unsupported,appended}); + } + std::cout<<"PASS: Vulkan pipeline filtering preserves valid disk records across repeated loads and append.\n"; +} +''' + args.output.mkdir(parents=True, exist_ok=True) + source = args.output.resolve() / "vulkan-pipeline-storage.cpp" + exe = args.output.resolve() / "vulkan-pipeline-storage" + source.write_text(harness) + subprocess.run([args.compiler, "-std=c++20", "-UNDEBUG", + "-I" + str(root / "thirdparty/xxHash"), + str(source), "-o", str(exe)], check=True, timeout=45) + subprocess.run([str(exe), str(args.output.resolve())], check=True, timeout=10) + + +if __name__ == "__main__": + main() From e486d9983fd8d0f1ef3e526a55067b56768b421e Mon Sep 17 00:00:00 2001 From: AlenHay <82121826+AlenHay@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:50:06 +0200 Subject: [PATCH 3/3] Keep the runtime dispatcher published until final workers join Delay singleton removal until graphics, audio, input, and kernel shutdown complete, then clear it before dispatcher destruction. This keeps final indirect guest callbacks resolvable. Production-body concurrent fixture covers partial/repeated teardown, failure retry, foreign instance ownership, and the old early-clear failure. This does not solve existing guest thread stragglers or arbitrary concurrent runtime destruction. --- src/system/runtime.cpp | 10 +- tests/CMakeLists.txt | 2 +- tests/regression/test_runtime_shutdown.py | 214 ++++++++++++++++++++++ 3 files changed, 221 insertions(+), 5 deletions(-) create mode 100644 tests/regression/test_runtime_shutdown.py diff --git a/src/system/runtime.cpp b/src/system/runtime.cpp index 3d85e79..bdf69fb 100644 --- a/src/system/runtime.cpp +++ b/src/system/runtime.cpp @@ -272,10 +272,6 @@ void Runtime::Shutdown() { return; } - if (instance_ == this) { - instance_ = nullptr; - } - if (graphics_system_) { graphics_system_->Shutdown(); graphics_system_.reset(); @@ -289,6 +285,12 @@ void Runtime::Shutdown() { input_system_.reset(); } kernel_state_.reset(); + // Joined GPU/audio/kernel workers may make final indirect guest calls during + // shutdown. Keep their dispatcher reachable until those workers have stopped, + // then unpublish before destroying the dispatcher and its backing memory. + if (instance_ == this) { + instance_ = nullptr; + } function_dispatcher_.reset(); export_resolver_.reset(); file_system_.reset(); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a482a21..db457d5 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -16,7 +16,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU") find_package(Python3 COMPONENTS Interpreter QUIET) if(Python3_Interpreter_FOUND) - set(REXGLUE_REGRESSION_CHECKS app_launch timer_wait timer_lifecycle interrupt_tls graphics_interrupt_concurrency graphics_shutdown + set(REXGLUE_REGRESSION_CHECKS app_launch timer_wait timer_lifecycle interrupt_tls graphics_interrupt_concurrency graphics_shutdown runtime_shutdown vulkan_pipeline_storage shader_cache_bounds) foreach(check IN LISTS REXGLUE_REGRESSION_CHECKS) add_test(NAME regression_${check} diff --git a/tests/regression/test_runtime_shutdown.py b/tests/regression/test_runtime_shutdown.py new file mode 100644 index 0000000..1acead6 --- /dev/null +++ b/tests/regression/test_runtime_shutdown.py @@ -0,0 +1,214 @@ +"""Keep real final-worker indirect resolution valid through production shutdown.""" +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + + +def function(source, signature): + start = source.index(signature) + end = source.index('{', start) + 1 + depth = 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('output', type=Path) + parser.add_argument('--compiler', default='clang++') + parser.add_argument('--legacy-order', action='store_true') + args = parser.parse_args() + sdk = Path(__file__).resolve().parents[2] + source = (sdk/'src/system/runtime.cpp').read_text() + dispatcher = (sdk/'src/system/function_dispatcher.cpp').read_text() + shutdown = function(source, 'void Runtime::Shutdown()') + if args.legacy_order: + clear = function(shutdown, 'if (instance_ == this)') + assert shutdown.index(clear) > shutdown.index('kernel_state_.reset();') + shutdown = shutdown.replace(clear, '', 1) + shutdown = shutdown.replace(' if (graphics_system_) {', clear+'\n if (graphics_system_) {', 1) + getters = function(source, 'Runtime* Runtime::instance()') + bound = function(dispatcher, 'FunctionDispatcher* GetBoundFunctionDispatcher()') + resolve = function(dispatcher, 'PPCFunc* ResolveIndirectFunction(') + code = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace rex { +using PPCFunc=void(); +struct State { + std::mutex mutex;std::condition_variable cv; + bool entered=false,permit=false;unsigned callbacks=0,profiler_stops=0; + std::atomic resolution_failed{false};std::vector events; + void Event(const char* text){events.push_back(text);} + void Require(bool value,const char* name){if(!value)throw std::runtime_error(name);} +}; +State* active_state; +void Guest(){++active_state->callbacks;} +namespace runtime { +struct FunctionDispatcher { + State& state;bool must_be_unpublished; + FunctionDispatcher(State& s,bool owned=true):state(s),must_be_unpublished(owned){} + PPCFunc* GetFunction(uint32_t address){return address==0x82000000?&Guest:nullptr;} + ~FunctionDispatcher(); +}; +void InvalidFunctionTrap(){} +PPCFunc* ResolveIndirectFunction(uint32_t); +} +class Runtime; +struct Resource { + State& state;const char* name;bool must_be_unpublished; + Resource(State& s,const char* n,bool owned=true):state(s),name(n),must_be_unpublished(owned){} + ~Resource(); +}; +struct Service { + State& state;const char* name;bool fail_shutdown=false; + std::thread worker; + Service(State& s,const char* n,bool start_worker=false); + void Shutdown();void Join(); + ~Service(){Join();state.Event(name);} +}; +struct Kernel { + State& state;std::unique_ptr worker; + Kernel(State& s,bool start_worker=false):state(s){ + if(start_worker)worker=std::make_unique(s,"kernel_worker_destroy",true); + } + ~Kernel(){if(worker)worker->Join();state.Event("kernel_destroy");} +}; +class Runtime { +public: + static Runtime* instance_;bool setup_complete_=false; + std::unique_ptr graphics_system_,audio_system_,input_system_; + std::unique_ptr kernel_state_; + std::unique_ptr function_dispatcher_; + std::unique_ptr export_resolver_,file_system_,memory_; + static Runtime* instance();void Shutdown(); + runtime::FunctionDispatcher* function_dispatcher(){return function_dispatcher_.get();} +}; +Runtime* Runtime::instance_=nullptr; +namespace perf {struct Profiler{static void Shutdown(){++active_state->profiler_stops;active_state->Event("profiler_stop");}};} +''' + getters + '\nnamespace runtime {\n' + bound + '\n' + resolve + r''' +FunctionDispatcher::~FunctionDispatcher(){ + state.Require(!must_be_unpublished||!Runtime::instance(),"dispatcher_destroyed_while_published"); + state.Event("dispatcher_destroy"); +} +} // runtime +Resource::~Resource(){ + state.Require(!must_be_unpublished||!Runtime::instance(),"backing_resource_destroyed_while_published");state.Event(name); +} +Service::Service(State& s,const char* n,bool start_worker):state(s),name(n){ + if(!start_worker)return; + worker=std::thread([this]{ + {std::unique_lock lock(state.mutex);state.entered=true;state.cv.notify_all(); + if(!state.cv.wait_for(lock,std::chrono::seconds(2),[&]{return state.permit;})){ + state.resolution_failed=true;return; + }} + // Actual global-bound resolver is called after the service's stop begins. + auto* owner=Runtime::instance(); + PPCFunc* target=runtime::ResolveIndirectFunction(0x82000000); + if(!owner||!owner->memory_||target!=&Guest)state.resolution_failed=true; + else target(); + }); + std::unique_lock lock(state.mutex); + state.Require(state.cv.wait_for(lock,std::chrono::seconds(2),[&]{return state.entered;}),"worker_setup_timeout"); +} +void Service::Join(){ + if(!worker.joinable())return; + {std::lock_guard lock(state.mutex);state.permit=true;}state.cv.notify_all();worker.join(); +} +void Service::Shutdown(){ + state.Event(name); + if(fail_shutdown)throw std::runtime_error("service_shutdown_fixture_failure"); + Join();state.Require(!state.resolution_failed,"final_worker_indirect_resolution"); +} +''' + shutdown + r''' +} // rex +using namespace rex; +void Populate(Runtime& owner,State& state,int worker_kind){ + active_state=&state;Runtime::instance_=&owner;owner.setup_complete_=true; + owner.function_dispatcher_=std::make_unique(state); + owner.memory_=std::make_unique(state,"memory_destroy"); + owner.export_resolver_=std::make_unique(state,"resolver_destroy"); + owner.file_system_=std::make_unique(state,"filesystem_destroy"); + owner.graphics_system_=std::make_unique(state,"graphics",worker_kind==0); + owner.audio_system_=std::make_unique(state,"audio",worker_kind==1); + owner.input_system_=std::make_unique(state,"input"); + owner.kernel_state_=std::make_unique(state,worker_kind==2); +} +int main(){try{ + // Each joining lifecycle boundary retains the actual indirect resolver. + for(int worker_kind=0;worker_kind<3;++worker_kind){ + State state;Runtime owner;Populate(owner,state,worker_kind);owner.Shutdown(); + state.Require(!state.resolution_failed&&state.callbacks==1,"final_worker_indirect_resolution"); + assert(!Runtime::instance_&&!owner.setup_complete_&&!owner.memory_&&!owner.function_dispatcher_); + std::vector expected{"graphics","graphics","audio","audio","input","input","kernel_destroy"}; + if(worker_kind==2)expected.push_back("kernel_worker_destroy"); + for(const auto* event:{"dispatcher_destroy","resolver_destroy","filesystem_destroy","memory_destroy","profiler_stop"}) + expected.push_back(event); + assert(state.events==expected); + const auto events=state.events;owner.Shutdown();assert(state.events==events&&state.profiler_stops==1); + } + // Setup failure may have published the runtime before any backing object exists. + for(bool memory:{false,true}){ + State state;active_state=&state;Runtime owner;Runtime::instance_=&owner; + if(memory)owner.memory_=std::make_unique(state,"memory_destroy"); + owner.Shutdown();assert(!Runtime::instance_&&!owner.memory_&&!owner.setup_complete_); + const auto calls=state.profiler_stops;owner.Shutdown();assert(state.profiler_stops==calls); + } + // A service failure preserves publication until a later successful cleanup. + { + State state;Runtime owner;Populate(owner,state,-1);owner.graphics_system_->fail_shutdown=true; + bool failed=false;try{owner.Shutdown();}catch(const std::runtime_error& error){ + failed=std::string(error.what())=="service_shutdown_fixture_failure";} + assert(failed&&Runtime::instance_==&owner&&owner.memory_&&owner.function_dispatcher_); + assert(runtime::ResolveIndirectFunction(0x82000000)==&Guest); + owner.graphics_system_->fail_shutdown=false;owner.Shutdown();assert(!Runtime::instance_); + } + // An inactive/foreign runtime must not unpublish another runtime's dispatcher. + { + State state;active_state=&state;Runtime live,foreign;Runtime::instance_=&live; + live.function_dispatcher_=std::make_unique(state,false); + foreign.Shutdown();assert(Runtime::instance_==&live); + assert(runtime::ResolveIndirectFunction(0x82000000)==&Guest);Runtime::instance_=nullptr; + } + // Completely inactive shutdown remains a no-op. + {State state;active_state=&state;Runtime owner;owner.Shutdown();assert(state.events.empty());} + std::cout<<"PASS: production shutdown/final-worker indirect resolution, partial/repeat/failure/foreign ownership\n"; +}catch(const std::exception& error){std::cerr<