Account for the interval a model proposes; never clamp it

M4.3 advances a cohort over one declared interval and deliberately does not model
one. ECOLOGY_MODEL keeps population maths an experiment and asks for several
candidates to be compared, so choosing one here would turn a recommendation into
a locked rule. A model proposes fluxes; this checks the declared result is
exactly what they imply, for counts and for every inventory channel.

Nothing is clamped. A loss larger than what is there refuses the interval and
says whether it was the population or the biomass, so a caller can subdivide;
subtraction is checked against what is present rather than performed and
repaired, so a negative population is never constructed. That is the answer to
the named risk: a clamp is how an interval a model could not integrate becomes a
plausible result, and how a false extinction arrives. Both clamp mutations are
detected by the tests.

Counts carry whole members and owed fractions as one quantity, so a population
below one member is a number rather than a rounding decision. Biomass has no
birth term at all, so a birth cannot bring inventory in and newborns are
necessarily funded from what the cohort holds. Immigration draws from a reservoir
that already held it, so a late transfer is not new production. Conservation runs
through the ledger as one atomic transaction; an interval where nothing moves
submits none.

Two amendments to M4.1 were forced, not chosen. A cohort records the reservoir
backing it, because an advance cannot otherwise know where the inventory is and
passing it alongside would let a caller advance one cohort against another's
store, which comparing balances cannot detect between equal reserves; the
registry now refuses two cohorts sharing one. And a cohort may be vacant, through
a separate factory so vacancy stays deliberate, because a decline to exactly zero
was otherwise unrepresentable and the only way through would have been the clamp
this milestone exists to refuse. A vacant cohort is not an extinction: the
record, its genome, its habitat and its provenance remain and it stays installed.

Fourteen guards confirmed load-bearing by removing each and rerunning. Two of my
own expectations were wrong rather than the code: escrow arithmetic in the
migration test, and a dwindling case that shed all but one femtogram while
declaring a result holding none. The second surfaced a real tension now recorded
in ADR-0038 rather than worked around: a class reduced to a fraction of a member
may hold no reserve, because reserve belongs to members and a fraction is not one
yet, so that biomass has to go somewhere the same interval.

Closure is checked and stability is not, so an interval whose arithmetic balances
and whose ecology is nonsense is accepted. The declared age structure is not
verified to be what ageing would produce, because that needs the within-class
distribution the record discards.

Release 36/36, analysis, ASan 36/36 and clang-format all ran and passed here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-24 10:23:09 -04:00
co-authored by Claude Opus 5
parent 0697895e25
commit cabada70c4
16 changed files with 1331 additions and 8 deletions
+53 -1
View File
@@ -50,7 +50,8 @@ std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
// Every identity a cohort names has to name something. A zero owner or epoch
// would be a record nobody is responsible for integrating.
if (draft.habitat.value == 0 || draft.genome == 0 || draft.owner.worker == 0 ||
draft.owner.epoch == 0 || draft.revision == 0 || draft.conversion == 0) {
draft.owner.epoch == 0 || draft.revision == 0 || draft.conversion == 0 ||
draft.reservoir.value == 0) {
return std::unexpected{CohortError::invalid_identity};
}
if (draft.classes.empty()) {
@@ -90,6 +91,11 @@ std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
return std::unexpected{CohortError::overflow};
}
}
// Whole members and owed fractions are also read as one scaled quantity, so
// the count has to stay inside what that scaling can hold.
if (count > maximum / residual_scale || residual > maximum - count * residual_scale) {
return std::unexpected{CohortError::overflow};
}
Cohort cohort;
cohort.version_ = draft.representation_version;
cohort.habitat_ = draft.habitat;
@@ -98,11 +104,40 @@ std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
cohort.last_tick_ = draft.last_tick;
cohort.revision_ = draft.revision;
cohort.conversion_ = draft.conversion;
cohort.reservoir_ = draft.reservoir;
cohort.classes_ = std::move(draft.classes);
cohort.bound_ = draft.bound;
return cohort;
}
std::expected<Cohort, CohortError> Cohort::vacant(const CohortDraft& draft) {
// A record with no members may hold nothing: a reserve with nobody to own it
// is the same defect a class with no members and a reserve would be.
if (!draft.classes.empty()) {
return std::unexpected{CohortError::not_vacant};
}
// Everything else a cohort must name, it still must. The identity checks are
// borrowed from `create` through a placeholder class that is then discarded,
// so the two factories cannot drift apart on what an identity is.
auto probe = draft;
probe.classes = {{0, 1, 1, {}, 0}};
const auto checked = create(std::move(probe));
if (!checked) {
return std::unexpected{checked.error()};
}
Cohort cohort;
cohort.version_ = draft.representation_version;
cohort.habitat_ = draft.habitat;
cohort.genome_ = draft.genome;
cohort.owner_ = draft.owner;
cohort.last_tick_ = draft.last_tick;
cohort.revision_ = draft.revision;
cohort.conversion_ = draft.conversion;
cohort.reservoir_ = draft.reservoir;
cohort.bound_ = draft.bound;
return cohort;
}
std::uint64_t Cohort::count() const noexcept {
std::uint64_t total = 0;
for (const auto& age : classes_) {
@@ -131,12 +166,24 @@ std::uint64_t Cohort::residual() const noexcept {
return total;
}
std::uint64_t Cohort::population() const noexcept {
// Construction proved this cannot overflow.
return count() * residual_scale + residual();
}
std::expected<void, CohortError> CohortRegistry::install(const Cohort& cohort) {
const auto wanted = key_of(cohort);
const auto at = std::ranges::lower_bound(cohorts_, wanted, {}, key_of);
if (at != cohorts_.end() && key_of(*at) == wanted) {
return std::unexpected{CohortError::duplicate_cohort};
}
// One reservoir backing two records would be the same inventory in two
// places, which is what this registry exists to make unrepresentable.
if (std::ranges::any_of(cohorts_, [&](const Cohort& other) {
return other.reservoir() == cohort.reservoir();
})) {
return std::unexpected{CohortError::duplicate_cohort};
}
if (cohorts_.size() >= max_cohorts) {
return std::unexpected{CohortError::registry_full};
}
@@ -172,6 +219,11 @@ std::expected<void, CohortError> CohortRegistry::replace(const Cohort& cohort) {
if (cohort.last_tick() < at->last_tick()) {
return std::unexpected{CohortError::backward_tick};
}
// A record cannot change which reservoir backs it: that would be a different
// store holding this cohort's inventory, not a later view of this one.
if (cohort.reservoir() != at->reservoir()) {
return std::unexpected{CohortError::unknown_cohort};
}
*at = cohort;
return {};
}
+3
View File
@@ -113,6 +113,9 @@ std::expected<CollapsePlan, CollapseError> plan_collapse(std::span<const ActiveM
draft.last_tick = request.tick;
draft.revision = request.revision;
draft.conversion = request.conversion;
// The gathering reservoir is where the cohort's reserve will live, so the
// record carries it rather than leaving it to be supplied again later.
draft.reservoir = request.destination;
draft.classes = std::move(classes);
draft.bound = request.bound;
// Built and validated here, so commit cannot fail on the record's validity
+201
View File
@@ -0,0 +1,201 @@
#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});
};
leg(flux.to_detritus, request.detritus, false);
leg(flux.to_predators, request.predators, false);
leg(flux.to_elsewhere, request.elsewhere, false);
leg(flux.from_elsewhere, request.elsewhere, true);
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