Files
aevolution/src/ecology/cohort.cpp
T
dingoandClaude Opus 5 14e0c1af5e An empty reservoir is not an unowned one
Two defects from review of 380d609.

Materialization treated an empty reservoir as available. A vacant cohort, or one
holding nothing, still owns its store, so a draw could credit it while the owning
record went on recording nothing: the same inventory in two places, reached from
the opposite direction to the destination defect in 1a59b63. Destinations are
checked against the registry's ownership now, not just their balance, and the
registry answers whether a reservoir is used rather than callers inferring it from
what the reservoir contains.

The same hole existed on the collapse side in a worse form, found by asking
whether the reported defect had a sibling. Nothing verified the destination was
unowned, so the shared-reservoir rule added in M4.3 would have refused the install
only after the transfer had run, leaving the members emptied and their biomass in
a reservoir nothing accounted for. That is exactly the stranding the M4.2 ordering
was chosen to prevent, defeated by a check that ran too late. Whichever registry
step follows a transfer is now proved to succeed before it, through may_install
and may_replace queries that install and replace delegate to, so there is one rule
and not a restatement that can drift.

The second finding was a functional gap the oscillation test hid by discarding its
registry each cycle. A full draw leaves a vacant record, which ADR-0036 retains
because absence is not extinction, and collapse then refused that habitat and
genome as occupied: a full materialization was a one-way door out of a habitat and
the lineage could never return. Collapse repopulates a vacant record in place now,
continuing its ownership and revision series rather than restarting them, and a
record still holding a population is refused, because merging two silently is not
a conversion. The test keeps one registry for all twelve cycles and asserts the
revision continues.

Four of the five new guards are load-bearing. The fifth is not and is recorded as
such: the may_replace pre-check in commit_materialize is unreachable given the
checks before it, since the installed record is already proved equal to the plan's
origin and the result differs only by a later revision. It is kept because it is
the right place for the guard and its collapse-side sibling is genuinely
reachable, not because it is exercised.

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

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

260 lines
10 KiB
C++

