M4.5 closes M4 by measuring what aggregation costs, and adds no library code except one defect fix the measurement found. One rule is written once and applied at both resolutions. The control is what makes the rest mean anything: with one member per class a class average is that member, so the two runs must agree exactly, and they do, tick by tick, in every channel. A deliberate one-unit drift in the aggregate rule is caught by it, so the instrument is verified rather than assumed. Without it a measured gap would be indistinguishable from a transcription mistake in one of the two runs. The result is reported, not smoothed into a tolerance. At class widths ten and fifty the aggregate population survives ten thousand ticks within 375 parts per thousand on population and 43 on energy. At twenty-five, one hundred and two hundred it dies out entirely while the individual run sustains seventy-five members: a false extinction caused by resolution alone, because a whole class starves the moment its average cannot pay upkeep, where individuals starve a few at a time and the survivors keep the shared per-capita share up. The collapse is not monotone in class width. Twenty-five destroys the population and fifty sustains it. An earlier version of the test asserted that coarser is never better; the measurement refuted it, so the assertion went rather than the widths being chosen to make it hold. The non-monotonicity is asserted now, because it is surprising and because the warning written around it could otherwise become wrong without failing. A tier policy cannot assume degradation worsens smoothly as classes widen, and M4.6 inherits that. Conservation was exact at every tick on both sides of all five runs, including the three that died out. That is the clearest available demonstration of the thing ECOLOGY_MODEL keeps saying: conservation is not ecological evidence. Two flaws in my own experiment were found before any number was believed. The aggregate model had been producing overlapping classes, so the model measured was not one a cohort could represent; newborns now extend the youngest class while it is narrower than the width, and every step is checked to construct a valid Cohort. The first figures were discarded. The comparison also found a real M4.3 defect, which is what a validation milestone is for. plan_advance checked affordability with arrivals added before losses were taken, but emitted the ledger legs outflows-first, so an interval affordable as a whole underflowed leg by leg and was refused at commit. A fifty-tick interval shedding 10,480 against 6,950 held while drawing 13,080 in reproduced it. Arrivals are the first leg now, matching the order the arithmetic was checked in, with a regression and a corrected escrow expectation in an existing test. Release 38/38, analysis, ASan 38/38 and clang-format all ran and passed here. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
207 lines
8.7 KiB
C++
207 lines
8.7 KiB
C++
#include "evo/ecology/population.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <limits>
|
|
#include <utility>
|
|
|
|
namespace evo::ecology {
|
|
namespace {
|
|
constexpr auto maximum = std::numeric_limits<std::uint64_t>::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<AdvancePlan, PopulationError> 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<accounting::Transfer> 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<Cohort, PopulationError>
|
|
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
|