Files
dingoandClaude Opus 5 cabada70c4 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>
2026-09-24 10:23:09 -04:00

506 lines
23 KiB
C++

#include "evo/biology/lineage.hpp"
#include "evo/ecology/cohort.hpp"
#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::Tick;
void check(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error("cohort 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, CohortError>& result, CohortError expected) {
return !result.has_value() && result.error() == expected;
}
Inventory held(std::uint64_t value) {
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
}
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 = {1};
source.classes = {{0, 100, 40, held(400), 0},
{100, 200, 25, held(900), 250'000},
{200, 300, 10, held(1'000), 999'999}};
source.bound = {2, held(30)};
return source;
}
Cohort valid() {
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;
}
void a_cohort_keeps_exactly_what_it_was_given() {
const auto cohort = valid();
CHECK(cohort.representation_version() == cohort_representation_version);
CHECK(cohort.habitat() == HabitatId{7});
CHECK(cohort.genome() == 3);
CHECK(cohort.owner() == Owner{11, 2});
CHECK(cohort.last_tick() == Tick{900});
CHECK(cohort.revision() == 4);
CHECK(cohort.conversion() == 5);
CHECK(cohort.reservoir() == ReservoirId{1});
CHECK(!cohort.is_vacant());
CHECK(cohort.population() == cohort.count() * residual_scale + cohort.residual());
CHECK(cohort.bound().count == 2);
CHECK(cohort.bound().inventory == held(30));
CHECK(cohort.classes().size() == 3);
// Totals are derived from the classes, so they cannot disagree with them.
CHECK(cohort.count() == 75);
CHECK(cohort.reserve() == held(2'300));
CHECK(cohort.residual() == 1'249'999);
std::uint64_t counted = 0;
Inventory reserved{};
for (const auto& age : cohort.classes()) {
counted += age.count;
reserved.energy.value += age.reserve.energy.value;
for (std::size_t channel = 0; channel < reserved.matter.size(); ++channel) {
reserved.matter[channel].value += age.reserve.matter[channel].value;
}
}
CHECK(counted == cohort.count());
CHECK(reserved == cohort.reserve());
// Summed across classes the residual may exceed a member; the per-class bound
// is what is invariant, and a fraction is never counted as a member.
CHECK(cohort.residual() > residual_scale);
CHECK(cohort.count() == 75);
}
void the_record_keeps_a_distribution_and_not_an_average() {
// Two cohorts with identical totals but different structure: one where every
// member is provisioned and one where a young class holds nothing at all. A
// record storing a count and a mean reserve could not tell these apart, which
// is exactly how an average hides whether anyone would survive.
auto spread = draft();
spread.classes = {{0, 100, 50, held(500), 0}, {100, 200, 50, held(500), 0}};
auto skewed = draft();
skewed.classes = {{0, 100, 50, held(0), 0}, {100, 200, 50, held(1'000), 0}};
const auto even = built(spread);
const auto uneven = built(skewed);
CHECK(even.count() == uneven.count());
CHECK(even.reserve() == uneven.reserve());
CHECK(even != uneven); // The totals agree; the records do not.
CHECK(even.classes()[0].reserve != uneven.classes()[0].reserve);
// A class with members but no reserve is a legitimate state, not an error:
// it is precisely the outlier an average would have dissolved.
CHECK(uneven.classes()[0].count == 50);
CHECK(uneven.classes()[0].reserve == Inventory{});
}
void every_invariant_is_rejected_by_name() {
auto wrong_version = draft();
wrong_version.representation_version = cohort_representation_version + 1;
CHECK(refused(Cohort::create(wrong_version), CohortError::unsupported_version));
// Each identity a cohort names has to name something, including its owner:
// a record nobody is responsible for integrating has no owner at all.
for (auto missing : {0U, 1U, 2U, 3U, 4U, 5U, 6U}) {
auto blank = draft();
if (missing == 0) {
blank.habitat = {};
} else if (missing == 1) {
blank.genome = 0;
} else if (missing == 2) {
blank.owner.worker = 0;
} else if (missing == 3) {
blank.owner.epoch = 0;
} else if (missing == 4) {
blank.revision = 0;
} else if (missing == 5) {
blank.conversion = 0;
} else {
// A cohort that does not say where its reserve is could be advanced
// against another cohort's reservoir.
blank.reservoir = {};
}
CHECK(refused(Cohort::create(blank), CohortError::invalid_identity));
}
auto none = draft();
none.classes.clear();
CHECK(refused(Cohort::create(none), CohortError::no_age_classes));
auto too_many = draft();
too_many.classes.clear();
for (std::uint64_t index = 0; index <= max_age_classes; ++index) {
too_many.classes.push_back({index * 10, index * 10 + 10, 1, held(1), 0});
}
CHECK(refused(Cohort::create(too_many), CohortError::overflow));
// An empty range makes a member's class impossible, an inverted one likewise,
// and an overlap or a descending order makes it ambiguous.
auto empty_range = draft();
empty_range.classes[1].age_high = empty_range.classes[1].age_low;
CHECK(refused(Cohort::create(empty_range), CohortError::unordered_age_classes));
auto inverted = draft();
inverted.classes[1].age_high = inverted.classes[1].age_low - 1;
CHECK(refused(Cohort::create(inverted), CohortError::unordered_age_classes));
auto overlapping = draft();
overlapping.classes[1].age_low = overlapping.classes[0].age_high - 1;
CHECK(refused(Cohort::create(overlapping), CohortError::unordered_age_classes));
auto descending = draft();
std::swap(descending.classes[0], descending.classes[2]);
CHECK(refused(Cohort::create(descending), CohortError::unordered_age_classes));
// A class with neither members nor a fraction owed is a boundary, not a class.
auto hollow = draft();
hollow.classes[1].count = 0;
hollow.classes[1].residual = 0;
hollow.classes[1].reserve = {};
CHECK(refused(Cohort::create(hollow), CohortError::empty_age_class));
// Reserve belongs to members; with none it would be biomass owned by nobody.
auto orphaned = draft();
orphaned.classes[1].count = 0;
orphaned.classes[1].residual = 1;
CHECK(refused(Cohort::create(orphaned), CohortError::unowned_reserve));
// A class owed a fraction and holding nothing is valid: nothing is unowned.
auto owed = draft();
owed.classes[1].count = 0;
owed.classes[1].residual = 1;
owed.classes[1].reserve = {};
CHECK(Cohort::create(owed).has_value());
// At a whole member a fraction is a member, so the bound is strict.
auto whole = draft();
whole.classes[1].residual = residual_scale;
CHECK(refused(Cohort::create(whole), CohortError::residual_out_of_range));
auto just_under = draft();
just_under.classes[1].residual = residual_scale - 1;
CHECK(Cohort::create(just_under).has_value());
// Summation rejects rather than wrapping, on counts and on every channel.
constexpr auto most = std::numeric_limits<std::uint64_t>::max();
auto counts = draft();
counts.classes[0].count = most;
counts.classes[1].count = 1;
CHECK(refused(Cohort::create(counts), CohortError::overflow));
auto energy = draft();
energy.classes[0].reserve.energy.value = most;
energy.classes[1].reserve.energy.value = 1;
CHECK(refused(Cohort::create(energy), CohortError::overflow));
for (std::size_t channel = 0; channel < 4; ++channel) {
auto matter = draft();
matter.classes[0].reserve.matter[channel].value = most;
matter.classes[1].reserve.matter[channel].value = 1;
CHECK(refused(Cohort::create(matter), CohortError::overflow));
}
// No negative reserve is representable, because every quantity here is
// unsigned. What is rejected is a declared state that would require one.
static_assert(!std::is_signed_v<decltype(Femtograms{}.value)>);
static_assert(!std::is_signed_v<decltype(Picojoules{}.value)>);
static_assert(!std::is_signed_v<decltype(AgeClass{}.count)>);
}
void one_habitat_and_genome_holds_one_cohort() {
CohortRegistry registry;
CHECK(registry.install(valid()).has_value());
CHECK(registry.size() == 1);
// A second record of the same genome in the same habitat would be a second
// place the same biomass could be spent, whoever claims to own it.
CHECK(refused(registry.install(valid()), CohortError::duplicate_cohort));
auto differing_owner = draft();
differing_owner.owner = {99, 4};
CHECK(refused(registry.install(built(differing_owner)), CohortError::duplicate_cohort));
CHECK(registry.size() == 1);
// Another genome, or the same genome elsewhere, is a different record.
auto other_genome = draft();
other_genome.genome = 4;
other_genome.reservoir = {2};
auto other_habitat = draft();
other_habitat.habitat = {8};
other_habitat.reservoir = {3};
CHECK(registry.install(built(other_genome)).has_value());
CHECK(registry.install(built(other_habitat)).has_value());
CHECK(registry.size() == 3);
// Every record stays findable whatever order they arrived in.
CHECK(registry.find(HabitatId{7}, 3)->owner() == Owner{11, 2});
CHECK(registry.find(HabitatId{7}, 4)->genome() == 4);
CHECK(registry.find(HabitatId{8}, 3)->habitat() == HabitatId{8});
CHECK(refused(registry.find(HabitatId{7}, 5), CohortError::unknown_cohort));
CHECK(refused(registry.find(HabitatId{9}, 3), CohortError::unknown_cohort));
}
void only_the_recorded_owner_may_replace_a_cohort() {
CohortRegistry registry;
CHECK(registry.install(valid()).has_value());
// A different worker is refused however current its epoch.
auto intruder = draft();
intruder.owner = {12, 99};
intruder.revision = 99;
CHECK(refused(registry.replace(built(intruder)), CohortError::wrong_owner));
// A writer holding an older view of its own cohort is refused too.
auto stale = draft();
stale.owner = {11, 1};
CHECK(refused(registry.replace(built(stale)), CohortError::stale_epoch));
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{900});
// Advancing the record under the same epoch requires a newer revision.
auto advanced_revision = draft();
advanced_revision.last_tick = Tick{1'000};
advanced_revision.revision = 5;
CHECK(registry.replace(built(advanced_revision)).has_value());
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'000});
// A newer epoch may restart the revision series, because re-acquiring
// ownership begins a new one.
auto reacquired = draft();
reacquired.owner = {11, 3};
reacquired.last_tick = Tick{1'100};
reacquired.revision = 1;
CHECK(registry.replace(built(reacquired)).has_value());
CHECK(registry.find(HabitatId{7}, 3)->owner() == Owner{11, 3});
CHECK(registry.find(HabitatId{7}, 3)->revision() == 1);
// Having advanced, the previously current epoch is now the stale one.
CHECK(refused(registry.replace(built(advanced_revision)), CohortError::stale_epoch));
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'100});
// A record naming a different habitat or genome is not a newer view of this
// one, and replacing a cohort never installed is refused outright.
auto elsewhere = draft();
elsewhere.habitat = {8};
CHECK(refused(registry.replace(built(elsewhere)), CohortError::unknown_cohort));
auto another = draft();
another.genome = 4;
CHECK(refused(registry.replace(built(another)), CohortError::unknown_cohort));
CHECK(registry.size() == 1); // A refused replacement installs nothing.
}
void an_epoch_alone_cannot_order_two_writes() {
// An owner replaying its own earlier record inside one epoch would restore
// inventory the installed record had already spent. The epoch is equal in
// both, so only the revision and the interval boundary can tell them apart.
CohortRegistry registry;
auto spent = draft();
spent.last_tick = Tick{1'000};
spent.revision = 5;
spent.classes = {{0, 100, 40, held(50), 0}};
CHECK(registry.install(built(spent)).has_value());
auto replayed = draft(); // tick 900, revision 4, the richer earlier state.
replayed.classes = {{0, 100, 40, held(100), 0}};
CHECK(refused(registry.replace(built(replayed)), CohortError::stale_revision));
// The installed record still holds what it held; nothing was restored.
CHECK(registry.find(HabitatId{7}, 3)->reserve() == held(50));
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'000});
// Re-sending the installed revision is refused as well: a write has to be
// strictly later, not merely not-earlier.
auto same_revision = spent;
same_revision.classes = {{0, 100, 40, held(100), 0}};
CHECK(refused(registry.replace(built(same_revision)), CohortError::stale_revision));
CHECK(registry.find(HabitatId{7}, 3)->reserve() == held(50));
// A newer revision that rewinds the boundary is refused too, so advancing a
// counter is not a way to rewind simulated time.
auto rewound = draft();
rewound.last_tick = Tick{999};
rewound.revision = 6;
CHECK(refused(registry.replace(built(rewound)), CohortError::backward_tick));
// Nor can re-acquiring ownership rewind it, though a new epoch may restart
// the revision series.
auto reacquired = draft();
reacquired.owner = {11, 9};
reacquired.revision = 1;
reacquired.last_tick = Tick{999};
CHECK(refused(registry.replace(built(reacquired)), CohortError::backward_tick));
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'000});
// A strictly later write at the same boundary is the ordinary case.
auto corrected = draft();
corrected.last_tick = Tick{1'000};
corrected.revision = 6;
corrected.classes = {{0, 100, 39, held(40), 0}};
CHECK(registry.replace(built(corrected)).has_value());
CHECK(registry.find(HabitatId{7}, 3)->count() == 39);
}
void a_moved_from_cohort_is_still_a_valid_cohort() {
// A moved-from record would keep its identities while losing its classes,
// which is the invalid cohort create refuses to build. The registry would
// then accept through a move what it rejects through construction, so the
// move is suppressed and decays to a copy.
static_assert(std::is_copy_constructible_v<Cohort>);
static_assert(std::is_copy_assignable_v<Cohort>);
// Move-constructing is still well formed; it selects the copy.
auto source = valid();
const auto before = 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)
auto moved = std::move(source);
// The source is untouched, because nothing was moved out of it.
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
CHECK(source == before);
// NOLINTNEXTLINE(bugprone-use-after-move)
CHECK(source.classes().size() == 3);
// NOLINTNEXTLINE(bugprone-use-after-move)
CHECK(source.count() == 75);
CHECK(moved == before);
// Both remain installable, and the source is not a record that bypasses
// create's rejection of a cohort with no classes.
CohortRegistry registry;
CHECK(registry.install(source).has_value());
CHECK(registry.find(HabitatId{7}, 3)->classes().size() == 3);
CHECK(registry.find(HabitatId{7}, 3)->count() == 75);
// The same holds for move assignment and for replacement.
auto target = valid();
// NOLINTNEXTLINE(performance-move-const-arg)
target = std::move(moved);
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
CHECK(moved.classes().size() == 3);
CHECK(target.classes().size() == 3);
auto later = draft();
later.revision = 5;
auto replacement = built(later);
// NOLINTNEXTLINE(performance-move-const-arg)
CHECK(registry.replace(std::move(replacement)).has_value());
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
CHECK(replacement.classes().size() == 3);
CHECK(registry.find(HabitatId{7}, 3)->count() == 75);
// No cohort anywhere reports an empty class list, which is what a genuine
// move would have produced and what create rejects by name.
auto hollow = draft();
hollow.classes.clear();
CHECK(refused(Cohort::create(hollow), CohortError::no_age_classes));
}
void one_reservoir_backs_one_cohort() {
// Two records sharing a reservoir would be the same inventory in two places,
// which is the whole point of the registry. Habitat and genome differing does
// not make it two stores.
CohortRegistry registry;
CHECK(registry.install(valid()).has_value());
auto sharing = draft();
sharing.genome = 4;
CHECK(refused(registry.install(built(sharing)), CohortError::duplicate_cohort));
auto elsewhere_sharing = draft();
elsewhere_sharing.habitat = {8};
CHECK(refused(registry.install(built(elsewhere_sharing)), CohortError::duplicate_cohort));
CHECK(registry.size() == 1);
auto separate = draft();
separate.genome = 4;
separate.reservoir = {2};
CHECK(registry.install(built(separate)).has_value());
CHECK(registry.size() == 2);
// A replacement cannot move a record to a different store either: that would
// be other inventory holding this cohort, not a later view of this one.
auto rehomed = draft();
rehomed.revision = 9;
rehomed.reservoir = {3};
CHECK(refused(registry.replace(built(rehomed)), CohortError::unknown_cohort));
CHECK(registry.find(HabitatId{7}, 3)->reservoir() == ReservoirId{1});
}
void vacancy_is_deliberate_and_keeps_the_record() {
// A population that reaches exactly zero has to be representable, or a caller
// would have to clamp, which ECOLOGY_MODEL forbids. It is a separate factory
// so it can never happen by leaving the classes out of a draft by accident.
auto empty_draft = draft();
empty_draft.classes.clear();
CHECK(refused(Cohort::create(empty_draft), CohortError::no_age_classes));
CHECK(refused(Cohort::vacant(draft()), CohortError::not_vacant));
const auto vacated = Cohort::vacant(empty_draft);
CHECK(vacated.has_value());
CHECK(vacated->is_vacant());
CHECK(vacated->count() == 0);
CHECK(vacated->residual() == 0);
CHECK(vacated->population() == 0);
CHECK(vacated->reserve() == Inventory{});
// Everything that identifies the record survives being empty. A vacant cohort
// is not an extinction: the genome and its habitat are both still here.
CHECK(vacated->genome() == 3);
CHECK(vacated->habitat() == HabitatId{7});
CHECK(vacated->owner() == Owner{11, 2});
CHECK(vacated->conversion() == 5);
CHECK(vacated->reservoir() == ReservoirId{1});
CHECK(vacated->last_tick() == Tick{900});
// The identities are still required, borrowed from the same checks.
auto anonymous = empty_draft;
anonymous.genome = 0;
CHECK(refused(Cohort::vacant(anonymous), CohortError::invalid_identity));
auto homeless = empty_draft;
homeless.reservoir = {};
CHECK(refused(Cohort::vacant(homeless), CohortError::invalid_identity));
// It installs and is kept like any other record.
CohortRegistry registry;
CHECK(registry.install(*vacated).has_value());
CHECK(registry.find(HabitatId{7}, 3)->is_vacant());
CHECK(registry.size() == 1);
}
void lineage_stays_the_archives_answer() {
// A cohort names a genome and never stores its ancestry, so it cannot claim a
// parentage the archive would contradict, and invents none from membership.
using namespace evo::biology;
GenomeDraft founder;
founder.id = 3;
founder.origin_event = 1;
founder.development_version = 1;
founder.capabilities = {{Capability::energy_conversion, 400, 0},
{Capability::membrane, 120, 0},
{Capability::target_size, 2'000, 0}};
const auto ancestor = Genome::create(founder);
CHECK(ancestor.has_value());
auto descended = founder;
descended.id = 9;
descended.origin_event = 2;
descended.parents = {3};
const auto child = Genome::create(descended);
CHECK(child.has_value());
LineageArchive archive;
CHECK(archive.admit(*ancestor).has_value());
CHECK(archive.admit(*child).has_value());
auto carrying = draft();
carrying.genome = 9;
const auto cohort = built(carrying);
// The cohort contributes the identity; the archive contributes the ancestry.
const auto line = archive.ancestry(cohort.genome());
CHECK(line.has_value());
CHECK(line->size() == 2);
CHECK(line->front() == 3);
CHECK(line->back() == 9);
CHECK(archive.find(cohort.genome()).has_value());
// Distinct genomes are never averaged into one, so each keeps its own record.
CohortRegistry registry;
CHECK(registry.install(cohort).has_value());
auto sibling = draft();
sibling.genome = 3;
sibling.reservoir = {2};
CHECK(registry.install(built(sibling)).has_value());
CHECK(registry.size() == 2);
CHECK(registry.find(HabitatId{7}, 3)->genome() != registry.find(HabitatId{7}, 9)->genome());
}
} // namespace
int main() try {
a_cohort_keeps_exactly_what_it_was_given();
the_record_keeps_a_distribution_and_not_an_average();
every_invariant_is_rejected_by_name();
one_habitat_and_genome_holds_one_cohort();
only_the_recorded_owner_may_replace_a_cohort();
one_reservoir_backs_one_cohort();
vacancy_is_deliberate_and_keeps_the_record();
an_epoch_alone_cannot_order_two_writes();
a_moved_from_cohort_is_still_a_valid_cohort();
lineage_stays_the_archives_answer();
std::cout << "PASS cohort state, declared resolution and exclusive ownership\n";
return 0;
} catch (...) {
return 1;
}