#include "evo/core/random.hpp" #include "evo/ecology/population.hpp" #include #include #include #include #include #include #include #include #include #include namespace { using namespace evo::ecology; using namespace evo::accounting; using evo::Random; using evo::Tick; void check(bool condition, std::source_location location = std::source_location::current()) { if (!condition) { throw std::runtime_error("population 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, PopulationError 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}}}; } // 1 backs the cohort, 2 detritus, 3 predators, 4 escrow elsewhere, 5 unrelated. constexpr ReservoirId backing{1}; constexpr ReservoirId detritus{2}; constexpr ReservoirId predators{3}; constexpr ReservoirId elsewhere{4}; constexpr std::size_t reservoir_count = 5; 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; source.classes = {{0, 100, 40, held(400, 4'000), 0}, {100, 200, 20, held(600, 6'000), 0}}; source.bound = {2, held(1, 1)}; return source; } Cohort standing() { const auto cohort = Cohort::create(draft()); check(cohort.has_value()); return *cohort; } Cohort built(const CohortDraft& source) { const auto cohort = Cohort::create(source); check(cohort.has_value()); return *cohort; } AdvanceRequest request() { AdvanceRequest source; source.to = Tick{1'000}; source.owner = {11, 2}; source.revision = 5; source.after = draft().classes; source.detritus = detritus; source.predators = predators; source.elsewhere = elsewhere; source.bound = {2, held(1, 1)}; return source; } Ledger world() { std::array opening{}; opening[0] = standing().reserve(); opening[4] = held(7, 7); // Unrelated, to prove nothing else moves. 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; } void an_interval_that_changes_nothing_still_advances_the_clock() { const auto before = standing(); CHECK(before.population() == 60 * residual_scale); const auto plan = plan_advance(before, request()); CHECK(plan.has_value()); CHECK(plan->span() == 100); CHECK(plan->after().last_tick() == Tick{1'000}); CHECK(plan->after().revision() == 5); CHECK(plan->after().population() == before.population()); CHECK(plan->after().reserve() == before.reserve()); CHECK(plan->after().reservoir() == before.reservoir()); CHECK(plan->legs().empty()); // Nothing moved, so nothing is transferred. auto ledger = world(); auto registry = registry_holding(before); const auto action = ledger.last_action(); const auto installed = commit_advance(ledger, registry, *plan); CHECK(installed.has_value()); CHECK(ledger.last_action() == action); // No empty transaction was submitted. CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'000}); } void a_birth_redistributes_and_never_creates_biomass() { // There is no term by which a birth could bring biomass in, so newborns are // funded from what the cohort already holds. The reserve is unchanged and the // declared structure says where inside the cohort it now sits. auto grown = request(); grown.flux.births = 5 * residual_scale; grown.after = {{0, 100, 45, held(400, 4'000), 0}, {100, 200, 20, held(600, 6'000), 0}}; const auto before = standing(); const auto plan = plan_advance(before, grown); CHECK(plan.has_value()); CHECK(plan->after().population() == before.population() + 5 * residual_scale); CHECK(plan->after().reserve() == before.reserve()); // Nothing was created. CHECK(plan->legs().empty()); auto ledger = world(); auto registry = registry_holding(before); const auto total = ledger.conserved_totals(); CHECK(commit_advance(ledger, registry, *plan).has_value()); CHECK(ledger.conserved_totals() == total); CHECK(ledger.balances()[0] == before.reserve()); } void death_predation_and_migration_move_biomass_once() { auto mixed = request(); mixed.flux.deaths = 4 * residual_scale; mixed.flux.predation = 3 * residual_scale; mixed.flux.emigration = 2 * residual_scale; mixed.flux.immigration = 1 * residual_scale; mixed.flux.to_detritus = held(40, 400); mixed.flux.to_predators = held(30, 300); mixed.flux.to_elsewhere = held(20, 200); mixed.flux.from_elsewhere = held(10, 100); // 60 - 4 - 3 - 2 + 1 = 52 members; 1000 - 40 - 30 - 20 + 10 = 920 energy. mixed.after = {{0, 100, 32, held(320, 3'200), 0}, {100, 200, 20, held(600, 6'000), 0}}; const auto before = standing(); const auto plan = plan_advance(before, mixed); CHECK(plan.has_value()); CHECK(plan->after().population() == 52 * residual_scale); CHECK(plan->after().reserve() == held(920, 9'200)); CHECK(plan->legs().size() == 4); auto registry = registry_holding(before); // The escrow has to be able to fund the immigrants it sends, and the arrival // is the first leg, so it must already hold that much before anything moves. auto seeded = std::array{}; seeded[backing.value - 1] = before.reserve(); seeded[elsewhere.value - 1] = held(10, 100); auto created = Ledger::create(seeded); CHECK(created.has_value()); auto ledger = std::move(*created); const auto total = ledger.conserved_totals(); const auto committed = commit_advance(ledger, registry, *plan); CHECK(committed.has_value()); // Conservation is the ledger's property; nothing was created or destroyed. CHECK(ledger.conserved_totals() == total); CHECK(ledger.balances()[backing.value - 1] == held(920, 9'200)); CHECK(ledger.balances()[backing.value - 1] == committed->reserve()); CHECK(ledger.balances()[detritus.value - 1] == held(40, 400)); CHECK(ledger.balances()[predators.value - 1] == held(30, 300)); // The escrow sent ten energy and a hundred matter, then received twenty and // two hundred, so from exactly what it needed to send it stands at ten and a // hundred more. Arrivals are the first leg, which is what makes an interval // affordable as a whole applicable leg by leg. CHECK(ledger.balances()[elsewhere.value - 1] == held(20, 200)); } void a_proposal_that_would_go_below_zero_is_refused_not_clamped() { const auto before = standing(); // More deaths than there are members. A clamp here would hide an interval // the model could not integrate and would invent an extinction. auto overkill = request(); overkill.flux.deaths = 61 * residual_scale; overkill.after.clear(); CHECK(refused(plan_advance(before, overkill), PopulationError::negative_population)); // By a single millionth of a member, which is the boundary that matters. auto barely = request(); barely.flux.deaths = before.population() + 1; barely.after.clear(); CHECK(refused(plan_advance(before, barely), PopulationError::negative_population)); // Exactly all of them is representable, and is vacancy rather than refusal. auto exact = request(); exact.flux.deaths = before.population(); exact.flux.to_detritus = before.reserve(); exact.after.clear(); const auto emptied = plan_advance(before, exact); CHECK(emptied.has_value()); CHECK(emptied->after().is_vacant()); CHECK(emptied->after().population() == 0); CHECK(emptied->after().reserve() == Inventory{}); // Biomass is bounded per channel, so any one channel may be the one refused. for (std::size_t channel = 0; channel < 4; ++channel) { auto greedy = request(); greedy.flux.to_detritus = before.reserve(); greedy.flux.to_detritus.matter[channel].value += 1; greedy.flux.deaths = before.population(); greedy.after.clear(); CHECK(refused(plan_advance(before, greedy), PopulationError::negative_biomass)); } auto too_much_energy = request(); too_much_energy.flux.to_detritus = before.reserve(); too_much_energy.flux.to_detritus.energy.value += 1; too_much_energy.flux.deaths = before.population(); too_much_energy.after.clear(); CHECK(refused(plan_advance(before, too_much_energy), PopulationError::negative_biomass)); } void a_population_below_one_member_is_still_a_population() { // Rounding a density to zero cannot declare an extinction, so a fraction of // a member is a number the record carries rather than a decision it makes. const auto before = standing(); auto dwindling = request(); dwindling.flux.deaths = before.population() - 250'000; // All of the biomass leaves with them. A class that is only a fraction of a // member may hold no reserve, because ADR-0036 gives reserve to members and a // fraction is not one yet; that tension is real and is recorded, not hidden. dwindling.flux.to_detritus = before.reserve(); dwindling.after = {{0, 100, 0, Inventory{}, 250'000}}; const auto plan = plan_advance(before, dwindling); CHECK(plan.has_value()); CHECK(plan->after().count() == 0); CHECK(plan->after().residual() == 250'000); CHECK(plan->after().population() == 250'000); CHECK(!plan->after().is_vacant()); // A quarter of a member is not vacancy. auto ledger = world(); auto registry = registry_holding(before); CHECK(commit_advance(ledger, registry, *plan).has_value()); // The record is still installed: nothing was removed for being small. const auto found = registry.find(HabitatId{7}, 3); CHECK(found.has_value()); CHECK(found->population() == 250'000); CHECK(registry.size() == 1); } void a_vacant_cohort_is_not_an_extinction() { auto empty_draft = draft(); empty_draft.classes.clear(); const auto vacated = Cohort::vacant(empty_draft); CHECK(vacated.has_value()); CHECK(vacated->is_vacant()); CHECK(vacated->population() == 0); CHECK(vacated->reserve() == Inventory{}); // It is still a whole record: genome, habitat, owner and provenance remain. CHECK(vacated->genome() == 3); CHECK(vacated->habitat() == HabitatId{7}); CHECK(vacated->conversion() == 5); CHECK(vacated->reservoir() == backing); // And it stays in the registry rather than being removed for being empty. auto registry = registry_holding(*vacated); CHECK(registry.size() == 1); CHECK(registry.find(HabitatId{7}, 3)->is_vacant()); // Vacancy is deliberate: `create` still refuses a draft that merely has no // classes, and `vacant` refuses one that has some. CHECK(!Cohort::create(empty_draft).has_value()); CHECK(!Cohort::vacant(draft()).has_value()); // A vacant record holding inventory would be biomass owned by nobody. const auto before = standing(); auto unfunded = request(); unfunded.flux.deaths = before.population(); unfunded.after.clear(); CHECK(refused(plan_advance(before, unfunded), PopulationError::biomass_mismatch)); } void the_declared_result_must_be_what_the_fluxes_imply() { const auto before = standing(); // A structure claiming more members than the fluxes produced. auto inflated = request(); inflated.after[0].count += 1; CHECK(refused(plan_advance(before, inflated), PopulationError::population_mismatch)); // A structure claiming biomass the fluxes did not leave behind. auto enriched = request(); enriched.after[0].reserve.energy.value += 1; CHECK(refused(plan_advance(before, enriched), PopulationError::biomass_mismatch)); // Biomass that left without anyone declaring where it went. auto vanished = request(); vanished.after[0].reserve.energy.value -= 1; CHECK(refused(plan_advance(before, vanished), PopulationError::biomass_mismatch)); // An interval must move forward, and one that ends where it began integrates // nothing while claiming a new revision. auto backwards = request(); backwards.to = Tick{800}; CHECK(refused(plan_advance(before, backwards), PopulationError::empty_interval)); auto standstill = request(); standstill.to = before.last_tick(); CHECK(refused(plan_advance(before, standstill), PopulationError::empty_interval)); // One owner integrates each interval, and only ever forwards. auto intruder = request(); intruder.owner = {12, 2}; CHECK(refused(plan_advance(before, intruder), PopulationError::wrong_owner)); auto replayed = request(); replayed.revision = before.revision(); CHECK(refused(plan_advance(before, replayed), PopulationError::stale_revision)); auto older = request(); older.owner = {11, 1}; CHECK(refused(plan_advance(before, older), PopulationError::stale_revision)); // Biomass cannot leave for the cohort's own reservoir, which would move // nothing while reporting that it had. auto circular = request(); circular.flux.deaths = 1 * residual_scale; circular.flux.to_detritus = held(10, 100); circular.detritus = backing; circular.after = {{0, 100, 39, held(390, 3'900), 0}, {100, 200, 20, held(600, 6'000), 0}}; CHECK(refused(plan_advance(before, circular), PopulationError::invalid_request)); auto unnamed = circular; unnamed.detritus = {}; CHECK(refused(plan_advance(before, unnamed), PopulationError::invalid_request)); } void a_stale_proposal_is_refused_and_changes_nothing() { const auto before = standing(); auto mover = request(); mover.flux.deaths = 4 * residual_scale; mover.flux.to_detritus = held(40, 400); mover.after = {{0, 100, 36, held(360, 3'600), 0}, {100, 200, 20, held(600, 6'000), 0}}; const auto plan = plan_advance(before, mover); CHECK(plan.has_value()); // Nothing installed at all. auto bare = world(); CohortRegistry nothing; const auto opening = std::vector{bare.balances().begin(), bare.balances().end()}; CHECK(refused(commit_advance(bare, nothing, *plan), PopulationError::not_installed)); CHECK(std::vector(bare.balances().begin(), bare.balances().end()) == opening); // Installed, but already advanced past the view the plan was built on. auto moved = world(); auto registry = registry_holding(before); auto newer = draft(); newer.revision = 9; newer.last_tick = Tick{950}; CHECK(registry.replace(built(newer)).has_value()); const auto action = moved.last_action(); CHECK(refused(commit_advance(moved, registry, *plan), PopulationError::stale_plan)); CHECK(std::vector(moved.balances().begin(), moved.balances().end()) == opening); CHECK(moved.last_action() == action); CHECK(registry.find(HabitatId{7}, 3)->revision() == 9); // Installed and current, but the reservoir no longer holds what was counted. auto drifted = world(); auto current = registry_holding(before); const std::array leak{Transfer{backing, {5}, held(1, 1)}}; CHECK(drifted.transfer(drifted.last_action() + 1, leak).has_value()); const auto after_leak = std::vector{drifted.balances().begin(), drifted.balances().end()}; const auto leaked_action = drifted.last_action(); CHECK(refused(commit_advance(drifted, current, *plan), PopulationError::stale_plan)); CHECK(std::vector(drifted.balances().begin(), drifted.balances().end()) == after_leak); CHECK(drifted.last_action() == leaked_action); CHECK(current.find(HabitatId{7}, 3)->last_tick() == Tick{900}); // Committing one plan twice: the second finds a record it does not match. auto once = world(); auto held_once = registry_holding(before); CHECK(commit_advance(once, held_once, *plan).has_value()); const auto settled = std::vector{once.balances().begin(), once.balances().end()}; const auto settled_action = once.last_action(); CHECK(refused(commit_advance(once, held_once, *plan), PopulationError::stale_plan)); CHECK(std::vector(once.balances().begin(), once.balances().end()) == settled); CHECK(once.last_action() == settled_action); } void an_interval_affordable_only_with_its_arrivals_still_commits() { // The cohort sheds more than it currently holds, and receives more than enough // to cover it. The interval as a whole is affordable, and planning says so, so // commit must apply it: the ledger applies legs in sequence, and an outflow // placed before the inflow would underflow a reservoir the interval affords. // Found by the M4.5 comparison, where a fifty-tick interval shed 10,480 against // 6,950 held while drawing 13,080 in, and was refused with ledger_failure. const auto before = standing(); CHECK(before.reserve() == held(1'000, 10'000)); auto crossing = request(); crossing.flux.to_detritus = held(1'400, 14'000); // More than is held. crossing.flux.from_elsewhere = held(1'900, 19'000); // Covers it and more. crossing.after = {{0, 100, 40, held(1'500, 15'000), 0}, {100, 200, 20, Inventory{}, 0}}; const auto plan = plan_advance(before, crossing); CHECK(plan.has_value()); CHECK(plan->after().reserve() == held(1'500, 15'000)); // The arrival is the first leg, so nothing underflows on the way through. CHECK(plan->legs().size() == 2); CHECK(plan->legs()[0].to == backing); CHECK(plan->legs()[0].amount == held(1'900, 19'000)); CHECK(plan->legs()[1].from == backing); auto registry = registry_holding(before); // The escrow has to be able to fund what it sends. auto seeded = std::array{}; seeded[backing.value - 1] = before.reserve(); seeded[elsewhere.value - 1] = held(2'000, 20'000); auto funded = Ledger::create(seeded); CHECK(funded.has_value()); const auto total = funded->conserved_totals(); const auto committed = commit_advance(*funded, registry, *plan); CHECK(committed.has_value()); CHECK(funded->conserved_totals() == total); CHECK(funded->balances()[backing.value - 1] == held(1'500, 15'000)); CHECK(funded->balances()[detritus.value - 1] == held(1'400, 14'000)); CHECK(funded->balances()[elsewhere.value - 1] == held(100, 1'000)); } void seeded_intervals_conserve_over_and_over() { // Many intervals of pseudo-random bounded flux. Nothing here is an ecology: // the point is that whatever a model proposes, the accounting either closes // or refuses, and the world total never moves. for (std::uint64_t seed = 1; seed <= 24; ++seed) { Random random{seed}; auto ledger = world(); const std::array seed_escrow{Transfer{{5}, elsewhere, held(7, 7)}}; CHECK(ledger.transfer(ledger.last_action() + 1, seed_escrow).has_value()); const auto total = ledger.conserved_totals(); auto cohort = standing(); auto registry = registry_holding(cohort); std::uint64_t revision = cohort.revision(); std::uint64_t tick = cohort.last_tick().value; std::uint64_t advanced = 0, refusals = 0; for (std::uint64_t step = 0; step < 40; ++step) { AdvanceRequest proposal; tick += 1 + random.next() % 50; proposal.to = Tick{tick}; proposal.owner = cohort.owner(); proposal.revision = ++revision; proposal.detritus = detritus; proposal.predators = predators; proposal.elsewhere = elsewhere; proposal.bound = cohort.bound(); // Deliberately unbounded relative to the cohort, so some proposals // ask for more than is there and must be refused rather than clamped. const auto deaths = (random.next() % 9) * residual_scale; const auto energy = random.next() % 120; const auto matter = random.next() % 900; proposal.flux.deaths = deaths; proposal.flux.to_detritus = held(energy, matter); auto remaining = cohort.population(); const bool survives = deaths <= remaining; remaining = survives ? remaining - deaths : 0; auto reserve = cohort.reserve(); const bool affordable = reserve.energy.value >= energy && reserve.matter[0].value >= matter; if (survives && affordable) { reserve.energy.value -= energy; for (auto& channel : reserve.matter) { channel.value -= matter; } if (remaining == 0) { proposal.flux.to_detritus = reserve; proposal.flux.to_detritus.energy.value = reserve.energy.value + energy; proposal.after.clear(); } else { proposal.after = { {0, 100, remaining / residual_scale, reserve, remaining % residual_scale}}; } } else { proposal.after = {{0, 100, 1, Inventory{}, 0}}; } const auto plan = plan_advance(cohort, proposal); if (!plan) { ++refusals; --revision; tick = cohort.last_tick().value; continue; } const auto committed = commit_advance(ledger, registry, *plan); CHECK(committed.has_value()); cohort = *committed; ++advanced; // Every invariant, every interval. CHECK(ledger.conserved_totals() == total); CHECK(ledger.balances()[backing.value - 1] == cohort.reserve()); CHECK(cohort.last_tick().value == tick); CHECK(registry.size() == 1); if (cohort.is_vacant()) { CHECK(cohort.population() == 0); CHECK(cohort.reserve() == Inventory{}); break; } } // Both paths must actually occur, or this would prove nothing. CHECK(advanced > 0); CHECK(refusals > 0); } } 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 mover = request(); mover.flux.deaths = 4 * residual_scale; mover.flux.to_detritus = held(40, 400); mover.after = {{0, 100, 36, held(360, 3'600), 0}, {100, 200, 20, held(600, 6'000), 0}}; auto source = plan_advance(before, mover); 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->legs().size() == 1); CHECK(moved == original); auto ledger = world(); auto registry = registry_holding(before); // NOLINTNEXTLINE(bugprone-use-after-move) const auto committed = commit_advance(ledger, registry, *source); CHECK(committed.has_value()); CHECK(ledger.balances()[detritus.value - 1] == held(40, 400)); } } // namespace int main() try { an_interval_that_changes_nothing_still_advances_the_clock(); a_birth_redistributes_and_never_creates_biomass(); death_predation_and_migration_move_biomass_once(); a_proposal_that_would_go_below_zero_is_refused_not_clamped(); a_population_below_one_member_is_still_a_population(); a_vacant_cohort_is_not_an_extinction(); the_declared_result_must_be_what_the_fluxes_imply(); a_stale_proposal_is_refused_and_changes_nothing(); an_interval_affordable_only_with_its_arrivals_still_commits(); seeded_intervals_conserve_over_and_over(); a_moved_from_plan_is_still_a_whole_plan(); std::cout << "PASS interval accounting, refusal without clamping and seeded conservation\n"; return 0; } catch (...) { return 1; }