#include "evo/ecology/materialize.hpp" #include #include #include #include #include #include #include #include #include #include namespace { using namespace evo::ecology; using namespace evo::accounting; using evo::Tick; void check(bool condition, std::source_location location = std::source_location::current()) { if (!condition) { throw std::runtime_error("materialize line " + std::to_string(location.line())); } } // Variadic so a braced initializer containing a comma stays one argument. #define CHECK(...) check(static_cast(__VA_ARGS__)) // Asserting on .error() alone is undefined when the call unexpectedly succeeded, // which would let a broken guard pass quietly. This checks the failure first. template [[nodiscard]] bool refused(const std::expected& result, MaterializeError expected) { return !result.has_value() && result.error() == expected; } Inventory held(std::uint64_t energy, std::uint64_t matter) { return {{energy}, {Femtograms{matter}, Femtograms{matter}, Femtograms{matter}, Femtograms{matter}}}; } // Reservoir 1 backs the cohort; 2 onwards are free stores for members. constexpr ReservoirId backing{1}; constexpr std::size_t reservoir_count = 12; CohortDraft draft() { CohortDraft source; source.representation_version = cohort_representation_version; source.habitat = {7}; source.genome = 3; source.owner = {11, 2}; source.last_tick = Tick{900}; source.revision = 4; source.conversion = 5; source.reservoir = backing; // Ten energy over four members divides exactly; the matter does not, so the // rounding remainder is exercised by the same fixture. source.classes = {{0, 100, 4, held(40, 10), 0}, {100, 200, 2, held(60, 600), 250'000}}; source.bound = {2, held(1, 1)}; return source; } Cohort built(const CohortDraft& source) { const auto cohort = Cohort::create(source); check(cohort.has_value()); return *cohort; } Cohort standing() { return built(draft()); } MaterializeRequest request(std::vector draws) { MaterializeRequest source; source.owner = {11, 2}; source.revision = 5; source.draws = std::move(draws); source.first_identity = 500; std::uint64_t total = 0; for (const auto& draw : source.draws) { total += draw.count; } for (std::uint64_t index = 0; index < total; ++index) { source.reservoirs.push_back({static_cast(index + 2)}); } source.bound = {2, held(1, 1)}; return source; } Ledger world(const Cohort& cohort) { std::array opening{}; opening[cohort.reservoir().value - 1] = cohort.reserve(); auto ledger = Ledger::create(opening); check(ledger.has_value()); return std::move(*ledger); } CohortRegistry registry_holding(const Cohort& cohort) { CohortRegistry registry; check(registry.install(cohort).has_value()); return registry; } Inventory sum_of(std::span members) { Inventory total{}; for (const auto& member : members) { total.energy.value += member.reserve.energy.value; for (std::size_t channel = 0; channel < total.matter.size(); ++channel) { total.matter[channel].value += member.reserve.matter[channel].value; } } return total; } void a_drawn_member_gets_the_floor_share_and_the_rest_stays() { // Two of four from a class holding forty energy and ten matter: each member // is entitled to ten and two, and the two matter the division could not split // stay with the class rather than being rounded up into existence. const auto before = standing(); const auto plan = plan_materialize(before, request({{0, 2}})); CHECK(plan.has_value()); CHECK(plan->members().size() == 2); for (const auto& member : plan->members()) { CHECK(member.reserve == held(10, 2)); CHECK(member.genome == 3); CHECK(member.habitat == HabitatId{7}); CHECK(member.state == MemberState::active); } CHECK(plan->members()[0].identity == 500); CHECK(plan->members()[1].identity == 501); CHECK(plan->withdrawn() == held(20, 4)); // The class keeps two members and what the rounding left behind. const auto after = plan->after(); CHECK(after.classes()[0].count == 2); CHECK(after.classes()[0].reserve == held(20, 6)); // Nothing was created: what left plus what stayed is what there was. Inventory recombined = after.reserve(); recombined.energy.value += plan->withdrawn().energy.value; for (std::size_t channel = 0; channel < recombined.matter.size(); ++channel) { recombined.matter[channel].value += plan->withdrawn().matter[channel].value; } CHECK(recombined == before.reserve()); // Materialization is instantaneous: the clock does not move. CHECK(after.last_tick() == before.last_tick()); CHECK(after.revision() == 5); } void a_class_drawn_empty_hands_over_everything_it_held() { // Four of four from a class holding ten matter: the two the division could // not split go one each to the first members, because a class with nobody // left may keep no reserve and leaving it would be biomass nobody owns. const auto before = standing(); const auto plan = plan_materialize(before, request({{0, 4}})); CHECK(plan.has_value()); CHECK(plan->members().size() == 4); CHECK(plan->members()[0].reserve == held(10, 3)); CHECK(plan->members()[1].reserve == held(10, 3)); CHECK(plan->members()[2].reserve == held(10, 2)); CHECK(plan->members()[3].reserve == held(10, 2)); CHECK(plan->withdrawn() == held(40, 10)); // Exactly what the class held. // The emptied class is gone, and the other one is untouched. CHECK(plan->after().classes().size() == 1); CHECK(plan->after().classes()[0].age_low == 100); CHECK(plan->after().reserve() == held(60, 600)); // A member never receives more than the class held, in any channel. CHECK(sum_of(plan->members()) == held(40, 10)); } void neither_a_residual_nor_a_missing_member_can_be_drawn() { const auto before = standing(); // The second class holds two members and a quarter of one owed. Three is // more than is there: an expected density is not an available individual. CHECK(refused(plan_materialize(before, request({{1, 3}})), MaterializeError::insufficient_members)); // Drawing both leaves the owed quarter behind, with no reserve to hold. const auto plan = plan_materialize(before, request({{1, 2}})); CHECK(plan.has_value()); CHECK(plan->after().classes().size() == 2); CHECK(plan->after().classes()[1].count == 0); CHECK(plan->after().classes()[1].residual == 250'000); CHECK(plan->after().classes()[1].reserve == Inventory{}); CHECK(plan->after().population() == 4 * residual_scale + 250'000); CHECK(!plan->after().is_vacant()); // A quarter of a member is not vacancy. } void taking_everyone_leaves_a_vacant_record_and_not_an_extinction() { auto whole = draft(); whole.classes = {{0, 100, 3, held(30, 33), 0}}; const auto before = built(whole); const auto plan = plan_materialize(before, request({{0, 3}})); CHECK(plan.has_value()); CHECK(plan->after().is_vacant()); CHECK(plan->after().population() == 0); CHECK(plan->after().reserve() == Inventory{}); // The record, its genome and its habitat all remain. CHECK(plan->after().genome() == 3); CHECK(plan->after().habitat() == HabitatId{7}); CHECK(plan->after().conversion() == 5); auto ledger = world(before); auto registry = registry_holding(before); const auto total = ledger.conserved_totals(); const auto members = commit_materialize(ledger, registry, *plan); CHECK(members.has_value()); CHECK(ledger.conserved_totals() == total); CHECK(ledger.balances()[backing.value - 1] == Inventory{}); CHECK(registry.size() == 1); // Nothing was removed for being empty. CHECK(registry.find(HabitatId{7}, 3)->is_vacant()); } void a_member_is_as_old_as_its_class_allows() { // The exact age is not recoverable, so the conservative bound is taken: a // round trip can only age someone. Any other choice lets an adversary who // picks when to convert roll back towards youth. const auto before = standing(); const auto plan = plan_materialize(before, request({{0, 1}, {1, 1}})); CHECK(plan.has_value()); CHECK(plan->members()[0].age == 99); // Top of [0, 100). CHECK(plan->members()[1].age == 199); // Top of [100, 200). // Collapsing them back puts each in the class it came from, so the choice is // stable under repetition rather than drifting upward through the classes. CollapseRequest regather; regather.conversion = 9; regather.owner = {11, 2}; regather.habitat = {7}; regather.genome = 3; regather.tick = Tick{900}; regather.revision = 1; regather.destination = {9}; regather.bounds = {{0, 100}, {100, 200}}; const auto regathered = plan_collapse(plan->members(), regather); CHECK(regathered.has_value()); CHECK(regathered->cohort().classes().size() == 2); CHECK(regathered->cohort().classes()[0].count == 1); CHECK(regathered->cohort().classes()[1].count == 1); } void a_round_trip_is_exact_when_a_class_holds_one_member() { // At full resolution nothing is averaged, so collapse and materialize return // exactly what they were given. This is the mitigation for the smoothing the // next test demonstrates, and it is the caller's choice of classes. auto fine = draft(); fine.classes = { {0, 10, 1, held(7, 70), 0}, {10, 20, 1, held(19, 3), 0}, {20, 30, 1, held(0, 0), 0}}; const auto before = built(fine); const auto plan = plan_materialize(before, request({{0, 1}, {1, 1}, {2, 1}})); CHECK(plan.has_value()); CHECK(plan->members()[0].reserve == held(7, 70)); CHECK(plan->members()[1].reserve == held(19, 3)); // Scarcity: a class holding nothing yields a member holding nothing, rather // than refusing or inventing a share. CHECK(plan->members()[2].reserve == Inventory{}); CHECK(plan->after().is_vacant()); CHECK(sum_of(plan->members()) == before.reserve()); // And regathering reproduces the classes exactly. CollapseRequest regather; regather.conversion = 9; regather.owner = {11, 2}; regather.habitat = {7}; regather.genome = 3; regather.tick = Tick{900}; regather.revision = 1; regather.destination = {9}; regather.bounds = {{0, 10}, {10, 20}, {20, 30}}; const auto regathered = plan_collapse(plan->members(), regather); CHECK(regathered.has_value()); CHECK(regathered->cohort().reserve() == before.reserve()); CHECK(regathered->cohort().classes()[0].reserve == held(7, 70)); CHECK(regathered->cohort().classes()[1].reserve == held(19, 3)); CHECK(regathered->cohort().classes()[2].reserve == Inventory{}); } void a_coarse_class_smooths_and_the_loss_is_not_hidden() { // One rich member and one destitute one in a single class. The total is // conserved and the individuals are averaged: the destitute one has been // healed at the rich one's expense. No accounting recovers what the declared // resolution discarded, and this test exists to say so rather than to pass. auto coarse = draft(); coarse.classes = {{0, 100, 2, held(100, 1'000), 0}}; const auto before = built(coarse); const auto plan = plan_materialize(before, request({{0, 2}})); CHECK(plan.has_value()); CHECK(sum_of(plan->members()) == before.reserve()); // Conserved exactly. CHECK(plan->members()[0].reserve == held(50, 500)); // And averaged. CHECK(plan->members()[1].reserve == held(50, 500)); // Neither member holds more than the pair held, which is what conservation // buys; it does not buy either of them being right. for (const auto& member : plan->members()) { CHECK(member.reserve.energy.value <= before.reserve().energy.value); } } void repeated_oscillation_never_pays() { // Collapse and materialize over and over. The conserved total must not move, // no member may ever hold more than the largest starting member held, and // nobody may get younger. Those three together are what stops a round trip // being a way to heal or to reset age. std::array opening{}; std::vector members{{1, 3, {7}, 10, {2}, held(90, 900), MemberState::active}, {2, 3, {7}, 40, {3}, held(10, 100), MemberState::active}, {3, 3, {7}, 150, {4}, held(50, 500), MemberState::active}}; for (const auto& member : members) { opening[member.reservoir.value - 1] = member.reserve; } auto ledger = Ledger::create(opening); CHECK(ledger.has_value()); const auto total = ledger->conserved_totals(); const auto ceiling = held(90, 900); std::uint64_t identity = 100; std::uint64_t revision = 1; std::vector ages{10, 40, 150}; for (std::uint64_t cycle = 0; cycle < 12; ++cycle) { CohortRegistry registry; CollapseRequest gather; gather.conversion = 5; gather.owner = {11, 2}; gather.habitat = {7}; gather.genome = 3; gather.tick = Tick{900}; gather.revision = ++revision; gather.destination = backing; gather.bounds = {{0, 100}, {100, 200}}; gather.bound = {0, {}}; const auto folded = plan_collapse(members, gather); CHECK(folded.has_value()); CHECK(commit_collapse(*ledger, registry, *folded).has_value()); CHECK(ledger->conserved_totals() == total); const auto cohort = registry.find(HabitatId{7}, 3); CHECK(cohort.has_value()); CHECK(ledger->balances()[backing.value - 1] == cohort->reserve()); std::vector draws; for (std::size_t index = 0; index < cohort->classes().size(); ++index) { draws.push_back({index, cohort->classes()[index].count}); } auto unfold = request(draws); unfold.revision = ++revision; unfold.first_identity = identity; identity += members.size(); const auto spread = plan_materialize(*cohort, unfold); CHECK(spread.has_value()); const auto drawn = commit_materialize(*ledger, registry, *spread); CHECK(drawn.has_value()); CHECK(ledger->conserved_totals() == total); CHECK(drawn->size() == members.size()); std::vector next; for (std::size_t index = 0; index < drawn->size(); ++index) { const auto& member = (*drawn)[index]; // Nobody ever ends up richer than the richest we started with. CHECK(member.reserve.energy.value <= ceiling.energy.value); CHECK(member.reserve.matter[0].value <= ceiling.matter[0].value); next.push_back(member.age); } std::ranges::sort(next); auto sorted = ages; std::ranges::sort(sorted); for (std::size_t index = 0; index < next.size(); ++index) { CHECK(next[index] >= sorted[index]); // Nobody got younger. } ages = next; // Give each member back an empty store for the next cycle. members = *drawn; std::vector drain; for (std::size_t index = 0; index < members.size(); ++index) { const ReservoirId fresh{static_cast(index + 2)}; if (members[index].reservoir != fresh && !(members[index].reserve == Inventory{})) { drain.push_back({members[index].reservoir, fresh, members[index].reserve}); } members[index].reservoir = fresh; } if (!drain.empty()) { CHECK(ledger->transfer(ledger->last_action() + 1, drain).has_value()); } CHECK(ledger->conserved_totals() == total); } // Everyone has been pushed to a class ceiling, which is the cost of the // conservative age rule and is a distortion, not a model of ageing. for (const auto age : ages) { CHECK(age == 99 || age == 199); } } void malformed_draws_and_stale_views_are_refused() { const auto before = standing(); CHECK(refused(plan_materialize(before, request({})), MaterializeError::nothing_drawn)); CHECK(refused(plan_materialize(before, request({{0, 0}})), MaterializeError::nothing_drawn)); CHECK( refused(plan_materialize(before, request({{9, 1}})), MaterializeError::unknown_age_class)); CHECK(refused(plan_materialize(before, request({{0, 1}, {0, 1}})), MaterializeError::duplicate_age_class)); auto short_list = request({{0, 2}}); short_list.reservoirs.pop_back(); CHECK(refused(plan_materialize(before, short_list), MaterializeError::reservoir_mismatch)); auto repeated = request({{0, 2}}); repeated.reservoirs[1] = repeated.reservoirs[0]; CHECK(refused(plan_materialize(before, repeated), MaterializeError::duplicate_reservoir)); auto into_the_cohort = request({{0, 1}}); into_the_cohort.reservoirs[0] = backing; CHECK(refused(plan_materialize(before, into_the_cohort), MaterializeError::invalid_request)); auto nameless = request({{0, 1}}); nameless.first_identity = 0; CHECK(refused(plan_materialize(before, nameless), MaterializeError::invalid_request)); auto intruder = request({{0, 1}}); intruder.owner = {12, 2}; CHECK(refused(plan_materialize(before, intruder), MaterializeError::wrong_owner)); auto replayed = request({{0, 1}}); replayed.revision = before.revision(); CHECK(refused(plan_materialize(before, replayed), MaterializeError::stale_revision)); const auto plan = plan_materialize(before, request({{0, 2}})); CHECK(plan.has_value()); // Nothing installed. auto bare = world(before); CohortRegistry nothing; const auto opening = std::vector{bare.balances().begin(), bare.balances().end()}; CHECK(refused(commit_materialize(bare, nothing, *plan), MaterializeError::not_installed)); CHECK(std::vector(bare.balances().begin(), bare.balances().end()) == opening); // Installed but already moved on. auto moved = world(before); auto registry = registry_holding(before); auto newer = draft(); newer.revision = 9; CHECK(registry.replace(built(newer)).has_value()); const auto action = moved.last_action(); CHECK(refused(commit_materialize(moved, registry, *plan), MaterializeError::stale_plan)); CHECK(std::vector(moved.balances().begin(), moved.balances().end()) == opening); CHECK(moved.last_action() == action); // A destination that already holds something would leave the member's reserve // understating what backs it, exactly as a collapse destination would. auto occupied = world(before); auto current = registry_holding(before); const std::array seed{Transfer{backing, {2}, held(1, 1)}}; CHECK(occupied.transfer(occupied.last_action() + 1, seed).has_value()); CHECK(refused(commit_materialize(occupied, current, *plan), MaterializeError::stale_plan)); // The cohort balance moved too. auto holding = registry_holding(before); // Something in a member's store, with the cohort's left exactly as sampled, // so this reaches the destination check rather than the staleness one. auto seeded = std::array{}; seeded[backing.value - 1] = before.reserve(); seeded[1] = held(1, 1); auto other = Ledger::create(seeded); CHECK(other.has_value()); CHECK( refused(commit_materialize(*other, holding, *plan), MaterializeError::reservoir_not_empty)); CHECK(other->balances()[backing.value - 1] == before.reserve()); CHECK(holding.find(HabitatId{7}, 3)->revision() == 4); // Committing one plan twice: the second finds a record it does not match. auto once = world(before); auto held_once = registry_holding(before); CHECK(commit_materialize(once, held_once, *plan).has_value()); const auto settled = std::vector{once.balances().begin(), once.balances().end()}; CHECK(refused(commit_materialize(once, held_once, *plan), MaterializeError::stale_plan)); CHECK(std::vector(once.balances().begin(), once.balances().end()) == settled); } void a_moved_from_plan_is_still_a_whole_plan() { static_assert(std::is_copy_constructible_v); static_assert(!std::is_nothrow_move_constructible_v); const auto before = standing(); auto source = plan_materialize(before, request({{0, 2}})); CHECK(source.has_value()); const auto original = *source; // Both diagnostics are the point of the check: clang-tidy is right that no // move happens here and wrong that it is a mistake. // NOLINTNEXTLINE(performance-move-const-arg) const auto moved = std::move(*source); // NOLINTNEXTLINE(bugprone-use-after-move): the point of the check. CHECK(*source == original); // NOLINTNEXTLINE(bugprone-use-after-move) CHECK(source->members().size() == 2); // NOLINTNEXTLINE(bugprone-use-after-move) CHECK(source->legs().size() == 2); CHECK(moved == original); auto ledger = world(before); auto registry = registry_holding(before); // NOLINTNEXTLINE(bugprone-use-after-move) const auto drawn = commit_materialize(ledger, registry, *source); CHECK(drawn.has_value()); CHECK(drawn->size() == 2); } } // namespace int main() try { a_drawn_member_gets_the_floor_share_and_the_rest_stays(); a_class_drawn_empty_hands_over_everything_it_held(); neither_a_residual_nor_a_missing_member_can_be_drawn(); taking_everyone_leaves_a_vacant_record_and_not_an_extinction(); a_member_is_as_old_as_its_class_allows(); a_round_trip_is_exact_when_a_class_holds_one_member(); a_coarse_class_smooths_and_the_loss_is_not_hidden(); repeated_oscillation_never_pays(); malformed_draws_and_stale_views_are_refused(); a_moved_from_plan_is_still_a_whole_plan(); std::cout << "PASS materialization shares, conservative ages and unprofitable round trips\n"; return 0; } catch (...) { return 1; }