#include "settlement/core/checkpoint.hpp" #include "settlement/core/simulation_runtime.hpp" #include #include #include #include #include #include #include #include #include #include namespace { using namespace settlement; using Void::Testing::Test; constexpr auto terminal = std::numeric_limits::max(); constexpr std::size_t next_production_offset = 101; constexpr Void::Uuid::Uuid world_id{{0x91, 2, 3, 4, 5, 6, 0x47, 8, 0x89, 10, 11, 12, 13, 14, 15, 16}}; void require(bool condition, const char* message = "production identity invariant failed") { if (!condition) throw std::runtime_error(message); } std::string bytes(const World& world, WorldSaveFormat format = WorldSaveFormat::Current14) { std::ostringstream stream(std::ios::binary); world.write_save(stream, format); return stream.str(); } 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); } template void put(std::string& data, std::size_t offset, T value) { Void::Binary::Writer writer(std::as_writable_bytes(std::span{data.data(), data.size()}).subspan(offset)); require(writer.writeLittle(value).has_value(), "fixture write failed"); } std::unique_ptr with_next(const World& world, ProductionId next) { auto data = bytes(world); put(data, next_production_offset, next); return restore(data); } std::unique_ptr checkpoint(const World& world, std::size_t workers = 1) { const auto rules = default_rules_manifest(); const auto catalog = builtin_rule_packages(); require(rules.has_value() && catalog.has_value()); const auto encoded = encode_checkpoint(world, world_id, 7, *rules); require(encoded.has_value()); auto decoded = decode_checkpoint(*encoded, *catalog, workers, workers == 1 ? ExecutionMode::SerialReference : ExecutionMode::Parallel); require(decoded.has_value() && decoded->world_id == world_id && bytes(*decoded->world) == bytes(world), "modern checkpoint changed stable identity or high-water state"); return std::move(decoded->world); } CommandStatus command(World& world, CommandKind kind, GridPosition cell = {}, std::uint8_t value = 0, GridPosition destination = {}) { return world.apply_command({1, world.next_command_sequence(1), kind, cell, value, destination}).status; } std::unique_ptr scenario(bool legacy_beds = false) { auto world = std::make_unique(43, 24, 24, 1, ExecutionMode::SerialReference); world->start_scenario({2, 2}); if (legacy_beds) { auto data = bytes(*world); data.back() = 0; // Historical scenario without staged beds. world = restore(data); } return world; } // Parse only field boundaries, using the public version-14 wire layout. This // avoids relying on C++ object layout when attacking references/counters. struct Locations { std::vector orders; std::vector links; }; Locations locations(const std::string& data) { Void::Binary::Reader reader(std::as_bytes(std::span{data.data(), data.size()})); const auto skip = [&](std::size_t n) { require(reader.skip(n).has_value()); }; const auto count = [&] { return reader.readLittle().value(); }; const auto route = [&] { const auto n = count(); skip(static_cast(n) * 8); }; skip(20); const auto width = count(), height = count(); skip(81 + static_cast(width) * height); Locations found; const auto agents = count(); for (std::uint32_t i = 0; i < agents; ++i) { skip(25); route(); skip(28 + item_type_count * 4); route(); found.links.push_back(reader.position()); skip(14); } const auto jobs = count(); skip(static_cast(jobs) * 25); const auto nodes = count(); skip(static_cast(nodes) * 39); const auto stores = count(); for (std::uint32_t i = 0; i < stores; ++i) { skip(25); const auto stacks = count(); skip(stacks * 9U); } const auto orders = count(); for (std::uint32_t i = 0; i < orders; ++i) { found.orders.push_back(reader.position()); skip(18); const auto materials = count(); skip(materials * 13U); const auto stops = count(); for (std::uint32_t j = 0; j < stops; ++j) { skip(8); route(); } skip(18); } return found; } void rejected(const std::string& data) { bool failed = false; try { static_cast(restore(data)); } catch (const std::runtime_error&) { failed = true; } require(failed, "corrupt stable production state was accepted"); } struct [[= Void::Testing::name("ProductionIdentityTests")]] ProductionIdentityTests : Void::Testing::Suite { [[= Void::Testing::tag("production-id")]] Test active_delivery_survives_lower_deletion_and_modern_replay(); [[= Void::Testing::tag("production-id")]] Test highest_and_all_deletions_preserve_high_water(); [[= Void::Testing::tag("production-id")]] Test last_single_id_and_complete_command_batches(); [[= Void::Testing::tag("production-id")]] Test demolition_preflights_every_product_before_losing_stock(); [[= Void::Testing::tag("production-id")]] Test demolition_counts_existing_supply_and_pending_crafts_exactly(); [[= Void::Testing::tag("production-id")]] Test legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result(); [[= Void::Testing::tag("production-id")]] Test malformed_ids_and_references_fail_before_dereference(); [[= Void::Testing::tag("production-id")]] Test legacy_projection_imports_deterministic_dense_ids(); }; Test ProductionIdentityTests::active_delivery_survives_lower_deletion_and_modern_replay() { World world(42, 32, 32, 1, ExecutionMode::SerialReference); const auto store = world.add_storage({3, 3}, 20); world.stock_storage(store, ItemType::Plank, 3); world.stock_storage(store, ItemType::StoneBlock, 2); static_cast(world.spawn_agent({2, 3})); world.queue_production({20, 20}, RecipeId::BuildMedicineCabinet); // No wood: remains available. world.queue_production({14, 3}, RecipeId::BuildCabin); const auto lower = world.production_orders().front().id; const auto active = world.production_orders().back().id; for (int tick = 0; tick < 30 && world.agents().front().inventory.empty(); ++tick) world.step(); require(world.agents().front().production_id == active && !world.agents().front().inventory.empty(), "fixture must exercise actual mid-delivery cargo"); require(command(world, CommandKind::DemolishObject, {20, 20}) == CommandStatus::Accepted); require(world.find_production(lower) == nullptr && world.find_production(0) == nullptr && world.find_production(terminal) == nullptr && world.agents().front().production_id == active); const auto legacy_bytes = bytes(world, WorldSaveFormat::Legacy13); const auto legacy = restore(legacy_bytes); require(legacy->agents().front().production_id == legacy->production_orders().front().id && bytes(*legacy, WorldSaveFormat::Legacy13) == legacy_bytes, "legacy positional projection changed a live delivery after lower deletion"); const auto held = world.capture(); const auto frozen = bytes(*held); std::vector> copies; for (auto workers : {1U, 2U, 6U, 12U}) copies.push_back(checkpoint(world, workers)); for (int tick = 0; tick < 70; ++tick) { world.step(); for (auto& copy : copies) { copy->step(); require(bytes(*copy) == bytes(world), "modern canonical tick replay diverged across worker counts"); } require(bytes(*held) == frozen, "capture did not retain production state independently"); } require(world.find_production(active)->state == JobState::Completed); require(command(world, CommandKind::DemolishObject, {14, 3}) == CommandStatus::Accepted); auto empty = checkpoint(world); empty->queue_production({15, 3}, RecipeId::BuildCabin); require(empty->production_orders().front().id > active, "deleting all orders reissued an identity"); } Test ProductionIdentityTests::highest_and_all_deletions_preserve_high_water() { auto world = scenario(); world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet); world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet); const auto highest = world->production_orders().back().id; require(command(*world, CommandKind::DemolishObject, {7, 6}) == CommandStatus::Accepted); world = checkpoint(*world); world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet); require(world->production_orders().back().id == highest + 1); require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted); require(command(*world, CommandKind::DemolishObject, {8, 6}) == CommandStatus::Accepted); world = checkpoint(*world); world->queue_production({9, 6}, RecipeId::BuildMedicineCabinet); require(world->production_orders().front().id == highest + 2); } Test ProductionIdentityTests::last_single_id_and_complete_command_batches() { World basic(42, 24, 24, 1, ExecutionMode::SerialReference); auto single = with_next(basic, terminal - 1); single->queue_production({6, 6}, RecipeId::BuildCabin); require(single->production_orders().back().id == terminal - 1); single = checkpoint(*single); const auto before = bytes(*single); bool exhausted = false; try { single->queue_production({7, 6}, RecipeId::BuildCabin); } catch (const ProductionCapacityError&) { exhausted = true; } require(exhausted && bytes(*single) == before); struct Batch { CommandKind kind; std::uint8_t value; std::size_t count; bool legacy; GridPosition last; }; const RoomPlan furnished{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Doctor}; const RoomPlan empty{{6, 6}, {9, 9}, RoomSide::South, RoomTemplate::Empty}; const std::array batches{ Batch{CommandKind::PlaceBed, 0, 1, false, {}}, Batch{CommandKind::PlaceBed, 0, 2, true, {}}, Batch{CommandKind::PlaceLoom, 0, 2, false, {}}, Batch{CommandKind::CraftDoor, 0, 1, false, {}}, Batch{CommandKind::CraftFurniture, static_cast(ItemType::MiningRack), 1, false, {}}, Batch{CommandKind::PlaceRoom, furnished.placement_value(), 20, false, furnished.last}, Batch{CommandKind::PlaceRoom, furnished.placement_value(), 21, true, furnished.last}, Batch{CommandKind::PlaceRoom, empty.placement_value(), 17, false, empty.last}}; for (const auto& batch : batches) { const auto initial = scenario(batch.legacy); auto refused = with_next(*initial, terminal - batch.count + 1); const auto original = bytes(*refused); require(command(*refused, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Busy, "insufficient complete command batch was not Busy"); require(bytes(*refused) == original && refused->next_command_sequence(1) == 1, "batch refusal changed orders, counter, stock, terrain or command sequence"); auto accepted = with_next(*initial, terminal - batch.count); require(command(*accepted, batch.kind, {6, 6}, batch.value, batch.last) == CommandStatus::Accepted); require(accepted->production_orders().size() == batch.count && accepted->production_orders().back().id == terminal - 1, "batch allocation count or last ID differs"); accepted = checkpoint(*accepted); const auto full = bytes(*accepted); require(command(*accepted, CommandKind::CraftDoor) == CommandStatus::Busy && bytes(*accepted) == full); } static_cast(basic.spawn_agent({2, 2})); auto loom = with_next(basic, terminal - 1); require(command(*loom, CommandKind::PlaceLoom, {6, 6}) == CommandStatus::Accepted && loom->production_orders().size() == 1 && loom->production_orders().front().id == terminal - 1); for (auto count : {5U, 6U}) { auto cabin = with_next(basic, terminal - count); const auto original = bytes(*cabin); bool failed = false; try { cabin->queue_cabin({10, 10}, {3, 3}, {4, 3}); } catch (const ProductionCapacityError&) { failed = true; } require(count == 5 ? failed && bytes(*cabin) == original : !failed && cabin->production_orders().size() == 6 && cabin->production_orders().back().id == terminal - 1); } } Test ProductionIdentityTests::demolition_preflights_every_product_before_losing_stock() { auto initial = scenario(); const auto store = initial->add_storage({3, 3}, 20); initial->stock_storage(store, ItemType::WoodenDoor, 1); initial->stock_storage(store, ItemType::Loom, 1); initial->stock_storage(store, ItemType::MedicineCabinet, 1); initial->queue_production({6, 6}, RecipeId::InstallDoorAlongX); initial->queue_production({7, 6}, RecipeId::InstallLoom); initial->queue_production({8, 6}, RecipeId::InstallMedicineCabinet); for (auto available : {0U, 1U, 2U}) { auto world = with_next(*initial, terminal - available); const auto before = bytes(*world); require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Busy && bytes(*world) == before, "multi-product demolition lost stock or allocated a partial replacement batch"); require(world->find_storage(store) != nullptr && world->next_command_sequence(1) == 1); } auto world = with_next(*initial, terminal - 3); require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted); require(world->find_storage(store) == nullptr && world->production_orders().size() == 6); for (auto recipe : {RecipeId::CraftWoodenDoor, RecipeId::CraftLoom, RecipeId::CraftMedicineCabinet}) { require(std::count_if(world->production_orders().begin(), world->production_orders().end(), [&](const auto& order) { return order.recipe == recipe; }) == 1); } static_cast(checkpoint(*world)); } Test ProductionIdentityTests::demolition_counts_existing_supply_and_pending_crafts_exactly() { auto world = scenario(); const auto lost = world->add_storage({3, 3}, 20); const auto retained = world->add_storage({4, 3}, 20); world->stock_storage(lost, ItemType::WoodenDoor, 1); world->stock_storage(lost, ItemType::Loom, 1); world->stock_storage(lost, ItemType::MedicineCabinet, 1); world->stock_storage(retained, ItemType::WoodenDoor, 1); world->queue_production({6, 6}, RecipeId::InstallDoorAlongX); world->queue_production({7, 6}, RecipeId::InstallLoom); world->queue_production({8, 6}, RecipeId::InstallMedicineCabinet); world->queue_production({2, 2}, RecipeId::CraftLoom); world = with_next(*world, terminal - 1); require(command(*world, CommandKind::DemolishObject, {3, 3}) == CommandStatus::Accepted, "demolition overcounted replacement orders already covered by stock or pending craft"); require(world->production_orders().size() == 5 && world->production_orders().back().recipe == RecipeId::CraftMedicineCabinet && world->production_orders().back().id == terminal - 1 && world->find_storage(retained)->item_count(ItemType::WoodenDoor) == 1); } Test ProductionIdentityTests::legacy_cabin_exhaustion_is_a_repeatable_healthy_runtime_result() { World initial(42, 24, 24, 1, ExecutionMode::SerialReference); static_cast(initial.spawn_agent({2, 2})); auto world = with_next(initial, terminal - 5); const auto before = bytes(*world); auto rules = default_rules_manifest(); require(rules.has_value()); SimulationRuntime runtime(WorldCheckpoint{std::move(world), world_id, 7, *rules}, {.ticking = false}); const auto identity = runtime.latest()->identity; const CommandEnvelope cabin{command_envelope_version, identity.world, identity.session, identity.city, 1, LegacyCabinPayload{{10, 10}, {3, 3}, {4, 3}}}; auto result = runtime.try_submit({1}, cabin); require(result.admission == RuntimeAdmission::Accepted); auto completed = result.completion.get(); require(completed.outcome == RuntimeOutcome::Completed && completed.receipt == DispatchReceipt{DispatchStatus::Completed, CommandStatus::Busy, 0, 0}); auto repeat = runtime.try_submit({1}, cabin); require(repeat.admission == RuntimeAdmission::Accepted && repeat.completion.get().receipt == completed.receipt); require(runtime.lookup({1}, cabin) == completed.receipt && runtime.latest()->next_requests[0] == 2 && runtime.view().state == RuntimeState::Running && bytes(*runtime.latest()->world) == before, "pre-mutation cabin refusal faulted the session, changed state or lost its retained receipt"); const CommandEnvelope storage{command_envelope_version, identity.world, identity.session, identity.city, 2, CommandPayload{CommandKind::PlaceStorage, {6, 6}}}; auto continued = runtime.try_submit({1}, storage); require(continued.admission == RuntimeAdmission::Accepted); const auto next = continued.completion.get(); require(next.outcome == RuntimeOutcome::Completed && next.receipt->command_status == CommandStatus::Accepted && runtime.view().state == RuntimeState::Running && runtime.latest()->world->storages().size() == 1); } Test ProductionIdentityTests::malformed_ids_and_references_fail_before_dereference() { auto world = scenario(); static_cast(world->spawn_agent({4, 4})); world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet); world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet); const auto valid = bytes(*world); const auto offsets = locations(valid); require(offsets.orders.size() == 2 && offsets.links.size() == 1); for (const auto value : {ProductionId{0}, ProductionId{2}, terminal}) { auto data = valid; put(data, offsets.orders.front(), value); rejected(data); } auto duplicate = valid; put(duplicate, offsets.orders.back(), ProductionId{1}); rejected(duplicate); auto unsorted = valid; put(unsorted, offsets.orders.front(), ProductionId{2}); put(unsorted, offsets.orders.back(), ProductionId{1}); rejected(unsorted); for (const auto value : {ProductionId{0}, ProductionId{2}}) { auto data = valid; put(data, next_production_offset, value); rejected(data); } for (const auto value : {ProductionId{1}, ProductionId{3}, terminal}) { auto data = valid; put(data, offsets.links.front(), value); rejected(data); } const auto store = world->add_storage({3, 3}, 20); world->stock_storage(store, ItemType::Wood, 4); world->step(); require(world->agents().front().production_id != 0); const auto active = bytes(*world); auto none = active; put(none, locations(active).links.front(), ProductionId{0}); rejected(none); auto wrong = active; put(wrong, locations(active).links.front(), world->production_orders().back().id); rejected(wrong); } Test ProductionIdentityTests::legacy_projection_imports_deterministic_dense_ids() { auto world = scenario(); world->queue_production({6, 6}, RecipeId::BuildMedicineCabinet); world->queue_production({7, 6}, RecipeId::BuildMedicineCabinet); require(command(*world, CommandKind::DemolishObject, {6, 6}) == CommandStatus::Accepted); world = with_next(*world, 123); world->queue_production({8, 6}, RecipeId::BuildMedicineCabinet); const auto old_bytes = bytes(*world, WorldSaveFormat::Legacy13); auto legacy = restore(old_bytes); require(legacy->production_orders()[0].id == 1 && legacy->production_orders()[1].id == 2 && bytes(*legacy, WorldSaveFormat::Legacy13) == old_bytes, "legacy positional projection or deterministic import changed"); legacy->queue_production({9, 6}, RecipeId::BuildMedicineCabinet); require(legacy->production_orders().back().id == 3); auto modern = checkpoint(*world); modern->queue_production({9, 6}, RecipeId::BuildMedicineCabinet); require(modern->production_orders().back().id == 124); } } // namespace