#include "settlement/core/world.hpp" #include "settlement/core/checkpoint.hpp" #include "replay_diagnostics.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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) { return replay_diagnostics::canonical(world); } std::unique_ptr 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 reference; private: struct Run { ExecutionConfig config; bool reloaded; std::unique_ptr 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 runs_; }; struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite { [[= Void::Testing::tag("replay")]] Test test_opposite_real_completion_orders(); [[= Void::Testing::tag("replay")]] Test test_semantic_divergence_diagnostics(); [[= Void::Testing::tag("replay")]] Test test_modern_custody_exposes_legacy_projection_blindness(); [[= Void::Testing::tag("replay")]] Test test_cancelled_partial_cargo_checkpoint_replay(); [[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world(); [[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work(); [[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes(); [[= 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 entered{}, permitted{}; std::vector 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{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(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{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(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(actual->add_job({6, 6}, 1)); require(replay_diagnostics::difference(expected, *actual).find("job id=2") != std::string::npos, "extra entity lost stable identity"); actual = load_state(fixture, execution_configs.front()); actual->set_blocked({7, 7}); require(replay_diagnostics::difference(expected, *actual).find("byte=") != std::string::npos, "unprojected canonical field lost byte fallback"); } Test ReplayTests::test_modern_custody_exposes_legacy_projection_blindness() { const auto legacy = [](const World& world) { std::ostringstream stream(std::ios::binary); world.write_save(stream, WorldSaveFormat::Current14); return stream.str(); }; const replay_diagnostics::Context context{2, 1, "custody", "legacy-import", 4096}; World stock(107, 12, 12, 1, ExecutionMode::SerialReference); const auto storage = stock.add_storage({2, 2}, 10); // Issued identities follow grants, while historical migration reconstructs // them from the canonically sorted item rows. stock.stock_storage(storage, ItemType::StoneBlock, 2); stock.stock_storage(storage, ItemType::Plank, 3); auto imported = load_state(legacy(stock), execution_configs.front()); require(legacy(stock) == legacy(*imported), "legacy stock projection changed on import"); auto report = replay_diagnostics::difference(stock, *imported, context); require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos && report.find("field=stack_id expected=2 actual=1") != std::string::npos, "modern comparison missed reconstructed stack identity: " + report); std::cout << report << '\n'; World accounting(108, 12, 12, 1, ExecutionMode::SerialReference); const auto store = accounting.add_storage({2, 2}, 10); accounting.stock_storage(store, ItemType::Wood, 2); imported = load_state(legacy(accounting), execution_configs.front()); require(legacy(accounting) == legacy(*imported), "legacy accounting projection changed on import"); report = replay_diagnostics::difference(accounting, *imported, context); require(report.find("balance item=1 field=grant expected=2 actual=0") != std::string::npos, "modern comparison missed opening/grant distinction: " + report); World active(109, 32, 32, 1, ExecutionMode::SerialReference); const auto materials = active.add_storage({3, 3}, 5); active.stock_storage(materials, ItemType::Plank, 3); active.stock_storage(materials, ItemType::StoneBlock, 2); static_cast(active.spawn_agent({1, 3})); active.queue_production({16, 3}, RecipeId::BuildCabin); active.step(); imported = load_state(legacy(active), execution_configs.front()); require(legacy(active) == legacy(*imported), "legacy active projection changed on import"); require(!active.custody_receipts().empty() && imported->custody_receipts().empty(), "fixture did not distinguish real and reconstructed history"); report = replay_diagnostics::difference(active, *imported, context); require(report.find("custody receipt kind=0 id=1 ordinal=1") != std::string::npos && report.find("actual=") != std::string::npos, "modern comparison missed retained admission result: " + report); std::cout << report << '\n'; const auto facts = replay_diagnostics::facts(active); const auto& transfer = *active.agents().front().execution; const auto& reservation = transfer.reservations.front(); require(facts.at({1, "transfer id=" + std::to_string(transfer.id) + " owner=agent:1 field=next_operation"}) == "1" && facts.at({1, "reservation id=" + std::to_string(reservation.id) + " transfer=" + std::to_string(transfer.id) + " field=stack_id"}) == std::to_string(reservation.stack), "active transfer/reservation diagnostics lost durable identities"); } Test ReplayTests::test_cancelled_partial_cargo_checkpoint_replay() { World reference(113, 32, 32, 1, ExecutionMode::SerialReference); const auto source = reference.add_storage({3, 3}, 5); reference.stock_storage(source, ItemType::Plank, 3); reference.stock_storage(source, ItemType::StoneBlock, 2); static_cast(reference.spawn_agent({1, 3})); reference.queue_production({16, 3}, RecipeId::BuildCabin); const auto order = reference.production_orders().front().id; for (int tick = 0; tick < 30 && reference.agents().front().state != AgentState::Working; ++tick) reference.step(); require(reference.agents().front().state == AgentState::Working, "cabin delivery did not reach the site"); const auto transfer = reference.agents().front().execution->id; require(reference.cancel_production(order) == CommandStatus::Accepted, "live construction cancellation failed"); reference.stock_storage(source, ItemType::Wood, 5); const auto partial = reference.add_storage({4, 3}, 1); for (int tick = 0; tick < 40; ++tick) reference.step(); const auto& actor = reference.agents().front(); require(actor.state == AgentState::Returning && actor.execution && actor.execution->id == transfer && actor.execution->blocked == CustodyStatus::NoDestination && actor.inventory.item_count(ItemType::Plank) == 2 && actor.inventory.item_count(ItemType::StoneBlock) == 2 && reference.find_storage(partial)->item_count(ItemType::Plank) == 1, "partial return did not retain the same transfer and remaining cargo"); const auto admission = *reference.custody_receipts().front(); const auto cancelled = std::find_if(reference.custody_receipts().begin(), reference.custody_receipts().end(), [](const auto& receipt) { return receipt->request.operation == CustodyOperation::Cancel; }); require(cancelled != reference.custody_receipts().end(), "cancel result was not retained"); const std::array retained{admission, **cancelled}; Void::Uuid::Uuid world_id; world_id.bytes.back() = 113; const auto rules = default_rules_manifest(); const auto catalog = builtin_rule_packages(); require(rules.has_value() && catalog.has_value(), "default rules unavailable"); const auto checkpoint = encode_checkpoint(reference, world_id, 7, *rules); require(checkpoint.has_value(), "partial cargo checkpoint failed"); std::vector> candidates; for (const auto config : execution_configs) { auto loaded = decode_checkpoint(*checkpoint, *catalog, config.workers, config.mode); require(loaded.has_value(), "partial cargo checkpoint was not decoded"); require(loaded->world_id == world_id && loaded->city == 7, "checkpoint identity changed"); const auto repeated = encode_checkpoint(*loaded->world, loaded->world_id, loaded->city, loaded->rules); require(repeated.has_value() && *repeated == *checkpoint, "partial checkpoint roundtrip changed bytes"); candidates.push_back(std::move(loaded->world)); } const auto repeat_without_effect = [&](World& world) { const auto before = saved_state(world); for (const auto& receipt : retained) { require(world.custody_request(receipt.request) == receipt.result, "retained result changed after reload"); auto conflict = receipt.request; ++conflict.destination; require(world.custody_request(conflict).status == CustodyStatus::Conflict, "changed payload reused an accepted transfer step"); } require(saved_state(world) == before, "retry repeated a physical transfer or consumed an ordinal"); }; repeat_without_effect(reference); for (auto& world : candidates) repeat_without_effect(*world); for (std::uint64_t attempt = 0; attempt < 40; ++attempt) { if (attempt == 5) { static_cast(reference.add_storage({6, 3}, 20)); for (auto& world : candidates) static_cast(world->add_storage({6, 3}, 20)); } reference.step(); for (std::size_t i = 0; i < candidates.size(); ++i) { candidates[i]->step(); const auto report = replay_diagnostics::difference(reference, *candidates[i], {attempt, execution_configs[i].workers, "cancel-return", "checkpoint", 4096}); require(report.empty(), report); repeat_without_effect(*candidates[i]); } } require(reference.agents().front().inventory.empty() && !reference.agents().front().execution && reference.item_balances()[2].installation == 0 && reference.item_balances()[3].installation == 0, "return duplicated consumption or retained finished cargo"); repeat_without_effect(reference); } Test ReplayTests::test_execution_configuration_and_empty_world() { World initial(20261202, 5, 5); const auto bytes = saved_state(initial); 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(255)}, }; for (auto config : invalid_configs) { expect_throw([&] { World invalid(20261202, 5, 5, config.workers, config.mode); }); expect_throw([&] { static_cast(load_state(bytes, config)); }); } expect_throw([] { 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(initial.spawn_agent({1, 1})); static_cast(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 reachable{}; for (int i = 0; i < 3; ++i) { static_cast(initial.spawn_agent({3, 3})); reachable[static_cast(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(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