Files
stoneheart_at_home/tests/replay_tests.cpp
T

325 lines
15 KiB
C++

#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,
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() {
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, options_)});
}
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()));
}
}
WorkerPoolOptions options_;
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_recorded_colony_at_capacity_one();
[[= 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");
}
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