#include "evo/ecology/population.hpp" #include #include #include namespace evo::ecology { namespace { constexpr auto maximum = std::numeric_limits::max(); [[nodiscard]] bool add(std::uint64_t& total, std::uint64_t amount) noexcept { if (amount > maximum - total) { return false; } total += amount; return true; } [[nodiscard]] bool take(std::uint64_t& total, std::uint64_t amount) noexcept { if (amount > total) { return false; } total -= amount; return true; } [[nodiscard]] bool add(accounting::Inventory& total, const accounting::Inventory& amount) noexcept { if (!add(total.energy.value, amount.energy.value)) { return false; } for (std::size_t channel = 0; channel < total.matter.size(); ++channel) { if (!add(total.matter[channel].value, amount.matter[channel].value)) { return false; } } return true; } // Every channel separately: a total mass is not an additional inventory, so any // one channel may be the one that would go below zero. [[nodiscard]] bool take(accounting::Inventory& total, const accounting::Inventory& amount) noexcept { if (!take(total.energy.value, amount.energy.value)) { return false; } for (std::size_t channel = 0; channel < total.matter.size(); ++channel) { if (!take(total.matter[channel].value, amount.matter[channel].value)) { return false; } } return true; } [[nodiscard]] bool empty(const accounting::Inventory& inventory) noexcept { return inventory == accounting::Inventory{}; } } // namespace std::expected plan_advance(const Cohort& before, const AdvanceRequest& request) { if (request.owner.worker == 0 || request.owner.epoch == 0 || request.revision == 0) { return std::unexpected{PopulationError::invalid_request}; } // The interval starts where the record stands, so intervals cannot overlap // or leave a gap, and a zero-length one integrates nothing. if (request.to <= before.last_tick()) { return std::unexpected{PopulationError::empty_interval}; } if (request.owner.worker != before.owner().worker) { return std::unexpected{PopulationError::wrong_owner}; } if (request.owner.epoch < before.owner().epoch) { return std::unexpected{PopulationError::stale_revision}; } if (request.owner.epoch == before.owner().epoch && request.revision <= before.revision()) { return std::unexpected{PopulationError::stale_revision}; } // Biomass has to leave for somewhere that is not the cohort itself, and only // where an amount actually moves does a counterparty have to be named. const auto& flux = request.flux; const auto needs = [&](const accounting::Inventory& amount, accounting::ReservoirId where) { return empty(amount) || (where.value != 0 && where != before.reservoir()); }; if (!needs(flux.to_detritus, request.detritus) || !needs(flux.to_predators, request.predators) || !needs(flux.to_elsewhere, request.elsewhere) || !needs(flux.from_elsewhere, request.elsewhere)) { return std::unexpected{PopulationError::invalid_request}; } // Population, in units of residual_scale. Additions first so a subtraction // never has to borrow against an arrival that has not been counted. auto population = before.population(); if (!add(population, flux.births) || !add(population, flux.immigration)) { return std::unexpected{PopulationError::overflow}; } if (!take(population, flux.deaths) || !take(population, flux.predation) || !take(population, flux.emigration)) { // Refused, never clamped: a clamp would hide an unstable interval and // manufacture an extinction the model never proposed. return std::unexpected{PopulationError::negative_population}; } // Biomass. There is deliberately no birth term: a birth redistributes what // the cohort already holds, so there is nowhere for one to bring biomass in. auto reserve = before.reserve(); if (!add(reserve, flux.from_elsewhere)) { return std::unexpected{PopulationError::overflow}; } if (!take(reserve, flux.to_detritus) || !take(reserve, flux.to_predators) || !take(reserve, flux.to_elsewhere)) { return std::unexpected{PopulationError::negative_biomass}; } CohortDraft draft; draft.representation_version = before.representation_version(); draft.habitat = before.habitat(); draft.genome = before.genome(); draft.owner = request.owner; draft.last_tick = request.to; draft.revision = request.revision; draft.conversion = before.conversion(); draft.reservoir = before.reservoir(); draft.classes = request.after; draft.bound = request.bound; // A population that reached exactly zero is a vacant record, not an absent // one and not an extinct one: the genome, the habitat and the history stay. const auto built = request.after.empty() ? Cohort::vacant(draft) : Cohort::create(std::move(draft)); if (!built) { return std::unexpected{PopulationError::invalid_cohort}; } // The declared result has to be exactly what the fluxes imply. Anything else // is a model whose own arithmetic does not close. if (built->population() != population) { return std::unexpected{PopulationError::population_mismatch}; } if (built->reserve() != reserve) { return std::unexpected{PopulationError::biomass_mismatch}; } std::vector legs; const auto leg = [&](const accounting::Inventory& amount, accounting::ReservoirId where, bool inbound) { if (empty(amount)) { return; } legs.push_back(inbound ? accounting::Transfer{where, before.reservoir(), amount} : accounting::Transfer{before.reservoir(), where, amount}); }; // Arrivals first, in the same order the arithmetic above was checked: the // ledger applies legs in sequence, so an outflow placed before an inflow could // underflow a reservoir that the interval as a whole affords. Without this a // cohort shedding more than it currently holds, while receiving enough to cover // it, would pass planning and then be refused at commit. leg(flux.from_elsewhere, request.elsewhere, true); leg(flux.to_detritus, request.detritus, false); leg(flux.to_predators, request.predators, false); leg(flux.to_elsewhere, request.elsewhere, false); if (legs.size() > accounting::max_transfers) { return std::unexpected{PopulationError::overflow}; } AdvancePlan plan{before, *built}; plan.legs_ = std::move(legs); plan.flux_ = flux; return plan; } std::expected commit_advance(accounting::Ledger& ledger, CohortRegistry& registry, const AdvancePlan& plan) { const auto& before = plan.before(); // The record the plan was computed against must still be the installed one, // to the revision: a proposal built on a stale view is refused, not applied. const auto installed = registry.find(before.habitat(), before.genome()); if (!installed) { return std::unexpected{PopulationError::not_installed}; } if (*installed != before) { return std::unexpected{PopulationError::stale_plan}; } const auto balances = ledger.balances(); if (before.reservoir().value > balances.size()) { return std::unexpected{PopulationError::stale_plan}; } // And the reservoir must still hold what the plan accounted for, or the // fluxes were measured against inventory that is no longer there. if (balances[before.reservoir().value - 1] != before.reserve()) { return std::unexpected{PopulationError::stale_plan}; } for (const auto& leg : plan.legs()) { if (leg.from.value > balances.size() || leg.to.value > balances.size()) { return std::unexpected{PopulationError::stale_plan}; } } if (!plan.legs().empty()) { if (ledger.last_action() == maximum) { return std::unexpected{PopulationError::ledger_failure}; } if (!ledger.transfer(ledger.last_action() + 1, plan.legs())) { return std::unexpected{PopulationError::ledger_failure}; } } // Proved above to be a strictly later view of the installed record, so this // cannot fail and nothing can be stranded between the two steps. if (!registry.replace(plan.after())) { return std::unexpected{PopulationError::stale_plan}; } return plan.after(); } } // namespace evo::ecology