#include "settlement/core/world.hpp" #include #include #include #include #include #include #include namespace { using namespace settlement; using Void::Testing::Test; void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); } void ticks(World& world, int count) { for (int i = 0; i < count; ++i) { world.step(); world.validate_custody(); } } std::unique_ptr cabin(std::uint32_t stock = 3) { auto w = std::make_unique(7, 32, 32, 1, ExecutionMode::SerialReference); auto storage = w->add_storage({3, 3}, 50); w->stock_storage(storage, ItemType::Plank, stock); w->stock_storage(storage, ItemType::StoneBlock, 2); (void)w->spawn_agent({1, 3}); w->queue_production({16, 3}, RecipeId::BuildCabin); return w; } struct [[= Void::Testing::name("CustodyTests")]] CustodyTests : Void::Testing::Suite { [[= Void::Testing::tag("custody")]] Test ownership_delivery_and_consumption(); [[= Void::Testing::tag("custody")]] Test cancel_site_returns_all_types(); [[= Void::Testing::tag("custody")]] Test split_merge_and_snapshot(); [[= Void::Testing::tag("custody")]] Test exact_receipt_and_conflict(); [[= Void::Testing::tag("custody")]] Test original_colony_continuous_balance(); [[= Void::Testing::tag("custody")]] Test five_sources(); [[= Void::Testing::tag("custody")]] Test blocked_return_retains_every_item(); [[= Void::Testing::tag("custody")]] Test suspended_bed_and_loom_resume(); [[= Void::Testing::tag("custody")]] Test admission_exhaustion_and_receipt_eviction(); [[= Void::Testing::tag("custody")]] Test recipes_meals_and_harvest_balance(); [[= Void::Testing::tag("custody")]] Test rejects_missing_execution_and_claims(); [[= Void::Testing::tag("custody")]] Test persistent_counter_boundaries_and_pending_completion(); [[= Void::Testing::tag("custody")]] Test resident_and_job_id_allocation_is_checked(); [[= Void::Testing::tag("custody")]] Test modern_roundtrip_cancel_and_exact_retry(); [[= Void::Testing::tag("custody-metrics")]] Test snapshot_metrics(); }; Test CustodyTests::ownership_delivery_and_consumption() { auto w = cabin(); const auto plank = w->storages()[0].items[0].id; ticks(*w, 2); require(w->agents()[0].inventory.stack_id(ItemType::Plank) == plank, "whole pickup changed ID"); for (int i = 0; i < 20 && w->agents()[0].state != AgentState::Working; ++i) ticks(*w, 1); require(w->production_orders()[0].input.stack_id(ItemType::Plank) == plank, "site lost ID"); require(w->production_orders()[0].input.item_count(ItemType::Plank) == 3, "site lost physical count"); ticks(*w, 40); require(w->production_orders()[0].state == JobState::Completed, "construction incomplete"); require(w->item_balances()[2].installation == 3, "installation sink missing"); } Test CustodyTests::cancel_site_returns_all_types() { auto w = cabin(); ticks(*w, 16); require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); w->validate_custody(); require(w->agents()[0].state == AgentState::Returning && !w->legacy_representable(), "cancel phase lost"); ticks(*w, 40); require(w->agents()[0].inventory.empty() && w->storages()[0].item_count(ItemType::Plank) == 3 && w->storages()[0].item_count(ItemType::StoneBlock) == 2, "return lost cargo"); } Test CustodyTests::split_merge_and_snapshot() { auto w = cabin(5); const auto original = w->storages()[0].items[0].id; auto snapshot = w->capture(); ticks(*w, 2); require(w->storages()[0].items[0].id == original && w->agents()[0].inventory.stack_id(ItemType::Plank) != original, "split identity wrong"); require(snapshot->storages()[0].item_count(ItemType::Plank) == 5 && snapshot->custody_receipts().empty(), "snapshot mutated"); require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); ticks(*w, 10); require(w->storages()[0].items[0].id == original && w->storages()[0].item_count(ItemType::Plank) == 5, "merge identity wrong"); } Test CustodyTests::exact_receipt_and_conflict() { auto w = cabin(); ticks(*w, 1); auto receipt = *w->custody_receipts().front(); require(w->custody_request(receipt.request) == receipt.result, "exact retry differed"); ++receipt.request.destination; require(w->custody_request(receipt.request).status == CustodyStatus::Conflict, "changed retry accepted"); receipt.request.key.ordinal += 100; require(w->custody_request(receipt.request).status == CustodyStatus::Future, "future retry accepted"); ticks(*w, 60); } Test CustodyTests::original_colony_continuous_balance() { auto w = make_first_colony(1, BedConstructionMode::Staged, ExecutionMode::SerialReference); w->validate_custody(); ticks(*w, 1000); } Test CustodyTests::five_sources() { auto w = std::make_unique(7, 32, 32, 1, ExecutionMode::SerialReference); for (int i = 0; i < 5; ++i) { const auto store = w->add_storage({3 + i, 3}, 10); w->stock_storage(store, i < 3 ? ItemType::Plank : ItemType::StoneBlock, 1); } (void)w->spawn_agent({1, 3}); w->queue_production({16, 3}, RecipeId::BuildCabin); ticks(*w, 1); require(w->custody_receipts()[0]->request.line_count == 5, "admission omitted sources"); ticks(*w, 80); require(w->production_orders()[0].state == JobState::Completed, "five-source cabin incomplete"); } Test CustodyTests::blocked_return_retains_every_item() { auto w = cabin(); ticks(*w, 16); require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); auto& store = const_cast(w->storages()[0]); store.capacity = 1; ticks(*w, 40); require(w->agents()[0].state == AgentState::Returning && w->agents()[0].execution && w->agents()[0].execution->blocked == CustodyStatus::NoDestination, "blocked return lost execution"); require(w->agents()[0].inventory.item_count(ItemType::Plank) == 2 && w->agents()[0].inventory.item_count(ItemType::StoneBlock) == 2, "partial return lost items"); auto id = w->add_storage({4, 3}, 20); ticks(*w, 20); require(w->agents()[0].inventory.empty() && w->find_storage(id)->total_items() == 4, "unblocked return incomplete"); } Test CustodyTests::suspended_bed_and_loom_resume() { World w(9, 20, 20, 1, ExecutionMode::SerialReference); const auto store = w.add_storage({2, 2}, 30); w.stock_storage(store, ItemType::Wood, 4); w.stock_storage(store, ItemType::Cloth, 2); const auto actor = w.spawn_agent({2, 2}); (void)actor; w.start_scenario({8, 8}); require(w.apply_command({1, 1, CommandKind::PlaceBed, {4, 2}}).status == CommandStatus::Accepted, "bed placement refused"); const auto id = w.production_orders()[0].id; for (int i = 0; i < 80 && w.find_production(id)->bed_stage == BedStage::Foundation; ++i) ticks(w, 1); require(w.find_production(id)->bed_stage == BedStage::Bedding, "bed foundation absent"); require(w.cancel_production(id) == CommandStatus::Accepted && w.find_production(id)->suspended, "partial bed not suspended"); ticks(w, 20); require(!w.legacy_representable(), "suspended bed projected"); require(w.resume_production(id) == CommandStatus::Accepted, "resume refused"); ticks(w, 100); require(w.find_production(id)->state == JobState::Completed, "bed resumed wrong stage"); require(w.item_balances()[0].installation == 1 && w.item_balances()[5].installation == 2, "bed installed twice"); require(w.cancel_production(id) == CommandStatus::Busy, "completed bed canceled"); w.queue_production({6, 2}, RecipeId::WeaveCloth); const auto loom = w.production_orders().back().id; require(w.cancel_production(loom) == CommandStatus::Accepted && w.find_production(loom)->suspended, "loom not retained"); w.stock_storage(store, ItemType::Flax, 1); require(w.resume_production(loom) == CommandStatus::Accepted, "loom resume refused"); ticks(w, 60); require(w.find_storage(store)->item_count(ItemType::Cloth) == 1, "loom failed after resume"); } Test CustodyTests::admission_exhaustion_and_receipt_eviction() { auto w = cabin(); auto& actor = const_cast(w->agents()[0]); actor.next_admission = std::numeric_limits::max(); ticks(*w, 2); require(!actor.execution && w->custody_receipts().empty() && w->storages()[0].items[0].reserved == 0, "exhausted admission mutated stock"); World loom(1, 16, 16, 1, ExecutionMode::SerialReference); const auto store = loom.add_storage({2, 2}, 4000); loom.stock_storage(store, ItemType::Flax, 3000); (void)loom.spawn_agent({3, 2}); loom.queue_production({3, 2}, RecipeId::WeaveCloth); loom.step(); auto first = *loom.custody_receipts()[0]; auto snapshot = loom.capture(); for (int i = 0; i < 26000; ++i) loom.step(); loom.validate_custody(); require(loom.custody_receipts().size() == custody_receipt_limit && loom.custody_request(first.request).status == CustodyStatus::Stale, "evicted admission not stale"); require(snapshot->custody_receipts()[0]->request == first.request && snapshot->custody_receipts()[0]->result == first.result, "retained snapshot receipt mutated"); for (const auto& receipt : loom.custody_receipts()) require(loom.custody_request(receipt->request) == receipt->result, "retained replay differed"); } Test CustodyTests::recipes_meals_and_harvest_balance() { World w(1, 20, 20, 1, ExecutionMode::SerialReference); const auto store = w.add_storage({2, 2}, 100); const auto pantry = w.add_storage({2, 3}, 20, StorageKind::Pantry); w.stock_storage(store, ItemType::Wood, 10); w.stock_storage(store, ItemType::Stone, 3); w.stock_storage(pantry, ItemType::Berries, 4); (void)w.spawn_agent({2, 2}); (void)w.add_resource_node({3, 3}, ItemType::Wood, 5); w.queue_production({4, 2}, RecipeId::SawPlank); w.queue_production({5, 2}, RecipeId::CutStoneBlock); w.enable_hunger(); ticks(w, 300); require(w.meals_eaten() > 0 && w.item_balances()[0].harvest == 5 && w.item_balances()[0].recipe_input == 1 && w.item_balances()[2].recipe_output == 1 && w.item_balances()[3].recipe_output == 1, "recipe/source/sink path omitted"); } Test CustodyTests::snapshot_metrics() { for (bool full : {false, true}) { World w(1, 512, 512, 1, ExecutionMode::SerialReference); if (full) { auto store = w.add_storage({1, 1}, 4000); w.stock_storage(store, ItemType::Flax, 3000); (void)w.spawn_agent({2, 1}); w.queue_production({2, 1}, RecipeId::WeaveCloth); for (int i = 0; i < 26000; ++i) w.step(); } while (w.agents().size() < 500) (void)w.spawn_agent({1, 1}); for (int i = 0; i < 1000; ++i) { auto store = w.add_storage({i % 500, i / 500 + 5}, 1000); for (std::size_t j = 1; j <= item_type_count; ++j) if (static_cast(j) != ItemType::Berries) w.stock_storage(store, static_cast(j), 1); } while (w.production_orders().size() < 2000) { const auto i = static_cast(w.production_orders().size()); w.queue_production({i % 100 + 3, i / 100 + 10}, RecipeId::SawPlank); } w.validate_custody(); std::vector samples; for (int i = 0; i < 101; ++i) { const auto begin = std::chrono::steady_clock::now(); auto snapshot = w.capture(); samples.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); } std::sort(samples.begin(), samples.end()); std::ostringstream bytes; w.write_save(bytes); std::ostringstream modern; w.write_save(modern, WorldSaveFormat::Current15); std::cout << "custody metrics residents=500 stacks=" << (full ? 10002 : 10000) << " orders=2000 receipts=" << w.custody_receipts().size() << " capture_ms_p50=" << samples[50] << " p95=" << samples[95] << " raw13_bytes=" << bytes.str().size() << " raw15_bytes=" << modern.str().size() << " receipt_object_bytes=" << sizeof(CustodyReceipt) << '\n'; std::vector validation, serialization, advancement; for (int i = 0; i < 21; ++i) { auto begin = std::chrono::steady_clock::now(); w.validate_custody(); validation.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); begin = std::chrono::steady_clock::now(); std::ostringstream encoded; w.write_save(encoded, WorldSaveFormat::Current15); serialization.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); begin = std::chrono::steady_clock::now(); w.step(); advancement.push_back(std::chrono::duration(std::chrono::steady_clock::now() - begin).count()); } w.validate_custody(); for (auto pair : {std::pair{"validate", &validation}, std::pair{"serialize15", &serialization}, std::pair{"step", &advancement}}) { std::sort(pair.second->begin(), pair.second->end()); std::cout << "custody metrics initial_receipts=" << (full ? 4096 : 0) << ' ' << pair.first << "_ms_p50=" << (*pair.second)[10] << " p95=" << (*pair.second)[19] << '\n'; } } } Test CustodyTests::rejects_missing_execution_and_claims() { auto w = cabin(); ticks(*w, 1); const auto rejects = [&] { try { w->validate_custody(); } catch (const std::runtime_error&) { return true; } return false; }; auto& actor = const_cast(w->agents()[0]); auto execution = actor.execution; actor.execution.reset(); require(rejects(), "active actor without execution accepted"); actor.execution = execution; actor.execution->reservations[0] = {}; require(rejects(), "missing material reservation accepted"); actor.execution = execution; actor.execution->reservations[1].id = actor.execution->reservations[0].id; require(rejects(), "duplicate claim ID accepted"); actor.execution = execution; auto& order = const_cast(w->production_orders()[0]); ++order.materials[0].count; require(rejects(), "different recipe quantity accepted"); --order.materials[0].count; w->validate_custody(); } Test CustodyTests::modern_roundtrip_cancel_and_exact_retry() { auto w = cabin(); ticks(*w, 16); require(w->cancel_production(w->production_orders()[0].id) == CommandStatus::Accepted, "cancel refused"); std::ostringstream encoded; w->write_save(encoded, WorldSaveFormat::Current15); std::istringstream input(encoded.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference); for (const auto& receipt : w->custody_receipts()) require(resumed->custody_request(receipt->request) == receipt->result, "restored exact receipt differed"); std::ostringstream legacy; bool refused = false; try { w->write_save(legacy); } catch (const UnsupportedLegacyState&) { refused = true; } require(refused && legacy.str().empty(), "legacy refusal wrote bytes"); for (int i = 0; i < 40; ++i) { ticks(*w, 1); ticks(*resumed, 1); std::ostringstream a,b; w->write_save(a, WorldSaveFormat::Current15); resumed->write_save(b, WorldSaveFormat::Current15); require(a.str() == b.str(), "modern return continuation changed"); } } Test CustodyTests::persistent_counter_boundaries_and_pending_completion() { const auto restored_counter = [](const World& world, std::size_t counter, std::uint64_t value) { std::ostringstream old, modern; world.write_save(old, WorldSaveFormat::Current14); world.write_save(modern, WorldSaveFormat::Current15); auto bytes = modern.str(); const auto offset = old.str().size() + counter * 8; require(offset + 8 <= bytes.size(), "custody extension missing"); for (std::size_t i = 0; i < 8; ++i) bytes[offset + i] = static_cast((value >> (i * 8)) & 255U); std::istringstream input(bytes); return World::read_save(input, 1, ExecutionMode::SerialReference); }; auto initial = cabin(); for (std::size_t counter = 0; counter < 3; ++counter) { bool invalid = false; try { auto ignored = restored_counter(*initial, counter, 0); } catch (const std::runtime_error&) { invalid = true; } require(invalid, "zero durable highwater accepted"); if (counter == 0) continue; auto exhausted = restored_counter(*initial, counter, std::numeric_limits::max()); ticks(*exhausted, 3); require(!exhausted->agents()[0].execution && exhausted->custody_receipts().empty() && exhausted->storages()[0].items[0].reserved == 0, "exhausted admission acquired claims"); } World saw(1, 10, 10, 1, ExecutionMode::SerialReference); const auto store = saw.add_storage({2, 2}, 10); saw.stock_storage(store, ItemType::Wood, 1); (void)saw.spawn_agent({3, 2}); saw.queue_production({3, 2}, RecipeId::SawPlank); auto exhausted = restored_counter(saw, 0, std::numeric_limits::max()); ticks(*exhausted, 12); const auto& actor = exhausted->agents()[0]; require(actor.state == AgentState::Working && actor.work_remaining == 0 && actor.execution->blocked == CustodyStatus::Exhausted, "completion did not preserve pending zero timer"); require(exhausted->storages()[0].item_count(ItemType::Wood) == 1 && exhausted->storages()[0].item_count(ItemType::Plank) == 0, "refused completion partially consumed input"); const auto ordinal = actor.execution->next_operation; ticks(*exhausted, 3); require(actor.work_remaining == 0 && actor.execution->next_operation == ordinal + 3 && !exhausted->legacy_representable(), "pending retry underflowed timer or reused ordinal"); std::ostringstream saved; exhausted->write_save(saved, WorldSaveFormat::Current15); std::istringstream input(saved.str()); auto resumed = World::read_save(input, 1, ExecutionMode::SerialReference); ticks(*resumed, 1); require(resumed->agents()[0].work_remaining == 0, "restored pending completion decremented zero"); } Test CustodyTests::resident_and_job_id_allocation_is_checked() { const auto bytes = [](const World& world) { std::ostringstream stream; world.write_save(stream, WorldSaveFormat::Current15); return stream.str(); }; for (std::size_t kind = 0; kind < 2; ++kind) { World empty(1, 10, 10, 1, ExecutionMode::SerialReference); auto encoded = bytes(empty); // Signature/version/seed/dimensions, five u64 counters, hunger flag. const std::size_t offset = 28 + 5 * 8 + 1 + kind * 8; for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = static_cast(255); std::istringstream input(encoded); auto restored = World::read_save(input, 1, ExecutionMode::SerialReference); const auto before = bytes(*restored); bool exhausted = false; try { if (kind == 0) (void)restored->spawn_agent({1,1}); else (void)restored->add_job({1,1}, 1); } catch (const std::overflow_error&) { exhausted = true; } require(exhausted && bytes(*restored) == before, "exhausted resident/job allocation changed state"); for (std::size_t i = 0; i < 8; ++i) encoded[offset + i] = 0; bool rejected = false; try { std::istringstream zero(encoded); auto ignored = World::read_save(zero,1,ExecutionMode::SerialReference); } catch (const std::runtime_error&) { rejected = true; } require(rejected, "zero resident/job counter accepted"); const auto valid_before = bytes(empty); try { if (kind == 0) (void)empty.spawn_agent({-1,-1}); else (void)empty.add_job({1,1}, 0); } catch (const std::invalid_argument&) {} require(bytes(empty) == valid_before, "invalid insertion consumed ID"); } World idle(1, 10, 10, 1, ExecutionMode::SerialReference); (void)idle.spawn_agent({1,1}); const_cast(idle.agents()[0]).work_remaining = 1; bool rejected = false; try { idle.validate_custody(); } catch (const std::runtime_error&) { rejected = true; } require(rejected, "idle timer escaped phase validation"); } }