Files
aevolution/tests/equivalence_tests.cpp
T
dingoandClaude Opus 5 55a728acd4 Make who breeds part of the rule, so the divergence is attributable
The two runs allocated contested breeding slots in different orders: the
individual run by member insertion order, the aggregate run by stored class order,
which is youngest first. When eligible parents outnumber free slots that decides
which parents reproduce, for a reason that has nothing to do with averaging. The
control never reached the capacity boundary and so could not see it, which left
ADR-0040's central claim unsupported rather than merely imprecise.

The allocation order is part of the stated rule now, oldest first, honoured at both
resolutions: classes partition ages, so the oldest class holds the oldest members,
and ordering inside a class stays something only the individual run can see, which
is a resolution effect rather than an implementation difference.

A second control sits at the capacity boundary, twelve eligible parents contending
for one free slot, and both controls compare the whole distribution of members
rather than censuses. That change matters by itself: whoever breeds hands the same
investment to a child either way, so every total agrees while the distribution does
not, and a census-only control cannot see a different parent having bred. The
probe diverging only by tick 44 is that effect.

Attribution was verified by mutation rather than argued. Restoring the individual
run's insertion order fails the new control; restoring the aggregate run's
youngest-first order fails it; the earlier one-unit drift in aggregate upkeep still
fails the first. Since either allocation order alone fails, the reported divergence
is attributable to averaging.

My first attempt at the control was wrong and the same sweep caught it. I gave the
contested fixture ages descending with the index, reasoning that this made
insertion order differ from age order; it does the opposite, and the
individual-side mutation passed. Ages ascend now, so oldest-first disagrees with
both the insertion order and the stored class order. Without the sweep the new
control would have looked like it established attribution while covering half of
it.

Also added the depletion check the ADR's attribution argument relies on: a shared
store that ran out would make intake order-dependent too. I had written that the
fixture asserts this before it did, which is now true.

The measurements were regenerated and are unchanged. Saying so plainly rather than
as confirmation: the finding was about what the numbers can be attributed to, not
about their values.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-25 07:21:55 -04:00

896 lines
38 KiB
C++

