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
+497
View File
@@ -0,0 +1,497 @@
#include "evo/core/random.hpp"
#include "evo/ecology/population.hpp"
#include <array>
#include <expected>
#include <iostream>
#include <limits>
#include <source_location>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
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<bool>(__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 <typename T>
[[nodiscard]] bool refused(const std::expected<T, PopulationError>& 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<Inventory, reservoir_count> 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 ledger = world();
auto registry = registry_holding(before);
// The escrow has to be able to fund the immigrants it sends.
const std::array seed{Transfer{{5}, elsewhere, held(7, 7)}};
CHECK(ledger.transfer(ledger.last_action() + 1, seed).has_value());
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 received twenty energy and two hundred matter and gave back ten
// and one hundred, so from seven it stands at seventeen and a hundred and
// seven. The legs apply in order, so it can fund the immigrants it sends.
CHECK(ledger.balances()[elsewhere.value - 1] == held(17, 107));
}
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<Inventory>{bare.balances().begin(), bare.balances().end()};
CHECK(refused(commit_advance(bare, nothing, *plan), PopulationError::not_installed));
CHECK(std::vector<Inventory>(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<Inventory>(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<Inventory>{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<Inventory>(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<Inventory>{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<Inventory>(once.balances().begin(), once.balances().end()) == settled);
CHECK(once.last_action() == settled_action);
}
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<AdvancePlan>);
static_assert(!std::is_nothrow_move_constructible_v<AdvancePlan>);
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();
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;
}