Round shares down and ages up, so a round trip never pays

M4.4 turns whole members of a cohort back into identified individuals, and does
nothing else: no habitat transfer, no persistence, no resolution-equivalence
claim. Materialization is instantaneous at the cohort's current tick, because
advancing time is M4.3's interval.

The named risk is that re-materialization becomes free healing, and it has two
separable sources. The arithmetic one is closed outright. A drawn member gets its
class share by integer division rounded down, because rounding up would create
biomass, and a class drawn empty hands over everything it held because a class
with no members may keep no reserve. A residual is never drawable, so an expected
density cannot become an individual.

Age is taken as the oldest the class admits. The exact age is unrecoverable, so
the question is only which direction to be wrong in, and every other answer makes
oscillation profitable: a member re-materialized at the bottom of its class is
younger than it was, and repeating that is immortality. Taking the top means a
round trip can only age someone. Both of these are the risk rather than ordinary
validation, and both mutations are detected: rounding the share up, and drawing
the age from the class floor.

The second source is the declared resolution itself and is stated rather than
mitigated. Members inside a class are indistinguishable by construction, so
collapsing a starving member with a well-provisioned one and materializing both
returns two average members, healing the first at the second's expense. The tests
demonstrate both halves instead of only the flattering one: a round trip is exact
when each class holds one member, and a coarse class conserves the total while
averaging the individuals. Conservation of the total is not evidence that any
individual is right, and the mitigation is the caller's choice of classes when it
collapses, not anything this code can recover.

Materialization produces exactly the record a collapse consumes, so the two
compose and are tested against each other rather than described as inverses. The
oscillation test runs twelve cycles and asserts every cycle that the conserved
total never moves, nobody holds more than the richest starting member held, and
nobody is younger than last cycle; it ends by asserting everyone has been pushed
to a class ceiling, which records the cost of the age rule rather than claiming
it away.

