Integrate immutable world snapshots into M01
This commit is contained in:
commit
4921dffe71
6 files changed
+350
-34
No files matched your search
@@ -113,6 +113,7 @@ if(BUILD_TESTING)
|
||||
tests/replay_tests.cpp
|
||||
tests/rules_tests.cpp
|
||||
tests/session_tests.cpp
|
||||
tests/snapshot_tests.cpp
|
||||
tests/test_main.cpp
|
||||
)
|
||||
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Capture immutable world state at a completed simulation boundary
|
||||
|
||||
Task ID: S01-03
|
||||
Role: sol_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Exclusive checkout /home/faumaray/Projects/stoneheart_at_home-worktrees/s01, system/s01-simulation at 68f91a2, verified S01-02. World owns complete data, execution mode/pool/caches; WorldSaveCodec reads and validates that data. M01-P2/F3 and upstream Void/Library #5 cover immutable caller-built snapshots.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide NEW World::capture() const -> std::shared_ptr<const World> for const renderer/serializer/snapshot users. Held snapshots preserve all observable data after subsequent live mutations, or when live World is destroyed.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
World snapshot representation and focused tests, no coordinator, UI, checkpoint, rules or generic atomic snapshot mirror. No byte roundtrip/allocation of a worker during capture. Capture must be called by owner at finished command/tick barrier.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect world.hpp, world.cpp, world_save.cpp, worker_pool.*, tests/{replay,executor,core}_tests.cpp, benchmarks/colony.cpp. Identify all persistent fields, visible counters, worker and transient cache state, const views and nested paths/inventory containers.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: engine/include/settlement/core/world.hpp; engine/src/world.cpp; tests/snapshot_tests.cpp; CMakeLists.txt; docs/plan/systems/S01.md
|
||||
No editing other worktrees, Git or Serena state. You are not alone and other agents own runtime, rules, persistence, dispatch. Preserve S01-02 exactly apart from necessary representation changes.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Group copyable logical World data in a single copyable representation such that future gameplay fields naturally join one copy. Keep executor, worker callbacks and cache out of captures (cache independent of future behavior; if a read-only getter exposes hit or path counters, preserve its observed value). Preserve source worker_count() reporting where practical, and forbid mutable snapshot access by type. Favor private or internal state and simple direct World access; no hand-maintained second serializer, dozens of copy assignments or per-capture thread starts. Reuse existing WorldSaveCodec public behavior. Validate current construction/layout/implicit move caller compatibility.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW public std::shared_ptr<const World> World::capture() const. Propagate normal allocation failures to the owner, source remains untouched, no mutation or pointer aliases to source vectors/agents. Existing factories, modes and format13 unchanged. Include upstream #5 link plus replacement criterion where publication is discussed.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root will plug capture into single-owner publication, sampled under one owner, snapshots can cross renderer/I/O/threads. This feature can compile from 68f91a2 without S16 or S19. No alternate restore API unless natural and actually required.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Snapshot retains owned nested inventories/routes/reservations, current pause, workshop, hidden sequence/revision/counters and profiling data needed by reads. Capture while a task is running is outside caller contract. Pools/hooks not allocated/retained by read-only view. Test held snapshot can be read on a worker while source advances without using sleeps as ordering controls. Bound benchmark scope to actually measured World/runs.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. compare canonical bytes immediately and after source changes/destruction incl mid-carry fixture; assert stable views/counters/pause. 2. Capture+serialize on actual const read path; callback ownership released with live world even if snapshot lives. 3. Cover 2/6 and serial or existing replay tests for legacy behavior. 4. Measure capture cost at 50/500 residents in x64 Wine and report exactly what was measured, no native claim.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/capture-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 wine <build>/settlement_core_tests.exe --tag snapshot, git diff --check; evidence including benchmark protocol and measurements. Separate output files from S01-02 logs.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not alter formats, owner scheduling or save/LAN fixtures. No unrequested generic server/runtime framework. Stop if renderer has mutating access disguised as const or impossible copy semantics. Escalate after two failed repairs of the same defect.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Parent owns all commits and pushes. User approved roadmap; planner/preflight accepted independent copies at owner barrier. This is the first S01 immutable-publication component.
|
||||
|
||||
## 14. Return format
|
||||
Return S01-03 READY/BLOCKED, exact API/files, fields/cache/executor boundary, actual tests/counts, measurements, limitations and contact on any compatibility risk. No children.
|
||||
@@ -57,6 +57,16 @@
|
||||
|
||||
Первый пакет имеет одного владельца контрактов времени, ID и публикации. После закрепления интерфейсов отдельные исполнители берут адаптацию навигации, экономики и клиента с раздельными файлами. Интеграционный тест проверяет целый такт.
|
||||
|
||||
## Неизменяемый снимок M01
|
||||
|
||||
`World::capture() const` возвращает `std::shared_ptr<const World>`. Владелец вызывает его после завершения всех заданий стадии. Логические поля мира и доступные читателю счётчики находятся в едином копируемом `detail::WorldState`. Снимок владеет отдельными контейнерами жителей, запасов, маршрутов, работ и резервов. Конфигурация числа исполнителей остаётся доступной читателю. Пул, обратные вызовы исполнителя и восстанавливаемый кэш маршрутов принадлежат рабочему миру. Ошибка выделения памяти передаётся владельцу. [Интерфейс и данные](../../../engine/include/settlement/core/world.hpp) · [Копирование](../../../engine/src/world.cpp)
|
||||
|
||||
Четыре проверки `settlement_core_tests.exe --tag snapshot` прошли в Windows x64 Release под Wine. Они проверяют копии в эталоне и на 2/6 потоках, удержание данных при дальнейшем развитии и уничтожении исходного мира, паузу с материалом в руках, вложенные маршруты и резервы, чтение из второго потока и освобождение обратных вызовов вместе с рабочим миром. Полный прогон дал 46 случаев ядра и 4 LAN, включая формат сохранения 13 и протокол 11. [Проверки снимков](../../../tests/snapshot_tests.cpp)
|
||||
|
||||
Для сцены из существующего `benchmarks/colony.cpp` на карте 80 × 80 с шестью потоками выполнены три прогона для 50 и 500 жителей. После 32 тактов прогрева снимок создавался после каждого из 240 тактов. Измерение охватывает выделение и копирование в `capture()`. Чтение снимка и освобождение ссылки выполнялись за пределами интервала. Медианы трёх p50/p95 составили 2/4 мкс для 50 жителей и 23/68 мкс для 500. Отдельные p95 составили 4, 7 и 4 мкс, затем 68, 81 и 67 мкс. Это измерение кросс-сборки GCC 16.2.0 под Wine 11.
|
||||
|
||||
Общая библиотечная публикация неизменяемого состояния отслеживается в Void/Library. Переход на неё требует проверок удержания старой версии, независимости от изменяемого источника, согласованной версии и освобождения читателей при остановке. Игровое копирование выполняет `World::capture()`. [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5)
|
||||
|
||||
## Приёмка
|
||||
|
||||
На ветке `system/s01-simulation` три параллельные стадии мира используют закреплённые `Void::Async::ThreadExecutor` и `FuturePool`. При заполнении лимита координатор выполняет задание сам. Стадия дожидается ранее принятых заданий и при исключении. Последовательный эталон вызывает те же игровые операции. На журнале из 750 тактов канонические сохранения после каждого такта совпали у эталона и вариантов с 2, 6 и 12 потоками, в том числе при лимите одного задания и после загрузки в процессе переноски. [Исполнитель](../../../engine/include/settlement/core/worker_pool.hpp) · [Проверки отказов](../../../tests/executor_tests.cpp) · [Воспроизведение](../../../tests/replay_tests.cpp)
|
||||
|
||||
@@ -345,7 +345,47 @@ struct ProductionOrder {
|
||||
}
|
||||
};
|
||||
|
||||
class World {
|
||||
namespace detail {
|
||||
|
||||
// Logical data and observable counters share one copy operation at publication.
|
||||
// Execution resources and rebuildable caches belong to World.
|
||||
struct WorldState {
|
||||
WorldState(std::uint64_t seed, std::int32_t width, std::int32_t height) noexcept
|
||||
: seed_(seed), width_(width), height_(height) {}
|
||||
|
||||
std::uint64_t seed_;
|
||||
std::uint64_t tick_ = 0;
|
||||
std::uint64_t path_searches_ = 0;
|
||||
std::uint64_t path_nodes_visited_ = 0;
|
||||
std::uint64_t assignment_path_cache_hits_ = 0;
|
||||
std::uint64_t jobs_completed_ = 0;
|
||||
std::uint64_t meals_eaten_ = 0;
|
||||
bool hunger_enabled_ = false;
|
||||
std::int32_t width_;
|
||||
std::int32_t height_;
|
||||
AgentId next_agent_id_ = 1;
|
||||
JobId next_job_id_ = 1;
|
||||
std::uint64_t next_resource_node_id_ = 1;
|
||||
std::uint64_t next_storage_id_ = 1;
|
||||
std::vector<std::uint8_t> blocked_;
|
||||
std::vector<Agent> agents_;
|
||||
std::vector<WorkJob> jobs_;
|
||||
std::vector<ResourceNode> resource_nodes_;
|
||||
std::vector<Storage> storages_;
|
||||
std::vector<ProductionOrder> production_orders_;
|
||||
bool scenario_active_ = false;
|
||||
bool staged_beds_ = false;
|
||||
bool paused_ = false;
|
||||
bool scenario_completed_ = false;
|
||||
WorkPriority work_priority_ = WorkPriority::Balanced;
|
||||
GridPosition scenario_sawmill_;
|
||||
std::array<std::uint64_t, colony_player_slots> player_sequences_{};
|
||||
std::uint64_t command_revision_ = 0;
|
||||
};
|
||||
|
||||
} // namespace detail
|
||||
|
||||
class World : private detail::WorldState {
|
||||
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,
|
||||
@@ -388,6 +428,9 @@ public:
|
||||
void step(TickProfile* profile = nullptr);
|
||||
void write_svg(const std::string& path) const;
|
||||
void write_save(std::ostream& stream) const;
|
||||
// Called by the owner after every stage has drained. The independent copy
|
||||
// can be retained by readers on other threads while the owner advances.
|
||||
[[nodiscard]] std::shared_ptr<const World> capture() const;
|
||||
[[nodiscard]] static std::unique_ptr<World> read_save(
|
||||
std::istream& stream, std::size_t workers = min_worker_count, ExecutionMode mode = ExecutionMode::Parallel,
|
||||
WorkerPoolOptions worker_options = {});
|
||||
@@ -412,6 +455,8 @@ public:
|
||||
|
||||
private:
|
||||
friend struct WorldSaveCodec;
|
||||
struct CaptureTag {};
|
||||
World(CaptureTag, const World& source);
|
||||
struct PathResult {
|
||||
std::vector<GridPosition> positions;
|
||||
std::uint64_t nodes_visited = 0;
|
||||
@@ -439,39 +484,11 @@ private:
|
||||
void grow_sites();
|
||||
[[nodiscard]] bool can_reach_object_cell(GridPosition position) const;
|
||||
|
||||
std::uint64_t seed_;
|
||||
std::uint64_t tick_ = 0;
|
||||
std::uint64_t path_searches_ = 0;
|
||||
std::uint64_t path_nodes_visited_ = 0;
|
||||
std::uint64_t assignment_path_cache_hits_ = 0;
|
||||
std::uint64_t jobs_completed_ = 0;
|
||||
std::uint64_t meals_eaten_ = 0;
|
||||
bool hunger_enabled_ = false;
|
||||
std::int32_t width_;
|
||||
std::int32_t height_;
|
||||
std::size_t worker_count_;
|
||||
ExecutionMode execution_mode_;
|
||||
WorkerPoolOptions worker_options_;
|
||||
std::unique_ptr<WorkerPool> worker_pool_;
|
||||
AgentId next_agent_id_ = 1;
|
||||
JobId next_job_id_ = 1;
|
||||
std::uint64_t next_resource_node_id_ = 1;
|
||||
std::uint64_t next_storage_id_ = 1;
|
||||
std::vector<std::uint8_t> blocked_;
|
||||
std::unordered_map<std::uint64_t, PathResult> assignment_path_cache_;
|
||||
std::vector<Agent> agents_;
|
||||
std::vector<WorkJob> jobs_;
|
||||
std::vector<ResourceNode> resource_nodes_;
|
||||
std::vector<Storage> storages_;
|
||||
std::vector<ProductionOrder> production_orders_;
|
||||
bool scenario_active_ = false;
|
||||
bool staged_beds_ = false;
|
||||
bool paused_ = false;
|
||||
bool scenario_completed_ = false;
|
||||
WorkPriority work_priority_ = WorkPriority::Balanced;
|
||||
GridPosition scenario_sawmill_;
|
||||
std::array<std::uint64_t, colony_player_slots> player_sequences_{};
|
||||
std::uint64_t command_revision_ = 0;
|
||||
};
|
||||
|
||||
inline constexpr std::int32_t first_colony_map_size = 32;
|
||||
|
||||
+13
-5
@@ -282,13 +282,21 @@ void Storage::add_item(ItemType type) {
|
||||
|
||||
World::World(std::uint64_t seed, std::int32_t width, std::int32_t height,
|
||||
std::size_t workers, ExecutionMode mode, WorkerPoolOptions worker_options)
|
||||
: seed_(seed),
|
||||
width_(width),
|
||||
height_(height),
|
||||
: WorldState(seed, width, height),
|
||||
worker_count_(checked_worker_count(workers, mode)),
|
||||
execution_mode_(mode),
|
||||
worker_options_(std::move(worker_options)),
|
||||
blocked_(checked_cell_count(width, height), 0) {}
|
||||
worker_options_(std::move(worker_options)) {
|
||||
blocked_.resize(checked_cell_count(width, height), 0);
|
||||
}
|
||||
|
||||
World::World(CaptureTag, const World& source)
|
||||
: WorldState(source),
|
||||
worker_count_(source.worker_count_),
|
||||
execution_mode_(source.execution_mode_) {}
|
||||
|
||||
std::shared_ptr<const World> World::capture() const {
|
||||
return std::shared_ptr<const World>(new const World(CaptureTag{}, *this));
|
||||
}
|
||||
|
||||
std::size_t World::cell_index(GridPosition position) const noexcept {
|
||||
return static_cast<std::size_t>(position.y) * static_cast<std::size_t>(width_) +
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <barrier>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace settlement;
|
||||
using Void::Testing::require;
|
||||
using Void::Testing::Test;
|
||||
|
||||
static_assert(std::is_same_v<decltype(std::declval<const World&>().capture()),
|
||||
std::shared_ptr<const World>>);
|
||||
static_assert(std::is_move_constructible_v<World>);
|
||||
static_assert(std::is_move_assignable_v<World>);
|
||||
static_assert(!std::is_copy_constructible_v<World>);
|
||||
|
||||
std::string bytes(const World& world) {
|
||||
std::ostringstream stream(std::ios::binary);
|
||||
world.write_save(stream);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void send(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) {
|
||||
const auto receipt = world.apply_command(
|
||||
{colony_host, world.next_command_sequence(colony_host), kind, cell, value});
|
||||
require(receipt.status == CommandStatus::Accepted);
|
||||
}
|
||||
|
||||
void compare_read_views(const World& source, const World& snapshot) {
|
||||
require(bytes(snapshot) == bytes(source));
|
||||
require(snapshot.seed() == source.seed());
|
||||
require(snapshot.width() == source.width() && snapshot.height() == source.height());
|
||||
require(snapshot.tick() == source.tick() && snapshot.worker_count() == source.worker_count());
|
||||
require(snapshot.path_searches() == source.path_searches());
|
||||
require(snapshot.path_nodes_visited() == source.path_nodes_visited());
|
||||
require(snapshot.assignment_path_cache_hits() == source.assignment_path_cache_hits());
|
||||
require(snapshot.jobs_completed() == source.jobs_completed());
|
||||
require(snapshot.meals_eaten() == source.meals_eaten());
|
||||
require(snapshot.scenario_active() == source.scenario_active());
|
||||
require(snapshot.staged_beds() == source.staged_beds());
|
||||
require(snapshot.paused() == source.paused());
|
||||
require(snapshot.work_priority() == source.work_priority());
|
||||
require(snapshot.carpenter_workshop() == source.carpenter_workshop());
|
||||
for (std::uint8_t player = 1; player <= colony_player_slots; ++player) {
|
||||
require(snapshot.next_command_sequence(player) == source.next_command_sequence(player));
|
||||
}
|
||||
for (int y = 0; y < source.height(); ++y) {
|
||||
for (int x = 0; x < source.width(); ++x) {
|
||||
require(snapshot.is_walkable({x, y}) == source.is_walkable({x, y}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("SnapshotTests")]] SnapshotTests : Void::Testing::Suite<SnapshotTests> {
|
||||
[[= Void::Testing::tag("snapshot")]] Test test_independent_state_in_all_execution_modes();
|
||||
[[= Void::Testing::tag("snapshot")]] Test test_mid_delivery_and_paused_command_state_survives_owner();
|
||||
[[= Void::Testing::tag("snapshot")]] Test test_reader_runs_while_owner_advances();
|
||||
[[= Void::Testing::tag("snapshot")]] Test test_capture_excludes_execution_callbacks_and_workers();
|
||||
};
|
||||
|
||||
Test SnapshotTests::test_independent_state_in_all_execution_modes() {
|
||||
constexpr std::array workers{1U, 2U, 6U};
|
||||
for (const auto count : workers) {
|
||||
const auto mode = count == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel;
|
||||
World source(53, 12, 12, count, mode);
|
||||
source.set_blocked({4, 4});
|
||||
static_cast<void>(source.spawn_agent({1, 1}));
|
||||
static_cast<void>(source.add_job({8, 8}, 3));
|
||||
source.step();
|
||||
const auto snapshot = source.capture();
|
||||
compare_read_views(source, *snapshot);
|
||||
require(source.agents().data() != snapshot->agents().data());
|
||||
require(source.agents().front().route.data() != snapshot->agents().front().route.data());
|
||||
require(source.jobs().data() != snapshot->jobs().data());
|
||||
const auto expected = bytes(*snapshot);
|
||||
const auto position = snapshot->agents().front().position;
|
||||
const auto searches = snapshot->path_searches();
|
||||
static_cast<void>(source.spawn_agent({2, 2}));
|
||||
static_cast<void>(source.add_job({2, 7}, 1));
|
||||
source.set_blocked({4, 4}, false);
|
||||
for (int i = 0; i < 30; ++i) source.step();
|
||||
require(bytes(*snapshot) == expected);
|
||||
require(snapshot->agents().front().position == position);
|
||||
require(snapshot->path_searches() == searches && !snapshot->is_walkable({4, 4}));
|
||||
|
||||
auto nested_snapshot = snapshot->capture();
|
||||
compare_read_views(*snapshot, *nested_snapshot);
|
||||
World moved(std::move(source));
|
||||
require(moved.agents().size() == 2);
|
||||
require(bytes(*snapshot) == expected);
|
||||
}
|
||||
}
|
||||
|
||||
Test SnapshotTests::test_mid_delivery_and_paused_command_state_survives_owner() {
|
||||
auto source = make_first_colony(6);
|
||||
send(*source, CommandKind::PlaceBed, {16, 18});
|
||||
send(*source, CommandKind::PlaceBed, {17, 18}, 1);
|
||||
send(*source, CommandKind::PlaceBed, {18, 18});
|
||||
bool carrying = false;
|
||||
for (int step = 0; step < 300 && !carrying; ++step) {
|
||||
source->step();
|
||||
carrying = source->assignment_path_cache_hits() > 0 &&
|
||||
std::any_of(source->agents().begin(), source->agents().end(), [](const Agent& agent) {
|
||||
return !agent.inventory.empty() && agent.production_index != no_entity_index;
|
||||
});
|
||||
}
|
||||
require(carrying);
|
||||
send(*source, CommandKind::SetPriority, {}, 1);
|
||||
send(*source, CommandKind::SetPaused, {}, 1);
|
||||
auto snapshot = source->capture();
|
||||
compare_read_views(*source, *snapshot);
|
||||
require(snapshot->paused() && snapshot->work_priority() == WorkPriority::FoodFirst);
|
||||
require(source->storages().data() != snapshot->storages().data());
|
||||
require(source->production_orders().data() != snapshot->production_orders().data());
|
||||
bool nested_materials = false;
|
||||
bool nested_routes = false;
|
||||
bool nested_stacks = false;
|
||||
for (std::size_t i = 0; i < source->production_orders().size(); ++i) {
|
||||
const auto& live = source->production_orders()[i];
|
||||
const auto& held = snapshot->production_orders()[i];
|
||||
if (!live.materials.empty()) {
|
||||
require(live.materials.data() != held.materials.data());
|
||||
nested_materials = true;
|
||||
}
|
||||
for (std::size_t stop = 0; stop < live.delivery_stops.size(); ++stop) {
|
||||
if (live.delivery_stops[stop].route_to_next.empty()) continue;
|
||||
require(live.delivery_stops[stop].route_to_next.data() !=
|
||||
held.delivery_stops[stop].route_to_next.data());
|
||||
nested_routes = true;
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < source->storages().size(); ++i) {
|
||||
if (source->storages()[i].items.empty()) continue;
|
||||
require(source->storages()[i].items.data() != snapshot->storages()[i].items.data());
|
||||
nested_stacks = true;
|
||||
}
|
||||
require(nested_materials && nested_routes && nested_stacks);
|
||||
const auto expected = bytes(*snapshot);
|
||||
const auto hits = snapshot->assignment_path_cache_hits();
|
||||
const auto sequence = snapshot->next_command_sequence(colony_host);
|
||||
send(*source, CommandKind::SetPaused, {}, 0);
|
||||
for (int step = 0; step < 100; ++step) source->step();
|
||||
source.reset();
|
||||
require(bytes(*snapshot) == expected);
|
||||
require(snapshot->paused() && snapshot->assignment_path_cache_hits() == hits);
|
||||
require(snapshot->next_command_sequence(colony_host) == sequence);
|
||||
|
||||
std::istringstream first(expected, std::ios::binary);
|
||||
std::istringstream second(expected, std::ios::binary);
|
||||
auto serial = World::read_save(first, 1, ExecutionMode::SerialReference);
|
||||
auto parallel = World::read_save(second, 2);
|
||||
send(*serial, CommandKind::SetPaused, {}, 0);
|
||||
send(*parallel, CommandKind::SetPaused, {}, 0);
|
||||
for (int step = 0; step < 100; ++step) {
|
||||
serial->step();
|
||||
parallel->step();
|
||||
require(bytes(*serial) == bytes(*parallel));
|
||||
}
|
||||
require(bytes(*snapshot) == expected);
|
||||
}
|
||||
|
||||
Test SnapshotTests::test_reader_runs_while_owner_advances() {
|
||||
auto source = make_first_colony(2);
|
||||
send(*source, CommandKind::PlaceBed, {16, 18});
|
||||
source->step();
|
||||
const auto snapshot = source->capture();
|
||||
const auto expected = bytes(*snapshot);
|
||||
std::barrier rendezvous(2);
|
||||
auto reader = std::async(std::launch::async, [snapshot, expected, &rendezvous] {
|
||||
bool consistent = true;
|
||||
for (int step = 0; step < 32; ++step) {
|
||||
rendezvous.arrive_and_wait();
|
||||
try {
|
||||
consistent = consistent && bytes(*snapshot) == expected;
|
||||
consistent = consistent && snapshot->tick() == 1 && snapshot->agents().size() == 3;
|
||||
} catch (...) {
|
||||
consistent = false;
|
||||
}
|
||||
rendezvous.arrive_and_wait();
|
||||
}
|
||||
return consistent;
|
||||
});
|
||||
// Drop this participant before joining the reader if an owner step fails.
|
||||
auto release_reader = Void::Scope::on_exit([&] { rendezvous.arrive_and_drop(); });
|
||||
for (int step = 0; step < 32; ++step) {
|
||||
rendezvous.arrive_and_wait();
|
||||
source->step();
|
||||
rendezvous.arrive_and_wait();
|
||||
}
|
||||
release_reader.release();
|
||||
require(reader.get());
|
||||
require(source->tick() == 33 && bytes(*snapshot) == expected);
|
||||
}
|
||||
|
||||
Test SnapshotTests::test_capture_excludes_execution_callbacks_and_workers() {
|
||||
std::shared_ptr<const World> snapshot;
|
||||
auto callback_state = std::make_shared<std::atomic<int>>(0);
|
||||
std::weak_ptr<std::atomic<int>> weak_state = callback_state;
|
||||
auto source = [&] {
|
||||
WorkerPoolOptions options;
|
||||
options.before_worker_start = [callback_state](std::size_t) { ++*callback_state; };
|
||||
return std::make_unique<World>(61, 8, 8, 2, ExecutionMode::Parallel, std::move(options));
|
||||
}();
|
||||
static_cast<void>(source->spawn_agent({1, 1}));
|
||||
static_cast<void>(source->add_job({6, 6}, 4));
|
||||
auto unstarted = source->capture();
|
||||
require(callback_state->load() == 0);
|
||||
source->step();
|
||||
require(callback_state->load() == 2);
|
||||
snapshot = source->capture();
|
||||
require(callback_state->load() == 2);
|
||||
const auto expected = bytes(*snapshot);
|
||||
callback_state.reset();
|
||||
source.reset();
|
||||
require(weak_state.expired());
|
||||
require(snapshot->worker_count() == 2 && bytes(*snapshot) == expected);
|
||||
require(unstarted->tick() == 0 && unstarted->agents().size() == 1);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
Reference in new issue
Block a user