diff --git a/CMakeLists.txt b/CMakeLists.txt index becaf96..b3ff46f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -38,6 +38,7 @@ endif() find_package(Threads REQUIRED) add_library(settlement_core + engine/src/command_dispatcher.cpp engine/src/first_colony.cpp engine/src/worker_pool.cpp engine/src/world.cpp @@ -51,8 +52,8 @@ target_include_directories(settlement_core target_compile_features(settlement_core PUBLIC cxx_std_20) target_link_libraries(settlement_core - PUBLIC Threads::Threads - PRIVATE Void::Binary Void::Core + PUBLIC Threads::Threads Void::Core + PRIVATE Void::Binary ) if(MSVC) @@ -104,7 +105,7 @@ else() endif() if(BUILD_TESTING) - add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/test_main.cpp) + add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/session_tests.cpp tests/test_main.cpp) target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing) add_test(NAME settlement_core_tests COMMAND settlement_core_tests) diff --git a/docs/agent-workflow/tasks/S16-01.md b/docs/agent-workflow/tasks/S16-01.md new file mode 100644 index 0000000..2818b02 --- /dev/null +++ b/docs/agent-workflow/tasks/S16-01.md @@ -0,0 +1,48 @@ +# Dispatch authenticated session commands with exact retry outcomes + +Task ID: S16-01 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Exclusive /home/faumaray/Projects/stoneheart_at_home-worktrees/s16 system/s16-authority, 8d2870a. Main checkout is a different task. F2/F3 and M01-P2 approve this scope; pinned Void 7b0fea6, upstream gap https://git.faumaray.com/Void/Library/issues/6. + +## 2. Objective and deliverables +Implement S16-W01 game command admission/dispatch in a single-owner component plus integration tests with two trusted client handles. Expose a frozen interface for S01 runtime and modern transport. + +## 3. Scope and non-goals +S16 dispatcher only, no sockets/UI/clock or save format. Preserve legacy World::apply_command behavior and LAN11 decoding for existing callers. + +## 4. Files to inspect +Inspect world.hpp, world.cpp World::next_command_sequence/apply_command and queue_cabin, app/lan_wire.cpp, tests/core_tests.cpp, docs/plan/systems/S16.md. Void/Core/Uuid.hpp at exact pin supplies nonnil identities/try_v4; source stubs/compile headers from known library checkout. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/command_dispatcher.hpp; engine/src/command_dispatcher.cpp; tests/session_tests.cpp; CMakeLists.txt +You are not alone. All writes only to specified worktree with explicit absolute paths/workdir. Root integrates branches and CMake; no switching shared Serena, changing others' files, committing/pushing or spawning. + +## 6. Implementation or investigation approach +Use one host dispatcher per world/session and one shared city for M01 (plus disallowed city test). Authenticate caller via trusted local connection slot passed separately, never trust payload player. Envelope includes version, nonnil world+session UUID, city, uint64 request id, game action fields. Per trusted client require contiguous monotonic numbers from 1. Session/identity/version and trusted slot validated before any cached response. For full payload and city equal to an existing key, replay original outcome; reject ID reuse with a changed payload (compare all fields) without mutation. Persist accepted and completed rejected results within session until replaced. Global or per-client configurable capacity: Busy before NEW requests at capacity; honor all previously admitted receipts, no eviction/reexecution. Stale/out-of-order/busy transient errors don't consume request; completed domain rejections do. Store or reserve result before applying effect. Do not silently drop prior receipts on exceptions; runtime will retire faulted owner and session before more commands. + +## 7. Interfaces and data contracts +NEW CommandEnvelope/CommandPayload, session identity (using Void::Uuid::Uuid or fixed byte-compatible game type), target city and explicit outcomes incl status, assigned tick and revision; trusted player is supplied to dispatcher, not a payload identity. Map payload to PlayerCommand using World::next_command_sequence after auth, with no change to legacy sequences on rejection. Provide bounded acceptance path for legacy queue_cabin when needed by viewer (new owner command, preserve checked prerequisite and return outcome) or report exact adaptation to root. New command and session types should be usable without event loop. Share exact API with root early. + +## 8. Dependencies and integration +Consumers S01 runtime, S15 checkpoint and modern transport. Worker owns CMake additions in isolated branch; link Void::Core PUBLIC only if publicly required. Reference #6 in companion task + local source/milestone decision with replacement check. No extra generic ledger. + +## 9. Edge cases security and performance +Check nonnil IDs, invalid/unsupported action, sequence zero, overflow, two clients same request numbers, different payload/city, old world/session, accepted and failed duplicates even after later requests, capacity and exception-safe reservation. Old rejection corrected under a new envelope ID must still use correct World sequence. No hidden trust from bytes. + +## 10. Acceptance criteria +1. Two clients converge and repeat accepted/rejected commands without reapplication, including after newer requests. 2. Stale after rollback and wrong city/identity rejected with identical world bytes. 3. Changed payload, exhaustion, unsupported version/order bounded and tested. 4. Legacy and new tests build/run using actual World. Header communicates semantics to runtime. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/session-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. Tag new tests session, including positive effects and exact repeat receipt tick/revision. Report performance bounds by inspection. + +## 12. Constraints and stop conditions +Escalate required cross-branch changes, genuine ambiguity or two failed repairs; use direct source in this worktree instead of querying the main graph as if it were the same checkout. No external actions. + +## 13. Authorization and decisions +User authorized full roadmap and branches/commits/push; root owns remote actions. F3 READY for S16 dispatcher under above semantics. + +## 14. Return format +Return S16-01 status, actual files and public interface early, semantics/complexity, test and build counts, gaps, runtime integration notes. No subagents. diff --git a/docs/plan/systems/S16.md b/docs/plan/systems/S16.md index a1dd0f8..dd98b37 100644 --- a/docs/plan/systems/S16.md +++ b/docs/plan/systems/S16.md @@ -47,6 +47,10 @@ ## Приёмка +Первый исполняемый срез — диспетчер одного города. Транспорт передаёт доверенный слот отдельно от конверта команды. Для каждого слота диспетчер хранит точные результаты принятых и отклонённых приказов, сверяет содержимое повтора и отсеивает команды прежней инкарнации. По умолчанию после 65 536 записей в слоте новые запросы получают ответ о занятости. Сохранённые ответы доступны до конца инкарнации. Копия журнала позволяет владельцу мира публиковать результат только после успешного изменения. [Диспетчер](../../../engine/include/settlement/core/command_dispatcher.hpp) · [Условие замены на Void](https://git.faumaray.com/Void/Library/issues/6) + +Селектор `--tag session` под Wine выполнил десять проверок, включая двух клиентов, конфликт данных повтора, откат с новой инкарнацией и отказ до/после изменения. Сценарий из 700 тактов сверяет эталон и 2/6/12 потоков. Подключение окна и сетевого транспорта к владельцу мира входит в следующий срез M01. [Сценарии](../../../tests/session_tests.cpp) + - **S16-A01.** Два клиента общего города одновременно заказывают последний доступный предмет. Выполняется один расход, второй запрос получает объяснимый результат. - **S16-A02.** Передать чужой `player`, чужой город, просроченный экземпляр сессии и повтор команды. Проверить авторизацию и устойчивые квитанции. - **S16-A03.** Разорвать соединение между принятием сделки и получением квитанции. После возврата предметы и деньги совпадают со снимком хозяина. diff --git a/engine/include/settlement/core/command_dispatcher.hpp b/engine/include/settlement/core/command_dispatcher.hpp new file mode 100644 index 0000000..fd83cd6 --- /dev/null +++ b/engine/include/settlement/core/command_dispatcher.hpp @@ -0,0 +1,133 @@ +#pragma once + +#include "settlement/core/world.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace settlement { + +inline constexpr std::uint32_t command_envelope_version = 1; + +struct SessionIdentity { + Void::Uuid::Uuid world; + Void::Uuid::Uuid session; + std::uint64_t city = 1; + bool operator==(const SessionIdentity&) const = default; +}; + +// Created by the trusted transport/local adapter, never decoded from payload data. +// Reconnected clients keep their assigned slot within the same session. +struct TrustedClient { + std::uint8_t player; +}; + +struct CommandPayload { + CommandKind kind = CommandKind::PlaceBed; + GridPosition cell{}; + std::uint8_t value = 0; + GridPosition destination{}; + AgentId resident = 0; + bool operator==(const CommandPayload&) const = default; +}; + +struct LegacyCabinPayload { + GridPosition cell; + GridPosition sawmill; + GridPosition stonecutter; + bool operator==(const LegacyCabinPayload&) const = default; +}; + +using SessionPayload = std::variant; + +struct CommandEnvelope { + std::uint32_t version = command_envelope_version; + Void::Uuid::Uuid world; + Void::Uuid::Uuid session; + std::uint64_t city = 1; + std::uint64_t request = 0; + SessionPayload payload; +}; + +enum class DispatchStatus : std::uint8_t { + Completed, + UnsupportedVersion, + WrongWorld, + StaleSession, + UnauthorizedClient, + InvalidRequest, + OutOfOrder, + Conflict, + Busy, + Faulted +}; + +struct DispatchReceipt { + DispatchStatus status; + // Meaningful for Completed. Revision counts successful dispatcher mutations + // in this session, including legacy cabin placement, independently of ticks. + CommandStatus command_status = CommandStatus::Unavailable; + std::uint64_t tick = 0; + std::uint64_t revision = 0; + bool operator==(const DispatchReceipt&) const = default; +}; + +enum class CommandMutationPhase : std::uint8_t { BeforeMutation, AfterMutation }; + +struct CommandDispatcherOptions { + std::size_t max_receipts_per_client = 65'536; + // Optional failure observer around authoritative application. An exception + // fences the staged dispatcher, so the owner must discard its candidate. + void (*mutation_observer)(CommandMutationPhase) = nullptr; +}; + +// Single-owner component. The caller must pass the session's authoritative World. +// Exact repeats retain their original result for the entire session. At capacity, +// new requests receive Busy and stored receipts remain available. No eviction. +// Domain rejections consume a request number; transient dispatch errors do not. +// Copies may be staged with a candidate World and committed only after publication. +// Any mutation exception poisons this instance. Old completed receipts remain +// readable, while further effects require a newly constructed session/dispatcher. +// Upstream replacement contract and tests: Void/Library#6 +// https://git.faumaray.com/Void/Library/issues/6 +class CommandDispatcher { +public: + explicit CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options = {}); + + [[nodiscard]] const SessionIdentity& identity() const noexcept { return identity_; } + [[nodiscard]] std::uint64_t revision() const noexcept { return revision_; } + [[nodiscard]] bool faulted() const noexcept { return faulted_; } + [[nodiscard]] std::size_t receipt_count(TrustedClient client) const noexcept; + [[nodiscard]] std::uint64_t next_request(TrustedClient client) const noexcept; + + [[nodiscard]] DispatchReceipt dispatch(World& world, TrustedClient client, const CommandEnvelope& command); + // Invalid context/conflicting reuse returns its dispatch error. An otherwise + // valid request without a retained receipt returns nullopt without side effects. + [[nodiscard]] std::optional lookup(TrustedClient client, const CommandEnvelope& command) const; + +private: + struct Record { + std::uint64_t city; + SessionPayload payload; + DispatchReceipt receipt{DispatchStatus::Faulted}; + bool completed = false; + }; + + [[nodiscard]] std::optional validate_context( + TrustedClient client, const CommandEnvelope& command) const noexcept; + [[nodiscard]] CommandStatus apply(World& world, TrustedClient client, const CommandEnvelope& command); + + SessionIdentity identity_; + CommandDispatcherOptions options_; + std::array, colony_player_slots> records_; + std::uint64_t revision_ = 0; + bool faulted_ = false; +}; + +} // namespace settlement diff --git a/engine/src/command_dispatcher.cpp b/engine/src/command_dispatcher.cpp new file mode 100644 index 0000000..f045ef9 --- /dev/null +++ b/engine/src/command_dispatcher.cpp @@ -0,0 +1,113 @@ +#include "settlement/core/command_dispatcher.hpp" + +#include +#include + +namespace settlement { +namespace { + +bool valid_client(TrustedClient client) noexcept { + return client.player >= colony_host && client.player <= colony_player_slots; +} + +std::size_t client_index(TrustedClient client) noexcept { + return static_cast(client.player - colony_host); +} + +} // namespace + +CommandDispatcher::CommandDispatcher(SessionIdentity identity, CommandDispatcherOptions options) + : identity_(identity), options_(options) { + if (identity.world.is_nil() || identity.session.is_nil() || identity.city == 0) { + throw std::invalid_argument("command dispatcher requires nonnil world/session and a city"); + } + if (options.max_receipts_per_client == 0 || + options.max_receipts_per_client >= std::numeric_limits::max()) { + throw std::invalid_argument("receipt capacity must be positive and leave a next request number"); + } +} + +std::size_t CommandDispatcher::receipt_count(TrustedClient client) const noexcept { + return valid_client(client) ? records_[client_index(client)].size() : 0; +} + +std::uint64_t CommandDispatcher::next_request(TrustedClient client) const noexcept { + if (!valid_client(client)) return 0; + return static_cast(records_[client_index(client)].size()) + 1; +} + +std::optional CommandDispatcher::validate_context( + TrustedClient client, const CommandEnvelope& command) const noexcept { + if (!valid_client(client)) return DispatchStatus::UnauthorizedClient; + if (command.version != command_envelope_version) return DispatchStatus::UnsupportedVersion; + if (command.world.is_nil() || command.world != identity_.world) return DispatchStatus::WrongWorld; + if (command.session.is_nil() || command.session != identity_.session) return DispatchStatus::StaleSession; + if (command.request == 0) return DispatchStatus::InvalidRequest; + return std::nullopt; +} + +std::optional CommandDispatcher::lookup( + TrustedClient client, const CommandEnvelope& command) const { + if (const auto invalid = validate_context(client, command)) return DispatchReceipt{*invalid}; + const auto& records = records_[client_index(client)]; + if (command.request > records.size()) return std::nullopt; + const auto& record = records[static_cast(command.request - 1)]; + if (command.city != record.city || command.payload != record.payload) { + return DispatchReceipt{DispatchStatus::Conflict}; + } + return record.completed ? record.receipt : DispatchReceipt{DispatchStatus::Faulted}; +} + +CommandStatus CommandDispatcher::apply(World& world, TrustedClient client, const CommandEnvelope& command) { + if (command.city != identity_.city) return CommandStatus::Unauthorized; + if (const auto* payload = std::get_if(&command.payload)) { + if (payload->kind > CommandKind::CraftFurniture) return CommandStatus::InvalidTarget; + if (payload->kind == CommandKind::PlaceRoom) { + const auto inside = [&world](GridPosition cell) { + return cell.x >= 0 && cell.y >= 0 && cell.x < world.width() && cell.y < world.height(); + }; + // Legacy room-size arithmetic assumes coordinates belong to this map. + if (!inside(payload->cell) || !inside(payload->destination)) return CommandStatus::InvalidTarget; + } + return world.apply_command({client.player, world.next_command_sequence(client.player), payload->kind, + payload->cell, payload->value, payload->destination, payload->resident}).status; + } + + if (client.player != colony_host) return CommandStatus::Unauthorized; + if (world.scenario_active()) return CommandStatus::Unavailable; + const auto& payload = std::get(command.payload); + try { + world.queue_cabin(payload.cell, payload.sawmill, payload.stonecutter); + } catch (const std::invalid_argument&) { + return CommandStatus::InvalidTarget; + } + return CommandStatus::Accepted; +} + +DispatchReceipt CommandDispatcher::dispatch(World& world, TrustedClient client, const CommandEnvelope& command) { + if (const auto recorded = lookup(client, command)) return *recorded; + if (faulted_) return {DispatchStatus::Faulted}; + auto& records = records_[client_index(client)]; + if (command.request != next_request(client)) return {DispatchStatus::OutOfOrder}; + if (records.size() == options_.max_receipts_per_client || + revision_ == std::numeric_limits::max()) return {DispatchStatus::Busy}; + + // All record allocation/copy work happens before the authoritative mutation. + // An exceptional effect leaves this entry incomplete and fences further work. + records.push_back(Record{command.city, command.payload}); + auto& record = records.back(); + try { + if (options_.mutation_observer) options_.mutation_observer(CommandMutationPhase::BeforeMutation); + const auto status = apply(world, client, command); + if (options_.mutation_observer) options_.mutation_observer(CommandMutationPhase::AfterMutation); + if (status == CommandStatus::Accepted) ++revision_; + record.receipt = {DispatchStatus::Completed, status, world.tick(), revision_}; + record.completed = true; + } catch (...) { + faulted_ = true; + throw; + } + return record.receipt; +} + +} // namespace settlement diff --git a/tests/session_tests.cpp b/tests/session_tests.cpp new file mode 100644 index 0000000..4a51882 --- /dev/null +++ b/tests/session_tests.cpp @@ -0,0 +1,407 @@ +#include "settlement/core/command_dispatcher.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace settlement; +using Void::Testing::expect_throw; +using Void::Testing::Test; + +constexpr TrustedClient host{colony_host}; +constexpr TrustedClient guest{2}; + +thread_local std::optional injected_failure; + +void observe_mutation(CommandMutationPhase phase) { + if (injected_failure == phase) throw std::runtime_error("injected command mutation failure"); +} + +void require(bool condition, std::string_view message) { + if (!condition) throw std::runtime_error(std::string(message)); +} + +SessionIdentity session_identity(std::uint8_t incarnation = 1) { + Void::Uuid::Uuid world; + world.bytes.back() = 41; + Void::Uuid::Uuid session; + session.bytes.back() = incarnation; + return {world, session, 1}; +} + +CommandEnvelope envelope(std::uint64_t request, SessionPayload payload, + SessionIdentity identity = session_identity()) { + return {command_envelope_version, identity.world, identity.session, identity.city, request, payload}; +} + +std::string saved_state(const World& world) { + std::ostringstream stream(std::ios::binary); + world.write_save(stream); + return stream.str(); +} + +std::unique_ptr load_state(const std::string& bytes, std::size_t workers = 2) { + std::istringstream input(bytes, std::ios::binary); + return World::read_save(input, workers, + workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel); +} + +void require_completed(const DispatchReceipt& receipt, CommandStatus expected, std::uint64_t tick, + std::uint64_t revision) { + require(receipt == DispatchReceipt{DispatchStatus::Completed, expected, tick, revision}, + "the completed result differs from the authoritative outcome"); +} + +struct [[= Void::Testing::name("SessionTests")]] SessionTests : Void::Testing::Suite { + [[= Void::Testing::tag("session")]] Test test_session_configuration_requires_valid_identity_and_capacity(); + [[= Void::Testing::tag("session")]] Test test_two_clients_replay_accepted_and_rejected_results(); + [[= Void::Testing::tag("session")]] Test test_conflicting_reuse_checks_every_payload_field_and_context(); + [[= Void::Testing::tag("session")]] Test test_transient_rejections_preserve_request_order(); + [[= Void::Testing::tag("session")]] Test test_capacity_retains_all_old_receipts_for_each_client(); + [[= Void::Testing::tag("session")]] Test test_rollback_fences_old_session_before_receipt_lookup(); + [[= Void::Testing::tag("session")]] Test test_dispatch_is_identical_in_reference_and_worker_modes(); + [[= Void::Testing::tag("session")]] Test test_legacy_cabin_placement_uses_the_same_ledger(); + [[= Void::Testing::tag("session")]] Test test_ledger_can_be_staged_with_an_unpublished_world(); + [[= Void::Testing::tag("session")]] Test test_exception_fences_uncommitted_receipts_and_preserves_old_results(); +}; + +Test SessionTests::test_session_configuration_requires_valid_identity_and_capacity() { + auto invalid = session_identity(); + invalid.world = {}; + expect_throw([&] { CommandDispatcher dispatcher(invalid); }); + invalid = session_identity(); + invalid.session = {}; + expect_throw([&] { CommandDispatcher dispatcher(invalid); }); + invalid = session_identity(); + invalid.city = 0; + expect_throw([&] { CommandDispatcher dispatcher(invalid); }); + expect_throw([] { CommandDispatcher dispatcher(session_identity(), {0}); }); + expect_throw([] { + CommandDispatcher dispatcher(session_identity(), {std::numeric_limits::max()}); + }); + CommandDispatcher dispatcher(session_identity()); + require(dispatcher.next_request(host) == 1 && dispatcher.next_request(guest) == 1 && + dispatcher.next_request({0}) == 0 && !dispatcher.faulted(), + "new session sequence or client validation is incorrect"); +} + +Test SessionTests::test_two_clients_replay_accepted_and_rejected_results() { + auto world = make_first_colony(2); + CommandDispatcher dispatcher(session_identity()); + const auto pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1}); + const auto guest_pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 0}); + const auto first_bed = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + const auto second_bed = envelope(2, CommandPayload{CommandKind::PlaceBed, {17, 18}, 1}); + const auto occupied = envelope(3, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + const auto resume = envelope(3, CommandPayload{CommandKind::SetPaused, {}, 0}); + const auto paused = dispatcher.dispatch(*world, host, pause); + const auto denied = dispatcher.dispatch(*world, guest, guest_pause); + const auto host_bed = dispatcher.dispatch(*world, host, first_bed); + const auto guest_bed = dispatcher.dispatch(*world, guest, second_bed); + const auto invalid = dispatcher.dispatch(*world, guest, occupied); + require_completed(paused, CommandStatus::Accepted, 0, 1); + require_completed(denied, CommandStatus::Unauthorized, 0, 1); + require_completed(host_bed, CommandStatus::Accepted, 0, 2); + require_completed(guest_bed, CommandStatus::Accepted, 0, 3); + require_completed(invalid, CommandStatus::InvalidTarget, 0, 3); + require_completed(dispatcher.dispatch(*world, host, resume), CommandStatus::Accepted, 0, 4); + for (int tick = 0; tick < 30; ++tick) world->step(); + const auto before_retry = saved_state(*world); + require(dispatcher.dispatch(*world, host, pause) == paused && + dispatcher.dispatch(*world, guest, guest_pause) == denied && + dispatcher.dispatch(*world, host, first_bed) == host_bed && + dispatcher.dispatch(*world, guest, second_bed) == guest_bed && + dispatcher.dispatch(*world, guest, occupied) == invalid, + "a delayed retry changed its original outcome, tick or revision"); + require(saved_state(*world) == before_retry && !world->paused(), + "a repeated operation applied its effects again"); + const auto corrected = envelope(4, CommandPayload{CommandKind::PlaceBed, {18, 18}}); + require_completed(dispatcher.dispatch(*world, guest, corrected), CommandStatus::Accepted, 30, 5); + require(world->next_command_sequence(1) == 4 && world->next_command_sequence(2) == 3 && + dispatcher.next_request(host) == 4 && dispatcher.next_request(guest) == 5, + "dispatcher rejections changed the legacy accepted-command sequence"); + require(dispatcher.lookup(guest, occupied) == invalid, + "reconnection to the same trusted slot lost a rejected result"); +} + +Test SessionTests::test_conflicting_reuse_checks_every_payload_field_and_context() { + auto world = make_first_colony(2); + CommandDispatcher dispatcher(session_identity()); + const auto original = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + const auto recorded = dispatcher.dispatch(*world, host, original); + const auto before = saved_state(*world); + const auto conflict = [&](CommandEnvelope changed) { + require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::Conflict, + "changed payload reused a completed request"); + require(saved_state(*world) == before && dispatcher.receipt_count(host) == 1, + "conflicting reuse changed the world or its original record"); + }; + auto changed = original; + ++changed.city; + conflict(changed); + changed = original; + std::get(changed.payload).kind = CommandKind::SetForaging; + conflict(changed); + changed = original; + ++std::get(changed.payload).cell.x; + conflict(changed); + changed = original; + ++std::get(changed.payload).value; + conflict(changed); + changed = original; + ++std::get(changed.payload).destination.y; + conflict(changed); + changed = original; + ++std::get(changed.payload).resident; + conflict(changed); + changed = original; + changed.payload = LegacyCabinPayload{{5, 5}, {3, 3}, {4, 3}}; + conflict(changed); + changed = original; + ++changed.version; + require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::UnsupportedVersion, + "cached result bypassed protocol validation"); + changed = original; + changed.world.bytes.back() ^= 1; + require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::WrongWorld, + "cached result bypassed world validation"); + changed = original; + changed.session.bytes.back() ^= 1; + require(dispatcher.dispatch(*world, host, changed).status == DispatchStatus::StaleSession, + "cached result bypassed incarnation validation"); + require(dispatcher.dispatch(*world, {0}, original).status == DispatchStatus::UnauthorizedClient && + dispatcher.dispatch(*world, {3}, original).status == DispatchStatus::UnauthorizedClient && + dispatcher.dispatch(*world, host, original) == recorded && saved_state(*world) == before, + "a transport identity error changed a retained result"); +} + +Test SessionTests::test_transient_rejections_preserve_request_order() { + auto world = make_first_colony(2); + CommandDispatcher dispatcher(session_identity()); + const auto before = saved_state(*world); + auto command = envelope(0, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::InvalidRequest, + "request zero was accepted"); + command.request = std::numeric_limits::max(); + require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::OutOfOrder, + "request arithmetic wrapped at the uint64 boundary"); + command.request = 2; + require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::OutOfOrder && + dispatcher.next_request(host) == 1 && !dispatcher.lookup(host, command), + "a missing request advanced the ledger"); + command.request = 1; + command.session = {}; + require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::StaleSession, + "nil session was accepted"); + command = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + command.world = {}; + require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::WrongWorld && + saved_state(*world) == before, + "nil world or transient rejection changed state"); + command = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + command.city = 9; + require_completed(dispatcher.dispatch(*world, host, command), CommandStatus::Unauthorized, 0, 0); + require(saved_state(*world) == before && dispatcher.next_request(host) == 2, + "city denial mutated state or failed to retain the rejection"); + command.city = 1; + require(dispatcher.dispatch(*world, host, command).status == DispatchStatus::Conflict, + "corrected city reused an already completed number"); + command.request = 2; + require_completed(dispatcher.dispatch(*world, host, command), CommandStatus::Accepted, 0, 1); + const auto unknown = envelope(3, CommandPayload{static_cast(255)}); + require_completed(dispatcher.dispatch(*world, host, unknown), CommandStatus::InvalidTarget, 0, 1); + require(dispatcher.next_request(host) == 4 && world->next_command_sequence(1) == 2, + "unsupported action confused dispatcher and legacy sequences"); + const auto extreme_room = envelope(4, CommandPayload{CommandKind::PlaceRoom, + {std::numeric_limits::min(), 0}, 0, {std::numeric_limits::max(), 4}}); + const auto before_extreme = saved_state(*world); + require_completed(dispatcher.dispatch(*world, host, extreme_room), CommandStatus::InvalidTarget, 0, 1); + require(saved_state(*world) == before_extreme, "unbounded room coordinates reached legacy size arithmetic"); +} + +Test SessionTests::test_capacity_retains_all_old_receipts_for_each_client() { + auto world = make_first_colony(2); + CommandDispatcher dispatcher(session_identity(), {2}); + const auto first = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + const auto second = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + const auto one = dispatcher.dispatch(*world, host, first); + const auto two = dispatcher.dispatch(*world, host, second); + require_completed(one, CommandStatus::Accepted, 0, 1); + require_completed(two, CommandStatus::InvalidTarget, 0, 1); + const auto before = saved_state(*world); + const auto third = envelope(3, CommandPayload{CommandKind::PlaceBed, {17, 18}}); + require(dispatcher.dispatch(*world, host, third).status == DispatchStatus::Busy && + dispatcher.dispatch(*world, host, third).status == DispatchStatus::Busy, + "full receipt ledger admitted a new effect"); + require(dispatcher.next_request(host) == 3 && dispatcher.receipt_count(host) == 2 && + dispatcher.dispatch(*world, host, first) == one && dispatcher.dispatch(*world, host, second) == two && + saved_state(*world) == before, + "capacity backpressure evicted/reexecuted an old receipt"); + require_completed(dispatcher.dispatch(*world, guest, + envelope(1, CommandPayload{CommandKind::PlaceBed, {17, 18}})), CommandStatus::Accepted, 0, 2); + require(dispatcher.next_request(guest) == 2 && dispatcher.receipt_count({0}) == 0, + "one client's retention capacity blocked another client"); +} + +Test SessionTests::test_rollback_fences_old_session_before_receipt_lookup() { + auto world = make_first_colony(2); + const auto early = saved_state(*world); + CommandDispatcher previous(session_identity()); + const auto old = envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + require_completed(previous.dispatch(*world, host, old), CommandStatus::Accepted, 0, 1); + for (int tick = 0; tick < 20; ++tick) world->step(); + auto restored = load_state(early); + CommandDispatcher current(session_identity(2)); + require(current.dispatch(*restored, host, old).status == DispatchStatus::StaleSession && + current.lookup(host, old)->status == DispatchStatus::StaleSession && + saved_state(*restored) == early && current.next_request(host) == 1, + "a request from before rollback changed or queried the new incarnation"); + const auto fresh = envelope(1, std::get(old.payload), session_identity(2)); + const auto accepted = current.dispatch(*restored, host, fresh); + require_completed(accepted, CommandStatus::Accepted, 0, 1); + const auto after = saved_state(*restored); + require(current.dispatch(*restored, host, fresh) == accepted && saved_state(*restored) == after, + "a retry in the new session executed twice"); +} + +Test SessionTests::test_dispatch_is_identical_in_reference_and_worker_modes() { + const auto initial = make_first_colony(2); + const auto bytes = saved_state(*initial); + constexpr std::array worker_counts{1, 2, 6, 12}; + std::array, 4> worlds; + std::array dispatchers{CommandDispatcher(session_identity()), CommandDispatcher(session_identity()), + CommandDispatcher(session_identity()), CommandDispatcher(session_identity())}; + for (std::size_t index = 0; index < worlds.size(); ++index) worlds[index] = load_state(bytes, worker_counts[index]); + const auto issue = [&](TrustedClient client, CommandEnvelope command, CommandStatus status) { + const auto expected = dispatchers[0].dispatch(*worlds[0], client, command); + require(expected.status == DispatchStatus::Completed && expected.command_status == status, + "reference command failed its expected domain check"); + for (std::size_t index = 1; index < worlds.size(); ++index) { + require(dispatchers[index].dispatch(*worlds[index], client, command) == expected, + "dispatch receipt differs across worker modes"); + } + }; + issue(host, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::Accepted); + issue(guest, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::InvalidTarget); + issue(guest, envelope(2, CommandPayload{CommandKind::PlaceBed, {17, 18}, 1}), CommandStatus::Accepted); + issue(host, envelope(2, CommandPayload{CommandKind::PlaceBed, {18, 18}}), CommandStatus::Accepted); + issue(host, envelope(3, CommandPayload{CommandKind::SetForaging, {14, 12}, 1}), CommandStatus::Accepted); + for (int tick = 0; tick < 700; ++tick) { + if (tick == 30) { + issue(host, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::Accepted); + issue(guest, envelope(1, CommandPayload{CommandKind::PlaceBed, {16, 18}}), CommandStatus::InvalidTarget); + } + worlds[0]->step(); + const auto expected = saved_state(*worlds[0]); + for (std::size_t index = 1; index < worlds.size(); ++index) { + worlds[index]->step(); + require(saved_state(*worlds[index]) == expected, "authoritative dispatch world diverged by worker count"); + } + } + require(worlds[0]->scenario_progress().completed && worlds[0]->meals_eaten() >= 3, + "the dispatched colony failed to build and feed its residents"); +} + +Test SessionTests::test_legacy_cabin_placement_uses_the_same_ledger() { + World world(1, 10, 10); + CommandDispatcher dispatcher(session_identity()); + const auto cabin = envelope(1, LegacyCabinPayload{{5, 5}, {3, 3}, {4, 3}}); + const auto denied = dispatcher.dispatch(world, guest, cabin); + require_completed(denied, CommandStatus::Unauthorized, 0, 0); + const auto accepted = dispatcher.dispatch(world, host, cabin); + require_completed(accepted, CommandStatus::Accepted, 0, 1); + require(world.production_orders().size() == 6 && world.production_orders().back().recipe == RecipeId::BuildCabin, + "legacy placement did not queue its cabin and five material orders"); + const auto bytes = saved_state(world); + require(dispatcher.dispatch(world, host, cabin) == accepted && + dispatcher.dispatch(world, guest, cabin) == denied && saved_state(world) == bytes, + "legacy cabin retry was applied again"); + auto occupied = cabin; + occupied.request = 2; + require_completed(dispatcher.dispatch(world, host, occupied), CommandStatus::InvalidTarget, 0, 1); + require(saved_state(world) == bytes && dispatcher.next_request(host) == 3, + "invalid legacy placement partially changed the world"); + auto changed = cabin; + std::get(changed.payload).sawmill.x = 2; + require(dispatcher.dispatch(world, host, changed).status == DispatchStatus::Conflict, + "cabin workshop change bypassed payload conflict detection"); + auto colony = make_first_colony(2); + CommandDispatcher active(session_identity()); + require_completed(active.dispatch(*colony, host, cabin), CommandStatus::Unavailable, 0, 0); +} + +Test SessionTests::test_ledger_can_be_staged_with_an_unpublished_world() { + auto world = make_first_colony(2); + CommandDispatcher committed(session_identity()); + require_completed(committed.dispatch(*world, host, + envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1})), CommandStatus::Accepted, 0, 1); + const auto before = saved_state(*world); + auto candidate = load_state(before); + auto staged = committed; + const auto building = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + const auto prepared = staged.dispatch(*candidate, host, building); + require_completed(prepared, CommandStatus::Accepted, 0, 2); + require(!committed.lookup(host, building) && committed.next_request(host) == 2 && + saved_state(*world) == before && saved_state(*candidate) != before, + "an unpublished candidate leaked its result or world state"); + committed = std::move(staged); + world = std::move(candidate); + const auto published = saved_state(*world); + require(committed.dispatch(*world, host, building) == prepared && saved_state(*world) == published, + "a committed candidate lost its retained receipt"); +} + +Test SessionTests::test_exception_fences_uncommitted_receipts_and_preserves_old_results() { + for (const auto phase : {CommandMutationPhase::BeforeMutation, CommandMutationPhase::AfterMutation}) { + auto committed_world = make_first_colony(2); + CommandDispatcher committed(session_identity(), {8, observe_mutation}); + const auto pause = envelope(1, CommandPayload{CommandKind::SetPaused, {}, 1}); + const auto previous = committed.dispatch(*committed_world, host, pause); + require_completed(previous, CommandStatus::Accepted, 0, 1); + const auto committed_bytes = saved_state(*committed_world); + auto candidate = load_state(committed_bytes); + auto staged = committed; + const auto building = envelope(2, CommandPayload{CommandKind::PlaceBed, {16, 18}}); + injected_failure = phase; + bool observed_failure = false; + try { + static_cast(staged.dispatch(*candidate, host, building)); + } catch (const std::runtime_error& error) { + observed_failure = std::string_view(error.what()) == "injected command mutation failure"; + } + injected_failure.reset(); + require(observed_failure && staged.faulted(), "an exceptional command did not fence the candidate"); + require((saved_state(*candidate) != committed_bytes) == (phase == CommandMutationPhase::AfterMutation), + "the mutation observer did not bracket the actual game effect"); + require(staged.lookup(host, pause) == previous && staged.dispatch(*candidate, host, pause) == previous, + "faulted state hid or reexecuted an earlier completed result"); + require(staged.lookup(host, building)->status == DispatchStatus::Faulted && + staged.dispatch(*candidate, host, building).status == DispatchStatus::Faulted, + "an uncommitted command became a replayable success"); + const auto faulted_bytes = saved_state(*candidate); + require(staged.dispatch(*candidate, host, + envelope(3, CommandPayload{CommandKind::PlaceBed, {17, 18}})).status == DispatchStatus::Faulted && + saved_state(*candidate) == faulted_bytes && staged.revision() == previous.revision, + "the faulted owner admitted another effect or committed a result revision"); + require(saved_state(*committed_world) == committed_bytes && !committed.lookup(host, building) && + committed.lookup(host, pause) == previous, + "a failed candidate leaked state or receipts into the publication"); + candidate.reset(); + auto restored = load_state(committed_bytes); + CommandDispatcher recovered(session_identity(2)); + require(recovered.dispatch(*restored, host, building).status == DispatchStatus::StaleSession, + "recovery admitted an envelope from the retired candidate"); + const auto fresh = envelope(1, building.payload, session_identity(2)); + require_completed(recovered.dispatch(*restored, host, fresh), CommandStatus::Accepted, 0, 1); + } +} + +} // namespace