Files
aevolution/tests/cohort_tests.cpp
T
dingoandClaude Opus 5 5a4c34a903 An epoch cannot order two writes an owner makes inside it
Two defects from review of 1c8b292.

Replacement checked the ownership epoch and nothing that ordered two writes made
inside one, so an owner could replay its own earlier record: a cohort installed
at tick 1,000 holding 50 picojoules accepted its own tick-900 record holding 100,
restoring inventory the installed one had already spent. A cohort now carries a
revision that strictly increases within an epoch, and a repeated revision is
refused as well as an older one, because a write has to be strictly later rather
than merely not earlier. A newer epoch may restart the series, since re-acquiring
ownership begins a new one, but the interval boundary is checked independently of
both, so neither advancing a revision nor re-acquiring ownership rewinds
simulated time. A later revision at the same boundary stays legitimate: that is a
correction, not a rewind.

The implicit move emptied a cohort's age classes while keeping its habitat,
genome and owner, so a moved-from record was exactly the invalid cohort create
refuses to build, and the registry accepted through a move what it rejects
through construction. The type is copy-only now, so a move decays to a copy and
the source stays whole. ADR-0030 made the genome copy-only for this same reason
in M3.1; the precedent existed and was not applied when this type was written.

Both fixes were confirmed load-bearing by reverting each alone. Removing either
ordering check fails the new regression. Removing the copy declarations fails to
compile, and not only through the static assertion: with that also removed, MSVC
proves the code after the class-count check unreachable, having established that
a moved-from vector is empty and the check always throws. That is a compile-time
proof rather than an execution, so the runtime path was checked separately under
ASan, where the same mutation exits 1.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 09:05:05 -04:00

429 lines
19 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.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.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}) {
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 {
blank.conversion = 0;
}
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;
auto other_habitat = draft();
other_habitat.habitat = {8};
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 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;
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();
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;
}