#include "settlement/core/checkpoint.hpp" #include "settlement/core/world.hpp" #include #include #include #include #include #include #include namespace { using namespace settlement; using Void::Testing::Test; void require(bool condition, const char* message = "identity invariant failed") { if (!condition) throw std::runtime_error(message); } constexpr auto last_counter = std::numeric_limits::max(); // Format 13 header, five tick/stat counters, hunger and four next-ID counters. constexpr std::size_t next_node_offset = 85; constexpr std::size_t next_storage_offset = 93; std::string bytes(const World& world) { std::ostringstream stream(std::ios::binary); world.write_save(stream); return stream.str(); } void put_u64(std::string& data, std::size_t at, std::uint64_t value) { require(at + 8 <= data.size(), "fixture offset outside save"); for (unsigned i = 0; i < 8; ++i) data[at + i] = static_cast((value >> (i * 8)) & 255); } std::unique_ptr restore(const std::string& data, std::size_t workers = 1) { std::istringstream input(data, std::ios::binary); return World::read_save(input, workers, workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel); } CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0) { return world.apply_command({1, world.next_command_sequence(1), kind, cell, value}).status; } void compare_continuation(World& original, int ticks) { const auto initial = bytes(original); std::array copies{restore(initial, 1), restore(initial, 2), restore(initial, 6), restore(initial, 12)}; const auto catalog = builtin_rule_packages(); const auto rules = default_rules_manifest(); require(catalog.has_value() && rules.has_value(), "built-in rule fixture failed"); const auto id = Void::Uuid::try_v4(); require(id.has_value(), "UUID fixture failed"); const auto checkpoint = encode_checkpoint(original, *id, 1, *rules); require(checkpoint.has_value(), "checkpoint encode failed"); auto candidate = decode_checkpoint(*checkpoint, *catalog, 1, ExecutionMode::SerialReference); require(candidate.has_value(), "checkpoint decode failed"); const auto held = original.capture(); for (int tick = 0; tick < ticks; ++tick) { original.step(); const auto expected = bytes(original); for (auto& copy : copies) { copy->step(); require(bytes(*copy) == expected, "ID-linked continuation differs across execution modes"); } candidate->world->step(); require(bytes(*candidate->world) == expected, "checkpoint continuation changed ID links"); require(bytes(*held) == initial, "held snapshot changed after ID-linked world advanced"); } } template void require_exhausted(World& world, Work work) { const auto before = bytes(world); bool overflow = false; try { work(); } catch (const std::overflow_error&) { overflow = true; } require(overflow && bytes(world) == before, "exhausted factory mutated state or failed to report overflow"); } struct [[= Void::Testing::name("IdentityTests")]] IdentityTests : Void::Testing::Suite { [[= Void::Testing::tag("identity")]] Test test_active_haul_survives_earlier_storage_and_node_deletion(); [[= Void::Testing::tag("identity")]] Test test_construction_stops_retain_ids_after_earlier_storage_deletion(); [[= Void::Testing::tag("identity")]] Test test_pantry_and_unstored_tending_restore_stable_ids(); [[= Void::Testing::tag("identity")]] Test test_carpenter_output_retains_its_storage_id(); [[= Void::Testing::tag("identity")]] Test test_factory_counters_stop_before_max_without_mutation(); [[= Void::Testing::tag("identity")]] Test test_command_counters_stop_before_max_without_terrain_changes(); [[= Void::Testing::tag("identity")]] Test test_invalid_legacy_positions_fail_before_candidate_publication(); }; Test IdentityTests::test_active_haul_survives_earlier_storage_and_node_deletion() { World world(42, 32, 32, 1, ExecutionMode::SerialReference); const auto unused_store = world.add_storage({1, 1}, 10, StorageKind::Pantry); const auto destination = world.add_storage({28, 4}, 30); const auto unused_node = world.add_resource_node({30, 25}, ItemType::Stone, 3); const auto source = world.add_resource_node({6, 4}, ItemType::Wood, 5); const auto resident = world.spawn_agent({4, 4}); require(world.apply_command({1, 1, CommandKind::AssignProfession, {}, static_cast(Profession::Woodcutter), {}, resident}).status == CommandStatus::Accepted); world.step(); require(world.agents().front().resource_node_id == source && world.agents().front().storage_id == destination, "fixture did not reserve the later node and store"); require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted && command(world, CommandKind::DemolishObject, {30, 25}) == CommandStatus::Accepted); require(world.find_storage(unused_store) == nullptr && world.find_resource_node(unused_node) == nullptr); require(world.agents().front().resource_node_id == source && world.agents().front().storage_id == destination, "deleting earlier records changed durable links"); require(world.find_storage(0) == nullptr && world.find_resource_node(last_counter) == nullptr); for (int tick = 0; tick < 40 && world.agents().front().state != AgentState::Hauling; ++tick) world.step(); require(world.agents().front().state == AgentState::Hauling && world.agents().front().inventory.item_count(ItemType::Wood) == 1); compare_continuation(world, 80); require(world.find_storage(destination)->item_count(ItemType::Wood) > 0, "cargo missed its stable destination"); } Test IdentityTests::test_construction_stops_retain_ids_after_earlier_storage_deletion() { World world(43, 32, 32, 1, ExecutionMode::SerialReference); static_cast(world.add_storage({1, 1}, 10, StorageKind::Pantry)); const auto planks = world.add_storage({3, 3}, 20); const auto blocks = world.add_storage({8, 3}, 20); world.stock_storage(planks, ItemType::Plank, 3); world.stock_storage(blocks, ItemType::StoneBlock, 2); static_cast(world.spawn_agent({2, 3})); world.queue_production({14, 3}, RecipeId::BuildCabin); world.step(); const auto& order = world.production_orders().front(); require(order.delivery_stops.size() == 2 && order.delivery_stops[0].storage_id == planks && order.delivery_stops[1].storage_id == blocks, "construction did not retain both actual store IDs"); require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted); require(order.materials[0].storage_id == planks && order.materials[1].storage_id == blocks); for (int tick = 0; tick < 20 && order.collected_stops == 0; ++tick) world.step(); require(order.collected_stops == 1 && !world.agents().front().inventory.empty()); compare_continuation(world, 65); require(order.state == JobState::Completed, "multi-store construction did not finish"); } Test IdentityTests::test_pantry_and_unstored_tending_restore_stable_ids() { World meal(44, 32, 32, 1, ExecutionMode::SerialReference); static_cast(meal.add_storage({1, 1}, 5)); const auto pantry = meal.add_storage({28, 4}, 50, StorageKind::Pantry); meal.stock_storage(pantry, ItemType::Berries, 40); static_cast(meal.spawn_agent({4, 4})); meal.enable_hunger(); for (int tick = 0; tick < 500 && meal.agents().front().state != AgentState::GoingToEat; ++tick) meal.step(); require(meal.agents().front().storage_id == pantry); require(command(meal, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted); compare_continuation(meal, 50); require(meal.meals_eaten() > 0); World tending(45, 32, 32, 1, ExecutionMode::SerialReference); static_cast(tending.spawn_agent({2, 3})); static_cast(tending.add_resource_node({30, 30}, ItemType::Stone, 1)); require(command(tending, CommandKind::PlaceBerryField, {9, 3}) == CommandStatus::Accepted); tending.step(); require(tending.agents().front().resource_node_id == tending.resource_nodes().back().id && tending.agents().front().storage_id == 0, "tending acquired an unrelated storage"); require(command(tending, CommandKind::DemolishObject, {30, 30}) == CommandStatus::Accepted); compare_continuation(tending, 100); require(tending.resource_nodes().front().quantity > 0); } Test IdentityTests::test_carpenter_output_retains_its_storage_id() { World world(49, 32, 32, 1, ExecutionMode::SerialReference); static_cast(world.add_storage({1, 1}, 10, StorageKind::Pantry)); const auto materials = world.add_storage({2, 3}, 10); world.stock_storage(materials, ItemType::Wood, 2); const auto carpenter = world.spawn_agent({2, 2}); world.start_scenario({8, 3}); require(world.apply_command({1, 1, CommandKind::AssignProfession, {}, static_cast(Profession::Carpenter), {}, carpenter}).status == CommandStatus::Accepted); world.queue_production({8, 3}, RecipeId::CraftWoodenDoor); world.step(); require(command(world, CommandKind::DemolishObject, {1, 1}) == CommandStatus::Accepted); for (int tick = 0; tick < 100 && world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 0; ++tick) world.step(); require(world.agents().front().inventory.item_count(ItemType::WoodenDoor) == 1 && world.agents().front().storage_id == materials && world.find_storage(materials)->reserved_slots == 1, "carpenter output lost its persistent reserved destination"); compare_continuation(world, 30); require(world.find_storage(materials)->item_count(ItemType::WoodenDoor) == 1 && world.find_storage(materials)->reserved_slots == 0, "carpenter delivered into the wrong storage"); } Test IdentityTests::test_factory_counters_stop_before_max_without_mutation() { World empty(46, 8, 8, 1, ExecutionMode::SerialReference); for (const auto offset : {next_node_offset, next_storage_offset}) { auto data = bytes(empty); put_u64(data, offset, last_counter - 1); auto world = restore(data); if (offset == next_node_offset) { require(world->add_resource_node({2, 2}, ItemType::Wood, 1) == last_counter - 1); world = restore(bytes(*world)); require_exhausted(*world, [&] { static_cast(world->add_resource_node({3, 3}, ItemType::Stone, 1)); }); } else { require(world->add_storage({2, 2}, 10) == last_counter - 1); world = restore(bytes(*world)); require_exhausted(*world, [&] { static_cast(world->add_storage({3, 3}, 10)); }); } put_u64(data, offset, last_counter); world = restore(data); if (offset == next_node_offset) { require_exhausted(*world, [&] { static_cast(world->add_resource_node({2, 2}, ItemType::Wood, 1)); }); } else { require_exhausted(*world, [&] { static_cast(world->add_storage({2, 2}, 10)); }); } } } Test IdentityTests::test_command_counters_stop_before_max_without_terrain_changes() { constexpr std::array kinds{CommandKind::PlaceBerryField, CommandKind::PlaceTreePlot, CommandKind::PlaceFlaxField, CommandKind::PlaceMine, CommandKind::PlaceStorage}; for (const auto kind : kinds) { World initial(47, 8, 8, 1, ExecutionMode::SerialReference); static_cast(initial.spawn_agent({2, 2})); const bool mine = kind == CommandKind::PlaceMine; if (mine) { initial.set_blocked({4, 4}); initial.set_blocked({5, 4}); } const auto offset = kind == CommandKind::PlaceStorage ? next_storage_offset : next_node_offset; auto data = bytes(initial); put_u64(data, offset, last_counter); auto world = restore(data); const auto before = bytes(*world); require(command(*world, kind, {4, 4}) == CommandStatus::Busy && bytes(*world) == before && world->next_command_sequence(1) == 1, "exhausted command changed world or consumed sequence"); if (mine) require(!world->is_walkable({4, 4})); put_u64(data, offset, last_counter - 1); world = restore(data); require(command(*world, kind, {4, 4}) == CommandStatus::Accepted); require(kind == CommandKind::PlaceStorage ? world->storages().back().id == last_counter - 1 : world->resource_nodes().back().id == last_counter - 1); world = restore(bytes(*world)); const auto exhausted = bytes(*world); require(command(*world, kind, {5, 4}) == CommandStatus::Busy && bytes(*world) == exhausted && world->next_command_sequence(1) == 2, "second exhausted command changed state"); if (mine) require(!world->is_walkable({5, 4})); } } Test IdentityTests::test_invalid_legacy_positions_fail_before_candidate_publication() { World world(48, 8, 8, 1, ExecutionMode::SerialReference); static_cast(world.spawn_agent({2, 2})); static_cast(world.add_resource_node({3, 3}, ItemType::Wood, 2)); static_cast(world.add_storage({4, 4}, 10)); const auto original = bytes(world); // The first resident has an empty route. Its two legacy links follow the // 101-byte prefix, cell mask, resident count and 41 bytes of resident fields. constexpr std::size_t node_link = 101 + 8 * 8 + 4 + 41; for (const auto at : {node_link, node_link + 8}) { auto invalid = original; put_u64(invalid, at, 2); // One-based position two, with a single record. bool rejected = false; try { static_cast(restore(invalid)); } catch (const std::runtime_error&) { rejected = true; } require(rejected && bytes(world) == original, "dangling legacy link escaped candidate validation"); } } } // namespace