#include "settlement/core/inventory_transaction.hpp" #include "settlement/core/simulation_runtime.hpp" #include #include #include #include #include #include #include namespace { using namespace settlement; using Void::Testing::Test; constexpr auto maximum = std::numeric_limits::max(); void require(bool condition, const char* message = "quantity transfer invariant failed") { if (!condition) throw std::runtime_error(message); } Storage source() { return {7, {3, 3}, 20, 0, {{ItemType::Wood, 4, 3}, {ItemType::Stone, 3, 2}}}; } void same_inventory(const Inventory& actual, const Inventory& expected) { for (std::size_t i = 1; i <= item_type_count; ++i) { require(actual.item_count(static_cast(i)) == expected.item_count(static_cast(i)), "failed pickup changed destination"); } } void same_storage(const Storage& actual, const Storage& expected) { require(actual.id == expected.id && actual.position == expected.position && actual.capacity == expected.capacity && actual.reserved_slots == expected.reserved_slots && actual.kind == expected.kind && actual.items.size() == expected.items.size(), "failed pickup changed storage metadata"); for (std::size_t i = 0; i < actual.items.size(); ++i) { require(actual.items[i].type == expected.items[i].type && actual.items[i].count == expected.items[i].count && actual.items[i].reserved == expected.items[i].reserved, "failed pickup changed source quantities/order"); } } void rejected(Storage& storage, Inventory& inventory, std::span materials, QuantityTransferError error, bool slot = false) { const auto before = storage; const auto cargo = inventory; const auto result = withdraw_reserved_materials(storage, inventory, materials, slot); require(!result && result.error() == error, "pickup accepted bad input or returned the wrong diagnostic"); same_storage(storage, before); same_inventory(inventory, cargo); } std::string bytes(const World& world) { std::ostringstream stream(std::ios::binary); world.write_save(stream, WorldSaveFormat::Current14); return stream.str(); } void same_pickup_actor(const Agent& actual, const Agent& expected) { same_inventory(actual.inventory, expected.inventory); require(actual.position == expected.position && actual.route == expected.route && actual.route_cursor == expected.route_cursor && actual.haul_route == expected.haul_route && actual.state == expected.state && actual.storage_id == expected.storage_id && actual.production_id == expected.production_id && actual.work_remaining == expected.work_remaining, "rejected pickup changed actor/route state"); } std::unique_ptr cabin() { auto world = std::make_unique(43, 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({1, 3})); world->queue_production({14, 3}, RecipeId::BuildCabin); world->step(); require(world->agents().front().state == AgentState::FetchingMaterials, "fixture already picked up materials"); return world; } // Test-only corruption uses public read views of a nonconst fixture. Production // code cannot create these malformed sources through the checked save loader. void at_pickup(World& world) { auto& agent = const_cast(world.agents().front()); agent.position = world.storages().front().position; agent.route.clear(); agent.route_cursor = 0; } struct [[= Void::Testing::name("QuantityTransactionTests")]] QuantityTransactionTests : Void::Testing::Suite { [[= Void::Testing::tag("quantity-transfer")]] Test late_failure_is_atomic(); [[= Void::Testing::tag("quantity-transfer")]] Test nonadjacent_duplicates_and_foreign_stops(); [[= Void::Testing::tag("quantity-transfer")]] Test invalid_selection_and_item_bounds(); [[= Void::Testing::tag("quantity-transfer")]] Test source_invariants_and_underflow(); [[= Void::Testing::tag("quantity-transfer")]] Test cumulative_and_destination_boundaries(); [[= Void::Testing::tag("quantity-transfer")]] Test stable_multiple_erasure_and_output_capacity(); [[= Void::Testing::tag("quantity-transfer")]] Test invalid_capacity_and_slot_overflow_are_atomic(); [[= Void::Testing::tag("quantity-transfer")]] Test real_construction_rejection_keeps_stop_actor_and_routes(); [[= Void::Testing::tag("quantity-transfer")]] Test real_split_lines_and_invalid_storage_selection(); [[= Void::Testing::tag("quantity-transfer")]] Test real_carpentry_invalid_capacity_keeps_pickup_untouched(); [[= Void::Testing::tag("quantity-transfer")]] Test real_meal_pickup_and_overflow_rejection(); [[= Void::Testing::tag("quantity-transfer")]] Test real_multistop_carpentry_reserves_first_ingredient_store(); [[= Void::Testing::tag("quantity-transfer")]] Test direct_crafting_stays_in_storage(); [[= Void::Testing::tag("quantity-transfer")]] Test owner_fault_preserves_last_healthy_publication(); }; Test QuantityTransactionTests::late_failure_is_atomic() { auto storage = source(); Inventory inventory; inventory.add(ItemType::Wood, 9); const std::array materials{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 3}}; rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock); inventory.add(ItemType::Stone, maximum); auto valid = materials; valid[1].count = 1; rejected(storage, inventory, valid, QuantityTransferError::Overflow, true); } Test QuantityTransactionTests::nonadjacent_duplicates_and_foreign_stops() { auto storage = source(); Inventory inventory; const std::array materials{MaterialReservation{7, ItemType::Wood, 1}, MaterialReservation{9, ItemType::Wood, 5}, MaterialReservation{7, ItemType::Stone, 2}, MaterialReservation{7, ItemType::Wood, 2}}; require(withdraw_reserved_materials(storage, inventory, materials).has_value()); require(inventory.item_count(ItemType::Wood) == 3 && inventory.item_count(ItemType::Stone) == 2); require(storage.items[0].count == 1 && storage.items[0].reserved == 0 && storage.items[1].count == 1 && storage.items[1].reserved == 0); auto insufficient = source(); const std::array duplicates{MaterialReservation{7, ItemType::Wood, 2}, MaterialReservation{7, ItemType::Stone, 1}, MaterialReservation{7, ItemType::Wood, 2}}; rejected(insufficient, inventory, duplicates, QuantityTransferError::InsufficientStock); } Test QuantityTransactionTests::invalid_selection_and_item_bounds() { auto storage = source(); Inventory inventory; const std::array valid{MaterialReservation{7, ItemType::Wood, 1}}; rejected(storage, inventory, {}, QuantityTransferError::MissingSelection); const std::array foreign{MaterialReservation{8, ItemType::Wood, 1}}; rejected(storage, inventory, foreign, QuantityTransferError::MissingSelection); const std::array zero_id{MaterialReservation{0, ItemType::Wood, 1}}; rejected(storage, inventory, zero_id, QuantityTransferError::MissingSelection); for (const auto type : {ItemType::None, static_cast(item_type_count + 1), static_cast(255)}) { const std::array bad{MaterialReservation{7, type, 1}}; rejected(storage, inventory, bad, QuantityTransferError::InvalidMaterial); } const std::array zero{MaterialReservation{7, ItemType::Wood, 0}}; rejected(storage, inventory, zero, QuantityTransferError::InvalidMaterial); storage.id = 0; rejected(storage, inventory, zero_id, QuantityTransferError::InvalidStorage); storage = source(); storage.kind = static_cast(255); rejected(storage, inventory, valid, QuantityTransferError::InvalidStorage); } Test QuantityTransactionTests::source_invariants_and_underflow() { Inventory inventory; const std::array materials{MaterialReservation{7, ItemType::Wood, 1}}; const std::array missing{MaterialReservation{7, ItemType::Plank, 1}}; auto storage = source(); rejected(storage, inventory, missing, QuantityTransferError::InsufficientStock); for (int fault = 0; fault < 8; ++fault) { storage = source(); switch (fault) { case 0: storage.items[0].reserved = 5; break; case 1: storage.items[0].count = 0; break; case 2: storage.items[0].type = ItemType::None; break; case 3: storage.items[0].type = static_cast(item_type_count + 1); break; case 4: storage.items[1].type = ItemType::Wood; break; case 5: std::swap(storage.items[0], storage.items[1]); break; case 6: storage.kind = StorageKind::Pantry; break; case 7: storage.items[1].reserved = 4; break; } rejected(storage, inventory, materials, QuantityTransferError::InvalidStock); } storage = source(); storage.items[0].reserved = 0; rejected(storage, inventory, materials, QuantityTransferError::InsufficientStock); storage.items[0].reserved = storage.items[0].count = 1; const std::array too_many{MaterialReservation{7, ItemType::Wood, 2}}; rejected(storage, inventory, too_many, QuantityTransferError::InsufficientStock); } Test QuantityTransactionTests::cumulative_and_destination_boundaries() { Storage storage{7, {}, maximum, 0, {{ItemType::Wood, maximum, maximum}}}; Inventory inventory; const std::array overflow{MaterialReservation{7, ItemType::Wood, maximum}, MaterialReservation{8, ItemType::Stone, 1}, MaterialReservation{7, ItemType::Wood, 1}}; rejected(storage, inventory, overflow, QuantityTransferError::Overflow); const std::array exact{MaterialReservation{7, ItemType::Wood, maximum - 1}, MaterialReservation{7, ItemType::Wood, 1}}; require(withdraw_reserved_materials(storage, inventory, exact).has_value()); require(storage.items.empty() && inventory.item_count(ItemType::Wood) == maximum); storage = source(); const std::array one{MaterialReservation{7, ItemType::Wood, 1}}; rejected(storage, inventory, one, QuantityTransferError::Overflow); Inventory boundary; boundary.add(ItemType::Wood, maximum - 1); require(withdraw_reserved_materials(storage, boundary, one).has_value()); require(boundary.item_count(ItemType::Wood) == maximum); } Test QuantityTransactionTests::stable_multiple_erasure_and_output_capacity() { Storage storage{7, {}, 10, 0, {{ItemType::Wood, 2, 2}, {ItemType::Stone, 3, 1}, {ItemType::Plank, 1, 1}, {ItemType::StoneBlock, 4, 0}}}; Inventory inventory; const std::array materials{MaterialReservation{7, ItemType::Plank, 1}, MaterialReservation{7, ItemType::Wood, 2}}; require(withdraw_reserved_materials(storage, inventory, materials, true).has_value()); require(storage.reserved_slots == 1 && storage.items.size() == 2 && storage.items[0].type == ItemType::Stone && storage.items[0].count == 3 && storage.items[0].reserved == 1 && storage.items[1].type == ItemType::StoneBlock && storage.items[1].count == 4 && storage.items[1].reserved == 0); Storage full{7, {}, 1, 0, {{ItemType::Wood, 1, 1}}}; const std::array one{MaterialReservation{7, ItemType::Wood, 1}}; require(withdraw_reserved_materials(full, inventory, one, true).has_value()); require(full.items.empty() && full.reserved_slots == 1 && full.total_items() + full.reserved_slots == full.capacity); } Test QuantityTransactionTests::invalid_capacity_and_slot_overflow_are_atomic() { Inventory inventory; const std::array materials{MaterialReservation{7, ItemType::Wood, 1}}; for (int fault = 0; fault < 4; ++fault) { auto storage = source(); switch (fault) { case 0: storage.capacity = 0; break; case 1: storage.capacity = 6; break; case 2: storage.reserved_slots = maximum; break; case 3: storage.capacity = 7; storage.reserved_slots = 1; break; } rejected(storage, inventory, materials, QuantityTransferError::Capacity, true); } } Test QuantityTransactionTests::real_construction_rejection_keeps_stop_actor_and_routes() { auto world = cabin(); at_pickup(*world); auto& storage = const_cast(world->storages().front()); storage.items.back().reserved = 1; // The first item is valid; the second fails. const auto before = storage; const auto actor = world->agents().front(); const auto order = world->production_orders().front(); bool failed = false; try { world->step(); } catch (const std::logic_error&) { failed = true; } require(failed); same_storage(storage, before); same_pickup_actor(world->agents().front(), actor); const auto& after = world->production_orders().front(); require(after.collected_stops == order.collected_stops && after.delivery_stops.size() == order.delivery_stops.size()); require(after.delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next); } Test QuantityTransactionTests::real_split_lines_and_invalid_storage_selection() { auto world = cabin(); at_pickup(*world); auto& order = const_cast(world->production_orders().front()); const auto id = world->storages().front().id; order.materials = {{id, ItemType::Plank, 1}, {id, ItemType::StoneBlock, 2}, {id, ItemType::Plank, 2}}; for (const auto invalid : {StorageId{0}, StorageId{123}, id}) { order.delivery_stops.front().storage_id = invalid; if (invalid == id) { // A real storage, but no selected reservation. for (auto& material : order.materials) material.storage_id = 123; } const auto before = world->storages().front(); const auto actor = world->agents().front(); const auto route = order.delivery_stops.front().route_to_next; bool failed = false; try { world->step(); } catch (const std::logic_error&) { failed = true; } require(failed && order.collected_stops == 0 && order.delivery_stops.front().route_to_next == route); same_pickup_actor(world->agents().front(), actor); same_storage(world->storages().front(), before); } for (auto& material : order.materials) material.storage_id = id; world->step(); require(order.collected_stops == 1 && world->storages().front().items.empty()); require(world->agents().front().inventory.item_count(ItemType::Plank) == 3 && world->agents().front().inventory.item_count(ItemType::StoneBlock) == 2); for (int i = 0; i < 80 && order.state != JobState::Completed; ++i) world->step(); require(order.state == JobState::Completed && world->agents().front().inventory.empty()); } Test QuantityTransactionTests::real_carpentry_invalid_capacity_keeps_pickup_untouched() { World world(49, 32, 32, 1, ExecutionMode::SerialReference); const auto store = world.add_storage({3, 3}, 1); world.stock_storage(store, ItemType::Wood, 1); const auto carpenter = world.spawn_agent({1, 3}); 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::CraftMedicineCabinet); world.step(); require(world.agents().front().state == AgentState::FetchingMaterials); at_pickup(world); auto& storage = const_cast(world.storages().front()); storage.reserved_slots = 1; // Already over capacity before this pickup. const auto before = storage; const auto actor = world.agents().front(); const auto order = world.production_orders().front(); bool failed = false; try { world.step(); } catch (const std::logic_error&) { failed = true; } require(failed && world.production_orders().front().collected_stops == 0); same_storage(storage, before); same_pickup_actor(world.agents().front(), actor); require(world.production_orders().front().delivery_stops.front().route_to_next == order.delivery_stops.front().route_to_next); } Test QuantityTransactionTests::real_meal_pickup_and_overflow_rejection() { World world(44, 32, 32, 1, ExecutionMode::SerialReference); const auto pantry = world.add_storage({28, 4}, 50, StorageKind::Pantry); world.stock_storage(pantry, ItemType::Berries, 40); static_cast(world.spawn_agent({4, 4})); world.enable_hunger(); for (int i = 0; i < 500 && world.agents().front().state != AgentState::GoingToEat; ++i) world.step(); require(world.agents().front().state == AgentState::GoingToEat); auto& actor = const_cast(world.agents().front()); at_pickup(world); actor.inventory.add(ItemType::Berries, maximum); const auto agent_before = actor; const auto storage_before = world.storages().front(); bool failed = false; try { world.step(); } catch (const std::logic_error&) { failed = true; } require(failed); same_pickup_actor(actor, agent_before); same_storage(world.storages().front(), storage_before); actor.inventory.remove(ItemType::Berries, maximum); world.step(); require(actor.state == AgentState::Eating && actor.inventory.item_count(ItemType::Berries) == 1 && actor.storage_id == 0); require(world.storages().front().item_count(ItemType::Berries) == 39); for (int i = 0; i < 5; ++i) world.step(); require(world.meals_eaten() == 1 && actor.inventory.empty() && actor.hunger == 0); } Test QuantityTransactionTests::real_multistop_carpentry_reserves_first_ingredient_store() { World world(49, 32, 32, 1, ExecutionMode::SerialReference); const auto stone = world.add_storage({3, 3}, 1); const auto wood = world.add_storage({6, 3}, 1); world.stock_storage(stone, ItemType::Stone, 1); world.stock_storage(wood, ItemType::Wood, 1); const auto carpenter = world.spawn_agent({2, 3}); 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::CraftMiningRack); world.step(); const auto& order = world.production_orders().front(); require(order.materials.front().storage_id == wood && order.delivery_stops.front().storage_id == stone); for (int i = 0; i < 20 && order.collected_stops == 0; ++i) world.step(); require(order.collected_stops == 1 && world.find_storage(stone)->reserved_slots == 0 && world.find_storage(wood)->reserved_slots == 0); for (int i = 0; i < 20 && order.collected_stops == 1; ++i) world.step(); require(order.collected_stops == 2 && world.find_storage(wood)->items.empty() && world.find_storage(wood)->reserved_slots == 1); for (int i = 0; i < 80 && world.find_storage(wood)->item_count(ItemType::MiningRack) == 0; ++i) world.step(); require(world.find_storage(wood)->item_count(ItemType::MiningRack) == 1 && world.find_storage(wood)->reserved_slots == 0 && world.find_storage(stone)->items.empty()); } Test QuantityTransactionTests::direct_crafting_stays_in_storage() { World world(51, 24, 24, 1, ExecutionMode::SerialReference); const auto store = world.add_storage({3, 3}, 2); world.stock_storage(store, ItemType::Wood, 1); world.stock_storage(store, ItemType::Stone, 1); static_cast(world.spawn_agent({2, 3})); world.queue_production({5, 3}, RecipeId::SawPlank); world.queue_production({7, 3}, RecipeId::CutStoneBlock); for (int i = 0; i < 80; ++i) { world.step(); require(world.agents().front().inventory.empty(), "direct recipe created physical carrier cargo"); } const auto* storage = world.find_storage(store); require(storage->item_count(ItemType::Wood) == 0 && storage->item_count(ItemType::Stone) == 0 && storage->item_count(ItemType::Plank) == 1 && storage->item_count(ItemType::StoneBlock) == 1 && storage->reserved_slots == 0); } Test QuantityTransactionTests::owner_fault_preserves_last_healthy_publication() { using namespace std::chrono_literals; auto world = cabin(); at_pickup(*world); auto* fixture = world.get(); auto clock = std::make_shared(); RuntimeOptions options{.clock = clock}; options.observer = [fixture](RuntimePhase phase) { if (phase == RuntimePhase::BeforeTick) { const_cast(fixture->storages().front()).items.back().reserved = 1; } }; auto rules = default_rules_manifest(); require(rules.has_value()); Void::Uuid::Uuid id; id.bytes.back() = 71; SimulationRuntime runtime({std::move(world), id, 1, std::move(*rules)}, std::move(options)); const auto previous = runtime.latest(); const auto healthy = bytes(*previous->world); require(clock->advance(50ms).has_value()); RuntimeSubmission fence; const auto limit = std::chrono::steady_clock::now() + 5s; do { fence = runtime.synchronize(); if (fence.admission != RuntimeAdmission::Busy) break; require(std::chrono::steady_clock::now() < limit, "runtime fence admission timed out"); std::this_thread::yield(); } while (true); require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(5s) == std::future_status::ready); require(fence.completion.get().outcome == RuntimeOutcome::Faulted && runtime.view().state == RuntimeState::Faulted && runtime.view().failure && !runtime.snapshot_for_save()); require(runtime.latest() == previous && bytes(*runtime.latest()->world) == healthy, "owner published the rejected pickup candidate"); } } // namespace