#include "evo/ecology/materialize.hpp"
#include "evo/ecology/population.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <expected>
#include <iostream>
#include <ranges>
#include <source_location>
#include <stdexcept>
#include <string>
#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("equivalence line " + std::to_string(location.line()));
}
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
// ---------------------------------------------------------------------------
// The rule. Written once, applied at both resolutions: the individual run gives
// it one member at a time and the aggregate run gives it a class average and
// multiplies by the count. It is a fixture constant, not a simulation contract:
// ADR-0038 deliberately declines to choose an ecology, and this does not choose
// one for it. Energy is the only scarce axis so that divergence is attributable.
// ---------------------------------------------------------------------------
namespace rule {
constexpr std::uint64_t environment_energy = 300; // per tick, shared by the living
constexpr std::uint64_t matter_intake = 4; // per member per tick, abundant
constexpr std::uint64_t upkeep_energy = 2;
constexpr std::uint64_t upkeep_matter = 1;
constexpr std::uint64_t lifespan = 400;
constexpr std::uint64_t maturity = 50;
constexpr std::uint64_t threshold_energy = 100;
constexpr std::uint64_t investment_energy = 40;
constexpr std::uint64_t investment_matter = 40;
constexpr std::uint64_t capacity = 200;
// A member that cannot pay its upkeep starves. At class resolution the average
// member is asked the same question, which is exactly where the resolution bites.
[[nodiscard]] constexpr bool starves(std::uint64_t energy) noexcept {
return energy < upkeep_energy;
}
[[nodiscard]] constexpr bool breeds(std::uint64_t age, std::uint64_t energy) noexcept {
return age >= maturity && energy >= threshold_energy;
}
[[nodiscard]] constexpr std::uint64_t per_capita(std::uint64_t living) noexcept {
return living == 0 ? 0 : environment_energy / living;
}
// Who breeds when there are fewer free slots than eligible parents. This has to be
// part of the rule rather than a consequence of how each run happens to iterate:
// allocating contested slots in different orders changes which parents reproduce
// independently of any averaging, and a divergence caused by that is not a
// divergence caused by resolution. Oldest first, which both resolutions can honour:
// classes partition ages, so the oldest class holds the oldest members. Ordering
// within a class is the one thing only the individual run can see, and that is a
// resolution effect rather than an implementation difference.
} // namespace rule
// Matter behaves identically in all four channels here, so one number is tracked
// and mirrored into the four. Stated rather than left for a reader to infer.
Inventory spread(std::uint64_t energy, std::uint64_t matter) {
return {{energy},
{Femtograms{matter}, Femtograms{matter}, Femtograms{matter}, Femtograms{matter}}};
}
struct Census {
std::uint64_t living{};
std::uint64_t energy{};
std::uint64_t matter{};
std::uint64_t births{};
std::uint64_t deaths{};
auto operator<=>(const Census&) const = default;
};
// ---------------------------------------------------------------------------
// Individual resolution. Inventory is tracked as plain values and conservation is
// asserted arithmetically: this is the reference fixture, not a contract, and a
// reservoir per member would exceed the ledger's per-transaction leg bound.
// ---------------------------------------------------------------------------
struct Member {
std::uint64_t age{};
std::uint64_t energy{};
std::uint64_t matter{};
bool alive{true};
};
struct IndividualRun {
std::vector<Member> members;
std::uint64_t environment{};
std::uint64_t detritus_energy{};
std::uint64_t detritus_matter{};
std::uint64_t matter_store{};
std::uint64_t births{};
std::uint64_t deaths{};
std::uint64_t capacity{rule::capacity};
[[nodiscard]] Census census() const {
Census now;
for (const auto& member : members) {
if (!member.alive) {
continue;
}
++now.living;
now.energy += member.energy;
now.matter += member.matter;
}
now.births = births;
now.deaths = deaths;
return now;
}
[[nodiscard]] std::uint64_t total_energy() const {
std::uint64_t total = environment + detritus_energy;
for (const auto& member : members) {
if (member.alive) {
total += member.energy;
}
}
return total;
}
[[nodiscard]] std::uint64_t total_matter() const {
std::uint64_t total = matter_store + detritus_matter;
for (const auto& member : members) {
if (member.alive) {
total += member.matter;
}
}
return total;
}
void step() {
std::uint64_t living = 0;
for (const auto& member : members) {
living += member.alive ? 1 : 0;
}
const auto share = rule::per_capita(living);
// Starvation first, then upkeep, then intake, then ageing, then breeding.
// The aggregate run applies the same five stages in the same order.
for (auto& member : members) {
if (!member.alive) {
continue;
}
if (rule::starves(member.energy)) {
member.alive = false;
detritus_energy += member.energy;
detritus_matter += member.matter;
member.energy = 0;
member.matter = 0;
++deaths;
}
}
for (auto& member : members) {
if (!member.alive) {
continue;
}
member.energy -= rule::upkeep_energy;
detritus_energy += rule::upkeep_energy;
const auto paid = std::min(member.matter, rule::upkeep_matter);
member.matter -= paid;
detritus_matter += paid;
}
for (auto& member : members) {
if (!member.alive) {
continue;
}
// Bounded by what is there, so the arithmetic is safe, but the fixture
// is sized so that it never binds: if it ever did, intake would depend
// on the order members are visited in, and a divergence caused by that
// would look like a divergence caused by resolution. Checked rather
// than assumed, on both sides.
check(environment >= share);
check(matter_store >= rule::matter_intake);
const auto taken = std::min(share, environment);
environment -= taken;
member.energy += taken;
const auto gathered = std::min(rule::matter_intake, matter_store);
matter_store -= gathered;
member.matter += gathered;
}
for (auto& member : members) {
if (!member.alive) {
continue;
}
++member.age;
if (member.age >= rule::lifespan) {
member.alive = false;
detritus_energy += member.energy;
detritus_matter += member.matter;
member.energy = 0;
member.matter = 0;
++deaths;
}
}
std::uint64_t population = 0;
for (const auto& member : members) {
population += member.alive ? 1 : 0;
}
// Oldest first, as the rule requires, with the index breaking ties so the
// order is total. Insertion order would have allocated contested slots to
// different parents than the aggregate run does, which would have shown up
// in the comparison as if resolution had caused it.
std::vector<std::size_t> eligible;
for (std::size_t index = 0; index < members.size(); ++index) {
const auto& member = members[index];
if (!member.alive || !rule::breeds(member.age, member.energy)) {
continue;
}
if (member.matter < rule::investment_matter) {
continue;
}
eligible.push_back(index);
}
std::ranges::sort(eligible, [&](std::size_t left, std::size_t right) {
if (members[left].age != members[right].age) {
return members[left].age > members[right].age;
}
return left < right;
});
for (const auto index : eligible) {
if (population >= capacity) {
break;
}
auto& member = members[index];
member.energy -= rule::investment_energy;
member.matter -= rule::investment_matter;
members.push_back({0, rule::investment_energy, rule::investment_matter, true});
++population;
++births;
}
}
};
IndividualRun founding_individuals(std::uint64_t count) {
IndividualRun run;
// Deliberately spread: variation is what averaging destroys, so a fixture
// where everyone is identical would measure nothing.
for (std::uint64_t index = 0; index < count; ++index) {
run.members.push_back({index % 60, 20 + index, 50 + index, true});
}
run.environment = 100'000'000;
run.matter_store = 100'000'000;
return run;
}
// ---------------------------------------------------------------------------
// Aggregate resolution. Real cohort records, real ledger, real conversions. The
// class state is advanced by the same five stages applied to a class average.
// ---------------------------------------------------------------------------
struct AggregateClass {
std::uint64_t age_low{};
std::uint64_t age_high{};
std::uint64_t count{};
std::uint64_t energy{}; // held by the class in total
std::uint64_t matter{};
};
struct AggregateRun {
std::vector<AggregateClass> classes;
std::uint64_t width{};
std::uint64_t environment{};
std::uint64_t matter_store{};
std::uint64_t detritus_energy{};
std::uint64_t detritus_matter{};
std::uint64_t births{};
std::uint64_t deaths{};
std::uint64_t capacity{rule::capacity};
[[nodiscard]] Census census() const {
Census now;
for (const auto& age : classes) {
now.living += age.count;
now.energy += age.energy;
now.matter += age.matter;
}
now.births = births;
now.deaths = deaths;
return now;
}
[[nodiscard]] std::uint64_t total_energy() const {
std::uint64_t total = environment + detritus_energy;
for (const auto& age : classes) {
total += age.energy;
}
return total;
}
[[nodiscard]] std::uint64_t total_matter() const {
std::uint64_t total = matter_store + detritus_matter;
for (const auto& age : classes) {
total += age.matter;
}
return total;
}
void step() {
std::uint64_t living = 0;
for (const auto& age : classes) {
living += age.count;
}
const auto share = rule::per_capita(living);
// Starvation, judged on the class average. This is the resolution error:
// the average pays for everyone until it cannot, and then the class goes
// together, where individuals would have starved one at a time.
for (auto& age : classes) {
if (age.count == 0) {
continue;
}
if (rule::starves(age.energy / age.count)) {
detritus_energy += age.energy;
detritus_matter += age.matter;
deaths += age.count;
age.count = 0;
age.energy = 0;
age.matter = 0;
}
}
std::erase_if(classes, [](const AggregateClass& age) { return age.count == 0; });
for (auto& age : classes) {
const auto owed = rule::upkeep_energy * age.count;
age.energy -= owed;
detritus_energy += owed;
const auto paid = std::min(age.matter, rule::upkeep_matter * age.count);
age.matter -= paid;
detritus_matter += paid;
}
for (auto& age : classes) {
const auto wanted = share * age.count;
// The same bound, and the same reason for checking it: a shared store
// that ran out would make intake depend on the order classes are
// visited in, which is not a resolution effect.
check(environment >= wanted);
check(matter_store >= rule::matter_intake * age.count);
const auto taken = std::min(wanted, environment);
environment -= taken;
age.energy += taken;
const auto gathered = std::min(rule::matter_intake * age.count, matter_store);
matter_store -= gathered;
age.matter += gathered;
}
// Ageing shifts the class bounds rather than moving members between
// classes, so no member ever has to be placed by an age the record cannot
// know. A class is a birth cohort and stays one.
for (auto& age : classes) {
++age.age_low;
++age.age_high;
}
for (auto& age : classes) {
if (age.age_low >= rule::lifespan) {
detritus_energy += age.energy;
detritus_matter += age.matter;
deaths += age.count;
age.count = 0;
age.energy = 0;
age.matter = 0;
}
}
std::erase_if(classes, [](const AggregateClass& age) { return age.count == 0; });
std::uint64_t population = 0;
for (const auto& age : classes) {
population += age.count;
}
std::uint64_t newborns = 0;
std::uint64_t taken_energy = 0;
std::uint64_t taken_matter = 0;
// Oldest class first, which is the same allocation rule the individual run
// follows. The classes are held youngest-first, so this walks them in
// reverse rather than relying on the storage order.
for (auto& age : std::ranges::reverse_view(classes)) {
if (age.count == 0 || population + newborns >= capacity) {
continue;
}
const auto average_energy = age.energy / age.count;
const auto average_matter = age.matter / age.count;
if (!rule::breeds(age.age_low, average_energy)) {
continue;
}
if (average_matter < rule::investment_matter) {
continue;
}
auto breeding = age.count;
if (population + newborns + breeding > capacity) {
breeding = capacity - population - newborns;
}
const auto energy_moved = rule::investment_energy * breeding;
const auto matter_moved = rule::investment_matter * breeding;
if (energy_moved > age.energy || matter_moved > age.matter) {
continue;
}
age.energy -= energy_moved;
age.matter -= matter_moved;
taken_energy += energy_moved;
taken_matter += matter_moved;
newborns += breeding;
}
if (newborns > 0) {
// Ageing shifted every class up by one, so nothing now starts at zero.
// The youngest class is extended down to cover the newborns while it is
// still narrower than the declared width, and otherwise a new one
// opens. That keeps the classes contiguous, ascending and never wider
// than the width, which is what makes the state a representable
// cohort: bounds that merely shift would overlap the moment a class
// was opened part way through an interval.
const auto at = std::ranges::min_element(
classes, {}, [](const AggregateClass& age) { return age.age_low; });
if (at != classes.end() && at->age_low == 1 && at->age_high - at->age_low < width) {
at->age_low = 0;
at->count += newborns;
at->energy += taken_energy;
at->matter += taken_matter;
} else {
classes.push_back({0, 1, newborns, taken_energy, taken_matter});
}
births += newborns;
} else {
// A class that opened and then had no births still has to grow to the
// declared width rather than staying one tick wide for ever, or the
// structure would drift towards one class per tick.
const auto at = std::ranges::min_element(
classes, {}, [](const AggregateClass& age) { return age.age_low; });
if (at != classes.end() && at->age_low == 1 && at->age_high - at->age_low < width) {
at->age_low = 0;
}
}
std::ranges::sort(classes, {}, [](const AggregateClass& age) { return age.age_low; });
}
};
AggregateRun founding_classes(const IndividualRun& source, std::uint64_t width) {
AggregateRun run;
run.width = width;
run.environment = source.environment;
run.matter_store = source.matter_store;
for (const auto& member : source.members) {
if (!member.alive) {
continue;
}
const auto low = member.age / width * width;
const auto at = std::ranges::find_if(
run.classes, [&](const AggregateClass& age) { return age.age_low == low; });
if (at == run.classes.end()) {
run.classes.push_back({low, low + width, 1, member.energy, member.matter});
} else {
++at->count;
at->energy += member.energy;
at->matter += member.matter;
}
}
std::ranges::sort(run.classes, {}, [](const AggregateClass& age) { return age.age_low; });
check(run.classes.size() <= max_age_classes);
return run;
}
// Whether the aggregate state is something a cohort record can actually hold. The
// experiment is worthless if it measures a model the library could not represent,
// so this is checked at every step rather than assumed.
[[nodiscard]] bool representable(const AggregateRun& run) {
if (run.classes.empty()) {
return true; // Vacancy is representable; ADR-0036 has a factory for it.
}
CohortDraft probe;
probe.representation_version = cohort_representation_version;
probe.habitat = {7};
probe.genome = 3;
probe.owner = {11, 1};
probe.last_tick = Tick{0};
probe.revision = 1;
probe.conversion = 1;
probe.reservoir = {1};
for (const auto& age : run.classes) {
probe.classes.push_back(
{age.age_low, age.age_high, age.count, spread(age.energy, age.matter), 0});
}
return Cohort::create(std::move(probe)).has_value();
}
// Every living member as (age, energy, matter), sorted. Comparing censuses is not
// enough to establish that the two runs allocate contested breeding slots to the
// same parents: whoever breeds hands the same investment to a child either way, so
// the totals agree while the distribution does not, and the disagreement only
// reaches a census many ticks later. The control therefore compares distributions.
using Portrait = std::vector<std::array<std::uint64_t, 3>>;
[[nodiscard]] Portrait portrait(const IndividualRun& run) {
Portrait rows;
for (const auto& member : run.members) {
if (member.alive) {
rows.push_back({member.age, member.energy, member.matter});
}
}
std::ranges::sort(rows);
return rows;
}
// Only meaningful at width one, where a class holds members of a single age. A
// class may still hold several of them, because several can be born in one tick, so
// each is expanded into its equal share; the division has to be exact or the
// expansion would not be the distribution it claims to be, and that is checked
// rather than assumed.
[[nodiscard]] Portrait portrait(const AggregateRun& run) {
Portrait rows;
for (const auto& age : run.classes) {
check(age.count > 0);
check(age.energy % age.count == 0);
check(age.matter % age.count == 0);
for (std::uint64_t index = 0; index < age.count; ++index) {
rows.push_back({age.age_low, age.energy / age.count, age.matter / age.count});
}
}
std::ranges::sort(rows);
return rows;
}
// Ages ascend with the index, so the oldest member is the last inserted and the
// youngest class is the first stored. Oldest-first therefore disagrees with both of
// the orders this fixture could have drifted into: allocating in insertion order
// would pick the first member, and walking the classes as stored would pick the
// youngest class. Each of those, introduced alone, makes the two runs choose
// different parents, which is what the control has to be able to see.
IndividualRun founding_contested(std::uint64_t count, std::uint64_t capacity) {
IndividualRun run;
for (std::uint64_t index = 0; index < count; ++index) {
run.members.push_back({rule::maturity + index, 100 + index, 60 + index, true});
}
run.environment = 100'000'000;
run.matter_store = 100'000'000;
run.capacity = capacity;
return run;
}
// ---------------------------------------------------------------------------
// The instrument check. With one member per class a class average is that member,
// so the two runs must agree exactly. Without this a measured divergence could be
// aggregation error or a transcription mistake, and nothing would tell them apart.
// ---------------------------------------------------------------------------
void one_member_per_class_agrees_exactly() {
auto individual = founding_individuals(20);
// Distinct ages so every class holds exactly one member at width one.
for (std::size_t index = 0; index < individual.members.size(); ++index) {
individual.members[index].age = index;
}
auto aggregate = founding_classes(individual, 1);
CHECK(aggregate.classes.size() == individual.members.size());
CHECK(individual.census() == aggregate.census());
for (std::uint64_t tick = 0; tick < 40; ++tick) {
individual.step();
aggregate.step();
// Every tick, not only at the end: a divergence that cancelled would
// otherwise pass.
CHECK(individual.census() == aggregate.census());
CHECK(individual.total_energy() == aggregate.total_energy());
CHECK(individual.total_matter() == aggregate.total_matter());
CHECK(aggregate.classes.size() <= max_age_classes);
CHECK(representable(aggregate));
// Distributions, not just totals: a census agrees even when the two runs
// have given the same investment to different parents.
CHECK(portrait(individual) == portrait(aggregate));
}
// The control has to have exercised something, or it proves nothing.
CHECK(individual.census().births > 0);
CHECK(individual.census().living > 20);
}
// The capacity boundary, which the control above never reaches. With fewer free
// slots than eligible parents the allocation order decides which parents reproduce,
// and that is an implementation choice rather than a consequence of resolution: if
// the two runs order differently, the published divergence cannot be attributed to
// averaging at all. One member per class again, so the two must agree exactly, and
// distributions rather than censuses because a different parent breeding leaves
// every total unchanged.
void contested_breeding_slots_go_to_the_same_parents() {
constexpr std::uint64_t count = 12;
auto individual = founding_contested(count, count + 1);
auto aggregate = founding_classes(individual, 1);
aggregate.capacity = individual.capacity;
CHECK(aggregate.classes.size() == count);
CHECK(portrait(individual) == portrait(aggregate));
bool contested = false;
for (std::uint64_t tick = 0; tick < 40; ++tick) {
// Before the step, count how many parents are eligible against how many
// slots are free, so the test can prove it actually reached the boundary.
std::uint64_t living = 0;
std::uint64_t eligible = 0;
for (const auto& member : individual.members) {
if (!member.alive) {
continue;
}
++living;
if (rule::breeds(member.age + 1, member.energy) &&
member.matter >= rule::investment_matter) {
++eligible;
}
}
const auto free_slots = individual.capacity > living ? individual.capacity - living : 0;
if (eligible > free_slots && free_slots > 0) {
contested = true;
}
individual.step();
aggregate.step();
CHECK(portrait(individual) == portrait(aggregate));
CHECK(individual.census() == aggregate.census());
CHECK(individual.total_energy() == aggregate.total_energy());
CHECK(individual.total_matter() == aggregate.total_matter());
CHECK(representable(aggregate));
}
// The boundary has to have been reached, or this control proves nothing about
// allocation and is just the first control again with fewer members.
CHECK(contested);
CHECK(individual.census().births > 0);
CHECK(individual.census().living == individual.capacity);
}
// ---------------------------------------------------------------------------
// The scenario ECOLOGY_MODEL asks for, through the real conversions.
// ---------------------------------------------------------------------------
struct Divergence {
std::uint64_t width{};
std::uint64_t individual_living{};
std::uint64_t aggregate_living{};
std::uint64_t individual_energy{};
std::uint64_t aggregate_energy{};
std::uint64_t living_gap_per_thousand{};
std::uint64_t energy_gap_per_thousand{};
};
std::uint64_t gap_per_thousand(std::uint64_t left, std::uint64_t right) {
const auto high = std::max(left, right);
const auto low = std::min(left, right);
if (high == 0) {
return 0;
}
return (high - low) * 1000 / high;
}
Divergence measure(std::uint64_t width, std::uint64_t ticks) {
auto individual = founding_individuals(100);
auto aggregate = founding_classes(individual, width);
const auto opening_energy = individual.total_energy();
const auto opening_matter = individual.total_matter();
CHECK(aggregate.total_energy() == opening_energy);
CHECK(aggregate.total_matter() == opening_matter);
for (std::uint64_t tick = 0; tick < ticks; ++tick) {
individual.step();
aggregate.step();
// Conservation is exact on both sides at every tick, whatever the two
// populations do to each other.
CHECK(individual.total_energy() == opening_energy);
CHECK(individual.total_matter() == opening_matter);
CHECK(aggregate.total_energy() == opening_energy);
CHECK(aggregate.total_matter() == opening_matter);
CHECK(aggregate.classes.size() <= max_age_classes);
// Every step of the aggregate run is a state a cohort could hold, so the
// envelope describes this library and not a model it cannot represent.
CHECK(representable(aggregate));
}
const auto left = individual.census();
const auto right = aggregate.census();
return {width,
left.living,
right.living,
left.energy,
right.energy,
gap_per_thousand(left.living, right.living),
gap_per_thousand(left.energy, right.energy)};
}
std::vector<Divergence> envelope;
void aggregation_costs_something_and_coarse_classes_destroy_the_population() {
// Ten thousand ticks, a hundred funded individuals, five declared resolutions.
// Nothing here asserts the runs agree, and nothing tunes a bound to fit.
for (const std::uint64_t width : {10U, 25U, 50U, 100U, 200U}) {
const auto measured = measure(width, 10'000);
envelope.push_back(measured);
std::cout << "{\"class_width\":" << measured.width
<< ",\"individual_living\":" << measured.individual_living
<< ",\"aggregate_living\":" << measured.aggregate_living
<< ",\"individual_energy\":" << measured.individual_energy
<< ",\"aggregate_energy\":" << measured.aggregate_energy
<< ",\"living_gap_per_thousand\":" << measured.living_gap_per_thousand
<< ",\"energy_gap_per_thousand\":" << measured.energy_gap_per_thousand << "}\n";
}
// The individual run is the reference and must survive in every case, or the
// comparison is against a corpse and every gap below is meaningless.
for (const auto& measured : envelope) {
CHECK(measured.individual_living > 0);
}
// The measured result, reported rather than smoothed. Below a width the
// aggregate tracks the individuals; above it the aggregate population dies out
// entirely while the individuals persist. That is a false extinction caused by
// resolution alone: a whole class starves together the moment its average
// cannot pay upkeep, where individuals would have starved a few at a time and
// the survivors would have kept the per-capita share up.
std::uint64_t usable = 0;
std::uint64_t destroyed = 0;
for (const auto& measured : envelope) {
if (measured.aggregate_living == 0) {
++destroyed;
// A false extinction, since the reference population is alive.
CHECK(measured.individual_living > 0);
CHECK(measured.living_gap_per_thousand == 1000);
} else {
++usable;
// Where the aggregate survives, this is the envelope. The bounds are
// chosen above the measurement with room for platform variation; they
// are a regression guard, not a theoretical limit. See ADR-0040.
CHECK(measured.living_gap_per_thousand <= 600);
CHECK(measured.energy_gap_per_thousand <= 600);
}
}
// Both regimes have to appear, or this measured one thing and reported two.
CHECK(usable > 0);
CHECK(destroyed > 0);
// And the collapse is not monotone in class width. A narrower class is not
// reliably safer: the measurement finds a width that destroys the population
// while a coarser one sustains it. Whether a whole class dips below upkeep
// together depends on how the width lands against the population cycle that
// the shared per-capita intake drives, and this fixture does not characterise
// that further. The consequence for a tier policy is the point: a resolution
// cannot be chosen by assuming degradation worsens smoothly with coarseness.
// Asserted because it is surprising: if a change ever made it monotone, the
// warning written around this number would have become wrong.
bool out_of_order = false;
for (std::size_t index = 1; index < envelope.size(); ++index) {
if (envelope[index - 1].aggregate_living == 0 && envelope[index].aggregate_living > 0) {
out_of_order = true;
}
}
CHECK(out_of_order);
// And the runs must not agree anywhere. A change that quietly made them match
// would mean the fixture stopped exercising aggregation or the comparison
// stopped comparing, and either should fail rather than look like progress.
for (const auto& measured : envelope) {
CHECK(measured.living_gap_per_thousand > 0 || measured.energy_gap_per_thousand > 0);
}
}
// ---------------------------------------------------------------------------
// The same hundred individuals through the real conversions, end to end.
// ---------------------------------------------------------------------------
void the_full_scenario_conserves_and_keeps_its_genome() {
constexpr ReservoirId backing{1};
constexpr ReservoirId detritus{2};
constexpr ReservoirId escrow{3};
constexpr std::uint32_t first_member_store = 4;
auto individual = founding_individuals(100);
// One ledger reservoir per founder, plus the cohort, detritus and the escrow
// that stands for the environment. The escrow is seeded with what the
// environment holds, because inventory arriving with immigration has to come
// out of a store that already held it: a late transfer is not new production.
// Sized for the capacity rather than the founders: the population grows, and a
// draw of more members than there were founders would otherwise run off the
// end of the ledger and be reported as a stale plan.
std::vector<Inventory> opening(first_member_store + rule::capacity);
opening[escrow.value - 1] = spread(individual.environment, individual.matter_store);
std::vector<ActiveMember> members;
for (std::size_t index = 0; index < individual.members.size(); ++index) {
const auto& source = individual.members[index];
const ReservoirId store{static_cast<std::uint32_t>(first_member_store + index)};
const auto reserve = spread(source.energy, source.matter);
opening[store.value - 1] = reserve;
members.push_back({index + 1, 3, {7}, source.age, store, reserve, MemberState::active});
}
auto ledger = Ledger::create(opening);
CHECK(ledger.has_value());
const auto total = ledger->conserved_totals();
CollapseRequest gather;
gather.conversion = 1;
gather.owner = {11, 1};
gather.habitat = {7};
gather.genome = 3;
gather.tick = Tick{0};
gather.revision = 1;
gather.destination = backing;
for (std::uint64_t low = 0; low < rule::lifespan; low += 50) {
gather.bounds.push_back({low, low + 50});
}
const auto folded = plan_collapse(members, gather);
CHECK(folded.has_value());
CohortRegistry registry;
const auto installed = commit_collapse(*ledger, registry, *folded);
CHECK(installed.has_value());
CHECK(ledger->conserved_totals() == total);
CHECK(installed->count() == 100);
CHECK(installed->genome() == 3);
// Ten thousand ticks, advanced through M4.3 in intervals of fifty. The model
// sub-steps internally; the interval reports the net flux it produced.
auto aggregate = founding_classes(individual, 50);
auto cohort = *installed;
std::uint64_t revision = 1;
std::uint64_t tick = 0;
for (std::uint64_t interval = 0; interval < 200; ++interval) {
const auto before = aggregate.census();
const auto before_detritus_energy = aggregate.detritus_energy;
const auto before_detritus_matter = aggregate.detritus_matter;
const auto before_environment = aggregate.environment;
const auto before_store = aggregate.matter_store;
for (std::uint64_t step = 0; step < 50; ++step) {
aggregate.step();
}
tick += 50;
const auto after = aggregate.census();
if (after.living == 0) {
break;
}
AdvanceRequest proposal;
proposal.to = Tick{tick};
proposal.owner = cohort.owner();
proposal.revision = ++revision + 1;
proposal.detritus = detritus;
proposal.predators = detritus;
proposal.elsewhere = escrow;
proposal.bound = cohort.bound();
// The cohort's classes are the aggregate model's classes, and its fluxes
// are the net change the model produced over the interval.
for (const auto& age : aggregate.classes) {
proposal.after.push_back(
{age.age_low, age.age_high, age.count, spread(age.energy, age.matter), 0});
}
const auto grew = after.living > before.living;
proposal.flux.births = grew ? (after.living - before.living) * residual_scale : 0;
proposal.flux.deaths = grew ? 0 : (before.living - after.living) * residual_scale;
const auto shed_energy = aggregate.detritus_energy - before_detritus_energy;
const auto shed_matter = aggregate.detritus_matter - before_detritus_matter;
const auto drawn_energy = before_environment - aggregate.environment;
const auto drawn_matter = before_store - aggregate.matter_store;
proposal.flux.to_detritus = spread(shed_energy, shed_matter);
proposal.flux.from_elsewhere = spread(drawn_energy, drawn_matter);
const auto plan = plan_advance(cohort, proposal);
CHECK(plan.has_value());
const auto committed = commit_advance(*ledger, registry, *plan);
CHECK(committed.has_value());
cohort = *committed;
CHECK(ledger->conserved_totals() == total);
CHECK(ledger->balances()[backing.value - 1] == cohort.reserve());
CHECK(cohort.genome() == 3);
}
CHECK(tick == 10'000);
CHECK(!cohort.is_vacant());
// Materialize the survivors, which is the other end of the round trip.
std::vector<ClassDraw> draws;
std::uint64_t drawn = 0;
for (std::size_t index = 0; index < cohort.classes().size(); ++index) {
const auto count = cohort.classes()[index].count;
if (count == 0 || drawn + count > rule::capacity) {
continue;
}
draws.push_back({index, count});
drawn += count;
}
CHECK(!draws.empty());
MaterializeRequest unfold;
unfold.owner = cohort.owner();
unfold.revision = cohort.revision() + 1;
unfold.draws = draws;
unfold.first_identity = 100'000;
for (std::uint64_t index = 0; index < drawn; ++index) {
unfold.reservoirs.push_back({static_cast<std::uint32_t>(first_member_store + index)});
}
unfold.bound = cohort.bound();
// Those founder stores are empty now, because the collapse emptied them.
const auto spread_out = plan_materialize(cohort, unfold);
CHECK(spread_out.has_value());
const auto representatives = commit_materialize(*ledger, registry, *spread_out);
CHECK(representatives.has_value());
CHECK(ledger->conserved_totals() == total);
CHECK(representatives->size() == drawn);
// Genome identity survives the whole round trip, and nothing invented one.
for (const auto& member : *representatives) {
CHECK(member.genome == 3);
CHECK(member.habitat == HabitatId{7});
CHECK(member.state == MemberState::active);
}
CHECK(registry.size() == 1);
CHECK(registry.find(HabitatId{7}, 3)->genome() == 3);
}
} // namespace
int main() try {
// The instrument check runs first: a failing control voids every number below.
one_member_per_class_agrees_exactly();
contested_breeding_slots_go_to_the_same_parents();
aggregation_costs_something_and_coarse_classes_destroy_the_population();
the_full_scenario_conserves_and_keeps_its_genome();
std::cout << "PASS resolution comparison, exact control and a published envelope\n";
return 0;
} catch (...) {
return 1;
}