Compare commits

...
15 changed files with 1209 additions and 58 deletions

No files matched your search

+25 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include <windows.h>
#include "settlement/core/colony_profile.hpp"
#include <algorithm>
#include <array>
@@ -19,6 +20,7 @@ constexpr int title_coop_id = 1103;
constexpr int title_exit_id = 1104;
constexpr int title_saves_id = 1105;
constexpr int title_open_id = 1106;
constexpr int title_rules_id = 1107;
inline std::filesystem::path saves_directory() {
const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0);
@@ -51,6 +53,14 @@ public:
0, 0, 0, 0, owner, id(title_saves_id), instance, nullptr);
open_ = CreateWindowExW(0, L"BUTTON", L"Загрузить выбранное", WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
0, 0, 0, 0, owner, id(title_open_id), instance, nullptr);
rules_label_ = CreateWindowExW(0, L"STATIC", L"Правила только новой колонии:", WS_CHILD,
0, 0, 0, 0, owner, nullptr, instance, nullptr);
rules_ = CreateWindowExW(0, L"COMBOBOX", L"Правила новой колонии",
WS_CHILD | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWNLIST,
0, 0, 0, 0, owner, id(title_rules_id), instance, nullptr);
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Поэтапная кровать: опора и 2 ткани"));
SendMessageW(rules_, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Простая кровать: 1 доска"));
SendMessageW(rules_, CB_SETCURSEL, 0, 0);
list_background_ = CreateSolidBrush(RGB(44, 63, 53));
font_ = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
@@ -58,6 +68,8 @@ public:
for (const auto button : buttons_) SendMessageW(button, WM_SETFONT, font, FALSE);
SendMessageW(saves_, WM_SETFONT, font, FALSE);
SendMessageW(open_, WM_SETFONT, font, FALSE);
SendMessageW(rules_label_, WM_SETFONT, font, FALSE);
SendMessageW(rules_, WM_SETFONT, font, FALSE);
}
void reload_saves() {
@@ -90,6 +102,8 @@ public:
for (const auto button : buttons_) ShowWindow(button, flags);
ShowWindow(saves_, flags);
ShowWindow(open_, flags);
ShowWindow(rules_label_, flags);
ShowWindow(rules_, flags);
}
void update(bool can_resume, bool offline) const {
@@ -98,6 +112,7 @@ public:
EnableWindow(buttons_[title_browse_id - title_continue_id], offline);
EnableWindow(open_, offline && selected_index() < saves.size());
EnableWindow(saves_, offline);
EnableWindow(rules_, offline);
}
HBRUSH paint_list_background(HWND control, HDC dc) const {
@@ -116,6 +131,10 @@ public:
return saves.empty() ? std::nullopt : std::optional{saves.front().path};
}
[[nodiscard]] ColonyProfile new_colony_profile() const {
return SendMessageW(rules_, CB_GETCURSEL, 0, 0) == 1 ? ColonyProfile::PlankBeds : ColonyProfile::Default;
}
void layout(int width, int height) const {
const RECT panel = bounds(width, height);
for (std::size_t i = 0; i < buttons_.size(); ++i) {
@@ -123,6 +142,8 @@ public:
}
position(saves_, panel.left + 318, panel.top + 146, panel.right - panel.left - 346, 118);
position(open_, panel.left + 318, panel.top + 274, panel.right - panel.left - 346, 33);
position(rules_label_, panel.left + 28, panel.top + 358, panel.right - panel.left - 56, 23);
position(rules_, panel.left + 28, panel.top + 383, panel.right - panel.left - 56, 100);
}
void draw(HDC dc, int width, int height, const std::wstring& notice) const {
@@ -160,7 +181,7 @@ public:
DrawTextW(dc, saves.empty() ? L"Сохранения · список пуст" : L"Сохранения", -1,
&saves_label, DT_SINGLELINE | DT_VCENTER);
if (!notice.empty()) {
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.bottom - 11};
RECT information{panel.left + 318, panel.top + 311, panel.right - 27, panel.top + 355};
DrawTextW(dc, notice.c_str(), -1, &information, DT_WORDBREAK | DT_NOPREFIX);
}
SetTextColor(dc, ink);
@@ -209,7 +230,7 @@ private:
static RECT bounds(int width, int height) {
constexpr int panel_width = 704;
constexpr int panel_height = 365;
constexpr int panel_height = 430;
const int left = (width - panel_width) / 2;
const int top = (height - panel_height) / 2;
return {left, top, left + panel_width, top + panel_height};
@@ -233,6 +254,8 @@ private:
std::array<HWND, 5> buttons_{};
HWND saves_ = nullptr;
HWND open_ = nullptr;
HWND rules_label_ = nullptr;
HWND rules_ = nullptr;
HBRUSH list_background_ = nullptr;
HFONT font_ = nullptr;
std::vector<SaveFile> saves;
+19 -14
View File
@@ -19,25 +19,24 @@ RulesManifest supported_rules() {
return std::move(*manifest);
}
void validate_supported(const WorldCheckpoint& candidate, const RulesManifest& rules) {
void validate_supported(const WorldCheckpoint& candidate) {
const auto valid = validate_colony_checkpoint(candidate);
if (!valid) throw std::runtime_error(valid.error().message);
if (!candidate.world || candidate.world->width() != first_colony_map_size ||
candidate.world->height() != first_colony_map_size) {
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
}
if (candidate.rules != rules) {
throw std::runtime_error("This viewer requires the installed default colony rules.");
}
}
WorldCheckpoint validated_initial(WorldCheckpoint candidate, const RulesManifest& rules) {
validate_supported(candidate, rules);
WorldCheckpoint validated_initial(WorldCheckpoint candidate) {
validate_supported(candidate);
return candidate;
}
WorldCheckpoint initial_colony(std::size_t workers) {
auto identity = Void::Uuid::try_v4();
if (!identity) throw std::runtime_error("Could not create a world identity.");
return {make_first_colony(workers), *identity, 1, supported_rules()};
WorldCheckpoint initial_colony(std::size_t workers, ColonyProfile profile = ColonyProfile::Default) {
auto candidate = make_colony_checkpoint(profile, workers);
if (!candidate) throw std::runtime_error(candidate.error().message);
return std::move(*candidate);
}
RuntimeOptions suspended(RuntimeOptions options) {
@@ -59,7 +58,7 @@ ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions options)
ViewerSession::ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options)
: workers_(workers), command_capacity_(options.command_capacity),
supported_rules_(supported_rules()),
runtime_(validated_initial(std::move(initial), supported_rules_), suspended(std::move(options.runtime))),
runtime_(validated_initial(std::move(initial)), suspended(std::move(options.runtime))),
files_(std::move(options.files)) {
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
}
@@ -74,6 +73,12 @@ bool ViewerSession::can_submit() const {
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
}
bool ViewerSession::can_host_legacy() const {
const auto current = runtime_.view();
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
current.snapshot->rules && *current.snapshot->rules == supported_rules_;
}
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
if (!can_submit()) return std::nullopt;
for (const auto& intent : intents_) {
@@ -111,7 +116,7 @@ LoadTicket ViewerSession::begin_change() {
}
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
validate_supported(candidate, supported_rules_);
validate_supported(candidate);
}
void ViewerSession::replace(WorldCheckpoint candidate) {
@@ -120,8 +125,8 @@ void ViewerSession::replace(WorldCheckpoint candidate) {
installing_.emplace(Installing{ticket, std::move(candidate)});
}
void ViewerSession::new_colony() {
replace(initial_colony(workers_));
void ViewerSession::new_colony(ColonyProfile profile) {
replace(initial_colony(workers_, profile));
}
void ViewerSession::load(const std::filesystem::path& path) {
+3 -1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "settlement/core/checkpoint_files.hpp"
#include "settlement/core/colony_profile.hpp"
#include <deque>
#include <filesystem>
@@ -39,13 +40,14 @@ public:
[[nodiscard]] bool guest() const noexcept { return guest_; }
[[nodiscard]] bool changing_world() const noexcept { return changing_world_; }
[[nodiscard]] bool can_submit() const;
[[nodiscard]] bool can_host_legacy() const;
[[nodiscard]] std::uint64_t generation() const noexcept { return generation_; }
[[nodiscard]] std::optional<std::uint64_t> submit(SessionPayload payload);
[[nodiscard]] bool pending(std::uint64_t id) const noexcept;
void set_ticking(bool enabled) noexcept { desired_ticking_ = enabled; }
[[nodiscard]] std::vector<ViewerEvent> poll();
void new_colony();
void new_colony(ColonyProfile profile = ColonyProfile::Default);
void load(const std::filesystem::path& path);
void save(const std::filesystem::path& path);
void enter_guest();
+21 -5
View File
@@ -204,6 +204,11 @@ constexpr const wchar_t* house_contents[] = {
L"Каменная кровать и стойка с инструментами",
L"Деревянная кровать и ткацкий станок",
};
constexpr const wchar_t* simple_house_contents[] = {
L"Кровать: 1 доска; аптечный шкаф",
L"Кровать: 1 доска; стойка с инструментами",
L"Кровать: 1 доска; ткацкий станок",
};
std::array<HICON, 3> house_artwork{};
struct DockSection {
WorkPanel panel;
@@ -1054,7 +1059,7 @@ void show_title_screen(HWND window, bool visible) {
}
void reset_world(HWND window) {
session->new_colony();
session->new_colony(title_screen.new_colony_profile());
host_after_replacement = false;
clear_blueprints();
placement_message = L"Создаём поселение…";
@@ -1254,7 +1259,13 @@ void handle_lan_menu(HWND window, int command) {
if (!showing_title) return;
try {
if (command == lan_host_id && lan->state() == LanState::Offline) {
if (!has_session || !world || !world->scenario_active()) {
// Modal menus pump loads, so inspect the authoritative publication
// here, immediately before any listener or replacement is started.
if (!session->can_host_legacy()) {
throw std::runtime_error("LAN requires a ready colony with the default rules. Wait for loading to finish.");
}
const auto current = session->runtime().latest();
if (!has_session || !current->world->scenario_active()) {
session->new_colony();
host_after_replacement = true;
clear_blueprints();
@@ -1715,8 +1726,12 @@ void pump_session(HWND window) {
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Поселение готово.");
if (std::exchange(host_after_replacement, false)) {
lan->host();
placement_message = L"Сетевая колония открыта. Адрес и код доступны в меню кооператива.";
if (lan->state() == LanState::Offline && session->can_host_legacy()) {
lan->host();
placement_message = L"Сетевая колония открыта. Адрес и код доступны в меню кооператива.";
} else {
placement_message = L"Кооператив требует готовую колонию со стандартными правилами.";
}
} else {
show_title_screen(window, false);
}
@@ -2201,7 +2216,8 @@ void draw_world(HDC dc, int width, int height) {
DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
auto details = has_blueprint() ? blueprint_details() :
selected_room_template != settlement::RoomTemplate::Empty
? std::wstring(house_contents[static_cast<std::size_t>(selected_room_template) - 1])
? std::wstring((world->staged_beds() ? house_contents : simple_house_contents)
[static_cast<std::size_t>(selected_room_template) - 1])
: resident_details();
if (work_panel == WorkPanel::Carpenter) {
const auto orders = std::count_if(world->production_orders().begin(), world->production_orders().end(),
+48
View File
@@ -0,0 +1,48 @@
# Select supported rules when starting a colony in the Win32 client
Task ID: S18-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
Isolated s18 worktree after root fast-forwards to db0a872 or a descendant containing the reviewed b7f18c0 client and 2759563 compiled profiles. S18-01 uses a long-lived runtime, exact default-only constructor/load, healthy views, transactional guest admission and fresh session identity. S19 core factory and validator already run the two real cost chains. M01-F6/F7 require validating initial, asynchronous and legacy hosts.
## 2. Objective and deliverables
Make the actual Russian title screen offer staged beds (default) or one-plank beds for a new colony, apply the selected compiled rules to the new world, reload either supported profile exactly, and restrict LAN protocol 11 to default rules before any network side effect.
## 3. Scope and non-goals
Only S18 profile selection/validation and accurate colony presentation. Preserve general S19 resolver, format1–14, LAN bridge/wire, legacy guest leave and unrelated keyboard/settings. Initial factory default stays staged, UI title selection is local to this process and only affects New.
## 4. Files to inspect
Read root/s18 actual app/title_screen_win32.hpp, viewer_win32.cpp, viewer_session.hpp/.cpp, tests/viewer_session_tests.cpp, colony_profile.hpp/.cpp (colony_rules, compile_colony_rules, make_colony_checkpoint, validate_colony_checkpoint), S19 profile_tests and S18/S19 docs. Inspect LAN direct and deferred host event paths BEFORE making changes, current supported_rules_ also supplies legacy guest import. Actual smoke sources client_{ui,handlers,regression}_smoke.cpp in temp.
## 5. Write ownership and coordination
Write scope: app/title_screen_win32.hpp; app/viewer_win32.cpp (title/new/host/bed labels only); app/viewer_session.hpp and .cpp (factory/validator/host readiness); tests/viewer_session_tests.cpp; docs/plan/systems/S18.md
Isolated s18 only. Other workers edit separate branches. Do not revert others' changes or modify CMake/other components. Root owns all Git/remote operations. Distinct test build directory.
## 6. Implementation or investigation approach
Use one accessible native control for a clearly labeled New-only choice, ensure keyboard (focus/Tab/arrows/Space/Enter as appropriate) and mouse operate at supported dimensions. Preserve title layout/order and new/continue/save list. Factory creates a new UUID and selected actual world; Continue/Open ignore current selector. Run candidate validation for both supplied initial and replacement/latest prepared loads before owner install and preserve current 32×32 restriction. Preserve default simple/inactive historical modes. Display correct cost including Miner house in simple profile; hide staged foundation material controls when simple.
## 7. Interfaces and data contracts
Host immediate path must reject if changing_world or the current authoritative publication does not have exact default rules. Recheck after returning from modal menu before opening a listener; deferred path revalidate the newly installed publication immediately before network start. Error preserves active world/local file operation/peer. Existing default simple legacy world can host if other established gates pass. Legacy guest import still uses exact frozen default. Do not expose optional rules via old wire. Keep S18-01 fresh ticket/epoch gating and bounded queues.
## 8. Dependencies and integration
Root owns fast-forward to integrated base before starting. Backend S19 and first viewer are independently accepted. New choice has real compiled behavior. Future S17 render-timer changes are separately owned; avoid edits to WM_TIMER or D3D unless a real unexpected dependency is reported.
## 9. Edge cases security and performance
Reject unknown/forged/extra manifests, optional+staged, unusable dimensions/identity before any effect. Restore valid default raw simple, active optional simple and authentic old saves. A superseded valid load followed by failing newest must keep current world. Titles with small width/DPI should retain usable label/control. No external files in real saves, never open real network beyond loopback.
## 10. Acceptance criteria
1. Real title New creates both variants (including exact selected manifest in saved checkpoint and visible costs). 2. Continue/Open preserve saved choice despite different selection, exact default old inactive/simple accepted. 3. Bad initial/load gate leaves session/world untouched. 4. Immediate/deferred legacy Host refusal before listener or peer change, including held optional load over old default. 5. Existing ten viewer tests, integration CTest and prior three-process/handler regressions still pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/client-profiles-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V, viewer suite selectors as actually registered and git diff --check. Run an actual GUI smoke with isolated LOCALAPPDATA, exercise both choices with mouse/key, New, save/open with opposite selector, confirm actual stored manifest/bed mode. Extend /tmp smoke only as appropriate and record client-profile-* source/logs. Named current published checks are baselines.
## 12. Constraints and stop conditions
Do not change staged vs simple game costs or default digest, add fake settings, change wire or unrelated app controls. No lowering exact-default admission. If title input cannot be exercised with available Windows/Wine tooling, describe specific gap and continue core meaningful checks. No children/commits/push; two failed same-cause fixes escalate.
## 13. Authorization and decisions
User asked for complete milestones/system branches and actual compatible module selection. M01-F7 recorded corrective host gate and accurate simple Miner description. Root owns external side effects. Existing upstream #4 tracks generic resolution.
## 14. Return format
Return S18-02 READY/PARTIAL, actual chosen title control + normal flow, exception/load/LAN boundaries, paths, commands/logs and any native UI caveats.
+48
View File
@@ -0,0 +1,48 @@
# Prove deterministic arbitration under opposing worker completion orders
Task ID: S21-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated system/s21-verification at 66af7c5. World assign_idle_agents calculates independent candidates for idle residents then assigns competing jobs in stable order. Meal claim is serial before parallel movement. Existing replay compares Current14 state for 1/2/6/12, last meal and mid-delivery plus capacity1; scheduler hooks currently before_submit/before_execute only. M01-P6/F9 request an observer of actual returns and readable divergence reports.
## 2. Objective and deliverables
Implement a minimal optional success observer in the real WorkerPool adapter, prove opposite actual calculation completions and deterministic arbitration, and report first divergence through domain facts tied to canonical bytes. Verify runtime install waits for outstanding work and fresh session fences stale results.
## 3. Scope and non-goals
WorkerPool instrumentation, tests and S21 verification docs only. No World scheduling/codec/receipt semantic changes, no synthetic exploit inputs or unrelated rendering/milestone changes. Native Windows hardware separate.
## 4. Files to inspect
Read engine/include/settlement/core/worker_pool.hpp, engine/src/worker_pool.cpp/world.cpp (actual partitions and meal selection), runtime source, tests/{executor,replay,runtime}_tests.cpp, M01-P6/F9 and S21. Void FuturePool/Testing at pinned clone and issue #15.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/worker_pool.hpp; tests/executor_tests.cpp; tests/replay_tests.cpp; tests/runtime_tests.cpp; NEW tests/replay_diagnostics.hpp only if useful; docs/plan/systems/S21.md
Isolated s21 only. Other agents own sibling source. No CMake mutations, shared project switch, children/Git/remote changes. Root integrates.
## 6. Implementation or investigation approach
NEW optional WorkerPoolOptions::after_execute(index), success-only after callable returns before result future ready. Account for optional observer alone in submission indexing. Preserve original no-hook path and hook/call behavior for void, values, lvalue refs, move-only closures/results and exceptions on worker + inline fallback. Observer exceptions reach corresponding future; no throwing destructor. Test using separate driver and bounded CV gate for two known submissions; release on all exit paths. Only block task B until A has actually returned (post hook), then reverse. Never wait for all tasks/lanes or rely on sleeps/scheduling chance.
## 7. Interfaces and data contracts
Fresh two-resident/one real reachable WorkJob scenario, opposite completion traces must be observed even with max_admitted1 on a separate driver, 2/6/12. Verify deterministic winner and each future state equal serial canonical Current14. Last berry serial claim test/cargo/movement preserve independent one-winner evidence, do not claim parallel meal arbitration. Add old worker held, queue same-world earlier load, verify old view remains readable/install pending until drained, replacement identity fresh, old request rejected, current state intact after further fence.
## 8. Dependencies and integration
Test-local semantic reporting only when canonical byte comparison differs (existing Current14 encoder remains oracle). Include seed/scenario, attempt/tick, concurrency/schedule, load, stable first differing entity/property and expected/actual, command/receipt player/number/status/revision or byte-offset fallback. Actor/job/storage stack as owner plus type for current14; support absent/extra records. Test at least stock/job/command divergences individually and equal-case. Later body15 will extend this; don't introduce alternate persistence schema. Reuse existing helpers/tests.
## 9. Edge cases security and performance
Bound waits even on CI; each branch releases gates before destroying/joining pool; no assertion library calls from worker threads. Keep hook captures alive; no mutex while running user callbacks. When no selector installed, no new allocations/counters per job. Tested genuine Submit paths including inline. No simulated full native performance claim.
## 10. Acceptance criteria
1. Tests fail when completion acknowledgement incorrectly moves to start, schedules traces must be opposite and canonical states match. 2. Observer sees returned value/reference/void, exceptions incl hook and overload, callable ownership preserved. 3. Reload barrier stale work/commands and snapshot fencing checked. 4. Domain diagnostics exercised with expected entity ID/field/receipt context. 5. All CTest, corpus, focused tags and docs checks pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V and --tag executor, --tag replay and --tag runtime under Wine; record s21-replay-* logs and commands. Old normal corpus should remain unchanged, use available trajectory probes as appropriate. Actual checks rather than latency claims.
## 12. Constraints and stop conditions
Stop if index pair cannot be tied to real first job-choice partition: identify actual code and adjust fixture, no pretend success. No global installation or unrelated changes. Two failed same-cause fixes escalate. No children/Git/remote writes.
## 13. Authorization and decisions
User authorizes complete M01 and separate S21 system branch; root approved test-only success observer and strict canonical oracle. [Void/Library completion test facility](https://git.faumaray.com/Void/Library/issues/15) documents the replacement test. Root publishes.
## 14. Return format
Return S21-01 READY/PARTIAL, bounded integration/worker semantics, branch files, tests with actual opposing traces/diagnostic cases/corpus, native limits.
+50
View File
@@ -0,0 +1,50 @@
# Compare authoritative custody state in journal and runtime replay
Task ID: S21-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
S21 sibling at 3c7cc3c merges approved replay ef980af with provisional live World/codec 539cea0, later partner fixes will be included. tests/replay_diagnostics.hpp canonical and tests/replay_tests.cpp saved_state still choose Current14, tests/runtime_tests.cpp bytes currently defaults to Legacy13. Both projections drop custody15. S15 owns tests/snapshot_tests.cpp. Released S21 real opposite-order tests and prior hashes must still pass.
## 2. Objective and deliverables
Use current complete raw15 state for replay/owner snapshots and identify divergent item owner, stack/reservation/transfer/receipt/balance when those facts change. Exercise retained cancel/retry and continuation on 1/2/6/12. Keep intentional legacy13/14 compatibility fixtures and golden outputs as separate existing coverage.
## 3. Scope and non-goals
Only test replay/diagnostics and their S21 explanation. No changes to application World, protocol/codec, CMake unless unavoidable for existing registered suites, generator/M02 or unrelated tests. This is a contracted validation extension of S21-01 (M01-F8/F9).
## 4. Files to inspect
Inspect tests/replay_tests.cpp, replay_diagnostics.hpp, runtime_tests.cpp, tests/custody_tests.cpp and custody_migration_tests.cpp, engine/include/settlement/core/{world,custody,simulation_runtime}.hpp, custody.cpp, world_save.cpp, S06-03/S15-04/docs/plan/custody.md and S21. Read surrounding domain projections and fallback.
## 5. Write ownership and coordination
Write scope: tests/replay_tests.cpp; tests/replay_diagnostics.hpp; tests/runtime_tests.cpp; docs/plan/systems/S21.md
Isolated s21 only. You share checkout state with others in separate working directories; do not revert others or change other WTs/branches, shared Serena or any Git/Gitea state. Parent handles schema source seals.
## 6. Implementation or investigation approach
Centralize canonical save selection in the test helper to Current15 and apply it to current replay & runtime owner world equality paths, preserving any explicit legacy compatibility expectations. Extend first-difference report from real public immutable facts with stable entity/owner IDs: resident/storage/order input stack quantities/IDs, execution and active claims, admission/operation receipt keys and result outcome, material balance. Compare canonical bytes first and retain unknown/opaque byte fallback. Organize human-readable distinctions so stock change still reports stock, before a secondary balance if relevant. Do not construct huge diagnostic maps on equality.
## 7. Interfaces and data contracts
Consume Inventory::stack_id, Agent.execution and next_admission, ProductionOrder.input and suspended, World::item_balances(), custody_receipts() and public receipt/request/result. A public vector is a ring backing store; use key and true order only when authoritative, avoid exposing physical ring layout as game identity. No modifying private counters nor pointers into mutable shared data for assertions. Use a valid game action/migrated world with same historical projection but differing modern owner/receipts if possible (old projected world loaded vs originating modern).
## 8. Dependencies and integration
Real source base includes custody and codec; parent will furnish final stricter validation and zero-count terminal semantics as local commits. S06 owns normal domain fixtures S15 authenticated raw15/history; S21 owns comparison and divergent-entity diagnostics, runtime stale/reload, not another codec test. External library support references existing issue #15 real execution, #7 ids/#8 transfer only if relevant. No request creation.
## 9. Edge cases security and performance
Only derive proof from real accepted actions with invariant-valid states. Catch first divergence when original legacy projection matches despite changed durable facts; do not falsely flag a different ring backing index as a logical change. Preserve old positive-negative receipt/stale owner and reproducible opposing completion trace. Keep replay test runtime bounded (first compare bytes and build facts on mismatch only). Notify root early of genuine production defects.
## 10. Acceptance criteria
1. Current canonical captures include all custody state on real replay and after load; regression makes prior projection blind yet new one finds named entity/step. 2. Existing identity/stock/job/context and byte fallback still work. 3. Continue canceled in-flight durable cargo through checkpoint on serial/2/6/12, retained replay/conflict without physical duplicate. 4. Root can integrate while all registered tests, 24 actual completion traces and historical golden checks remain intact.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Focus --tag replay and --tag runtime after build, full CTest -V, named /tmp/stoneheart-milestones.xprJ2SVp/s21-custody-*.log and git diff --check. Authentic raw13 corpora old-trajectory.bin + identity-compat-old.bin independently validated by S06; compare if behavior or underlying partner revisions change.
## 12. Constraints and stop conditions
No application edits, publishing, shared source checkout switch, new helper API into World or script internals just for diagnostics. If blocked by partner fix, obtain it through root while implementing independent diagnostics; report exact evidence. Review independent via root.
## 13. Authorization and decisions
Approved milestone/system work plus explicit exact-state replay and ID diagnostics from M01. Root keeps transient cross-branch commits local pending package acceptance.
## 14. Return format
Return S21-02 READY or PARTIAL with real base, owned diff, command results, source domain/id and regression observations, test runtime and external dependencies.
Worktree now at `e26b9c2` includes the stricter S06 validator and S15 zero-count terminal effects, count budgets and authentic migration/ring tests from `ccd50ec`. Begin on this combined source.
+9 -3
View File
@@ -1,6 +1,6 @@
# S18. Интерфейс, управление и обратная связь
Статус — первый срез S18-W01 реализован: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — первый срез S18-W01 и выбор двух встроенных правил S18-02 реализованы: существующий Win32-клиент читает опубликованные снимки и получает результаты команд и файловых операций асинхронно. Остальные части интерфейса остаются планом. Интерфейс должен давать игроку понятный путь от выбора правил до устойчивого города и объяснять препятствия в работе жителей. Первый полный путь проверяется в [M03](../milestones/M03.md), сетевые состояния — в [M09](../milestones/M09.md), доступность и установка — в [M11](../milestones/M11.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
@@ -16,7 +16,11 @@
## Последовательность реализации
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное и загружаемое состояние проверяются на карту 32×32 и точное совпадение поддержанного стандартного состава правил. Настоящие альтернативные правила относятся к [S19](S19.md).
Первый срез S18-W01 отделяет владение миром от оконных обработчиков через [ViewerSession](../../../app/viewer_session.hpp). Один `SimulationRuntime` и один `CheckpointFiles` живут до выхода из приложения. Новый мир, загрузка и выход гостя устанавливают подготовленное состояние через билет загрузки с новой инкарнацией; долгий тик не требует ожидания или остановки прежнего потока в окне. Отображение удерживает неизменяемый мир, а гость сохраняет последнее полученное состояние для продолжения после явного выхода из сети. Начальное, непосредственно заменяемое и последнее подготовленное состояние проходят `validate_colony_checkpoint` из [S19](S19.md) до установки и дополнительно ограничены картой 32×32. Допускаются только точные встроенные составы стандартной колонии и `settlement.plankbeds`; неизвестный, лишний или изменённый пакет, пустой мир, нулевой идентификатор либо поэтапная кровать с простыми правилами отклоняются с сохранением текущего мира.
На настоящем главном экране нативный список «Правила только новой колонии» выбирает поэтапную кровать с опорой и тканью (исходный выбор) либо простую кровать из одной доски. Выбор живёт в процессе и применяется только кнопкой «Новая колония»: `make_colony_checkpoint` создаёт соответствующий мир, новый UUID и точный манифест. «Продолжить», список сохранений и выбор файла восстанавливают правила самого сохранения. Исторический стандартный мир с простыми кроватями, поэтапными кроватями или без активного сценария принимается без смены режима. В простом режиме описания всех готовых домов, включая дом шахтёра, показывают одну доску; выбор деревянной/каменной опоры скрыт.
Старый LAN-протокол 11 допускает только точный стандартный манифест из текущей авторитетной публикации. Проверка выполняется при выборе Host после возврата из модального меню, а для отложенного создания — повторно перед запуском сети после установки мира. Пока ожидается любая смена мира, Host отклоняется без замены мира, отмены загрузки или изменения сетевого объекта. Даже если опубликованный старый мир стандартный, ожидающая загрузка простых правил не открывает слушатель. Выход старого гостя по-прежнему присваивает полученному миру замороженные стандартные правила; формат LAN не расширен.
Локальная очередь ограничена 64 намерениями и одной отправленной командой. Номер запроса берётся из подтверждённого снимка; занятая очередь владельца оставляет намерение для повтора. Чертёж комнаты, мебели или старого домика удаляется только после принятого результата. Отказ сохраняет возможность редактирования, повторное нажатие не дублирует ожидающую операцию. Гостевые квитанции сопоставляются с ограниченной очередью отправок и поколением сессии. Таймер обслуживает завершения также на главном экране и внутри модальных меню. Одиночная пауза и выбор файла приостанавливают игровое время; меню хозяина сохраняет существующее сетевое поведение.
@@ -24,6 +28,8 @@
Проверка среза: сборка Windows x64 GCC 16.2; Wine 11, verbose CTest — 99 проверок ядра, 9 LAN и 10 состояния клиента. Отдельный прогон настоящего `settlement_viewer.exe` прошёл создание колонии, движение времени, подтверждённую смену приоритета, модальную паузу, выбор файла сохранения, продолжение партии, загрузку нового формата через главное меню в новом процессе, отказ повреждённого файла, загрузку старого формата из списка и штатное закрытие трёх процессов. Сохранения размещались в отдельном временном `LOCALAPPDATA`. Дополнительный Win32-прогон настоящих обработчиков проверил отказ и повтор чертежа, принятую комнату при переносе другой комнаты, старый домик через общий журнал, отрисовку и сохранение при заблокированном тике, смену мира и гостя без ожидания тика. Регрессионный прогон проверил отказ ошибочного повторного подключения с сохранением полученной колонии, откат при отказе владельца после подготовки соединения и запрет подтверждения сноса во время ожидающей загрузки. Отдельная проверка состояния клиента покрывает остановку после сбоя, успешную загрузку и возобновление тиков. Нативная Windows, доступность и визуальная проверка масштабирования остаются отдельной приёмкой; настройки масштаба, клавиш и звука за пределами этого среза.
Проверка S18-02: повторная Windows x64 GCC 16.2 сборка и verbose CTest под Wine 11 — 122 проверки ядра, 9 LAN и 14 состояния клиента. Четыре новые проверки покрывают оба профиля при создании/сохранении/повторной загрузке, начальные и асинхронные отказы манифестов и идентификаторов, отмену актуальности старой правильной загрузки последующей несовместимой, исторические режимы и стандартный импорт гостя. Отдельный прогон настоящего приложения в изолированном `LOCALAPPDATA` проверяет окно 775×640, Tab/стрелки и мышь в нативном списке, мышь/Space на «Новая колония», точные манифесты и режимы в реальных сохранениях, продолжение, список и диалог открытия при противоположном выборе новых правил. Новый процесс возвращает стандартный выбор новой колонии и открывает последнее сохранение с простыми правилами. Прогон настоящих обработчиков удерживает загрузку простого мира поверх стандартного при прямом Host и Host из модального меню, проверяет сохранение мира/билета/сетевого объекта/кода/порта и отсутствие слушателя; отложенный Host повторно отклоняет несовместимую установленную публикацию. Проверены скрытие опор и описание дома шахтёра. Нативная Windows, экранный диктор и повышенный DPI остаются отдельной приёмкой.
1. **S18-W01, M01–M02.** Отделить чтение снимков и отправку команд от Win32-обработчиков. Определить модель состояния инструмента, выделения и отмены. Добавить настройку масштаба, клавиш и звука с проверкой конфликтов назначений.
2. **S18-W02, M02–M03.** Собрать путь демо. Игрок размечает склон, ставит склад, выбирает этаж, редактирует дом, видит материалы и подтверждает строительство. Затем назначает мебель, проверяет потребности жителей и сохраняет незавершённую работу.
3. **S18-W03, M04–M06.** Добавить панели рабочих очередей, профессий, запасов и торговых сделок. Фильтры и сортировки устойчиво сохраняют выбранный объект при обновлении снимка. Список населения ведёт к жителю или объясняет его нахождение в другом регионе.
@@ -50,7 +56,7 @@
## VoidLibrary
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
Сверить доступные возможности конфигурации, строк, Unicode, коллекций, наблюдаемости и диспетчеризации в закреплённой VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности до локальной реализации найти или открыть issue в `Void/Library`, указав необходимое поведение и Windows-проверку. Срез использует `SimulationRuntime` и `CheckpointFiles` поверх закреплённой версии `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, без нового исполнителя. Выбор S18-02 использует готовые фабрику и проверку профилей S19; общий пробел разрешения пакетов связан с [Void/Library #4](https://git.faumaray.com/Void/Library/issues/4). Схема игровых правил и нативные контролы остаются у игры. Повторно используются связанные пробелы [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5) для удержания опубликованного состояния и [#6](https://git.faumaray.com/Void/Library/issues/6) для результатов команд. Условие будущей замены — сохранить проверенные отказы очереди, отсечение старой инкарнации, результат отклонённой команды и удержание предыдущего снимка. Наличие библиотеки не переносит авторитет игровой команды из симуляции в интерфейс. [Матрица VoidLibrary](../void-library.md)
## Приёмка
+113
View File
@@ -73,3 +73,116 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
Текущие тесты используют `Void::Testing`. Перед собственным runner, профилировщиком, таймером, журналом и форматом отчёта проверить существующие возможности VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности найти или создать issue в `Void/Library`, приложить воспроизводимый пример нужного поведения и связать локальную реализацию с issue. [Матрица VoidLibrary](../void-library.md)
Система принята, когда каждый обязательный сценарий имеет команду запуска либо точную ручную процедуру, исходный мир, фактический результат и границы среды. Финальный отчёт различает кросс-сборку, Wine, нативную Windows, физические ПК и измерения GPU. Готовность пакета подтверждается запуском из поставки с её библиотеками и материалами. [Сохранения](S15.md) · [Сеть](S16.md) · [Происхождение материалов](S20.md)
## M01: наблюдаемый порядок завершения (S21-01)
Проверка подготовлена поверх `66af7c5` в `system/s21-verification`. Закреплённый
Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `FuturePool::try_submit`
с сохранением отклонённого callable и доставкой исключений через future. Его
`Testing::DeterministicRun` управляет тестовыми действиями; он не наблюдает возврат
реального `World` callable. Поэтому локальный `WorkerPoolOptions::after_execute(index)`
вызывается после успешного возврата callable, перед готовностью future. Исключение
наблюдателя попадает в тот же future; ошибка до исполнения или внутри callable
не вызывает наблюдателя. Без хуков остаётся прежняя ветка без счётчика отправок.
[Реализация](../../../engine/include/settlement/core/worker_pool.hpp) ·
[Контракт замены Void/Library#15](https://git.faumaray.com/Void/Library/issues/15).
Условие замены локального наблюдателя библиотечным — сохранить проверяемые возврат
`void`, значения, lvalue-ссылки, move-only результата и callable, ровно одно
успешное уведомление, исключения и исполнение при переполнении на координаторе.
[ExecutorTests](../../../tests/executor_tests.cpp) дополнительно удерживает сам
наблюдатель и проверяет, что future ещё не готов. Перенос уведомления к началу
вызова нарушает проверку завершённого действия.
[ReplayTests](../../../tests/replay_tests.cpp) использует два отдельных сценария:
- Seed 101, два жителя в `(5,1)`, одно достижимое общее задание в `(1,1)`.
При 2/6/12 потоках первые отправки 0 и 1 — реальные независимые вычисления
`choose_jobs` для жителей 0 и 1. Контроллер разрешает первый расчёт, ждёт его
`after_execute`, затем разрешает второй. Получены обе последовательности
`A->B` и `B->A`; владельцем задания остаётся житель с меньшим стабильным ID.
- Seed 97, два голодных жителя и одна ягода. Здесь общих заданий нет, поэтому
отправки 0 и 1 — стадии продвижения жителей. Захват еды выполняется
последовательно в `assign_meals` до этих стадий. Проверяются противоположные
завершения продвижения, один владелец, сохранность ягоды и ровно одно потребление;
параллельный арбитраж еды этим сценарием не заявляется.
Оба сценария проверены с `max_admitted=4096` и `1`. Контроллер находится вне
координатора, который при переполнении сам может ждать в inline callable.
Ожидания ограничены пятью секундами; scope guard всегда открывает ворота до
ожидания координатора или разрушения пула. Каждая из 24 конфигураций сравнивает
все 40 тактов с последовательным эталоном через настоящий `Current15` writer.
Лог содержит фактическую последовательность завершений каждой конфигурации.
[RuntimeTests](../../../tests/runtime_tests.cpp) удерживает старую задачу во время
постановки загрузки того же сохранения в очередь. Пока задача удержана, доступны
старый неизменяемый снимок и захват сохранения, а установка и старая команда ещё
не завершены. Перед захватом кандидата проверяется равенство числа начатых и
вернувшихся задач. После установки меняется session, старая команда получает
`StaleSession`; дополнительный барьер и следующий такт подтверждают неизменность
старого снимка и соответствие нового мира эталону.
[Test-local диагностика](../../../tests/replay_diagnostics.hpp) сначала сравнивает
канонические байты. Только при несовпадении она показывает первый различающийся
публичный факт с ID жителя, задания или производства, именем поля и значениями
expected/actual. Для запасов указываются владелец, тип предмета и ID стека,
для команд — игрок и следующий номер.
Сравнение квитанций содержит игрока, номер команды, статус, tick и revision.
Контекст включает первый обнаруженный tick/attempt, seed мира, число потоков,
расписание, состояние загрузки и предел допуска. Непокрытое публичной проекцией
поле получает смещение и значения байта. Это диагностическая проекция, а не
второй кодек или альтернативный критерий равенства. Отдельно проверены равенство,
ошибки запаса/задания/команды/квитанции, лишний ID и байтовый fallback.
Проверка 2 декабря 2026 года: Windows x64 Release кросс-сборка GCC 16.2.0,
выполнение Wine 11.0. CTest `-V`: 3/3 цели, 141 core + 9 LAN + 10 viewer тестов.
Отдельные теги: executor 10/10, replay 8/8, runtime 11/11. Логи:
`/tmp/stoneheart-milestones.xprJ2SVp/s21-replay-{configure,build,ctest,executor,replay,runtime}.log`.
Повторная окончательная сборка/CTest: `s21-replay-final-build.log`, `s21-replay-final-ctest.log` (3/3, 18,35 с).
Два внешних probe собраны заново против этой библиотеки; при 1/2/6/12 потоках
`cmp` подтвердил совпадение обоих исторических корпусов:
- `trajectory.cpp`: 361 такт, 5 приёмов пищи; SHA-256
`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`.
- `identity-compat.cpp`: доставка и строительство после удаления других объектов;
SHA-256 `05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`.
Логи probe: `s21-replay-probe-build.log`, `s21-replay-golden.log` в том же каталоге.
Физическая Windows, длительная нагрузка и производительность GPU здесь не проверялись.
Serena/граф были связаны с основным checkout; для изолированного worktree использована
прямая проверка исходников без переключения общего проекта и без заявления о покрытии графом.
## Полное состояние владения грузом
Потактный эталон и сравнение публикаций владельца используют `Current15`.
Сравнение включает имущество у производства, приостановку заказа, следующий
номер назначения, действующее исполнение и его резервы, результаты передач
и баланс каждого предмета. При расхождении диагностика показывает сначала
видимое изменение запасов или задания, затем постоянные ID и шаги исполнения,
сохранённые результаты и счётчики баланса. Ключ квитанции состоит из вида,
ID и номера операции. Положение квитанции в кольцевом буфере не служит её ID.
Если публичные факты совпали, сравнение сообщает первое различие байтов.
Проверка загрузки прежнего формата создаёт корректные миры с одинаковыми
байтами `Current14` и разными данными `Current15`. Она выявляет восстановленный
ID стека, различие начального остатка и начисления и отсутствие квитанции
назначения в историческом сохранении. Диагностический пример сообщает
`stock owner=storage:1 item=3 field=stack_id expected=2 actual=1`.
Отдельный сценарий отменяет настоящую стройку после доставки, заполняет
исходный склад и возвращает одну доску в склад вместимостью один предмет.
Оставшиеся две доски и два каменных блока ждут места у того же исполнителя
с тем же ID передачи. Контрольная точка восстанавливается на 1/2/6/12
исполнителях. После появления свободного склада каждый такт совпадает
с непрерывной партией. Точные и конфликтующие повторы квитанций назначения
и отмены проверяются до и после загрузки и после возврата груза.
Windows x64 Release GCC 16.2 под Wine 11 выполнил 10 проверок `replay` за 2,71 с
и 11 проверок `runtime` за 30 мс на рабочем срезе `e26b9c2` с этой проверкой.
Все 24 расписания завершения настоящих задач сохранились. Сценарий частичного
возврата занял 19,1 мс. Логи находятся в
`/tmp/stoneheart-milestones.xprJ2SVp/s21-custody-{configure,build-final,replay,runtime}.log`.
После объединения с исправлением проверки времени и ссылок S06 в `8522f91`
повторная сборка и CTest завершились с кодом 0. Все три цели прошли за 26,91 с,
включая 169 проверок ядра, 9 LAN и 10 клиента. Журналы этой сборки и запуска —
`s21-custody-build-validated.log` и `s21-custody-ctest-validated.log`.
+16 -3
View File
@@ -21,6 +21,9 @@ struct WorkerPoolOptions {
std::function<void(std::size_t)> before_worker_start;
std::function<void(std::size_t)> before_submit;
std::function<void(std::size_t)> before_execute;
// Success-only observation after invocation returns, before future readiness.
// A throwing observer fails that future. Replacement contract: Void/Library#15.
std::function<void(std::size_t)> after_execute;
};
class WorkerPool {
@@ -38,12 +41,22 @@ public:
if (executor_->is_executor_thread()) {
throw std::logic_error("cannot submit nested work to the same worker pool");
}
if (options_.before_submit || options_.before_execute) {
if (options_.before_submit || options_.before_execute || options_.after_execute) {
const auto index = submission_index_.fetch_add(1, std::memory_order_relaxed);
if (options_.before_submit) options_.before_submit(index);
return admit([this, index, function = std::forward<Function>(function)]() mutable -> decltype(auto) {
return admit([this, index, function = std::forward<Function>(function)]() mutable
-> std::invoke_result_t<Function> {
if (options_.before_execute) options_.before_execute(index);
return std::invoke(function);
if (!options_.after_execute) return std::invoke(function);
using Result = std::invoke_result_t<Function>;
if constexpr (std::is_void_v<Result>) {
std::invoke(function);
options_.after_execute(index);
} else {
Result result = std::invoke(function);
options_.after_execute(index);
return result;
}
});
}
return admit(std::forward<Function>(function));
+102 -1
View File
@@ -6,6 +6,9 @@
#include <atomic>
#include <chrono>
#include <array>
#include <condition_variable>
#include <mutex>
#include <future>
#include <memory>
#include <sstream>
@@ -82,6 +85,8 @@ void check_world_unwind(std::size_t phase, bool submit_failure) {
}
struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing::Suite<ExecutorTests> {
[[= Void::Testing::tag("executor")]] Test test_completion_observer_results_and_failures();
[[= Void::Testing::tag("executor")]] Test test_completion_observer_precedes_future_readiness();
[[= Void::Testing::tag("executor")]] Test test_limits_and_nested_submission();
[[= Void::Testing::tag("executor")]] Test test_capacity_retains_move_only_work_and_exceptions();
[[= Void::Testing::tag("executor")]] Test test_failed_callable_transfer_releases_capacity();
@@ -92,6 +97,102 @@ struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing:
[[= Void::Testing::tag("executor")]] Test test_world_capacity_one_matches_reference();
};
// Exercise the same wrapper on a worker and on the submitting thread. Keeping
// index zero admitted forces every other submission through inline overload.
Test ExecutorTests::test_completion_observer_results_and_failures() {
for (bool inline_work : {false, true}) {
std::promise<void> release;
auto permit = release.get_future().share();
std::promise<void> entered;
auto running = entered.get_future();
std::array<std::atomic<int>, 8> observed{};
std::array<std::atomic<bool>, 8> returned{};
std::atomic<bool> observed_too_early{false};
WorkerPoolOptions options{.max_admitted = inline_work ? 1U : 4096U};
options.before_submit = [](std::size_t index) {
if (index == 8) throw std::bad_alloc();
};
options.before_execute = [](std::size_t index) {
if (index == 6) throw std::runtime_error("before invocation");
};
options.after_execute = [&](std::size_t index) {
if (index >= observed.size()) throw std::logic_error("observer on failed submission");
if (!returned[index].load()) observed_too_early.store(true);
++observed[index];
if (index == 7) throw std::runtime_error("after invocation");
};
WorkerPool pool(2, std::move(options));
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
auto held = pool.submit([&] {
entered.set_value();
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout");
returned[0] = true;
});
require(running.wait_for(5s) == std::future_status::ready);
const auto caller = std::this_thread::get_id();
auto value = pool.submit([&] {
returned[1] = true;
return std::pair{17, std::this_thread::get_id() == caller};
});
require(value.get() == std::pair{17, inline_work});
int referent = 23;
auto reference = pool.submit([&]() -> int& { returned[2] = true; return referent; });
require(&reference.get() == &referent);
auto nothing = pool.submit([&] { returned[3] = true; });
nothing.get();
auto owned = pool.submit([&, value = std::make_unique<int>(31)]() mutable {
returned[4] = true;
return std::move(value);
});
require(*owned.get() == 31);
auto failure = pool.submit([]() -> int { throw std::runtime_error("invocation failed"); });
expect_throw<std::runtime_error>([&] { static_cast<void>(failure.get()); });
auto before = pool.submit([&] { returned[6] = true; });
expect_throw<std::runtime_error>([&] { before.get(); });
auto after = pool.submit([&] { returned[7] = true; });
expect_throw<std::runtime_error>([&] { after.get(); });
bool submitted_failure_ran = false;
expect_throw<std::bad_alloc>([&] {
static_cast<void>(pool.submit([&] { submitted_failure_ran = true; }));
});
require(!submitted_failure_ran);
release_task.release();
release.set_value();
held.get();
for (std::size_t i = 0; i < observed.size(); ++i) {
require(observed[i] == ((i == 5 || i == 6) ? 0 : 1));
}
require(!returned[6] && !observed_too_early);
}
}
Test ExecutorTests::test_completion_observer_precedes_future_readiness() {
std::promise<void> observed;
auto entered = observed.get_future();
std::promise<void> release;
auto permit = release.get_future().share();
std::atomic<int> calls{0};
WorkerPoolOptions options;
// Observer alone must enable monotonically increasing submission indices.
options.after_execute = [&](std::size_t index) {
if (index != static_cast<std::size_t>(calls.fetch_add(1))) throw std::runtime_error("bad index");
if (index == 0) {
observed.set_value();
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout");
}
};
WorkerPool pool(2, std::move(options));
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
auto result = pool.submit([] { return 11; });
require(entered.wait_for(5s) == std::future_status::ready);
require(result.wait_for(0s) == std::future_status::timeout);
release_task.release();
release.set_value();
require(result.get() == 11);
pool.submit([] {}).get();
require(calls == 2);
}
Test ExecutorTests::test_limits_and_nested_submission() {
expect_throw<std::invalid_argument>([] { WorkerPool pool(1); });
expect_throw<std::invalid_argument>([] { WorkerPool pool(2, {.max_admitted = 0}); });
@@ -118,7 +219,7 @@ Test ExecutorTests::test_capacity_retains_move_only_work_and_exceptions() {
const auto coordinator = std::this_thread::get_id();
std::atomic<int> executions{0};
auto answer = pool.submit([value = std::make_unique<int>(17), coordinator, &executions] {
require(std::this_thread::get_id() == coordinator);
if (std::this_thread::get_id() != coordinator) throw std::runtime_error("expected inline work");
++executions;
return *value;
});
+218
View File
@@ -0,0 +1,218 @@
#pragma once
#include "settlement/core/world.hpp"
#include <algorithm>
#include <map>
#include <sstream>
#include <string>
#include <type_traits>
namespace replay_diagnostics {
using namespace settlement;
struct Context {
std::uint64_t attempt = 0;
std::size_t workers = 1;
std::string schedule = "uncontrolled";
std::string load = "uninterrupted";
std::size_t capacity = 4096;
};
inline std::string canonical(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current15);
return stream.str();
}
template<class T> std::string value(T item) {
if constexpr (std::is_enum_v<T>) return std::to_string(static_cast<unsigned>(item));
else return std::to_string(item);
}
inline std::string value(GridPosition p) { return "(" + value(p.x) + "," + value(p.y) + ")"; }
inline std::string value(StockOwner owner) { return value(owner.kind) + ":" + value(owner.id); }
inline std::string value(const std::vector<GridPosition>& route) {
std::string text = "[";
for (auto p : route) text += value(p) + ",";
return text + "]";
}
// Diagnostic projection of public domain objects, never a save parser or an
// alternate equality oracle. Unknown/private fields retain the byte fallback.
// Prefer visible stock/job changes, then durable identities, retained results
// and accounting. A secondary balance change must not hide the changed stock.
using Facts = std::map<std::pair<unsigned, std::string>, std::string>;
inline Facts facts(const World& world) {
Facts out;
const auto put = [&](const std::string& owner, const char* field, const auto& item, unsigned priority = 0) {
out[{priority, owner + " field=" + field}] = value(item);
};
for (const auto& a : world.agents()) {
const auto key = "agent id=" + value(a.id);
#define AGENT_FIELD(field) put(key, #field, a.field)
AGENT_FIELD(position); AGENT_FIELD(state); AGENT_FIELD(current_job);
AGENT_FIELD(route); AGENT_FIELD(route_cursor); AGENT_FIELD(work_remaining);
AGENT_FIELD(resource_node_id); AGENT_FIELD(storage_id); AGENT_FIELD(haul_route);
AGENT_FIELD(production_id); AGENT_FIELD(hunger); AGENT_FIELD(fatigue);
AGENT_FIELD(resting_on_ground); AGENT_FIELD(profession);
#undef AGENT_FIELD
put(key, "next_admission", a.next_admission, 1);
put(key, "transfer_id", a.execution ? a.execution->id : 0, 1);
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto stock = "stock owner=agent:" + value(a.id) + " item=" + value(item);
put(stock, "count",
a.inventory.item_count(static_cast<ItemType>(item)));
put(stock, "stack_id", a.inventory.stack_id(static_cast<ItemType>(item)), 1);
}
if (a.execution) {
const auto& transfer = *a.execution;
const auto transfer_key = "transfer id=" + value(transfer.id) + " owner=agent:" + value(a.id);
put(transfer_key, "kind", transfer.kind, 1);
put(transfer_key, "production", transfer.production, 1);
put(transfer_key, "source", transfer.source, 1);
put(transfer_key, "destination", transfer.destination, 1);
put(transfer_key, "next_operation", transfer.next_operation, 1);
put(transfer_key, "blocked", transfer.blocked, 1);
put(transfer_key, "reservation_count", transfer.reservation_count, 1);
for (const auto& claim : transfer.reservations) {
if (!claim.id) continue;
const auto claim_key = "reservation id=" + value(claim.id) + " transfer=" + value(transfer.id);
put(claim_key, "kind", claim.kind, 1);
put(claim_key, "owner", claim.owner, 1);
put(claim_key, "stack_id", claim.stack, 1);
put(claim_key, "item", claim.item, 1);
put(claim_key, "count", claim.count, 1);
put(claim_key, "backing", claim.backing, 1);
put(claim_key, "origin_storage", claim.origin_storage, 1);
}
}
}
for (const auto& j : world.jobs()) {
const auto key = "job id=" + value(j.id);
put(key, "position", j.position); put(key, "state", j.state);
put(key, "work_required", j.work_required); put(key, "work_remaining", j.work_remaining);
}
for (const auto& p : world.production_orders()) {
const auto key = "production id=" + value(p.id);
put(key, "position", p.position); put(key, "recipe", p.recipe); put(key, "state", p.state);
put(key, "collected_stops", p.collected_stops); put(key, "bed_owner", p.bed_owner);
put(key, "bed_base", p.bed_base); put(key, "bed_stage", p.bed_stage);
put(key, "suspended", p.suspended, 1);
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto stock = "stock owner=production:" + value(p.id) + " item=" + value(item);
put(stock, "count", p.input.item_count(static_cast<ItemType>(item)));
put(stock, "stack_id", p.input.stack_id(static_cast<ItemType>(item)), 1);
}
for (const auto& m : p.materials) {
put(key + " material owner=storage:" + value(m.storage_id) + " item=" + value(m.type),
"count", m.count);
}
for (std::size_t i = 0; i < p.delivery_stops.size(); ++i) {
const auto stop = key + " stop=" + value(i);
put(stop, "storage_id", p.delivery_stops[i].storage_id);
put(stop, "route_to_next", p.delivery_stops[i].route_to_next);
}
}
for (const auto& s : world.storages()) {
const auto key = "storage id=" + value(s.id);
put(key, "position", s.position); put(key, "capacity", s.capacity);
put(key, "reserved_slots", s.reserved_slots); put(key, "kind", s.kind);
for (const auto& stack : s.items) {
const auto stock = "stock owner=storage:" + value(s.id) + " item=" + value(stack.type);
put(stock, "count", stack.count); put(stock, "reserved", stack.reserved);
put(stock, "stack_id", stack.id, 1);
}
}
// Keys identify logical results independently of the ring's backing slots.
for (const auto& receipt : world.custody_receipts()) {
const auto& request = receipt->request;
const auto& result = receipt->result;
const auto key = "custody receipt kind=" + value(request.key.kind) + " id=" + value(request.key.id) +
" ordinal=" + value(request.key.ordinal);
put(key, "operation", request.operation, 2);
put(key, "kind", request.kind, 2);
put(key, "production", request.production, 2);
put(key, "source", request.source, 2);
put(key, "destination", request.destination, 2);
put(key, "line_count", request.line_count, 2);
for (std::size_t i = 0; i < request.line_count; ++i) {
const auto line_key = key + " line=" + value(i);
put(line_key, "storage", request.lines[i].storage, 2);
put(line_key, "item", request.lines[i].item, 2);
put(line_key, "count", request.lines[i].count, 2);
}
put(key, "status", result.status, 2);
put(key, "transfer_id", result.transfer, 2);
put(key, "terminal", result.terminal, 2);
put(key, "reservation_count", result.reservation_count, 2);
put(key, "effect_count", result.effect_count, 2);
for (std::size_t i = 0; i < result.reservation_count; ++i) {
put(key + " reservation=" + value(i), "id", result.reservations[i], 2);
}
for (std::size_t i = 0; i < result.effect_count; ++i) {
const auto effect_key = key + " effect=" + value(i);
const auto& effect = result.effects[i];
put(effect_key, "owner", effect.owner, 2);
put(effect_key, "stack_id", effect.stack, 2);
put(effect_key, "item", effect.item, 2);
put(effect_key, "count", effect.count, 2);
}
}
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto key = "balance item=" + value(item);
const auto& balance = world.item_balances()[item - 1];
put(key, "opening", balance.opening, 3);
put(key, "grant", balance.grant, 3);
put(key, "harvest", balance.harvest, 3);
put(key, "recipe_output", balance.recipe_output, 3);
put(key, "recipe_input", balance.recipe_input, 3);
put(key, "meal", balance.meal, 3);
put(key, "installation", balance.installation, 3);
put(key, "demolition", balance.demolition, 3);
}
for (std::uint8_t player = 1; player <= colony_player_slots; ++player) {
put("command player=" + value(player), "next_sequence", world.next_command_sequence(player));
}
return out;
}
inline std::string context(const World& world, const Context& c) {
return "replay divergence tick=" + value(world.tick()) + " attempt=" + value(c.attempt) +
" seed=" + value(world.seed()) + " workers=" + value(c.workers) + " schedule=" + c.schedule +
" load=" + c.load + " capacity=" + value(c.capacity) + " ";
}
inline std::string difference(const World& expected, const World& actual, const Context& c = {}) {
const auto left = canonical(expected), right = canonical(actual);
if (left == right) return {};
const auto a = facts(expected), b = facts(actual);
auto ai = a.begin(), bi = b.begin();
while (ai != a.end() || bi != b.end()) {
if (bi == b.end() || (ai != a.end() && ai->first < bi->first)) {
return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=<absent>";
}
if (ai == a.end() || bi->first < ai->first) {
return context(expected, c) + bi->first.second + " expected=<absent> actual=" + bi->second;
}
if (ai->second != bi->second) {
return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=" + bi->second;
}
++ai; ++bi;
}
const auto mismatch = std::mismatch(left.begin(), left.end(), right.begin(), right.end());
const auto offset = static_cast<std::size_t>(mismatch.first - left.begin());
const auto byte = [offset](const std::string& bytes) {
return offset < bytes.size() ? value(static_cast<unsigned char>(bytes[offset])) : "<end>";
};
return context(expected, c) + "byte=" + value(offset) + " expected=" + byte(left) + " actual=" + byte(right);
}
inline std::string receipt_difference(const World& world, const PlayerCommand& command,
CommandReceipt expected, CommandReceipt actual, const Context& c) {
if (expected.status == actual.status && expected.tick == actual.tick && expected.revision == actual.revision) return {};
const auto receipt = [](CommandReceipt r) {
return "{status=" + value(r.status) + ",tick=" + value(r.tick) + ",revision=" + value(r.revision) + "}";
};
return context(world, c) + "command player=" + value(command.player) + " sequence=" + value(command.sequence) +
" field=receipt expected=" + receipt(expected) + " actual=" + receipt(actual);
}
} // namespace replay_diagnostics
+313 -19
View File
@@ -1,10 +1,18 @@
#include "settlement/core/world.hpp"
#include "settlement/core/checkpoint.hpp"
#include "replay_diagnostics.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <condition_variable>
#include <future>
#include <iostream>
#include <mutex>
#include <cstddef>
#include <cstdint>
#include <memory>
@@ -37,9 +45,7 @@ void require(bool condition, std::string_view message) {
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
return replay_diagnostics::canonical(world);
}
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config,
@@ -66,6 +72,7 @@ public:
}
void step() {
++attempt_;
reference->step();
for (auto& run : runs_) run.world->step();
compare();
@@ -75,9 +82,10 @@ public:
std::uint64_t expected_tick, std::uint64_t expected_revision) {
const auto check = [&](World& world) {
const auto result = world.apply_command(command);
require(result.status == expected_status && result.tick == expected_tick &&
result.revision == expected_revision,
"command receipt differs from the recorded status, tick or revision");
const auto diagnostic = replay_diagnostics::receipt_difference(world, command,
{expected_status, expected_tick, expected_revision}, result,
{attempt_, world.worker_count(), "journal", "command", options_.max_admitted});
require(diagnostic.empty(), diagnostic);
};
check(*reference);
for (auto& run : runs_) check(*run.world);
@@ -102,28 +110,25 @@ private:
};
void compare() const {
const auto expected = saved_state(*reference);
for (const auto& run : runs_) {
const auto actual = saved_state(*run.world);
if (actual == expected) continue;
const auto mismatch = std::mismatch(expected.begin(), expected.end(), actual.begin(), actual.end());
const auto offset = static_cast<std::size_t>(mismatch.first - expected.begin());
throw std::runtime_error("replay diverged at tick " + std::to_string(reference->tick()) +
", workers " + std::to_string(run.config.workers) +
(run.reloaded ? ", reloaded" : ", uninterrupted") +
", byte " + std::to_string(offset) +
", path searches " + std::to_string(reference->path_searches()) + "/" +
std::to_string(run.world->path_searches()) + ", path nodes " +
std::to_string(reference->path_nodes_visited()) + "/" +
std::to_string(run.world->path_nodes_visited()));
const auto diagnostic = replay_diagnostics::difference(*reference, *run.world,
{attempt_, run.config.workers, "uncontrolled", run.reloaded ? "reloaded" : "uninterrupted",
options_.max_admitted});
require(diagnostic.empty(), diagnostic);
}
}
std::uint64_t attempt_ = 0;
WorkerPoolOptions options_;
std::vector<Run> runs_;
};
struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite<ReplayTests> {
[[= Void::Testing::tag("replay")]] Test test_opposite_real_completion_orders();
[[= Void::Testing::tag("replay")]] Test test_semantic_divergence_diagnostics();
[[= Void::Testing::tag("replay")]] Test test_modern_custody_exposes_legacy_projection_blindness();
[[= Void::Testing::tag("replay")]] Test test_cancelled_partial_cargo_checkpoint_replay();
[[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world();
[[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work();
[[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes();
@@ -132,6 +137,295 @@ struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Sui
[[= Void::Testing::tag("replay")]] Test test_last_meal_has_one_winner_and_one_consumer();
};
// The driver is the test thread, separate from World::step's coordinator:
// capacity one can run submission 1 inline while submission 0 is held.
struct CompletionGate {
std::mutex mutex;
std::condition_variable changed;
std::array<bool, 2> entered{}, permitted{};
std::vector<std::size_t> completed;
bool released = false;
void before(std::size_t index) {
if (index > 1) return;
std::unique_lock lock(mutex);
entered[index] = true;
changed.notify_all();
if (!changed.wait_for(lock, std::chrono::seconds(5), [&] { return released || permitted[index]; })) {
throw std::runtime_error("completion gate release timeout");
}
}
void after(std::size_t index) {
if (index > 1) return;
std::lock_guard lock(mutex);
completed.push_back(index);
changed.notify_all();
}
void drive(std::size_t first) {
std::unique_lock lock(mutex);
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return entered[0] && entered[1]; }),
"both real calculations did not enter");
require(completed.empty(), "a calculation completed before its gate was released");
permitted[first] = true;
changed.notify_all();
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return !completed.empty(); }),
"first real calculation did not return");
require(completed == std::vector<std::size_t>{first}, "completion order was not forced");
permitted[1 - first] = true;
changed.notify_all();
}
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
Test ReplayTests::test_opposite_real_completion_orders() {
for (bool meal : {false, true}) {
World initial(meal ? 97 : 101, 8, 8, 1, ExecutionMode::SerialReference);
const auto winner = initial.spawn_agent({5, 1});
static_cast<void>(initial.spawn_agent({5, 1}));
JobId job = 0;
if (meal) {
const auto pantry = initial.add_storage({1, 1}, 1, StorageKind::Pantry);
initial.enable_hunger();
for (std::uint16_t tick = 0; tick < hunger_threshold; ++tick) initial.step();
initial.stock_storage(pantry, ItemType::Berries, 1);
} else {
job = initial.add_job({1, 1}, 3);
}
const auto fixture = saved_state(initial);
for (auto workers : {2U, 6U, 12U}) for (auto capacity : {4096U, 1U}) for (auto first : {0U, 1U}) {
CompletionGate gate;
WorkerPoolOptions options{.max_admitted = capacity};
options.before_execute = [&](std::size_t index) { gate.before(index); };
options.after_execute = [&](std::size_t index) { gate.after(index); };
auto reference = load_state(fixture, execution_configs.front());
auto candidate = load_state(fixture, {workers, ExecutionMode::Parallel}, std::move(options));
auto step = std::async(std::launch::async, [&] { candidate->step(); });
// Always release before joining the coordinator, including assertion failure.
auto release = Void::Scope::on_exit([&] { gate.release(); });
gate.drive(first);
gate.release();
require(step.wait_for(std::chrono::seconds(5)) == std::future_status::ready, "world step did not drain");
step.get();
require(gate.completed == std::vector<std::size_t>{first, 1 - first}, "wrong actual return trace");
const std::string schedule = first == 0 ? "A->B" : "B->A";
std::cout << "actual " << (meal ? "meal movement" : "job choices") << " workers=" << workers
<< " capacity=" << capacity << " completions=" << schedule << '\n';
for (std::uint64_t attempt = 1; attempt <= 40; ++attempt) {
reference->step();
const auto diagnostic = replay_diagnostics::difference(*reference, *candidate,
{attempt, workers, schedule, "fixture", capacity});
require(diagnostic.empty(), diagnostic);
if (attempt == 1) {
require(candidate->agents()[0].id == winner, "fixture IDs changed");
if (meal) {
require(candidate->agents()[0].state == AgentState::GoingToEat &&
candidate->agents()[1].state == AgentState::Idle,
"serial meal claim lost its stable winner");
} else {
require(candidate->agents()[0].current_job == job && candidate->agents()[1].current_job == 0,
"competing real calculations changed the lower-ID winner");
}
}
if (meal) {
const auto& agents = candidate->agents();
require(candidate->storages()[0].item_count(ItemType::Berries) +
agents[0].inventory.item_count(ItemType::Berries) + agents[1].inventory.item_count(ItemType::Berries) +
candidate->meals_eaten() == 1, "meal duplicated or lost");
require(agents[1].inventory.empty() && agents[1].state != AgentState::GoingToEat &&
agents[1].state != AgentState::Eating, "second resident consumed reserved meal");
}
if (attempt != 40) candidate->step();
}
require(meal ? candidate->meals_eaten() == 1 : candidate->jobs_completed() == 1,
"the sole job or meal did not finish exactly once");
}
}
}
Test ReplayTests::test_semantic_divergence_diagnostics() {
const replay_diagnostics::Context context{7, 6, "B->A", "checkpoint", 1};
World expected(103, 8, 8, 1, ExecutionMode::SerialReference);
const auto storage = expected.add_storage({1, 1}, 20);
expected.stock_storage(storage, ItemType::Wood, 2);
const auto job = expected.add_job({4, 4}, 2);
const auto fixture = saved_state(expected);
auto actual = load_state(fixture, execution_configs.front());
require(replay_diagnostics::difference(expected, *actual, context).empty(), "equal worlds reported divergence");
actual->stock_storage(storage, ItemType::Wood, 1);
auto report = replay_diagnostics::difference(expected, *actual, context);
require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos &&
report.find("item=1 field=count expected=2 actual=3") != std::string::npos &&
report.find("attempt=7 seed=103 workers=6 schedule=B->A load=checkpoint capacity=1") != std::string::npos,
"stock diagnostic omitted context or identity: " + report);
actual = load_state(fixture, execution_configs.front());
// These are deliberate diagnostic inputs built by public domain operations.
World changed_job(103, 8, 8, 1, ExecutionMode::SerialReference);
const auto matching = changed_job.add_storage({1, 1}, 20);
changed_job.stock_storage(matching, ItemType::Wood, 2);
static_cast<void>(changed_job.add_job({4, 4}, 3));
report = replay_diagnostics::difference(expected, changed_job, context);
require(report.find("job id=" + std::to_string(job)) != std::string::npos &&
report.find("field=work_remaining expected=2 actual=3") != std::string::npos,
"job diagnostic omitted identity: " + report);
auto command_world = make_first_colony(2);
auto command_copy = load_state(saved_state(*command_world), execution_configs.front());
const PlayerCommand command{1, 1, CommandKind::SetPaused, {}, 1};
const auto receipt = command_copy->apply_command(command);
report = replay_diagnostics::difference(*command_world, *command_copy, context);
require(report.find("command player=1 field=next_sequence expected=1 actual=2") != std::string::npos,
"command diagnostic omitted player and sequence: " + report);
report = replay_diagnostics::receipt_difference(*command_copy, command,
{CommandStatus::Accepted, 0, 0}, receipt, context);
require(report.find("command player=1 sequence=1 field=receipt") != std::string::npos &&
report.find("revision=0") != std::string::npos && report.find("revision=1") != std::string::npos,
"receipt diagnostic omitted revision: " + report);
require(replay_diagnostics::receipt_difference(*command_copy, command, receipt, receipt, context).empty(),
"equal receipts reported divergence");
// An absent entity and a private field exercise identity and byte fallbacks.
static_cast<void>(actual->add_job({6, 6}, 1));
require(replay_diagnostics::difference(expected, *actual).find("job id=2") != std::string::npos,
"extra entity lost stable identity");
actual = load_state(fixture, execution_configs.front());
actual->set_blocked({7, 7});
require(replay_diagnostics::difference(expected, *actual).find("byte=") != std::string::npos,
"unprojected canonical field lost byte fallback");
}
Test ReplayTests::test_modern_custody_exposes_legacy_projection_blindness() {
const auto legacy = [](const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
};
const replay_diagnostics::Context context{2, 1, "custody", "legacy-import", 4096};
World stock(107, 12, 12, 1, ExecutionMode::SerialReference);
const auto storage = stock.add_storage({2, 2}, 10);
// Issued identities follow grants, while historical migration reconstructs
// them from the canonically sorted item rows.
stock.stock_storage(storage, ItemType::StoneBlock, 2);
stock.stock_storage(storage, ItemType::Plank, 3);
auto imported = load_state(legacy(stock), execution_configs.front());
require(legacy(stock) == legacy(*imported), "legacy stock projection changed on import");
auto report = replay_diagnostics::difference(stock, *imported, context);
require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos &&
report.find("field=stack_id expected=2 actual=1") != std::string::npos,
"modern comparison missed reconstructed stack identity: " + report);
std::cout << report << '\n';
World accounting(108, 12, 12, 1, ExecutionMode::SerialReference);
const auto store = accounting.add_storage({2, 2}, 10);
accounting.stock_storage(store, ItemType::Wood, 2);
imported = load_state(legacy(accounting), execution_configs.front());
require(legacy(accounting) == legacy(*imported), "legacy accounting projection changed on import");
report = replay_diagnostics::difference(accounting, *imported, context);
require(report.find("balance item=1 field=grant expected=2 actual=0") != std::string::npos,
"modern comparison missed opening/grant distinction: " + report);
World active(109, 32, 32, 1, ExecutionMode::SerialReference);
const auto materials = active.add_storage({3, 3}, 5);
active.stock_storage(materials, ItemType::Plank, 3);
active.stock_storage(materials, ItemType::StoneBlock, 2);
static_cast<void>(active.spawn_agent({1, 3}));
active.queue_production({16, 3}, RecipeId::BuildCabin);
active.step();
imported = load_state(legacy(active), execution_configs.front());
require(legacy(active) == legacy(*imported), "legacy active projection changed on import");
require(!active.custody_receipts().empty() && imported->custody_receipts().empty(),
"fixture did not distinguish real and reconstructed history");
report = replay_diagnostics::difference(active, *imported, context);
require(report.find("custody receipt kind=0 id=1 ordinal=1") != std::string::npos &&
report.find("actual=<absent>") != std::string::npos,
"modern comparison missed retained admission result: " + report);
std::cout << report << '\n';
const auto facts = replay_diagnostics::facts(active);
const auto& transfer = *active.agents().front().execution;
const auto& reservation = transfer.reservations.front();
require(facts.at({1, "transfer id=" + std::to_string(transfer.id) + " owner=agent:1 field=next_operation"}) == "1" &&
facts.at({1, "reservation id=" + std::to_string(reservation.id) + " transfer=" +
std::to_string(transfer.id) + " field=stack_id"}) == std::to_string(reservation.stack),
"active transfer/reservation diagnostics lost durable identities");
}
Test ReplayTests::test_cancelled_partial_cargo_checkpoint_replay() {
World reference(113, 32, 32, 1, ExecutionMode::SerialReference);
const auto source = reference.add_storage({3, 3}, 5);
reference.stock_storage(source, ItemType::Plank, 3);
reference.stock_storage(source, ItemType::StoneBlock, 2);
static_cast<void>(reference.spawn_agent({1, 3}));
reference.queue_production({16, 3}, RecipeId::BuildCabin);
const auto order = reference.production_orders().front().id;
for (int tick = 0; tick < 30 && reference.agents().front().state != AgentState::Working; ++tick) reference.step();
require(reference.agents().front().state == AgentState::Working, "cabin delivery did not reach the site");
const auto transfer = reference.agents().front().execution->id;
require(reference.cancel_production(order) == CommandStatus::Accepted, "live construction cancellation failed");
reference.stock_storage(source, ItemType::Wood, 5);
const auto partial = reference.add_storage({4, 3}, 1);
for (int tick = 0; tick < 40; ++tick) reference.step();
const auto& actor = reference.agents().front();
require(actor.state == AgentState::Returning && actor.execution && actor.execution->id == transfer &&
actor.execution->blocked == CustodyStatus::NoDestination &&
actor.inventory.item_count(ItemType::Plank) == 2 && actor.inventory.item_count(ItemType::StoneBlock) == 2 &&
reference.find_storage(partial)->item_count(ItemType::Plank) == 1,
"partial return did not retain the same transfer and remaining cargo");
const auto admission = *reference.custody_receipts().front();
const auto cancelled = std::find_if(reference.custody_receipts().begin(), reference.custody_receipts().end(),
[](const auto& receipt) { return receipt->request.operation == CustodyOperation::Cancel; });
require(cancelled != reference.custody_receipts().end(), "cancel result was not retained");
const std::array retained{admission, **cancelled};
Void::Uuid::Uuid world_id;
world_id.bytes.back() = 113;
const auto rules = default_rules_manifest();
const auto catalog = builtin_rule_packages();
require(rules.has_value() && catalog.has_value(), "default rules unavailable");
const auto checkpoint = encode_checkpoint(reference, world_id, 7, *rules);
require(checkpoint.has_value(), "partial cargo checkpoint failed");
std::vector<std::unique_ptr<World>> candidates;
for (const auto config : execution_configs) {
auto loaded = decode_checkpoint(*checkpoint, *catalog, config.workers, config.mode);
require(loaded.has_value(), "partial cargo checkpoint was not decoded");
require(loaded->world_id == world_id && loaded->city == 7, "checkpoint identity changed");
const auto repeated = encode_checkpoint(*loaded->world, loaded->world_id, loaded->city, loaded->rules);
require(repeated.has_value() && *repeated == *checkpoint, "partial checkpoint roundtrip changed bytes");
candidates.push_back(std::move(loaded->world));
}
const auto repeat_without_effect = [&](World& world) {
const auto before = saved_state(world);
for (const auto& receipt : retained) {
require(world.custody_request(receipt.request) == receipt.result, "retained result changed after reload");
auto conflict = receipt.request;
++conflict.destination;
require(world.custody_request(conflict).status == CustodyStatus::Conflict,
"changed payload reused an accepted transfer step");
}
require(saved_state(world) == before, "retry repeated a physical transfer or consumed an ordinal");
};
repeat_without_effect(reference);
for (auto& world : candidates) repeat_without_effect(*world);
for (std::uint64_t attempt = 0; attempt < 40; ++attempt) {
if (attempt == 5) {
static_cast<void>(reference.add_storage({6, 3}, 20));
for (auto& world : candidates) static_cast<void>(world->add_storage({6, 3}, 20));
}
reference.step();
for (std::size_t i = 0; i < candidates.size(); ++i) {
candidates[i]->step();
const auto report = replay_diagnostics::difference(reference, *candidates[i],
{attempt, execution_configs[i].workers, "cancel-return", "checkpoint", 4096});
require(report.empty(), report);
repeat_without_effect(*candidates[i]);
}
}
require(reference.agents().front().inventory.empty() && !reference.agents().front().execution &&
reference.item_balances()[2].installation == 0 && reference.item_balances()[3].installation == 0,
"return duplicated consumption or retained finished cargo");
repeat_without_effect(reference);
}
Test ReplayTests::test_execution_configuration_and_empty_world() {
World initial(20261202, 5, 5);
const auto bytes = saved_state(initial);
+66 -3
View File
@@ -1,4 +1,5 @@
#include "settlement/core/simulation_runtime.hpp"
#include "replay_diagnostics.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
@@ -20,9 +21,7 @@ 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();
return replay_diagnostics::canonical(world);
}
WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) {
@@ -98,6 +97,7 @@ void command_observer(CommandMutationPhase phase) {
}
struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::Suite<RuntimeTests> {
[[= Void::Testing::tag("runtime")]] Test test_queued_same_save_install_drains_old_world();
[[= 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();
@@ -110,6 +110,69 @@ struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::S
[[= Void::Testing::tag("runtime")]] Test test_exhausted_clock_faults_without_spinning();
};
Test RuntimeTests::test_queued_same_save_install_drains_old_world() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
std::atomic<std::size_t> started{0}, completed{0};
std::atomic<bool> install_saw_drained{false};
WorkerPoolOptions workers;
workers.before_execute = [&](std::size_t index) {
++started;
if (index == 0) gate->block();
};
workers.after_execute = [&](std::size_t) { ++completed; };
RuntimeOptions options{.clock = clock};
options.observer = [&](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeInstallCapture) {
install_saw_drained = started.load() >= 2 && started.load() == completed.load();
}
};
auto replacement = colony();
const auto replacement_bytes = replay_diagnostics::canonical(*replacement.world);
SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto old_view = runtime.latest();
const auto old_bytes = replay_diagnostics::canonical(*old_view->world);
const auto stale_command = envelope(*old_view, 1, CommandKind::SetPaused, 1);
require(clock->advance(50ms).has_value());
runtime.notify_clock();
gate->wait();
const auto ticket = runtime.begin_load();
require(ticket.has_value());
auto installing = admitted([&] { return runtime.try_install(*ticket, replacement); });
require(installing.admission == RuntimeAdmission::Accepted && !replacement.world);
auto stale = admitted([&] { return runtime.try_submit(host, stale_command); });
require(stale.admission == RuntimeAdmission::Accepted);
require(installing.completion.wait_for(0s) == std::future_status::timeout);
require(stale.completion.wait_for(0s) == std::future_status::timeout);
require(!install_saw_drained && started.load() > completed.load());
require(runtime.latest() == old_view);
require(runtime.snapshot_for_save().value() == old_view);
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
gate->release();
const auto installed = finished(std::move(installing));
require(installed.outcome == RuntimeOutcome::Completed && install_saw_drained);
require(installed.snapshot->identity.world == old_view->identity.world);
require(installed.snapshot->identity.session != old_view->identity.session);
require(installed.snapshot->world->tick() == 0);
const auto rejected = finished(std::move(stale));
require(rejected.receipt && rejected.receipt->status == DispatchStatus::StaleSession);
const auto drained_count = completed.load();
require(fence(runtime).outcome == RuntimeOutcome::Completed);
require(runtime.latest() == installed.snapshot);
require(replay_diagnostics::canonical(*runtime.latest()->world) == replacement_bytes);
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
require(completed.load() == drained_count && started.load() == completed.load());
auto serial = colony(1);
serial.world->step();
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Completed);
const auto diagnostic = replay_diagnostics::difference(*serial.world, *runtime.latest()->world,
{1, 2, "old-worker-held", "same-save-replacement", 4096});
if (!diagnostic.empty()) throw std::runtime_error(diagnostic);
require(completed.load() == drained_count);
}
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<Void::Time::ManualClock>();
+158 -7
View File
@@ -87,16 +87,18 @@ bool has(const std::vector<ViewerEvent>& events, ViewerEventKind kind) {
return std::any_of(events.begin(), events.end(), [kind](const auto& event) { return event.kind == kind; });
}
void flush_owner(ViewerSession& session) {
void flush_owner(ViewerSession& session, RuntimeOutcome expected = RuntimeOutcome::Completed) {
const auto deadline = std::chrono::steady_clock::now() + 5s;
for (;;) {
auto sync = session.runtime().synchronize();
if (sync.admission == RuntimeAdmission::Busy) {
require(std::chrono::steady_clock::now() < deadline);
std::this_thread::yield();
continue;
}
require(sync.admission == RuntimeAdmission::Accepted);
require(sync.completion.wait_for(5s) == std::future_status::ready);
require(sync.completion.get().outcome == RuntimeOutcome::Completed);
require(sync.completion.wait_until(deadline) == std::future_status::ready);
require(sync.completion.get().outcome == expected);
return;
}
}
@@ -112,6 +114,10 @@ struct [[= Void::Testing::name("ViewerSessionTests")]] ViewerSessionTests : Void
[[= Void::Testing::tag("viewer-session")]] Test test_initial_candidate_requires_supported_rules_and_dimensions();
[[= Void::Testing::tag("viewer-session")]] Test test_fault_retains_view_and_explicit_load_recovers();
[[= Void::Testing::tag("viewer-session")]] Test test_failed_guest_transitions_retain_received_replica();
[[= Void::Testing::tag("viewer-session")]] Test test_profiles_new_save_load_and_legacy_host_admission();
[[= Void::Testing::tag("viewer-session")]] Test test_profile_validation_rejects_initial_and_loaded_mismatches();
[[= Void::Testing::tag("viewer-session")]] Test test_pending_optional_load_blocks_host_and_newest_invalid_load_wins();
[[= Void::Testing::tag("viewer-session")]] Test test_historical_default_modes_and_guest_leave_keep_default_rules();
};
Test ViewerSessionTests::test_commands_wait_for_commit_and_keep_rejected_drafts_retryable() {
@@ -355,10 +361,7 @@ Test ViewerSessionTests::test_fault_retains_view_and_explicit_load_recovers() {
require(rejected_save);
session.set_ticking(false);
static_cast<void>(session.poll());
auto suspended = session.runtime().synchronize();
require(suspended.admission == RuntimeAdmission::Accepted);
require(suspended.completion.wait_for(5s) == std::future_status::ready);
require(suspended.completion.get().outcome == RuntimeOutcome::Faulted);
flush_owner(session, RuntimeOutcome::Faulted);
static_cast<void>(session.poll());
session.load(files.root / "recover.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
@@ -392,4 +395,152 @@ Test ViewerSessionTests::test_failed_guest_transitions_retain_received_replica()
require(rejected_leave && session.guest() && session.world() == received);
}
template<class T, class E>
T checked(std::expected<T, E> result) {
if (!result) throw std::runtime_error(result.error().message);
return std::move(*result);
}
std::string checkpoint_bytes(const WorldCheckpoint& candidate) {
return checked(encode_checkpoint(*candidate.world, candidate.world_id, candidate.city, candidate.rules));
}
Test ViewerSessionTests::test_profiles_new_save_load_and_legacy_host_admission() {
TempFiles files;
ViewerSession session(2);
for (const auto profile : {ColonyProfile::PlankBeds, ColonyProfile::Default}) {
const auto before = session.runtime().latest();
session.new_colony(profile);
require(session.changing_world() && !session.can_host_legacy());
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
const auto created = session.runtime().latest();
const auto expected = checked(colony_rules(profile));
require(created->identity.world != before->identity.world && created->identity.session != before->identity.session);
require(*created->rules == expected.manifest());
require(created->world->staged_beds() == (profile == ColonyProfile::Default));
require(session.can_host_legacy() == (profile == ColonyProfile::Default));
const auto path = files.root / "profile.settlement";
session.save(path);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Saved); });
CheckpointFiles reader;
auto read = reader.try_load(path, 2);
require(read.admission == CheckpointLoadAdmission::Accepted);
require(read.completion.wait_for(5s) == std::future_status::ready);
const auto saved = checked(read.completion.get());
require(saved.rules == expected.manifest() && saved.world_id == created->identity.world);
require(bytes(*saved.world) == bytes(*created->world));
session.new_colony(profile == ColonyProfile::Default ? ColonyProfile::PlankBeds : ColonyProfile::Default);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
session.load(path);
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(*session.runtime().latest()->rules == saved.rules);
require(session.runtime().latest()->identity.world == saved.world_id);
require(bytes(*session.world()) == bytes(*saved.world));
}
}
Test ViewerSessionTests::test_profile_validation_rejects_initial_and_loaded_mismatches() {
TempFiles files;
auto catalog = checked(builtin_rule_packages());
const auto optional_rules = checked(colony_rules(ColonyProfile::PlankBeds)).manifest();
const auto core_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.core"}}));
catalog.push_back(checked(load_rule_package("extra",
R"({"schema":1,"id":"game.extra","version":"1.0.0","dependencies":[],"exclusive_capabilities":[],"definitions":[]})")));
const auto extra_rules = checked(resolve_rules(catalog,
std::array{std::string{"settlement.colony"}, std::string{"game.extra"}}));
auto altered = std::string(catalog[1].canonical_json());
const auto recipe = altered.find("\"output_count\":1");
require(recipe != std::string::npos);
altered.replace(recipe, std::string_view{"\"output_count\":1"}.size(), "\"output_count\":2");
catalog[1] = checked(load_rule_package("forged", altered));
const auto forged_rules = checked(resolve_rules(catalog, std::array{std::string{"settlement.colony"}}));
ViewerSession session(2);
const auto before = session.runtime().latest();
for (const auto& rules : {core_rules, extra_rules, forged_rules, optional_rules}) {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
candidate.rules = rules;
write(files.root / "invalid.settlement", checkpoint_bytes(candidate));
bool rejected = false;
try { ViewerSession invalid(std::move(candidate), 2); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected);
session.load(files.root / "invalid.settlement");
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
require(!has(events, ViewerEventKind::Replaced));
require(session.runtime().latest() == before && !session.changing_world());
}
for (int problem = 0; problem < 3; ++problem) {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
if (problem == 0) candidate.world.reset();
if (problem == 1) candidate.world_id = {};
if (problem == 2) candidate.city = 0;
bool rejected = false;
try { ViewerSession invalid(std::move(candidate), 2); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected);
}
bool rejected = false;
try { session.new_colony(static_cast<ColonyProfile>(255)); }
catch (const std::runtime_error&) { rejected = true; }
require(rejected && session.runtime().latest() == before && session.can_host_legacy());
auto supported = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
ViewerSession optional(std::move(supported), 2);
require(!optional.world()->staged_beds() && !optional.can_host_legacy());
}
Test ViewerSessionTests::test_pending_optional_load_blocks_host_and_newest_invalid_load_wins() {
TempFiles files;
auto valid = checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2));
write(files.root / "optional.settlement", checkpoint_bytes(valid));
valid.world = make_first_colony(2);
write(files.root / "invalid.settlement", checkpoint_bytes(valid));
auto gate = std::make_shared<Gate>();
std::atomic<bool> block{true};
ViewerSessionOptions options;
options.files.read_observer = [gate, &block](CheckpointReadPhase phase) {
if (phase == CheckpointReadPhase::Opened && block.exchange(false)) gate->hold();
};
ViewerSession session(2, std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto before = session.runtime().latest();
require(session.can_host_legacy());
session.load(files.root / "optional.settlement");
gate->wait();
require(session.changing_world() && !session.can_host_legacy() && session.runtime().latest() == before);
// Invalid direct New preparation must retain the pending load and its ticket.
const auto generation = session.generation();
try { session.new_colony(static_cast<ColonyProfile>(255)); }
catch (const std::runtime_error&) {}
require(session.changing_world() && session.generation() == generation);
session.load(files.root / "invalid.settlement");
gate->release();
const auto events = pump_until(session, [](const auto& values) { return has(values, ViewerEventKind::Error); });
require(!has(events, ViewerEventKind::Replaced) && session.runtime().latest() == before);
flush_owner(session);
require(session.poll().empty() && session.runtime().latest() == before && session.can_host_legacy());
}
Test ViewerSessionTests::test_historical_default_modes_and_guest_leave_keep_default_rules() {
TempFiles files;
const auto defaults = checked(default_rules_manifest());
for (int mode = 0; mode < 3; ++mode) {
auto candidate = checked(make_colony_checkpoint(ColonyProfile::Default, 2));
if (mode == 1) candidate.world = make_first_colony(2, BedConstructionMode::Plank);
if (mode == 2) candidate.world = std::make_unique<World>(17, 32, 32, 2);
const auto expected = bytes(*candidate.world);
ViewerSession session(std::move(candidate), 2);
require(bytes(*session.world()) == expected && session.can_host_legacy());
write(files.root / "legacy.settlement", expected);
session.load(files.root / "legacy.settlement");
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(bytes(*session.world()) == expected && *session.runtime().latest()->rules == defaults);
}
ViewerSession session(checked(make_colony_checkpoint(ColonyProfile::PlankBeds, 2)), 2);
session.enter_guest();
session.receive_guest(make_first_colony(2, BedConstructionMode::Plank));
session.leave_guest();
pump_until(session, [](const auto& events) { return has(events, ViewerEventKind::Replaced); });
require(!session.world()->staged_beds() && *session.runtime().latest()->rules == defaults && session.can_host_legacy());
}
} // namespace