Files
stoneheart_at_home/tests/replay_tests.cpp
T

487 lines
24 KiB
C++

#include "settlement/core/world.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>
#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, WorldSaveFormat::Current14);
return stream.str();
}
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config,
WorkerPoolOptions options = {}) {
std::istringstream stream(bytes, std::ios::binary);
auto world = World::read_save(stream, config.workers, config.mode, std::move(options));
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, std::size_t capacity = 4096)
: options_{.max_admitted = capacity} {
const auto bytes = saved_state(initial);
reference = load_state(bytes, execution_configs.front(), options_);
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], options_)});
}
compare();
}
void step() {
++attempt_;
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);
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);
compare();
}
void checkpoint() {
const auto bytes = saved_state(*reference);
for (auto config : execution_configs) {
runs_.push_back({config, true, load_state(bytes, config, options_)});
}
compare();
}
std::unique_ptr<World> reference;
private:
struct Run {
ExecutionConfig config;
bool reloaded;
std::unique_ptr<World> world;
};
void compare() const {
for (const auto& run : runs_) {
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_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_recorded_colony_at_capacity_one();
[[= 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_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");
}
void replay_colony_journal(std::size_t capacity) {
const auto initial = make_first_colony(2);
ReplayWorlds replay(*initial, capacity);
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_recorded_colony_commands_and_loaded_delivery() {
replay_colony_journal(4096);
}
Test ReplayTests::test_recorded_colony_at_capacity_one() {
replay_colony_journal(1);
}
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