Release 37/37, analysis, ASan 37/37 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 15:41:49 -04:00
co-authored by Claude Opus 5
parent cabada70c4
commit 380d609f06
10 changed files with 1095 additions and 3 deletions
+235
View File
@@ -0,0 +1,235 @@
#include "evo/ecology/materialize.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 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 one member of a class is entitled to: the class reserve divided by the
// class count, per channel, rounded down. Rounding up would create biomass.
[[nodiscard]] accounting::Inventory share_of(const AgeClass& age) noexcept {
accounting::Inventory share{};
share.energy.value = age.reserve.energy.value / age.count;
for (std::size_t channel = 0; channel < share.matter.size(); ++channel) {
share.matter[channel].value = age.reserve.matter[channel].value / age.count;
}
return share;
}
// What rounding down left behind, per channel, strictly less than the count.
[[nodiscard]] accounting::Inventory remainder_of(const AgeClass& age) noexcept {
accounting::Inventory left{};
left.energy.value = age.reserve.energy.value % age.count;
for (std::size_t channel = 0; channel < left.matter.size(); ++channel) {
left.matter[channel].value = age.reserve.matter[channel].value % age.count;
}
return left;
}
} // namespace
std::expected<MaterializePlan, MaterializeError>
plan_materialize(const Cohort& before, const MaterializeRequest& request) {
if (request.owner.worker == 0 || request.owner.epoch == 0 || request.revision == 0 ||
request.first_identity == 0) {
return std::unexpected{MaterializeError::invalid_request};
}
if (request.owner.worker != before.owner().worker) {
return std::unexpected{MaterializeError::wrong_owner};
}
if (request.owner.epoch < before.owner().epoch) {
return std::unexpected{MaterializeError::stale_revision};
}
if (request.owner.epoch == before.owner().epoch && request.revision <= before.revision()) {
return std::unexpected{MaterializeError::stale_revision};
}
if (request.draws.empty()) {
return std::unexpected{MaterializeError::nothing_drawn};
}
auto classes = std::vector<AgeClass>{before.classes().begin(), before.classes().end()};
std::vector<std::size_t> seen;
std::uint64_t drawn = 0;
for (const auto& draw : request.draws) {
if (draw.age_class >= classes.size()) {
return std::unexpected{MaterializeError::unknown_age_class};
}
if (std::ranges::find(seen, draw.age_class) != seen.end()) {
return std::unexpected{MaterializeError::duplicate_age_class};
}
seen.push_back(draw.age_class);
if (draw.count == 0) {
return std::unexpected{MaterializeError::nothing_drawn};
}
// Only whole members present in the class. A residual is owed and not
// there, so it can never become an individual.
if (draw.count > classes[draw.age_class].count) {
return std::unexpected{MaterializeError::insufficient_members};
}
if (!add(drawn, draw.count)) {
return std::unexpected{MaterializeError::overflow};
}
}
if (request.reservoirs.size() != drawn) {
return std::unexpected{MaterializeError::reservoir_mismatch};
}
if (drawn > accounting::max_transfers) {
return std::unexpected{MaterializeError::overflow};
}
for (std::size_t index = 0; index < request.reservoirs.size(); ++index) {
const auto where = request.reservoirs[index];
if (where.value == 0 || where == before.reservoir()) {
return std::unexpected{MaterializeError::invalid_request};
}
if (std::ranges::find(request.reservoirs.begin() + static_cast<std::ptrdiff_t>(index) + 1,
request.reservoirs.end(), where) != request.reservoirs.end()) {
return std::unexpected{MaterializeError::duplicate_reservoir};
}
}
std::vector<ActiveMember> members;
std::vector<accounting::Transfer> legs;
members.reserve(drawn);
legs.reserve(drawn);
accounting::Inventory withdrawn{};
std::uint64_t identity = request.first_identity;
std::size_t next_reservoir = 0;
for (const auto& draw : request.draws) {
auto& age = classes[draw.age_class];
const auto share = share_of(age);
// A class drawn empty hands over everything it held: a class with no
// members may keep no reserve, and leaving it would be biomass nobody
// owns. The rounding remainder goes one unit each to the first members.
const auto emptied = draw.count == age.count;
const auto left = emptied ? remainder_of(age) : accounting::Inventory{};
for (std::uint64_t index = 0; index < draw.count; ++index) {
auto reserve = share;
if (emptied) {
if (index < left.energy.value) {
++reserve.energy.value;
}
for (std::size_t channel = 0; channel < reserve.matter.size(); ++channel) {
if (index < left.matter[channel].value) {
++reserve.matter[channel].value;
}
}
}
if (identity == 0 || !add(withdrawn, reserve)) {
return std::unexpected{MaterializeError::overflow};
}
members.push_back({identity, before.genome(), before.habitat(),
// The oldest the class admits. The exact age is not
// recoverable, and every other choice lets a round
// trip return someone younger than they were.
age.age_high - 1, request.reservoirs[next_reservoir], reserve,
MemberState::active});
legs.push_back({before.reservoir(), request.reservoirs[next_reservoir], reserve});
++next_reservoir;
if (identity == maximum) {
return std::unexpected{MaterializeError::overflow};
}
++identity;
}
age.count -= draw.count;
if (emptied) {
age.reserve = {};
} else {
age.reserve.energy.value -= share.energy.value * draw.count;
for (std::size_t channel = 0; channel < age.reserve.matter.size(); ++channel) {
age.reserve.matter[channel].value -= share.matter[channel].value * draw.count;
}
}
}
// A class with neither members nor an owed fraction is not a class any more.
std::erase_if(classes, [](const AgeClass& age) { return age.count == 0 && age.residual == 0; });
CohortDraft draft;
draft.representation_version = before.representation_version();
draft.habitat = before.habitat();
draft.genome = before.genome();
draft.owner = request.owner;
// Instantaneous: the clock is ADR-0038's business and this is not an interval.
draft.last_tick = before.last_tick();
draft.revision = request.revision;
draft.conversion = before.conversion();
draft.reservoir = before.reservoir();
draft.classes = classes;
draft.bound = request.bound;
const auto built = classes.empty() ? Cohort::vacant(draft) : Cohort::create(std::move(draft));
if (!built) {
return std::unexpected{MaterializeError::invalid_cohort};
}
MaterializePlan plan{before, *built};
plan.members_ = std::move(members);
plan.legs_ = std::move(legs);
plan.withdrawn_ = withdrawn;
return plan;
}
std::expected<std::vector<ActiveMember>, MaterializeError>
commit_materialize(accounting::Ledger& ledger, CohortRegistry& registry,
const MaterializePlan& plan) {
const auto& before = plan.before();
const auto installed = registry.find(before.habitat(), before.genome());
if (!installed) {
return std::unexpected{MaterializeError::not_installed};
}
if (*installed != before) {
return std::unexpected{MaterializeError::stale_plan};
}
const auto balances = ledger.balances();
if (before.reservoir().value > balances.size()) {
return std::unexpected{MaterializeError::stale_plan};
}
if (balances[before.reservoir().value - 1] != before.reserve()) {
return std::unexpected{MaterializeError::stale_plan};
}
// Each member's store must be empty first, so its reserve is the whole of
// what backs it rather than a part sharing a reservoir with inventory nobody
// counted. This is the rule a collapse destination has, from the other side.
for (const auto& member : plan.members()) {
if (member.reservoir.value > balances.size()) {
return std::unexpected{MaterializeError::stale_plan};
}
if (!empty(balances[member.reservoir.value - 1])) {
return std::unexpected{MaterializeError::reservoir_not_empty};
}
}
if (!plan.legs().empty()) {
if (ledger.last_action() == maximum) {
return std::unexpected{MaterializeError::ledger_failure};
}
if (!ledger.transfer(ledger.last_action() + 1, plan.legs())) {
return std::unexpected{MaterializeError::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{MaterializeError::stale_plan};
}
return std::vector<ActiveMember>{plan.members().begin(), plan.members().end()};
}
} // namespace evo::ecology