#include "evo/ecology/cohort.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;
}
// Summed per channel: a total mass is not an additional inventory, so the
// channels are added separately and any one of them may be what overflows.
[[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;
}
[[nodiscard]] bool empty(const accounting::Inventory& inventory) noexcept {
return inventory == accounting::Inventory{};
}
// What the registry is keyed by, which is also the uniqueness it enforces: one
// record per habitat and genome.
struct Key {
HabitatId habitat;
std::uint64_t genome;
auto operator<=>(const Key&) const = default;
};
[[nodiscard]] Key key_of(const Cohort& cohort) noexcept {
return {cohort.habitat(), cohort.genome()};
}
} // namespace
std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
if (draft.representation_version != cohort_representation_version) {
return std::unexpected{CohortError::unsupported_version};
}
// 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.reservoir.value == 0) {
return std::unexpected{CohortError::invalid_identity};
}
if (draft.classes.empty()) {
return std::unexpected{CohortError::no_age_classes};
}
if (draft.classes.size() > max_age_classes) {
return std::unexpected{CohortError::overflow};
}
std::uint64_t count = 0;
accounting::Inventory reserve{};
std::uint64_t residual = 0;
for (std::size_t index = 0; index < draft.classes.size(); ++index) {
const auto& age = draft.classes[index];
// Ascending, non-overlapping and non-empty. An empty or overlapping range
// would make a member's class ambiguous or impossible.
if (age.age_high <= age.age_low) {
return std::unexpected{CohortError::unordered_age_classes};
}
if (index > 0 && age.age_low < draft.classes[index - 1].age_high) {
return std::unexpected{CohortError::unordered_age_classes};
}
// A residual is a fraction of one member. At a whole member it is one.
if (age.residual >= residual_scale) {
return std::unexpected{CohortError::residual_out_of_range};
}
// A class with neither members nor a fraction owed is not a class; it is
// a boundary someone declared and left empty.
if (age.count == 0 && age.residual == 0) {
return std::unexpected{CohortError::empty_age_class};
}
// Reserve belongs to members. A class with no members holding inventory
// would be biomass owned by nobody, which no later transfer could settle.
if (age.count == 0 && !empty(age.reserve)) {
return std::unexpected{CohortError::unowned_reserve};
}
if (!add(count, age.count) || !add(reserve, age.reserve) || !add(residual, age.residual)) {
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;
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.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_) {
// Construction proved this cannot overflow, so the sum is exact here.
total += age.count;
}
return total;
}
accounting::Inventory Cohort::reserve() const noexcept {
accounting::Inventory total{};
for (const auto& age : classes_) {
total.energy.value += age.reserve.energy.value;
for (std::size_t channel = 0; channel < total.matter.size(); ++channel) {
total.matter[channel].value += age.reserve.matter[channel].value;
}
}
return total;
}
std::uint64_t Cohort::residual() const noexcept {
std::uint64_t total = 0;
for (const auto& age : classes_) {
total += age.residual;
}
return total;
}
std::uint64_t Cohort::population() const noexcept {
// Construction proved this cannot overflow.
return count() * residual_scale + residual();
}
bool CohortRegistry::reservoir_used(accounting::ReservoirId reservoir) const noexcept {
return std::ranges::any_of(cohorts_,
[&](const Cohort& other) { return other.reservoir() == reservoir; });
}
std::expected<void, CohortError> CohortRegistry::may_install(const Cohort& cohort) const {
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 (reservoir_used(cohort.reservoir())) {
return std::unexpected{CohortError::duplicate_cohort};
}
if (cohorts_.size() >= max_cohorts) {
return std::unexpected{CohortError::registry_full};
}
return {};
}
std::expected<void, CohortError> CohortRegistry::install(const Cohort& cohort) {
if (const auto allowed = may_install(cohort); !allowed) {
return allowed;
}
const auto at = std::ranges::lower_bound(cohorts_, key_of(cohort), {}, key_of);
cohorts_.insert(at, cohort);
return {};
}
std::expected<void, CohortError> CohortRegistry::replace(const Cohort& cohort) {
if (const auto allowed = may_replace(cohort); !allowed) {
return allowed;
}
const auto at = std::ranges::lower_bound(cohorts_, key_of(cohort), {}, key_of);
*at = cohort;
return {};
}
std::expected<void, CohortError> CohortRegistry::may_replace(const Cohort& cohort) const {
const auto wanted = key_of(cohort);
const auto at = std::ranges::lower_bound(cohorts_, wanted, {}, key_of);
// Habitat and genome are the record's membership, so a replacement changing
// either is not a newer view of this cohort; it names one that is not here.
if (at == cohorts_.end() || key_of(*at) != wanted) {
return std::unexpected{CohortError::unknown_cohort};
}
if (cohort.owner().worker != at->owner().worker) {
return std::unexpected{CohortError::wrong_owner};
}
if (cohort.owner().epoch < at->owner().epoch) {
return std::unexpected{CohortError::stale_epoch};
}
// Within one epoch the revision is what orders two writes. Without it an
// owner could replay its own earlier record and restore inventory the
// installed one had already spent, because the epoch alone cannot tell the
// two apart. A newer epoch may restart the series, since re-acquiring
// ownership begins a new one.
if (cohort.owner().epoch == at->owner().epoch && cohort.revision() <= at->revision()) {
return std::unexpected{CohortError::stale_revision};
}
// Simulated time does not run backwards, whatever the epoch. This holds even
// where a new epoch restarts the revision series, so re-acquiring ownership
// is not a way to rewind the record.
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};
}
return {};
}
std::expected<Cohort, CohortError> CohortRegistry::find(HabitatId habitat,
std::uint64_t genome) const {
const Key wanted{habitat, genome};
const auto at = std::ranges::lower_bound(cohorts_, wanted, {}, key_of);
if (at == cohorts_.end() || key_of(*at) != wanted) {
return std::unexpected{CohortError::unknown_cohort};
}
return *at;
}
} // namespace evo::ecology