Add the M01 serial simulation reference and per-tick replay

This commit is contained in:
faumaray committed 2026-12-02 21:03:50 +03:00
1 parent 904bdf8827
commit 8d2870a6f8
11 files changed
+538 -28

No files matched your search

+1 -1
View File
@@ -104,7 +104,7 @@ else()
endif()
if(BUILD_TESTING)
add_executable(settlement_core_tests tests/core_tests.cpp tests/test_main.cpp)
add_executable(settlement_core_tests tests/core_tests.cpp tests/replay_tests.cpp tests/test_main.cpp)
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
add_test(NAME settlement_core_tests COMMAND settlement_core_tests)
+2
View File
@@ -67,6 +67,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1 -VoidLibrary
Void Library требует поддержки C++26. Тесты ядра и LAN используют рефлексию C++26. `Void::Testing::Suite<T>` регистрирует методы без аргументов с возвращаемым типом `Void::Testing::Test`. Необязательный `setup()` выполняется перед каждым запускаемым тестом. Метки задаются через `[[= Void::Testing::tag("construction")]]`, а `[[= Void::Testing::skip("причина")]]` пропускает тест с пояснением. Чтобы запустить только тесты строительства, выполните `build/settlement_core_tests.exe --tag construction`. Для сборки игры без тестов задайте `-DBUILD_TESTING=OFF` при прямом вызове CMake.
Потактную проверку симуляции можно запустить командой `build\settlement_core_tests.exe --tag replay`. Она сравнивает последовательную партию с исполнением на 2, 6 и 12 рабочих потоках и с продолжением из сохранения. [Сценарий M01](docs/plan/milestones/M01.md)
## Структура
```text
+16
View File
@@ -59,3 +59,19 @@ ctest --test-dir "$SETTLEMENT_VERIFY/candidate" -V --output-on-failure
Из корня игры собрана свежая Windows x64 Release в отдельном каталоге с закреплённым исходным деревом Void, CMake 4.5.0, GCC 16.2.0 и Ninja. Команды `cmake --build <build-dir> --parallel 8` и `ctest --test-dir <build-dir> -V --output-on-failure` под Wine 11 дали 28/28 случаев ядра и 4/4 LAN. Результат относится к кросс-сборке. Аппаратные измерения Windows и изготовление материалов относятся к следующим этапам.
[Итоговая проверка M00-V](tasks/M00-V.md) приняла этот срез и передачу M01. Проверены 80 идентификаторов, 43 документа и 1 041 локальная ссылка до добавления данной записи, хеши иконок, подключение ресурсов и журналы исходной сборки. Обход остальных исторических изменений, приёмка игровых сценариев и права на будущие файлы остаются открытыми.
## M01. Последовательный эталон и журнал
Пользователь подтвердил полный план, локальные коммиты и отправку веток этапов и систем в origin. M00 принят и опубликован в `milestone/m00-inventory` на `904bdf8`. Ветка `milestone/m01-authoritative-simulation` создана от него. Первая поставка S01 включает [режим мира](tasks/M01-C.md) и [пять сценариев воспроизведения](tasks/M01-T.md).
Под Wine 11 новая Windows x64 Release прошла 33/33 теста ядра и 4/4 LAN. Селектор `settlement_core_tests.exe --tag replay` выполнил пять новых случаев. Журнал из десяти команд дал 750 тактов с одинаковыми сохранениями в эталоне и на 2/6/12 потоках, включая продолжение с материалом в руках. Отдельная программа, собранная сначала с заголовками и ядром до M01, затем с новым ядром, сравнила квитанции и сохранения после каждой из 365 попыток шага. При 361 такте и пяти съеденных порциях все четыре режима совпали с прототипом по всем 738 386 байтам. [Итог M01-V1](tasks/M01-V1.md) — **READY** для эталона и тестов.
Контрольные команды из корня игры, в окружении кросс-сборки из записи выше:
```sh
cmake --build /tmp/stoneheart-milestones.xprJ2SVp/windows --parallel 8
ctest --test-dir /tmp/stoneheart-milestones.xprJ2SVp/windows -V --output-on-failure
wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag replay
```
Далее в M01 входят исполнитель Void с проверкой отказов, манифесты правил, авторитетный диспетчер команд, фоновый такт, снимки и транзакционная загрузка/запись. Приёмка этих систем ведётся отдельными коммитами.
+48
View File
@@ -0,0 +1,48 @@
# Run the same world kernels in an explicit serial reference mode
Task ID: M01-C
Role: sol_implementer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation, M00 checkpoint 904bdf8. Legacy task notes/.serena are user work. M00-P/F and M01-R established the prototype's three worker sites and checked the pinned Void APIs.
## 2. Objective and deliverables
Implement the first M01 execution seam: an explicit true serial reference and the existing threaded game mode for World construction and load.
## 3. Scope and non-goals
Work only on simulation execution selection, including path selection/route/advancement. Keep normal CLI, viewer, LAN, wire bytes, command behavior and parallel executor compatible.
## 4. Files to inspect
Inspect engine/include/settlement/core/world.hpp, engine/src/{world,world_save}.cpp, worker_pool.hpp/cpp, tests/core_tests.cpp, docs/plan/milestones/M01.md and docs/plan/void-library.md. choose_jobs, find_path and advance_agents already exist in World.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; engine/src/world_save.cpp
You are not alone in this checkout. Other authors own tests and CMake; root owns docs and Git. Do not revert others' work.
## 6. Implementation or investigation approach
Add the explicit mode to World construction and read_save. Validate count/mode before stepping. For serial work call the same domain kernels on the caller thread: compute all candidate choices against one starting state before committing winners, run the same find_path and apply requests in the same order, advance agents for the whole range once and sum actual completions. Preserve existing chunking and order in threaded mode. Use direct domain calls and avoid building any generic executor or new state codec.
## 7. Interfaces and data contracts
NEW settlement::ExecutionMode::{Parallel, SerialReference}. World(seed,w,h, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel); World::read_save(stream, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel). Parallel accepts 2..64 as today. SerialReference requires logical count 1, creates zero OS workers and reports worker_count()==1. Reject invalid combinations/unknown enum with std::invalid_argument. Configuration is local and never serialized. Other source-compatible choices inside these paths are discretionary.
## 8. Dependencies and integration
Tests owner will use frozen interface immediately. Preserve save v13 fixture, old versions, LAN 11, performance of ordinary pool dispatch and its current lifetimes. Pinned Void covers binary/test primitives; game-specific direct invocation adds no generic library facility. ThreadExecutor migration has its own later failure/performance contract.
## 9. Edge cases security and performance
Account for no agents/jobs, paused world, one resident, fewer agents than workers, competing jobs, retries for unreachable routes, reload and cache state. Keep parallel error behavior; do not broaden lifetime hazards. No detached tasks or implicit threads in serial.
## 10. Acceptance criteria
1. Serial mode reaches all 3 sites without a worker pool. 2. Invalid ordinary counts still fail, valid serial passes constructor and load. 3. Exact v13 save bytes and outcomes match 2/6/12 for useful scenarios. 4. Default behavior and old consumers compile.
## 11. Verification commands and evidence
From game root source /tmp/stoneheart-verify.KoZwE4o8/env.sh; then cmake --build "$SETTLEMENT_VERIFY/candidate" --parallel 8 --target settlement_core. Use git diff --check and inspect actual diff. Tell root/tests when implementation compiles; tests use another build directory and root runs integrated suites.
## 12. Constraints and stop conditions
Do not alter other files, registry, network, branch or legacy pool, stage/commit or spawn. Escalate a required interface change and report errors before changing approach twice.
## 13. Authorization and decisions
User approved starting the roadmap on per-milestone branches and parallel subagents. Root selected first M01 replay increment after independent preflight.
## 14. Return format
Return M01-C status, changed paths/symbols, mode and ordering decisions, commands/results, untested paths and integration notes.
+48
View File
@@ -0,0 +1,48 @@
# Replay actual colony commands and compare every tick
Task ID: M01-T
Role: sol_implementer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home, milestone/m01-authoritative-simulation based on M00 checkpoint 904bdf8. The baseline has 28 core and 4 LAN cases, reflection suites from pinned Void. Legacy task notes/.serena are untracked.
## 2. Objective and deliverables
Build an executable M01 replay regression in the normal settlement_core_tests target, exercising the explicit serial reference and normal modes on the same saved starting state.
## 3. Scope and non-goals
Own the test fixture, useful game scenarios, mode/legacy boundary assertions and minimal source registration. Keep every existing core and LAN case. No new runner or game production logic.
## 4. Files to inspect
Inspect tests/core_tests.cpp (save_contents and test_two_players_share_the_first_colony, resource/hauling and parallel job tests), tests/test_main.cpp, CMakeLists.txt, world.hpp, docs/plan/milestones/M01.md, docs/plan/void-library.md and actual game behavior.
## 5. Write ownership and coordination
Write scope: tests/replay_tests.cpp; CMakeLists.txt
You are not alone. Core owner writes only world.hpp/world.cpp/world_save.cpp. Root owns docs and Git. Do not revert their changes; serialize your new file registration in CMake yourself.
## 6. Implementation or investigation approach
Add a reflected Void Suite in NEW tests/replay_tests.cpp, register this file on existing settlement_core_tests. Mark new cases with tag replay. Use the actual write_save binary bytes as prototype oracle (no hashes or shadow codec). Record a fixed test-local set of PlayerCommand values including explicit player sequences and scheduled step attempt ordinals. Check expected receipts/rejections, tick/revision and pause/resume, then compare state bytes every attempt through meaningful colony output. See preflight requirements below.
## 7. Interfaces and data contracts
NEW frozen API settlement::ExecutionMode::{Parallel, SerialReference}; World(seed,w,h, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel); World::read_save(stream, size_t workers=min_worker_count, ExecutionMode mode=ExecutionMode::Parallel). Serial requires logical count 1 and reports worker_count()==1. Parallel 2..64 and ordinary one-worker rejection remain. Invalid combinations/unknown enum throw invalid_argument. Existing PlayerCommand, CommandReceipt, make_first_colony, resource/job APIs apply.
## 8. Dependencies and integration
Core author implements the frozen API concurrently. Use an uninterrupted serial reference versus 2/6/12 from the same initial bytes. At a proven material-in-hand checkpoint resume another world per mode from bytes, keep uninterrupted reference alive and compare every subsequent tick. Use warmed path cache in the live history; report path counters and first differing tick/mode/object or byte offset if a comparison fails. Coordinate builds after both sides compile.
## 9. Edge cases security and performance
Cover empty, paused, one resident/fewer residents than workers. Include multiple competing generic jobs and an unreachable route forcing a retry to another job (all three dispatch points), and two eligible residents contending for the last item, with a specific winner and conservation after delivery/consumption. Choose meaningful positive outcomes to rule out all modes equally doing nothing. Compare bounded scenarios and avoid OS timing assertions.
## 10. Acceptance criteria
1. Reproducible command schedule advances a real colony and checks accepted and rejected commands. 2. Exact byte equality every tick for serial/2/6/12 including reload vs uninterrupted; prove in-hand stop and useful work. 3. Contention winner and unit accounting, job selection/retry, and valid/invalid configs are checked. 4. Existing tag/CTest entry points still work.
## 11. Verification commands and evidence
From game root source /tmp/stoneheart-verify.KoZwE4o8/env.sh; cmake --build /tmp/stoneheart-milestones.xprJ2SVp/windows --parallel 8 --target settlement_core_tests; wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag replay. Root built this directory from the exact clean Void pin. Report counts and time. Work with core owner if build awaits API.
## 12. Constraints and stop conditions
Do not weaken old tests, compare only hashes/final counts, edit game files, change branches, stage/commit or spawn. Investigate actual source when a fixture fails; distinguish bad setup from real divergence and inform root.
## 13. Authorization and decisions
User requested milestone implementation with subagents. This scoped M01 tranche establishes replay evidence before replacing the executor or changing the authoritative command format.
## 14. Return format
Return M01-T status, changes, fixture/expected state, counts and commands, any coverage you could not verify and integration notes. Send early if there is a real disagreement across modes.
+48
View File
@@ -0,0 +1,48 @@
# Review the serial reference and replay checkpoint
Task ID: M01-V1
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Game root /home/faumaray/Projects/stoneheart_at_home on milestone/m01-authoritative-simulation, parent 904bdf8. User asks that reviewed milestone/system work be committed and pushed. Initial M01 tranche only. Pre-existing untracked .serena and older task files are outside the diff.
## 2. Objective and deliverables
Review the actual integrated M01-C/T source and tests; give an independent defect-oriented verdict on this checkpoint before push.
## 3. Scope and non-goals
Audit constructor/load mode, all worker dispatch paths, exact-state comparison, normal suite/CLI callers and documentation plus boundary to future work. Work on later M01 packages is planned separately.
## 4. Files to inspect
Read git diff 904bdf8 and NEW tests/replay_tests.cpp, docs/agent-workflow/tasks/M01-{C,T}.md, README and M01 plan. Check world.hpp/world.cpp/world_save.cpp, CMakeLists.txt, test_main.cpp, existing core and LAN suites against the frozen contract.
## 5. Write ownership and coordination
Write scope: none
Do not change any shared checkout files or branches. No children, push or external writes.
## 6. Implementation or investigation approach
Inspect actual worker lifetime, order, exception handling changes since baseline, empty/paused/one-resident cases, mode validation and save ingress. Review each new case for effective contention, warmed-cache checkpoint and positive useful progress. Check mode-specific reporting, new API compatibility and CMake discovery.
## 7. Interfaces and data contracts
Parallel rejects 0,1,65+ and serial admits only 1 logical lane, with zero pool threads. Preserve save13/LAN11, existing commands and parallel results. Full M01 authority/async saves belong to later packages.
## 8. Dependencies and integration
M01-C/T complete. Root observed an independent original-ABI Windows probe vs candidate serial/2/6/12, 365 attempts (361 ticks, 5 meals), 738386 bytes of saves and receipts identical bytewise. Five replay tests pass under Wine. Full CTest and build on integrated state in /tmp/stoneheart-milestones.xprJ2SVp/windows; logs m01-first-build.log and m01-first-ctest.log.
## 9. Edge cases security and performance
Check directional reference equivalence when candidates all target same work and routes retry, stable movement/jobs state and flag any newly widened lifetime risk. Native Windows/GPU remains outstanding. Do not waive failed assertions.
## 10. Acceptance criteria
1. Return verdict on first M01 execution tranche. 2. Concrete severity, affected callers, reproduction for bugs and proposed fix. 3. Report untested risks and distinguish them from observed regressions.
## 11. Verification commands and evidence
From game root git diff 904bdf8 --stat; git diff --cached --check; source /tmp/stoneheart-verify.KoZwE4o8/env.sh for any targeted read-only testing. Review /tmp/stoneheart-milestones.xprJ2SVp/{replay-tests,m01-first-ctest}.log and actual new file. Do not start a competing build.
## 12. Constraints and stop conditions
Read-only. No docs or fixes, no commit/push. Return bounded findings promptly so root can integrate and continue the active goal.
## 13. Authorization and decisions
User authorizes implementing, committing and pushing each milestone/system. This review covers the first M01 tranche and does not declare the milestone complete.
## 14. Return format
Return M01-V1 READY/CHANGES_REQUIRED/INSUFFICIENT_EVIDENCE, findings by severity/location, observed checks, unrun checks and remaining milestones.
+10
View File
@@ -15,6 +15,16 @@
## Первый переход с текущего клиента
### Потактный эталон прототипа
Для контрольного прогона мир создаётся с одним логическим исполнителем и `settlement::ExecutionMode::SerialReference`. Этот режим выполняет расчёт выбора работ, поиск пути и движение в вызывающем потоке. Сначала все свободные жители выбирают задание по одному состоянию, затем мир разбирает совпадающие заявки в порядке жителей. Обычный конструктор и загрузчик по умолчанию используют пул с 2–64 рабочими потоками. Конфигурацию исполнения выбирает клиент при создании или чтении мира. Один файл сохранения подходит для обоих вариантов. [Интерфейс мира](../../../engine/include/settlement/core/world.hpp)
Из корня репозитория после сборки Windows запустить `build\settlement_core_tests.exe --tag replay`. Журнал теста задаёт номера команд и попытки шага, поэтому может снять паузу даже тогда, когда номер такта остановился. Проверка сравнивает квитанции команд и полные байты сохранения по мере продвижения мира. Непрерывная партия задаёт ожидаемый результат для загруженной копии. [Исполняемые сценарии](../../../tests/replay_tests.cpp)
Этот срез открывает разработку M01. Фиксированный такт вне окна, неизменяемые снимки для клиентов, инкарнация после загрузки и идемпотентный результат повтора требуют отдельных изменений. Для замены пула остаются проверки переполнения, частичного запуска, времени жизни захваченных данных при отказе и стоимости работы на малом и нагруженном мире. [Проверка VoidLibrary](../void-library.md)
### Переход к авторитетному такту
Выделить одну воспроизводимую партию прототипа и записать последовательность приказов. Сначала пропустить её через очередь авторитетного мира и дать окну читать последний завершённый снимок. Далее заменить один участок независимого расчёта, сверить результат каждого такта, затем подключить следующий. Так первое расхождение привязано к конкретной стадии. Для суммы запасов, состояния задания и номера команды выводить в отчёт также идентификатор первого отличающегося объекта.
Проверить для нынешнего `WorkerPool` исполнителя `Void::Async::ThreadExecutor` с `FuturePool`. На частичном отказе запуска уже созданные потоки должны штатно завершиться. При заполненной очереди логическая работа остаётся в такте до исполнения. При одновременных заявках на предмет ожидаемый победитель определяется правилами арбитража. Доступность API и управляемое воспроизведение отказов записать до удаления прежнего пути. Эталонный последовательный исполнитель — новый тестовый режим. Исторический тест, отклоняющий конфигурацию с одним рабочим потоком, остаётся свидетельством поведения прототипа.
+6 -2
View File
@@ -172,6 +172,7 @@ enum class CommandKind : std::uint8_t {
CraftDoor = 14, CraftFurniture = 15
};
enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy };
enum class ExecutionMode : std::uint8_t { Parallel, SerialReference };
inline constexpr std::uint8_t colony_host = 1;
inline constexpr std::size_t colony_player_slots = 2;
@@ -346,8 +347,9 @@ struct ProductionOrder {
class World {
public:
// SerialReference uses one logical worker and executes on the calling thread.
World(std::uint64_t seed, std::int32_t width, std::int32_t height,
std::size_t workers = min_worker_count);
std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
void set_blocked(GridPosition position, bool blocked = true);
[[nodiscard]] bool is_walkable(GridPosition position) const noexcept;
@@ -385,7 +387,8 @@ public:
void step(TickProfile* profile = nullptr);
void write_svg(const std::string& path) const;
void write_save(std::ostream& stream) const;
[[nodiscard]] static std::unique_ptr<World> read_save(std::istream& stream, std::size_t workers = min_worker_count);
[[nodiscard]] static std::unique_ptr<World> read_save(
std::istream& stream, std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel);
[[nodiscard]] std::uint64_t tick() const noexcept;
[[nodiscard]] std::uint64_t seed() const noexcept;
@@ -445,6 +448,7 @@ private:
std::int32_t width_;
std::int32_t height_;
std::size_t worker_count_;
ExecutionMode execution_mode_;
std::unique_ptr<WorkerPool> worker_pool_;
AgentId next_agent_id_ = 1;
JobId next_job_id_ = 1;
+45 -23
View File
@@ -139,7 +139,18 @@ std::size_t checked_cell_count(std::int32_t width, std::int32_t height) {
return static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
}
std::size_t checked_worker_count(std::size_t workers) {
std::size_t checked_worker_count(std::size_t workers, ExecutionMode mode) {
switch (mode) {
case ExecutionMode::SerialReference:
if (workers != 1) {
throw std::invalid_argument("serial reference requires one logical worker");
}
return workers;
case ExecutionMode::Parallel:
break;
default:
throw std::invalid_argument("execution mode is not supported");
}
if (workers < min_worker_count || workers > max_worker_count) {
throw std::invalid_argument("worker count must be in the range 2..64");
}
@@ -268,11 +279,12 @@ void Storage::add_item(ItemType type) {
}
World::World(std::uint64_t seed, std::int32_t width, std::int32_t height,
std::size_t workers)
std::size_t workers, ExecutionMode mode)
: seed_(seed),
width_(width),
height_(height),
worker_count_(checked_worker_count(workers)),
worker_count_(checked_worker_count(workers, mode)),
execution_mode_(mode),
blocked_(checked_cell_count(width, height), 0) {}
std::size_t World::cell_index(GridPosition position) const noexcept {
@@ -1059,19 +1071,22 @@ void World::assign_idle_agents() {
return choices;
};
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
choice_futures.reserve(chunk_count);
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
const std::size_t end = chunk_start(chunk + 1);
choice_futures.push_back(worker_pool_->submit([&choose_jobs, begin, end] {
return choose_jobs(begin, end);
}));
}
std::vector<std::vector<std::size_t>> choices;
choices.reserve(chunk_count);
for (auto& future : choice_futures) choices.push_back(future.get());
if (execution_mode_ == ExecutionMode::SerialReference) {
choices.push_back(choose_jobs(0, agents_.size()));
} else {
std::vector<std::future<std::vector<std::size_t>>> choice_futures;
choice_futures.reserve(chunk_count);
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
const std::size_t end = chunk_start(chunk + 1);
choice_futures.push_back(worker_pool_->submit([&choose_jobs, begin, end] {
return choose_jobs(begin, end);
}));
}
for (auto& future : choice_futures) choices.push_back(future.get());
}
for (std::size_t chunk = 0; chunk < chunk_count; ++chunk) {
const std::size_t begin = chunk_start(chunk);
for (std::size_t offset = 0; offset < choices[chunk].size(); ++offset) {
@@ -1089,17 +1104,20 @@ void World::assign_idle_agents() {
if (requests.empty()) return;
std::vector<std::future<PathResult>> futures;
futures.reserve(requests.size());
for (const Request& request : requests) {
futures.push_back(worker_pool_->submit([this, start = request.start, goal = request.goal] {
return find_path(start, goal);
}));
if (execution_mode_ == ExecutionMode::Parallel) {
futures.reserve(requests.size());
for (const Request& request : requests) {
futures.push_back(worker_pool_->submit([this, start = request.start, goal = request.goal] {
return find_path(start, goal);
}));
}
}
for (std::size_t index = 0; index < requests.size(); ++index) {
auto path = futures[index].get();
const Request& request = requests[index];
auto path = execution_mode_ == ExecutionMode::SerialReference
? find_path(request.start, request.goal) : futures[index].get();
++path_searches_;
path_nodes_visited_ += path.nodes_visited;
const Request& request = requests[index];
Agent& agent = agents_[request.agent_index];
WorkJob& job = jobs_[request.job_index];
if (!path.reachable) {
@@ -1565,7 +1583,9 @@ void World::grow_sites() {
void World::step(TickProfile* profile) {
if (paused_) return;
if (!worker_pool_ && !agents_.empty()) worker_pool_ = std::make_unique<WorkerPool>(worker_count_);
if (execution_mode_ == ExecutionMode::Parallel && !worker_pool_ && !agents_.empty()) {
worker_pool_ = std::make_unique<WorkerPool>(worker_count_);
}
using Clock = std::chrono::steady_clock;
auto phase_start = profile ? Clock::now() : Clock::time_point{};
const auto finish_phase = [&](std::chrono::nanoseconds TickProfile::*phase) {
@@ -1636,7 +1656,9 @@ void World::step(TickProfile* profile) {
return completed;
};
if (!agents_.empty()) {
if (execution_mode_ == ExecutionMode::SerialReference) {
jobs_completed_ += advance_agents(0, agents_.size());
} else if (!agents_.empty()) {
const auto chunk_count = std::min(worker_count_, agents_.size());
std::vector<std::future<std::uint64_t>> futures;
futures.reserve(chunk_count);
+2 -2
View File
@@ -609,7 +609,7 @@ void World::write_save(std::ostream& stream) const {
WorldSaveCodec::body(archive, *this, save_version);
}
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers) {
std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t workers, ExecutionMode mode) {
SaveReader archive(stream);
for (char letter : signature) {
char actual = 0;
@@ -626,7 +626,7 @@ std::unique_ptr<World> World::read_save(std::istream& stream, std::size_t worker
archive.field(seed);
archive.field(width);
archive.field(height);
auto world = std::make_unique<World>(seed, width, height, workers);
auto world = std::make_unique<World>(seed, width, height, workers, mode);
WorldSaveCodec::body(archive, *world, version);
archive.finish();
if (version < 5) {
+312
View File
@@ -0,0 +1,312 @@
#include "settlement/core/world.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace {
using namespace settlement;
using Void::Testing::expect_throw;
using Void::Testing::Test;
struct ExecutionConfig {
std::size_t workers;
ExecutionMode mode;
};
constexpr std::array execution_configs{
ExecutionConfig{1, ExecutionMode::SerialReference},
ExecutionConfig{2, ExecutionMode::Parallel},
ExecutionConfig{6, ExecutionMode::Parallel},
ExecutionConfig{12, ExecutionMode::Parallel},
};
void require(bool condition, std::string_view message) {
if (!condition) throw std::runtime_error(std::string(message));
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
}
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config) {
std::istringstream stream(bytes, std::ios::binary);
auto world = World::read_save(stream, config.workers, config.mode);
require(world->worker_count() == config.workers, "load changed the requested worker count");
return world;
}
// Every run starts from one serialized fixture. The reference stays alive when
// checkpoint copies are added, so reload is checked against uninterrupted work.
class ReplayWorlds {
public:
explicit ReplayWorlds(const World& initial) {
const auto bytes = saved_state(initial);
reference = load_state(bytes, execution_configs.front());
require(saved_state(*reference) == bytes, "loading changed the starting fixture");
for (std::size_t i = 1; i < execution_configs.size(); ++i) {
runs_.push_back({execution_configs[i], false, load_state(bytes, execution_configs[i])});
}
compare();
}
void step() {
reference->step();
for (auto& run : runs_) run.world->step();
compare();
}
void command(const PlayerCommand& command, CommandStatus expected_status,
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");
};
check(*reference);
for (auto& run : runs_) check(*run.world);
compare();
}
void checkpoint() {
const auto bytes = saved_state(*reference);
for (auto config : execution_configs) {
runs_.push_back({config, true, load_state(bytes, config)});
}
compare();
}
std::unique_ptr<World> reference;
private:
struct Run {
ExecutionConfig config;
bool reloaded;
std::unique_ptr<World> world;
};
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()));
}
}
std::vector<Run> runs_;
};
struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite<ReplayTests> {
[[= 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();
[[= Void::Testing::tag("replay")]] Test test_recorded_colony_commands_and_loaded_delivery();
[[= Void::Testing::tag("replay")]] Test test_last_meal_has_one_winner_and_one_consumer();
};
Test ReplayTests::test_execution_configuration_and_empty_world() {
World initial(20261202, 5, 5);
const auto bytes = saved_state(initial);
constexpr std::array invalid_configs{
ExecutionConfig{0, ExecutionMode::Parallel},
ExecutionConfig{1, ExecutionMode::Parallel},
ExecutionConfig{max_worker_count + 1, ExecutionMode::Parallel},
ExecutionConfig{0, ExecutionMode::SerialReference},
ExecutionConfig{2, ExecutionMode::SerialReference},
ExecutionConfig{max_worker_count + 1, ExecutionMode::SerialReference},
ExecutionConfig{2, static_cast<ExecutionMode>(255)},
};
for (auto config : invalid_configs) {
expect_throw<std::invalid_argument>([&] {
World invalid(20261202, 5, 5, config.workers, config.mode);
});
expect_throw<std::invalid_argument>([&] { static_cast<void>(load_state(bytes, config)); });
}
expect_throw<std::invalid_argument>([] { World legacy(20261202, 5, 5, 1); });
World maximum(20261202, 5, 5, max_worker_count);
require(maximum.worker_count() == max_worker_count, "maximum parallel count was rejected");
require(saved_state(maximum) == bytes, "execution configuration changed the save bytes");
auto restored_maximum = load_state(bytes, {max_worker_count, ExecutionMode::Parallel});
require(saved_state(*restored_maximum) == bytes, "maximum-count load changed game state");
ReplayWorlds replay(initial);
for (int tick = 0; tick < 4; ++tick) replay.step();
require(replay.reference->tick() == 4 && replay.reference->agents().empty() &&
replay.reference->jobs_completed() == 0,
"an empty world failed to advance without residents");
}
Test ReplayTests::test_one_resident_completes_work() {
World initial(73, 8, 8);
static_cast<void>(initial.spawn_agent({1, 1}));
static_cast<void>(initial.add_job({6, 5}, 3));
ReplayWorlds replay(initial);
for (int tick = 0; tick < 20; ++tick) replay.step();
require(replay.reference->jobs_completed() == 1 &&
replay.reference->jobs().front().state == JobState::Completed &&
replay.reference->agents().front().position == GridPosition{6, 5},
"one resident failed to travel and complete the job");
}
Test ReplayTests::test_competing_jobs_retry_unreachable_routes() {
World initial(83, 12, 8);
for (int y = 0; y < 8; ++y) initial.set_blocked({5, y});
const auto unreachable = initial.add_job({6, 3}, 2);
std::array<JobId, 3> reachable{};
for (int i = 0; i < 3; ++i) {
static_cast<void>(initial.spawn_agent({3, 3}));
reachable[static_cast<std::size_t>(i)] = initial.add_job({0, 3 + i}, 2);
}
ReplayWorlds replay(initial);
replay.step();
for (std::size_t i = 0; i < reachable.size(); ++i) {
require(replay.reference->agents()[i].current_job == reachable[i],
"the job winner changed or an unreachable job prevented a retry");
}
require(replay.reference->path_searches() >= 6,
"the fixture did not attempt the unreachable route for every contender");
for (int tick = 1; tick < 20; ++tick) replay.step();
require(replay.reference->jobs_completed() == 3 &&
replay.reference->jobs().front().id == unreachable &&
replay.reference->jobs().front().state == JobState::Available,
"reachable work failed to complete or the sealed job was completed");
require(std::all_of(replay.reference->jobs().begin() + 1, replay.reference->jobs().end(),
[](const WorkJob& job) { return job.state == JobState::Completed; }),
"the completed count hid an unfinished reachable job");
}
Test ReplayTests::test_recorded_colony_commands_and_loaded_delivery() {
const auto initial = make_first_colony(2);
ReplayWorlds replay(*initial);
struct RecordedCommand {
int attempt;
PlayerCommand command;
CommandStatus status;
std::uint64_t tick;
std::uint64_t revision;
};
// Ordinals include the two paused step attempts. Rejected commands do not
// consume a sequence number or advance the command revision.
const std::array journal{
RecordedCommand{0, {1, 1, CommandKind::SetPaused, {}, 1}, CommandStatus::Accepted, 0, 1},
RecordedCommand{0, {2, 1, CommandKind::SetPaused, {}, 0}, CommandStatus::Unauthorized, 0, 1},
RecordedCommand{0, {1, 2, CommandKind::PlaceBed, {16, 18}}, CommandStatus::Accepted, 0, 2},
RecordedCommand{0, {2, 1, CommandKind::PlaceBed, {17, 18}, 1}, CommandStatus::Accepted, 0, 3},
RecordedCommand{0, {2, 1, CommandKind::PlaceBed, {18, 18}}, CommandStatus::WrongSequence, 0, 3},
RecordedCommand{0, {2, 2, CommandKind::PlaceBed, {16, 18}}, CommandStatus::InvalidTarget, 0, 3},
RecordedCommand{0, {2, 2, CommandKind::PlaceBed, {18, 18}}, CommandStatus::Accepted, 0, 4},
RecordedCommand{2, {1, 3, CommandKind::SetPaused, {}, 0}, CommandStatus::Accepted, 0, 5},
RecordedCommand{302, {2, 3, CommandKind::SetForaging, {14, 12}, 1}, CommandStatus::Accepted, 300, 6},
RecordedCommand{302, {1, 4, CommandKind::SetPriority, {}, 1}, CommandStatus::Accepted, 300, 7},
};
std::size_t next_command = 0;
bool saved_delivery = false;
for (int attempt = 0; attempt < 752; ++attempt) {
while (next_command < journal.size() && journal[next_command].attempt == attempt) {
const auto& entry = journal[next_command++];
replay.command(entry.command, entry.status, entry.tick, entry.revision);
}
const auto before = saved_state(*replay.reference);
replay.step();
if (attempt < 2) {
require(saved_state(*replay.reference) == before,
"a paused step changed the colony");
}
if (attempt == 301) {
require(replay.reference->scenario_progress().assigned_beds == 3 &&
!replay.reference->scenario_progress().completed &&
replay.reference->scenario_progress().available_food == 0,
"construction failed or unmarked food bypassed the recorded command");
}
const bool carrying_material = std::any_of(replay.reference->agents().begin(),
replay.reference->agents().end(), [](const Agent& agent) {
return agent.inventory.item_count(ItemType::Wood) > 0 ||
agent.inventory.item_count(ItemType::Stone) > 0 ||
agent.inventory.item_count(ItemType::Cloth) > 0;
});
if (!saved_delivery && carrying_material && replay.reference->assignment_path_cache_hits() > 0) {
replay.checkpoint();
saved_delivery = true;
}
}
require(saved_delivery, "no material-in-hand checkpoint with a warmed path cache was replayed");
require(next_command == journal.size() && replay.reference->tick() == 750,
"the recorded command schedule did not finish");
require(replay.reference->scenario_progress().completed && replay.reference->meals_eaten() >= 3,
"the recorded colony failed to build its beds and feed its residents");
require(replay.reference->next_command_sequence(1) == 5 &&
replay.reference->next_command_sequence(2) == 4,
"rejected commands changed player sequence progress");
}
Test ReplayTests::test_last_meal_has_one_winner_and_one_consumer() {
World initial(97, 8, 8);
const auto pantry = initial.add_storage({1, 1}, 1, StorageKind::Pantry);
const auto winner = initial.spawn_agent({5, 1});
static_cast<void>(initial.spawn_agent({5, 1}));
initial.enable_hunger();
// Hunger is staggered by resident ID. Supply the item only after both are
// eligible, so the first arbitration has two contenders for the same unit.
for (std::uint16_t tick = 0; tick < hunger_threshold; ++tick) initial.step();
require(initial.agents()[0].hungry() && initial.agents()[1].hungry(),
"the last-meal fixture requires two hungry contenders");
initial.stock_storage(pantry, ItemType::Berries, 1);
ReplayWorlds replay(initial);
bool saw_reservation = false;
bool saved_meal = false;
for (int tick = 0; tick < 40; ++tick) {
replay.step();
const auto& world = *replay.reference;
const auto& first = world.agents()[0];
const auto& second = world.agents()[1];
const auto& storage = world.storages().front();
const auto accounted = storage.item_count(ItemType::Berries) +
first.inventory.item_count(ItemType::Berries) + second.inventory.item_count(ItemType::Berries) +
world.meals_eaten();
require(accounted == 1, "the last meal was lost or duplicated");
require(second.inventory.empty() && second.state != AgentState::GoingToEat &&
second.state != AgentState::Eating,
"both contenders reserved the last meal");
if (first.state == AgentState::GoingToEat) {
require(first.id == winner && storage.items.front().reserved == 1 && first.inventory.empty(),
"stable resident order did not determine the last-meal reservation");
saw_reservation = true;
}
if (!saved_meal && first.inventory.item_count(ItemType::Berries) == 1) {
require(first.state == AgentState::Eating, "the meal was held outside its eating state");
replay.checkpoint();
saved_meal = true;
}
}
require(saw_reservation && saved_meal && replay.reference->meals_eaten() == 1 &&
replay.reference->storages().front().total_items() == 0 &&
replay.reference->agents()[0].hunger < hunger_threshold &&
replay.reference->agents()[1].hunger >= hunger_threshold,
"the stable winner did not consume the one available meal exactly once");
}
} // namespace