From 7979fff16cfd40a5458904a90bf224785ef3d83a Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 21:52:31 +0300 Subject: [PATCH] Advance the authoritative world on a fixed background clock --- CMakeLists.txt | 6 +- docs/agent-workflow/tasks/S01-04.md | 48 +++ docs/plan/systems/S01.md | 8 + .../settlement/core/simulation_runtime.hpp | 100 +++++ engine/src/simulation_runtime.cpp | 372 ++++++++++++++++ tests/runtime_tests.cpp | 398 ++++++++++++++++++ 6 files changed, 930 insertions(+), 2 deletions(-) create mode 100644 docs/agent-workflow/tasks/S01-04.md create mode 100644 engine/include/settlement/core/simulation_runtime.hpp create mode 100644 engine/src/simulation_runtime.cpp create mode 100644 tests/runtime_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 16702fc..258f3ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,7 +23,7 @@ function(add_void_library) set(BUILD_SHARED_LIBS OFF) set(VOID_ENABLE_TESTING OFF) set(VOID_ENABLE_BENCHMARKS OFF) - set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text) + set(VOID_ENABLED_MODULES Algorithms Async Binary Core Crypto Data Text Time) set(CMAKE_DISABLE_FIND_PACKAGE_OpenSSL ON) if(BUILD_TESTING) list(APPEND VOID_ENABLED_MODULES Testing) @@ -44,6 +44,7 @@ add_library(settlement_core engine/src/first_colony.cpp engine/src/rules_manifest.cpp engine/src/save_service_win32.cpp + engine/src/simulation_runtime.cpp engine/src/worker_pool.cpp engine/src/world.cpp engine/src/world_save.cpp @@ -56,7 +57,7 @@ target_include_directories(settlement_core target_compile_features(settlement_core PUBLIC cxx_std_23) target_link_libraries(settlement_core - PUBLIC Threads::Threads Void::Async Void::Core + PUBLIC Threads::Threads Void::Async Void::Core Void::Time PRIVATE Void::Algorithms Void::Binary Void::Crypto Void::Data Void::Text ) @@ -115,6 +116,7 @@ if(BUILD_TESTING) tests/executor_tests.cpp tests/replay_tests.cpp tests/rules_tests.cpp + tests/runtime_tests.cpp tests/save_service_tests.cpp tests/session_tests.cpp tests/snapshot_tests.cpp diff --git a/docs/agent-workflow/tasks/S01-04.md b/docs/agent-workflow/tasks/S01-04.md new file mode 100644 index 0000000..e086b47 --- /dev/null +++ b/docs/agent-workflow/tasks/S01-04.md @@ -0,0 +1,48 @@ +# Run the single-owner simulation clock and publish committed snapshots + +Task ID: S01-04 +Role: astra_implementer +Status: READY + +## 1. Context and baseline +Exclusive s01 checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01 fast-forwarded to 2224299. Actual S01::World::capture, S16 CommandDispatcher+SessionIdentity and S15 WorldCheckpoint + rules exist in this tree; S01/S19/S15/S16 reviews M01-V3/V4/V5. M01-F3 defines fault, epoch, capacity, and load fencing. Pin 7b0fea6 provides Time::MonotonicClock/SystemMonotonicClock/ManualClock, Uuid::try_v4, Async executor. Public library snapshot gap https://git.faumaray.com/Void/Library/issues/5. + +## 2. Objective and deliverables +Build NEW SimulationRuntime, sole mutable World owner on a background worker, 20 Hz at normal speed and real immutable publications. Provide a usable asynchronous adapter for commands, save capture and load replacement before later viewer integration. + +## 3. Scope and non-goals +Core scheduler, snapshot, bounded commands, validated installs, compatibility with existing serial/parallel World, tests/docs. UI, LAN packet codec, file dialogs, disk decoding/reading, stable-ID internals and content selection UI have other owners. Keep standalone old World entry points compatible. + +## 4. Files to inspect +Inspect actual engine/include/settlement/core/{world,command_dispatcher,checkpoint,save_service,rules_manifest}.hpp + implementations, app/viewer_win32.cpp timer/menu/pause/command placement, M01-F3 and relevant systems, pinned Void/Time/Clock.hpp, Void/Core/Uuid.hpp and Void/Async. Use stage barrier capture() exactly as documented. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; tests/runtime_tests.cpp; CMakeLists.txt; docs/plan/systems/S01.md +Do not change any other worktree, Git refs, existing command/save interfaces or shared Serena activation. You are not alone; other workers own viewer, library and custody concerns. + +## 6. Implementation or investigation approach +Single mutable owner, initial validated WorldCheckpoint (already contains stable world_id, city, rules) or explicit initial equivalent. Generate ephemeral session UUID for each start/install, including rollback of the same stable world. One stable PublishedSnapshot (identity/tick/publication revision, shared_ptr, shared immutable RulesManifest, command request metadata as needed). publish prepared snapshot/ledger results only after complete tick or command. Reader snapshot retrieval never waits for a tick or disk work. On any active tick/command/preparation exception: retain previous publication, drop/disable partial working world and uncommitted ledger, make observable Faulted, complete queued futures predictably, retain old exact committed receipt lookup. Ordinary domain rejection and failed install/file validation leave healthy owner alive. Keep owner responsive to queued work while paused, external presentation suspend independent from in-game pause. Target fixed logical 50 ms steps using pinned MonotonicClock; process elapsed debt deterministically bounded per pass, no starvation or time skipping; re-anchor on suspend/paused/resume so idle time cannot burst into gameplay. Provide manual-clock wake/test barrier so tests avoid arbitrary sleeps. Publish revision changes even for accepted commands at equal tick. Use atomic or short critical sections, no locks around World::step/capture, I/O or joining. Efficient ledger staging: avoid copying the ledger on each tick or replay. Unexpected post-effect failures never return success. + +## 7. Interfaces and data contracts +Expose a bounded try_submit(TrustedClient, CommandEnvelope) + future/typed result with immediate admission outcomes and safe always-completed accepted requests. Allow viewer to allocate correct contiguous per-client IDs (normal local queue/order and retries). Provide trusted read-only snapshot for UI and a coherent capture_for_save that checks health at its linearization point. Expose begin_load()/install(ticket, independently validated WorldCheckpoint) or equivalent with latest requested serial and expected active epoch, rechecked immediately before publication incl concurrent newer load during preparation. Failed/superseded install keeps current publication/owner/ledger. Honor F3 even if faulted and guarantee recovery by a valid newest load. A fresh epoch discards old command history and fences stale commands/errors. Provide a simple clock notification or deterministic owner fence for tests. Communicate frozen signatures early to root; UI/transport packages depend on them. + +## 8. Dependencies and integration +Root owns CMake integration, app adapters, Gitea and current ports. Runtime must be usable from Win32 WM_TIMER to poll latest view and command futures while rendering. Prefer existing Void supported primitive for generic work/time (standard condition-variable/synchronization where appropriate). Service writer owns disk background; use capture API without calling writer on the owner thread. Link #5 + replacement criterion in docs. Default config limits consistent with existing M01 subsystems. + +## 9. Edge cases security and performance +Stress lifecycle races: complete all accepted work on shutdown with normal/Closed/Faulted status, no borrowed tasks after World destruction, success never races visibility. New accepted work has deterministic FIFO/admission and explicit capacity; ensure load recovery possible after fault, old work only commits in old session. Faulted current view still valid for read-only rendering. UUID/allocation failures during load leave old state unchanged. Document shared snapshot ownership memory tradeoff. Test reads return previous stable view while deliberately blocked tick is running. Determine nonfatal invalid inputs before owner mutation. + +## 10. Acceptance criteria +1. Under manual time, exactly 20 ticks per second (or observe per step) with same canonical data as direct reference. Commands can pause/unpause while no ticks progress, same-tick publications update. 2. Two clients exact repeats, old session after rollback, altered payload, load supersession, capacity and orderly shutdown. 3. Inject stage failure / after command mutation / snapshot preparation, verify last publication and committed receipts survive, no fresh mutation/save silently succeeds, queue futures all settle, valid load recovers cleanly. 4. Gate real long tick and show a UI reader and immutable save capture return previous completed state. 5. Whole x64 Wine suite passes, no native claim. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/runtime-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Run wine /settlement_core_tests.exe --tag runtime, full verbose CTest, git diff --check. Name logs runtime-* under /tmp/stoneheart-milestones.xprJ2SVp. Communicate before schedule/contract changes. + +## 12. Constraints and stop conditions +No external services, branches/commits/push, children or template frameworks. Stop if a shared API makes F3 impossible. Two failed fixes for same problem -> distinguish failure and escalate to parent for re-diagnosis. No scheduling behavior on UI or disk paths. + +## 13. Authorization and decisions +User authorizes whole roadmap, separate system branches and PRs. Planner/preflight M01-F3 and reviewed implementations freeze the conditions. Root decides integration and release separately. + +## 14. Return format +Return S01-04 status, early exact public header/contract for viewer, concrete timing/fault/install/ID outcomes, files, actual compile/tests/counts, open native or integration limitations. No subagents. diff --git a/docs/plan/systems/S01.md b/docs/plan/systems/S01.md index 476b5f7..b80608c 100644 --- a/docs/plan/systems/S01.md +++ b/docs/plan/systems/S01.md @@ -69,6 +69,14 @@ ## Приёмка +В срезе S01-04 `SimulationRuntime` владеет изменяемым миром в отдельном потоке Void. Шаг соответствует 50 мс монотонных часов. Очередь допускает по умолчанию 256 операций вместе с исполняемой, а перегрузка возвращает `Busy`. После каждой операции владелец может выполнить один просроченный такт, сохраняя обслуживание команд. Пауза мира и остановка тактов из-за меню имеют отдельные состояния. При продолжении отсчёт начинается заново. [Интерфейс владельца](../../../engine/include/settlement/core/simulation_runtime.hpp) + +Публикация содержит UUID мира и инкарнации, ревизию, неизменяемые мир и правила, следующие номера запросов двух клиентов. `latest()` возвращает последний завершённый снимок, а `snapshot_for_save()` дополнительно проверяет рабочее состояние владельца. Читатель может удерживать предыдущие поколения, поэтому потребление памяти зависит от числа таких ссылок. Новая команда подготавливает копию журнала квитанций. Потактное продвижение и точные повторы используют уже опубликованный журнал. + +Исключение при такте, команде или подготовке публикации переводит владельца в `Faulted`. Предыдущий снимок и завершённые квитанции доступны для чтения, новые изменения получают ошибку. Восстановление требует подходящего кандидата загрузки. `begin_load()` фиксирует текущую инкарнацию и номер запроса, который проверяется повторно непосредственно при переключении мира. Более новый запрос отменяет публикацию старого кандидата. Каждая успешная загрузка создаёт новую инкарнацию, в том числе при откате того же мира. + +Регрессии `--tag runtime` проверяют 20 тактов в секунду с управляемыми часами и эталон на 1/2/6/12 исполнителях, команды на паузе, чтение во время заблокированной задачи, отказы и восстановление, порядок загрузок, переполнение очереди и завершение принятых операций при выходе. Подключение окна к этому интерфейсу выполняется отдельным срезом. [Проверки владельца](../../../tests/runtime_tests.cpp) + На ветке `system/s01-simulation` три параллельные стадии мира используют закреплённые `Void::Async::ThreadExecutor` и `FuturePool`. При заполнении лимита координатор выполняет задание сам. Стадия дожидается ранее принятых заданий и при исключении. Последовательный эталон вызывает те же игровые операции. На журнале из 750 тактов канонические сохранения после каждого такта совпали у эталона и вариантов с 2, 6 и 12 потоками, в том числе при лимите одного задания и после загрузки в процессе переноски. [Исполнитель](../../../engine/include/settlement/core/worker_pool.hpp) · [Проверки отказов](../../../tests/executor_tests.cpp) · [Воспроизведение](../../../tests/replay_tests.cpp) В Windows x64-сборках под Wine при шести потоках медиана измерений p95 такта при переходе на Void изменилась с 86 до 96 мкс для 50 жителей и с 407 до 333 мкс для 500. Нативные замеры Windows, неизменяемая публикация завершённого такта и восстановление после ошибки остаются отдельными проверками. diff --git a/engine/include/settlement/core/simulation_runtime.hpp b/engine/include/settlement/core/simulation_runtime.hpp new file mode 100644 index 0000000..4e85ea7 --- /dev/null +++ b/engine/include/settlement/core/simulation_runtime.hpp @@ -0,0 +1,100 @@ +#pragma once + +#include "settlement/core/checkpoint.hpp" +#include "settlement/core/command_dispatcher.hpp" +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { + +enum class RuntimeState { Running, Faulted, Closed }; +enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted }; +enum class RuntimeOutcome { Completed, Faulted, Closed, Superseded, InvalidCandidate }; +enum class RuntimePhase { BeforeTick, BeforeCapture, BeforeInstallCapture }; + +struct PublishedSnapshot { + SessionIdentity identity; + std::uint64_t revision; + std::shared_ptr world; + std::shared_ptr rules; + std::array next_requests; +}; + +struct RuntimeView { + RuntimeState state; + std::shared_ptr snapshot; + std::exception_ptr failure; +}; + +struct RuntimeResult { + RuntimeOutcome outcome; + std::optional receipt; + std::shared_ptr snapshot; +}; + +struct RuntimeSubmission { + RuntimeAdmission admission; + std::future completion; +}; + +struct LoadTicket { + std::uint64_t request; + Void::Uuid::Uuid expected_session; +}; + +struct RuntimeOptions { + std::size_t capacity = 256; // Accepted operations, including the active operation. + bool ticking = true; // Presentation suspension is separate from World's pause. + std::shared_ptr clock; + CommandDispatcherOptions dispatcher; + // Runs on the owner thread. May block or throw for diagnostics/tests. + // Captures must outlive shutdown. Calling shutdown here throws logic_error. + std::function observer; +}; + +// A single background owner advances 50 ms logical steps and publishes independent +// immutable views. Supply a validated decoded checkpoint or an owned newly built +// world with a resolved manifest. No caller may retain mutable aliases to that world. +// Upstream publication replacement contract: https://git.faumaray.com/Void/Library/issues/5 +class SimulationRuntime { +public: + explicit SimulationRuntime(WorldCheckpoint initial, RuntimeOptions options = {}); + ~SimulationRuntime(); + SimulationRuntime(const SimulationRuntime&) = delete; + SimulationRuntime& operator=(const SimulationRuntime&) = delete; + + [[nodiscard]] std::shared_ptr latest() const; + [[nodiscard]] RuntimeView view() const; + [[nodiscard]] std::expected, RuntimeState> snapshot_for_save() const; + // Reads only the committed ledger, also available after a fault. + [[nodiscard]] std::optional lookup( + TrustedClient client, const CommandEnvelope& command) const; + [[nodiscard]] RuntimeSubmission try_submit(TrustedClient client, const CommandEnvelope& command); + [[nodiscard]] RuntimeSubmission set_ticking(bool enabled); + // Fences earlier queued operations and all eligible clock debt through the + // admission time. Advancing a ManualClock should be followed by this or notify_clock(). + [[nodiscard]] RuntimeSubmission synchronize(); + void notify_clock(); + + [[nodiscard]] std::expected begin_load(); + // Moves candidate only on Accepted. Latest ticket and epoch are checked again + // at publication. Invalid/superseded candidates leave the live party intact. + [[nodiscard]] RuntimeSubmission try_install(LoadTicket ticket, WorldCheckpoint& candidate); + // Closes admission, settles queued futures as Closed, and joins the active + // operation. Safe concurrently with submissions and other shutdown calls. + // Object destruction itself requires callers to have stopped using the object. + void shutdown(); + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace settlement diff --git a/engine/src/simulation_runtime.cpp b/engine/src/simulation_runtime.cpp new file mode 100644 index 0000000..2bbcd2c --- /dev/null +++ b/engine/src/simulation_runtime.cpp @@ -0,0 +1,372 @@ +#include "settlement/core/simulation_runtime.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { +namespace { +using Clock = Void::Time::MonotonicClock; +constexpr auto tick_interval = std::chrono::milliseconds(50); + +SessionIdentity new_identity(const WorldCheckpoint& checkpoint) { + if (!checkpoint.world || checkpoint.world_id.is_nil() || checkpoint.city == 0) { + throw std::invalid_argument("runtime requires a world, nonnil identity and a city"); + } + const auto session = Void::Uuid::try_v4(); + if (!session) throw std::runtime_error("cannot generate a simulation session UUID"); + return {checkpoint.world_id, *session, checkpoint.city}; +} + +std::shared_ptr capture( + const World& world, const CommandDispatcher& dispatcher, + std::shared_ptr rules, std::uint64_t revision) { + std::array next{}; + for (std::size_t i = 0; i < next.size(); ++i) { + next[i] = dispatcher.next_request({static_cast(i + colony_host)}); + } + return std::make_shared( + dispatcher.identity(), revision, world.capture(), std::move(rules), next); +} +} // namespace + +struct SimulationRuntime::Impl { + enum class Kind { Command, Ticking, Fence, Install }; + struct Work { + Kind kind; + TrustedClient client{}; + CommandEnvelope command{}; + bool enabled = false; + Clock::time_point deadline{}; + LoadTicket ticket{}; + std::optional candidate; + std::promise promise; + explicit Work(Kind value) : kind(value) {} + }; + + RuntimeOptions options; + std::shared_ptr clock; + std::unique_ptr world; + mutable std::mutex mutex; + std::condition_variable changed; + std::deque> queue; + std::size_t outstanding = 0; + std::uint64_t latest_load = 0; + RuntimeState state = RuntimeState::Running; + std::exception_ptr failure; + std::shared_ptr published; + std::shared_ptr committed; + std::atomic stopping{false}; + bool owner_faulted = false; + bool ticking; + Clock::time_point next_tick; + std::unique_ptr executor; + std::unique_ptr futures; + std::future owner_done; + + Impl(WorldCheckpoint initial, RuntimeOptions settings) + : options(std::move(settings)), + clock(options.clock ? options.clock : std::make_shared()), + ticking(options.ticking) { + if (options.capacity == 0) throw std::invalid_argument("runtime capacity must be positive"); + auto dispatcher = std::make_shared(new_identity(initial), options.dispatcher); + auto rules = std::make_shared(std::move(initial.rules)); + published = capture(*initial.world, *dispatcher, std::move(rules), 0); + committed = std::move(dispatcher); + world = std::move(initial.world); + reanchor(); + auto created = Void::Async::ThreadExecutor::create({.workers = 1, .max_admitted = 1}); + if (!created) throw std::runtime_error(created.error().message()); + executor = std::move(*created); + futures = std::make_unique(*executor); + const auto started = executor->start(); + if (!started) throw std::runtime_error(started.error().message()); + auto submitted = futures->try_submit([this] { run(); }); + if (!submitted) throw std::runtime_error("cannot start simulation owner"); + owner_done = std::move(*submitted); + } + + ~Impl() { shutdown(); } + + void reanchor() { next_tick = Void::Time::saturating_add(clock->now(), tick_interval); } + bool advancing() const { return !owner_faulted && ticking && world && !world->paused(); } + void observe(RuntimePhase phase) const { if (options.observer) options.observer(phase); } + + std::uint64_t next_revision() const { + if (published->revision == std::numeric_limits::max()) { + throw std::overflow_error("publication revision exhausted"); + } + return published->revision + 1; + } + + RuntimeSubmission enqueue(std::unique_ptr work, WorldCheckpoint* candidate = nullptr) { + auto completion = work->promise.get_future(); + std::unique_lock lock(mutex, std::try_to_lock); + if (!lock.owns_lock()) return {RuntimeAdmission::Busy, {}}; + if (stopping.load()) return {RuntimeAdmission::Closed, {}}; + if (outstanding == options.capacity) return {RuntimeAdmission::Busy, {}}; + queue.push_back(std::move(work)); + if (candidate) { + static_assert(std::is_nothrow_move_constructible_v); + queue.back()->candidate.emplace(std::move(*candidate)); + } + ++outstanding; + lock.unlock(); + changed.notify_one(); + return {RuntimeAdmission::Accepted, std::move(completion)}; + } + + bool publish(std::shared_ptr snapshot, + std::shared_ptr ledger) { + { + std::lock_guard lock(mutex); + if (stopping.load()) return false; + published.swap(snapshot); + committed.swap(ledger); + } + return true; + } + + void fault() { + owner_faulted = true; + const auto error = std::current_exception(); + { + std::lock_guard lock(mutex); + if (!stopping.load()) { + state = RuntimeState::Faulted; + failure = error; + } + } + // All World stage tasks have drained before an exception reaches here. + world.reset(); + } + + void tick() { + try { + const auto following = Void::Time::saturating_add(next_tick, tick_interval); + if (following == next_tick) throw std::overflow_error("simulation clock exhausted"); + observe(RuntimePhase::BeforeTick); + world->step(); + observe(RuntimePhase::BeforeCapture); + auto snapshot = capture(*world, *committed, published->rules, next_revision()); + static_cast(publish(std::move(snapshot), committed)); + next_tick = following; + } catch (...) { + fault(); + } + } + + RuntimeResult command(Work& work) { + if (const auto receipt = committed->lookup(work.client, work.command)) { + return {RuntimeOutcome::Completed, *receipt, published}; + } + if (owner_faulted) return {RuntimeOutcome::Faulted, {}, published}; + try { + const bool was_paused = world->paused(); + auto candidate = std::make_shared(*committed); + const auto receipt = candidate->dispatch(*world, work.client, work.command); + if (receipt.status != DispatchStatus::Completed) { + return {RuntimeOutcome::Completed, receipt, published}; + } + observe(RuntimePhase::BeforeCapture); + auto snapshot = capture(*world, *candidate, published->rules, next_revision()); + if (!publish(std::move(snapshot), std::move(candidate))) { + return {RuntimeOutcome::Closed, {}, published}; + } + if (was_paused != world->paused()) reanchor(); + return {RuntimeOutcome::Completed, receipt, published}; + } catch (...) { + fault(); + return {RuntimeOutcome::Faulted, {}, published}; + } + } + + bool current_ticket(const LoadTicket& ticket) const { + return ticket.request != 0 && ticket.request == latest_load && + ticket.expected_session == published->identity.session; + } + + RuntimeResult install(Work& work) { + { + std::lock_guard lock(mutex); + if (!current_ticket(work.ticket)) return {RuntimeOutcome::Superseded, {}, published}; + } + try { + auto& candidate = *work.candidate; + auto ledger = std::make_shared(new_identity(candidate), options.dispatcher); + auto rules = std::make_shared(std::move(candidate.rules)); + observe(RuntimePhase::BeforeInstallCapture); + auto snapshot = capture(*candidate.world, *ledger, std::move(rules), next_revision()); + std::shared_ptr immutable_ledger = std::move(ledger); + { + std::lock_guard lock(mutex); + if (stopping.load()) return {RuntimeOutcome::Closed, {}, published}; + if (!current_ticket(work.ticket)) return {RuntimeOutcome::Superseded, {}, published}; + world.swap(candidate.world); + published.swap(snapshot); + committed.swap(immutable_ledger); + owner_faulted = false; + state = RuntimeState::Running; + failure = {}; + } + reanchor(); + return {RuntimeOutcome::Completed, {}, published}; + } catch (...) { + return {RuntimeOutcome::InvalidCandidate, {}, published}; + } + } + + RuntimeResult process(Work& work) { + if (stopping.load()) return {RuntimeOutcome::Closed, {}, published}; + switch (work.kind) { + case Kind::Command: return command(work); + case Kind::Install: return install(work); + case Kind::Ticking: + if (ticking != work.enabled) { + ticking = work.enabled; + reanchor(); + } + break; + case Kind::Fence: break; + } + return {owner_faulted ? RuntimeOutcome::Faulted : RuntimeOutcome::Completed, {}, published}; + } + + void run() { + for (;;) { + std::unique_ptr work; + bool due = false; + { + std::unique_lock lock(mutex); + // No domain work or snapshot destruction occurs while holding mutex. + for (;;) { + if (stopping.load() && queue.empty()) return; + due = !stopping.load() && advancing() && next_tick <= clock->now(); + if (!queue.empty()) { + const auto& front = *queue.front(); + if (!(due && front.kind == Kind::Fence && next_tick <= front.deadline)) { + work = std::move(queue.front()); + queue.pop_front(); + } + break; + } + if (due) break; + if (advancing()) { + changed.wait_for(lock, Void::Time::remaining_until(*clock, next_tick)); + } else { + changed.wait(lock); + } + } + } + if (work) { + auto result = process(*work); + { + std::lock_guard lock(mutex); + --outstanding; + } + work->promise.set_value(std::move(result)); + work.reset(); + // One tick per turn bounds catch-up work and lets queued input run. + if (!stopping.load() && advancing() && next_tick <= clock->now()) tick(); + } else if (due) { + tick(); + } + } + } + + void shutdown() { + if (executor && executor->is_executor_thread()) { + throw std::logic_error("cannot shut down runtime from its owner"); + } + { + std::lock_guard lock(mutex); + stopping.store(true); + state = RuntimeState::Closed; + } + changed.notify_all(); + if (executor) static_cast(executor->join()); + } +}; + +SimulationRuntime::SimulationRuntime(WorldCheckpoint initial, RuntimeOptions options) + : impl_(std::make_unique(std::move(initial), std::move(options))) {} +SimulationRuntime::~SimulationRuntime() = default; + +std::shared_ptr SimulationRuntime::latest() const { + std::lock_guard lock(impl_->mutex); + return impl_->published; +} + +RuntimeView SimulationRuntime::view() const { + std::lock_guard lock(impl_->mutex); + return {impl_->state, impl_->published, impl_->failure}; +} + +std::expected, RuntimeState> SimulationRuntime::snapshot_for_save() const { + std::lock_guard lock(impl_->mutex); + if (impl_->state != RuntimeState::Running) return std::unexpected{impl_->state}; + return impl_->published; +} + +std::optional SimulationRuntime::lookup( + TrustedClient client, const CommandEnvelope& command) const { + std::shared_ptr ledger; + { + std::lock_guard lock(impl_->mutex); + ledger = impl_->committed; + } + return ledger->lookup(client, command); +} + +RuntimeSubmission SimulationRuntime::try_submit(TrustedClient client, const CommandEnvelope& command) { + auto work = std::make_unique(Impl::Kind::Command); + work->client = client; + work->command = command; + return impl_->enqueue(std::move(work)); +} + +RuntimeSubmission SimulationRuntime::set_ticking(bool enabled) { + auto work = std::make_unique(Impl::Kind::Ticking); + work->enabled = enabled; + return impl_->enqueue(std::move(work)); +} + +RuntimeSubmission SimulationRuntime::synchronize() { + auto work = std::make_unique(Impl::Kind::Fence); + work->deadline = impl_->clock->now(); + return impl_->enqueue(std::move(work)); +} + +void SimulationRuntime::notify_clock() { + // Pair with the owner's wait lock so a notification cannot be lost between + // checking the injected clock and beginning the condition-variable wait. + { std::lock_guard lock(impl_->mutex); } + impl_->changed.notify_one(); +} + +std::expected SimulationRuntime::begin_load() { + std::lock_guard lock(impl_->mutex); + if (impl_->stopping.load()) return std::unexpected{RuntimeAdmission::Closed}; + if (impl_->latest_load == std::numeric_limits::max()) { + return std::unexpected{RuntimeAdmission::IdExhausted}; + } + return LoadTicket{++impl_->latest_load, impl_->published->identity.session}; +} + +RuntimeSubmission SimulationRuntime::try_install(LoadTicket ticket, WorldCheckpoint& candidate) { + auto work = std::make_unique(Impl::Kind::Install); + work->ticket = ticket; + return impl_->enqueue(std::move(work), &candidate); +} + +void SimulationRuntime::shutdown() { impl_->shutdown(); } + +} // namespace settlement diff --git a/tests/runtime_tests.cpp b/tests/runtime_tests.cpp new file mode 100644 index 0000000..d998fe8 --- /dev/null +++ b/tests/runtime_tests.cpp @@ -0,0 +1,398 @@ +#include "settlement/core/simulation_runtime.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace settlement; +using namespace std::chrono_literals; +using Void::Testing::require; +using Void::Testing::Test; +constexpr TrustedClient host{1}; +constexpr TrustedClient guest{2}; + +std::string bytes(const World& world) { + std::ostringstream stream(std::ios::binary); + world.write_save(stream); + return stream.str(); +} + +WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) { + auto original = make_first_colony(2); + std::istringstream input(bytes(*original), std::ios::binary); + auto world = World::read_save(input, workers, + workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel, std::move(options)); + Void::Uuid::Uuid id; + id.bytes.back() = 71; + auto rules = default_rules_manifest(); + require(rules.has_value()); + return {std::move(world), id, 1, std::move(*rules)}; +} + +template +RuntimeSubmission admitted(Submit submit) { + const auto limit = std::chrono::steady_clock::now() + 5s; + for (;;) { + auto operation = submit(); + if (operation.admission != RuntimeAdmission::Busy) return operation; + require(std::chrono::steady_clock::now() < limit); + std::this_thread::yield(); + } +} + +RuntimeResult finished(RuntimeSubmission operation) { + require(operation.admission == RuntimeAdmission::Accepted); + require(operation.completion.wait_for(5s) == std::future_status::ready); + return operation.completion.get(); +} + +RuntimeResult fence(SimulationRuntime& runtime) { + return finished(admitted([&] { return runtime.synchronize(); })); +} + +CommandEnvelope envelope(const PublishedSnapshot& snapshot, std::uint64_t request, + CommandKind kind, std::uint8_t value = 0) { + return {command_envelope_version, snapshot.identity.world, snapshot.identity.session, + snapshot.identity.city, request, CommandPayload{kind, {}, value}}; +} + +RuntimeResult send(SimulationRuntime& runtime, TrustedClient client, const CommandEnvelope& command) { + return finished(admitted([&] { return runtime.try_submit(client, command); })); +} + +struct Gate { + std::mutex mutex; + std::condition_variable changed; + bool entered = false; + bool released = false; + void block() { + std::unique_lock lock(mutex); + entered = true; + changed.notify_all(); + if (!changed.wait_for(lock, 5s, [&] { return released; })) throw std::runtime_error("gate timed out"); + } + void wait() { + std::unique_lock lock(mutex); + require(changed.wait_for(lock, 5s, [&] { return entered; })); + } + void release() { + std::lock_guard lock(mutex); + released = true; + changed.notify_all(); + } +}; + +std::atomic fail_after_mutation{false}; +void command_observer(CommandMutationPhase phase) { + if (phase == CommandMutationPhase::AfterMutation && fail_after_mutation.exchange(false)) { + throw std::runtime_error("after command mutation"); + } +} + +struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::Suite { + [[= Void::Testing::tag("runtime")]] Test test_fixed_clock_matches_reference_and_suspend_discards_idle_time(); + [[= Void::Testing::tag("runtime")]] Test test_paused_commands_publish_and_two_clients_replay_exact_results(); + [[= Void::Testing::tag("runtime")]] Test test_readers_and_save_capture_progress_during_real_worker_tick(); + [[= Void::Testing::tag("runtime")]] Test test_tick_and_capture_failures_keep_previous_publication_and_recover(); + [[= Void::Testing::tag("runtime")]] Test test_failed_command_keeps_committed_receipts_and_settles_queue(); + [[= Void::Testing::tag("runtime")]] Test test_newer_load_supersedes_preparing_candidate_and_fences_old_commands(); + [[= Void::Testing::tag("runtime")]] Test test_invalid_install_preserves_healthy_world_and_ticket_scope(); + [[= Void::Testing::tag("runtime")]] Test test_capacity_and_shutdown_settle_accepted_work(); + [[= Void::Testing::tag("runtime")]] Test test_command_capture_failure_settles_queued_mutations(); + [[= Void::Testing::tag("runtime")]] Test test_exhausted_clock_faults_without_spinning(); +}; + +Test RuntimeTests::test_fixed_clock_matches_reference_and_suspend_discards_idle_time() { + for (const auto workers : {1U, 2U, 6U, 12U}) { + auto clock = std::make_shared(); + auto reference = colony(1); + SimulationRuntime runtime(colony(workers), {.clock = clock}); + for (int i = 0; i < 20; ++i) { + require(clock->advance(50ms).has_value()); + require(fence(runtime).outcome == RuntimeOutcome::Completed); + reference.world->step(); + require(bytes(*runtime.latest()->world) == bytes(*reference.world)); + } + require(runtime.latest()->world->tick() == 20); + require(finished(admitted([&] { return runtime.set_ticking(false); })).outcome == RuntimeOutcome::Completed); + require(clock->advance(1h).has_value()); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 20); + static_cast(finished(admitted([&] { return runtime.set_ticking(true); }))); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 20); + require(clock->advance(1s).has_value()); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 40); + } +} + +Test RuntimeTests::test_paused_commands_publish_and_two_clients_replay_exact_results() { + auto clock = std::make_shared(); + SimulationRuntime runtime(colony(), {.clock = clock}); + const auto initial = runtime.latest(); + auto pause = envelope(*initial, 1, CommandKind::SetPaused, 1); + auto result = send(runtime, host, pause); + require(result.receipt->command_status == CommandStatus::Accepted); + require(result.snapshot->world->paused() && result.snapshot->world->tick() == 0); + require(result.snapshot->revision > initial->revision); + require(clock->advance(1h).has_value()); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 0); + + auto invalid = envelope(*initial, 1, CommandKind::SetPriority, 255); + const auto rejected = send(runtime, guest, invalid); + require(rejected.receipt->status == DispatchStatus::Completed); + require(rejected.receipt->command_status != CommandStatus::Accepted); + const auto prior = runtime.latest(); + require(send(runtime, guest, invalid).receipt == rejected.receipt); + require(runtime.latest() == prior); + auto conflict = invalid; + std::get(conflict.payload).value = 1; + require(send(runtime, guest, conflict).receipt->status == DispatchStatus::Conflict); + require(send(runtime, host, pause).receipt == result.receipt); + require(runtime.latest()->next_requests == (std::array{2, 2})); + auto resume = envelope(*initial, 2, CommandKind::SetPaused, 0); + require(send(runtime, host, resume).receipt->command_status == CommandStatus::Accepted); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 0); + require(clock->advance(50ms).has_value()); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 1); +} + +Test RuntimeTests::test_readers_and_save_capture_progress_during_real_worker_tick() { + auto gate = std::make_shared(); + auto clock = std::make_shared(); + WorkerPoolOptions workers; + workers.before_execute = [gate](std::size_t) { gate->block(); }; + SimulationRuntime runtime(colony(2, std::move(workers)), {.clock = clock}); + auto release = Void::Scope::on_exit([&] { gate->release(); }); + const auto before = runtime.latest(); + const auto saved = bytes(*before->world); + require(clock->advance(50ms).has_value()); + runtime.notify_clock(); + gate->wait(); + auto reader = std::async(std::launch::async, [&] { + const auto snapshot = runtime.snapshot_for_save(); + require(snapshot.has_value() && *snapshot == before); + return bytes(*runtime.latest()->world); + }); + require(reader.wait_for(1s) == std::future_status::ready); + require(reader.get() == saved); + gate->release(); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 1); + require(bytes(*before->world) == saved); +} + +Test RuntimeTests::test_tick_and_capture_failures_keep_previous_publication_and_recover() { + for (const bool stage_failure : {false, true}) { + auto clock = std::make_shared(); + auto fail = std::make_shared>(false); + WorkerPoolOptions workers; + if (stage_failure) workers.before_execute = [fail](std::size_t) { + if (fail->exchange(false)) throw std::runtime_error("stage failure"); + }; + RuntimeOptions options{.clock = clock}; + options.observer = [fail, stage_failure](RuntimePhase phase) { + if (!stage_failure && phase == RuntimePhase::BeforeCapture && fail->exchange(false)) { + throw std::runtime_error("snapshot preparation failure"); + } + }; + SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options)); + const auto previous = runtime.latest(); + fail->store(true); + require(clock->advance(50ms).has_value()); + require(fence(runtime).outcome == RuntimeOutcome::Faulted); + require(runtime.view().state == RuntimeState::Faulted && runtime.view().failure); + require(runtime.latest() == previous && !runtime.snapshot_for_save()); + auto command = envelope(*previous, 1, CommandKind::SetPaused, 1); + require(send(runtime, host, command).outcome == RuntimeOutcome::Faulted); + auto ticket = runtime.begin_load(); + require(ticket.has_value()); + auto replacement = colony(); + const auto installed = finished(admitted([&] { return runtime.try_install(*ticket, replacement); })); + require(installed.outcome == RuntimeOutcome::Completed && !replacement.world); + require(runtime.view().state == RuntimeState::Running && !runtime.view().failure); + require(runtime.latest()->identity.session != previous->identity.session); + require(send(runtime, host, command).receipt->status == DispatchStatus::StaleSession); + require(clock->advance(50ms).has_value()); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 1); + } +} + +Test RuntimeTests::test_failed_command_keeps_committed_receipts_and_settles_queue() { + auto gate = std::make_shared(); + auto armed = std::make_shared>(false); + auto clock = std::make_shared(); + RuntimeOptions options{.clock = clock, .dispatcher = {.mutation_observer = command_observer}}; + options.observer = [gate, armed](RuntimePhase phase) { + if (phase == RuntimePhase::BeforeCapture && armed->load()) gate->block(); + }; + SimulationRuntime runtime(colony(), std::move(options)); + auto release = Void::Scope::on_exit([&] { gate->release(); fail_after_mutation.store(false); }); + const auto first = envelope(*runtime.latest(), 1, CommandKind::SetPaused, 1); + const auto accepted = send(runtime, host, first); + const auto committed = runtime.latest(); + fail_after_mutation.store(true); + auto second = envelope(*committed, 2, CommandKind::SetPriority, 1); + require(send(runtime, host, second).outcome == RuntimeOutcome::Faulted); + require(runtime.latest() == committed); + require(runtime.lookup(host, first) == accepted.receipt); + require(!runtime.lookup(host, second)); + require(send(runtime, host, first).receipt == accepted.receipt); + require(send(runtime, host, second).outcome == RuntimeOutcome::Faulted); + require(!runtime.snapshot_for_save()); + require(fence(runtime).outcome == RuntimeOutcome::Faulted); + + const auto ticket = runtime.begin_load(); + auto replacement = colony(); + require(finished(admitted([&] { return runtime.try_install(*ticket, replacement); })).outcome == RuntimeOutcome::Completed); + armed->store(true); + const auto before = runtime.latest(); + auto change = envelope(*before, 1, CommandKind::SetPaused, 1); + auto pending = admitted([&] { return runtime.try_submit(host, change); }); + gate->wait(); + require(runtime.latest() == before && !runtime.lookup(host, change)); + armed->store(false); + gate->release(); + require(finished(std::move(pending)).receipt->command_status == CommandStatus::Accepted); +} + +Test RuntimeTests::test_newer_load_supersedes_preparing_candidate_and_fences_old_commands() { + auto gate = std::make_shared(); + auto clock = std::make_shared(); + RuntimeOptions options{.clock = clock}; + options.observer = [gate](RuntimePhase phase) { if (phase == RuntimePhase::BeforeInstallCapture) gate->block(); }; + SimulationRuntime runtime(colony(), std::move(options)); + auto release = Void::Scope::on_exit([&] { gate->release(); }); + const auto previous = runtime.latest(); + const auto first = runtime.begin_load(); + auto earlier = colony(); + auto installing = admitted([&] { return runtime.try_install(*first, earlier); }); + gate->wait(); + const auto second = runtime.begin_load(); + require(second.has_value()); + gate->release(); + require(finished(std::move(installing)).outcome == RuntimeOutcome::Superseded); + require(runtime.latest() == previous); + auto newer = colony(); + require(finished(admitted([&] { return runtime.try_install(*second, newer); })).outcome == RuntimeOutcome::Completed); + require(runtime.latest()->identity.world == previous->identity.world); + require(runtime.latest()->identity.session != previous->identity.session); + auto stale = envelope(*previous, 1, CommandKind::SetPaused, 1); + require(send(runtime, host, stale).receipt->status == DispatchStatus::StaleSession); + auto reused = colony(); + require(finished(admitted([&] { return runtime.try_install(*second, reused); })).outcome == RuntimeOutcome::Superseded); +} + +Test RuntimeTests::test_invalid_install_preserves_healthy_world_and_ticket_scope() { + auto clock = std::make_shared(); + auto fail = std::make_shared>(false); + RuntimeOptions options{.clock = clock}; + options.observer = [fail](RuntimePhase phase) { + if (phase == RuntimePhase::BeforeInstallCapture && fail->load()) throw std::bad_alloc(); + }; + SimulationRuntime runtime(colony(), std::move(options)); + const auto previous = runtime.latest(); + auto invalid = colony(); + invalid.world_id = {}; + auto ticket = runtime.begin_load(); + require(finished(admitted([&] { return runtime.try_install(*ticket, invalid); })).outcome == RuntimeOutcome::InvalidCandidate); + require(runtime.latest() == previous && runtime.view().state == RuntimeState::Running); + fail->store(true); + auto valid = colony(); + require(finished(admitted([&] { return runtime.try_install(*ticket, valid); })).outcome == RuntimeOutcome::InvalidCandidate); + require(runtime.latest() == previous && runtime.snapshot_for_save()); + fail->store(false); + require(clock->advance(50ms).has_value()); + static_cast(fence(runtime)); + require(runtime.latest()->world->tick() == 1); +} + +Test RuntimeTests::test_capacity_and_shutdown_settle_accepted_work() { + auto gate = std::make_shared(); + auto clock = std::make_shared(); + RuntimeOptions options{.capacity = 2, .clock = clock}; + options.observer = [gate](RuntimePhase phase) { if (phase == RuntimePhase::BeforeCapture) gate->block(); }; + SimulationRuntime runtime(colony(), std::move(options)); + auto release = Void::Scope::on_exit([&] { gate->release(); }); + const auto before = runtime.latest(); + auto command = envelope(*before, 1, CommandKind::SetPaused, 1); + auto active = admitted([&] { return runtime.try_submit(host, command); }); + gate->wait(); + auto queued = admitted([&] { return runtime.synchronize(); }); + auto full = runtime.synchronize(); + require(full.admission == RuntimeAdmission::Busy && !full.completion.valid()); + auto candidate = colony(); + auto ticket = runtime.begin_load(); + require(runtime.try_install(*ticket, candidate).admission == RuntimeAdmission::Busy && candidate.world); + auto stopped = std::async(std::launch::async, [&] { runtime.shutdown(); }); + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (runtime.view().state != RuntimeState::Closed) { + require(std::chrono::steady_clock::now() < deadline); + std::this_thread::yield(); + } + gate->release(); + require(finished(std::move(active)).outcome == RuntimeOutcome::Closed); + require(finished(std::move(queued)).outcome == RuntimeOutcome::Closed); + require(stopped.wait_for(5s) == std::future_status::ready); + stopped.get(); + runtime.shutdown(); + require(runtime.latest() == before); + require(runtime.try_submit(host, command).admission == RuntimeAdmission::Closed); + require(runtime.begin_load().error() == RuntimeAdmission::Closed); + require(!runtime.snapshot_for_save()); +} + +Test RuntimeTests::test_command_capture_failure_settles_queued_mutations() { + auto gate = std::make_shared(); + auto fail = std::make_shared>(false); + auto clock = std::make_shared(); + RuntimeOptions options{.clock = clock}; + options.observer = [gate, fail](RuntimePhase phase) { + if (phase == RuntimePhase::BeforeCapture && fail->load()) { + gate->block(); + throw std::bad_alloc(); + } + }; + SimulationRuntime runtime(colony(), std::move(options)); + auto release = Void::Scope::on_exit([&] { gate->release(); }); + const auto first = envelope(*runtime.latest(), 1, CommandKind::SetPaused, 1); + const auto accepted = send(runtime, host, first); + const auto committed = runtime.latest(); + const auto second = envelope(*committed, 2, CommandKind::SetPriority, 1); + fail->store(true); + auto active = admitted([&] { return runtime.try_submit(host, second); }); + gate->wait(); + auto third = envelope(*committed, 3, CommandKind::SetPaused, 0); + auto queued = admitted([&] { return runtime.try_submit(host, third); }); + auto repeat = admitted([&] { return runtime.try_submit(host, first); }); + require(runtime.lookup(host, first) == accepted.receipt); + require(!runtime.lookup(host, second)); + gate->release(); + require(finished(std::move(active)).outcome == RuntimeOutcome::Faulted); + require(finished(std::move(queued)).outcome == RuntimeOutcome::Faulted); + require(finished(std::move(repeat)).receipt == accepted.receipt); + require(runtime.latest() == committed && !runtime.snapshot_for_save()); +} + +Test RuntimeTests::test_exhausted_clock_faults_without_spinning() { + auto clock = std::make_shared(); + require(clock->set(Void::Time::MonotonicClock::time_point::max()).has_value()); + SimulationRuntime runtime(colony(), {.clock = clock}); + require(fence(runtime).outcome == RuntimeOutcome::Faulted); + require(runtime.latest()->world->tick() == 0); + require(runtime.view().failure != nullptr); +} +} // namespace