Two defects from review of380d609. 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 in1a59b63. 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>
410 lines
18 KiB
C++
410 lines
18 KiB
C++
#include "evo/ecology/collapse.hpp"
|
|
|
|
#include <array>
|
|
#include <expected>
|
|
#include <iostream>
|
|
#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("collapse 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, CollapseError>& result, CollapseError expected) {
|
|
return !result.has_value() && result.error() == expected;
|
|
}
|
|
|
|
Inventory held(std::uint64_t energy, std::uint64_t matter) {
|
|
return {{energy},
|
|
{Femtograms{matter}, Femtograms{matter}, Femtograms{matter}, Femtograms{matter}}};
|
|
}
|
|
// Reservoirs 1..3 are the members, 4 is the cohort, 5 is an unrelated elsewhere.
|
|
constexpr std::size_t reservoir_count = 5;
|
|
constexpr ReservoirId destination{4};
|
|
|
|
std::vector<ActiveMember> members() {
|
|
return {{101, 3, {7}, 10, {1}, held(10, 100), MemberState::active},
|
|
{102, 3, {7}, 150, {2}, held(20, 200), MemberState::active},
|
|
{103, 3, {7}, 160, {3}, held(30, 300), MemberState::active}};
|
|
}
|
|
CollapseRequest request() {
|
|
CollapseRequest source;
|
|
source.conversion = 5;
|
|
source.owner = {11, 2};
|
|
source.habitat = {7};
|
|
source.genome = 3;
|
|
source.tick = Tick{900};
|
|
source.revision = 1;
|
|
source.destination = destination;
|
|
source.bounds = {{0, 100}, {100, 200}, {200, 300}};
|
|
source.bound = {2, held(1, 1)};
|
|
return source;
|
|
}
|
|
Ledger world() {
|
|
std::array<Inventory, reservoir_count> opening{};
|
|
const auto offered = members();
|
|
for (std::size_t index = 0; index < offered.size(); ++index) {
|
|
opening[index] = offered[index].reserve;
|
|
}
|
|
opening[4] = held(7, 7); // An unrelated reservoir, to prove nothing else moves.
|
|
auto ledger = Ledger::create(opening);
|
|
check(ledger.has_value());
|
|
return std::move(*ledger);
|
|
}
|
|
CollapsePlan planned() {
|
|
const auto offered = members();
|
|
auto plan = plan_collapse(offered, request());
|
|
check(plan.has_value());
|
|
return *plan;
|
|
}
|
|
|
|
void a_plan_totals_its_members_exactly() {
|
|
const auto plan = planned();
|
|
// Nothing is created or lost in the sample itself.
|
|
CHECK(plan.total() == held(60, 600));
|
|
CHECK(plan.legs().size() == 3);
|
|
CHECK(plan.members().size() == 3);
|
|
CHECK(plan.destination() == destination);
|
|
const auto offered = members();
|
|
for (std::size_t index = 0; index < offered.size(); ++index) {
|
|
// Each leg moves that member's whole reserve, so nothing stays behind.
|
|
CHECK(plan.legs()[index].from == offered[index].reservoir);
|
|
CHECK(plan.legs()[index].to == destination);
|
|
CHECK(plan.legs()[index].amount == offered[index].reserve);
|
|
CHECK(plan.members()[index] == offered[index].identity);
|
|
}
|
|
const auto& cohort = plan.cohort();
|
|
CHECK(cohort.habitat() == HabitatId{7});
|
|
CHECK(cohort.genome() == 3);
|
|
CHECK(cohort.owner() == Owner{11, 2});
|
|
CHECK(cohort.last_tick() == Tick{900});
|
|
CHECK(cohort.conversion() == 5);
|
|
CHECK(cohort.count() == 3);
|
|
CHECK(cohort.reserve() == plan.total());
|
|
}
|
|
|
|
void ages_and_the_distribution_survive_the_move() {
|
|
const auto plan = planned();
|
|
const auto classes = plan.cohort().classes();
|
|
// A bound nobody fell into is not carried, because there is no empty class.
|
|
CHECK(classes.size() == 2);
|
|
// The member aged 10 is alone in the first class with exactly its own reserve.
|
|
CHECK(classes[0].age_low == 0);
|
|
CHECK(classes[0].age_high == 100);
|
|
CHECK(classes[0].count == 1);
|
|
CHECK(classes[0].reserve == held(10, 100));
|
|
// The two in the second class keep their combined reserve, not a share of the
|
|
// total: a redistribution would conserve mass and destroy the distribution.
|
|
CHECK(classes[1].age_low == 100);
|
|
CHECK(classes[1].age_high == 200);
|
|
CHECK(classes[1].count == 2);
|
|
CHECK(classes[1].reserve == held(50, 500));
|
|
CHECK(classes[0].reserve != classes[1].reserve);
|
|
// Individuals are whole, so nothing is owed.
|
|
CHECK(classes[0].residual == 0);
|
|
CHECK(classes[1].residual == 0);
|
|
// Declaring one wide class is a resolution choice that produces the average
|
|
// this record exists to avoid; it is permitted and it is visibly coarser.
|
|
auto coarse = request();
|
|
coarse.bounds = {{0, 300}};
|
|
const auto offered = members();
|
|
const auto flat = plan_collapse(offered, coarse);
|
|
CHECK(flat.has_value());
|
|
CHECK(flat->cohort().classes().size() == 1);
|
|
CHECK(flat->cohort().reserve() == plan.cohort().reserve());
|
|
CHECK(flat->cohort().count() == plan.cohort().count());
|
|
}
|
|
|
|
void an_ineligible_member_refuses_the_whole_plan() {
|
|
// Skipping one would let a caller obtain a plan by omitting whoever was
|
|
// inconvenient, and the result would look exactly like an honest conversion.
|
|
for (const auto state : {MemberState::controlled, MemberState::suspended, MemberState::dead,
|
|
MemberState::unsettled}) {
|
|
auto offered = members();
|
|
offered[1].state = state;
|
|
CHECK(refused(plan_collapse(offered, request()), CollapseError::ineligible_member));
|
|
}
|
|
// A member of another habitat or genome is not part of this group at all.
|
|
auto foreign_habitat = members();
|
|
foreign_habitat[2].habitat = {8};
|
|
CHECK(refused(plan_collapse(foreign_habitat, request()), CollapseError::foreign_member));
|
|
auto foreign_genome = members();
|
|
foreign_genome[2].genome = 4;
|
|
CHECK(refused(plan_collapse(foreign_genome, request()), CollapseError::foreign_member));
|
|
// One member offered twice would be converted twice.
|
|
auto twice = members();
|
|
twice.push_back(twice[0]);
|
|
twice.back().reservoir = {5};
|
|
CHECK(refused(plan_collapse(twice, request()), CollapseError::duplicate_member));
|
|
// An age outside every declared bound cannot be placed without resetting it.
|
|
auto unplaceable = members();
|
|
unplaceable[2].age = 900;
|
|
CHECK(refused(plan_collapse(unplaceable, request()), CollapseError::unclassified_age));
|
|
// Gathering into a member's own reservoir would convert nothing.
|
|
auto into_itself = request();
|
|
into_itself.destination = {2};
|
|
const auto offered = members();
|
|
CHECK(refused(plan_collapse(offered, into_itself), CollapseError::invalid_request));
|
|
CHECK(refused(plan_collapse({}, request()), CollapseError::no_members));
|
|
std::vector<ActiveMember> crowd;
|
|
for (std::uint64_t index = 0; index <= max_transfers; ++index) {
|
|
crowd.push_back({index + 1, 3, {7}, 10, {1}, held(0, 0), MemberState::active});
|
|
}
|
|
CHECK(refused(plan_collapse(crowd, request()), CollapseError::too_many_members));
|
|
// Bounds are the same declared resolution ADR-0036 validates.
|
|
for (auto broken : {0U, 1U, 2U}) {
|
|
auto spoiled = request();
|
|
if (broken == 0) {
|
|
spoiled.bounds.clear();
|
|
} else if (broken == 1) {
|
|
spoiled.bounds[1].high = spoiled.bounds[1].low;
|
|
} else {
|
|
spoiled.bounds[1].low = spoiled.bounds[0].high - 1;
|
|
}
|
|
CHECK(refused(plan_collapse(offered, spoiled), CollapseError::invalid_bounds));
|
|
}
|
|
for (auto missing : {0U, 1U, 2U, 3U, 4U, 5U, 6U}) {
|
|
auto blank = request();
|
|
if (missing == 0) {
|
|
blank.conversion = 0;
|
|
} else if (missing == 1) {
|
|
blank.owner.worker = 0;
|
|
} else if (missing == 2) {
|
|
blank.owner.epoch = 0;
|
|
} else if (missing == 3) {
|
|
blank.habitat = {};
|
|
} else if (missing == 4) {
|
|
blank.genome = 0;
|
|
} else if (missing == 5) {
|
|
blank.revision = 0;
|
|
} else {
|
|
blank.destination = {};
|
|
}
|
|
CHECK(refused(plan_collapse(offered, blank), CollapseError::invalid_request));
|
|
}
|
|
}
|
|
|
|
void a_committed_collapse_conserves_and_empties_the_members() {
|
|
auto ledger = world();
|
|
CohortRegistry registry;
|
|
const auto before = ledger.conserved_totals();
|
|
const auto plan = planned();
|
|
const auto installed = commit_collapse(ledger, registry, plan);
|
|
CHECK(installed.has_value());
|
|
// Conservation is the ledger's property, not an assertion made beside it.
|
|
CHECK(ledger.conserved_totals() == before);
|
|
// Every member reservoir is empty: the same biomass is not in two tiers.
|
|
for (std::size_t index = 0; index < 3; ++index) {
|
|
CHECK(ledger.balances()[index] == Inventory{});
|
|
}
|
|
CHECK(ledger.balances()[destination.value - 1] == plan.total());
|
|
CHECK(ledger.balances()[4] == held(7, 7)); // Nothing unrelated moved.
|
|
CHECK(registry.size() == 1);
|
|
const auto found = registry.find(HabitatId{7}, 3);
|
|
CHECK(found.has_value());
|
|
CHECK(*found == plan.cohort());
|
|
CHECK(found->reserve() == plan.total());
|
|
// The cohort's recorded reserve is the whole of what backs it, not a part of
|
|
// it: nothing else shares the reservoir the conversion gathered into.
|
|
CHECK(ledger.balances()[destination.value - 1] == found->reserve());
|
|
CHECK(*installed == plan.cohort());
|
|
}
|
|
|
|
void every_rejection_leaves_the_world_as_it_was() {
|
|
// A plan that is never committed changes nothing at all.
|
|
auto untouched = world();
|
|
CohortRegistry idle;
|
|
const auto opening =
|
|
std::vector<Inventory>{untouched.balances().begin(), untouched.balances().end()};
|
|
const auto action = untouched.last_action();
|
|
const auto plan = planned();
|
|
CHECK(std::vector<Inventory>(untouched.balances().begin(), untouched.balances().end()) ==
|
|
opening);
|
|
CHECK(untouched.last_action() == action);
|
|
CHECK(idle.size() == 0);
|
|
|
|
// A destination already holding this habitat and genome refuses before the
|
|
// ledger is touched, so nothing is stranded in a reservoir nobody owns.
|
|
auto ledger = world();
|
|
CohortRegistry occupied;
|
|
auto sitting = request();
|
|
sitting.revision = 9;
|
|
const auto other = plan_collapse(members(), sitting);
|
|
CHECK(other.has_value());
|
|
CHECK(occupied.install(other->cohort()).has_value());
|
|
CHECK(refused(commit_collapse(ledger, occupied, plan), CollapseError::destination_occupied));
|
|
CHECK(std::vector<Inventory>(ledger.balances().begin(), ledger.balances().end()) == opening);
|
|
CHECK(ledger.last_action() == action);
|
|
CHECK(occupied.size() == 1);
|
|
|
|
// A sample that has gone stale is refused rather than partly applied. Moving
|
|
// only the sampled part would leave a remainder in the member's reservoir.
|
|
auto drifted = world();
|
|
CohortRegistry empty_registry;
|
|
const std::array leak{Transfer{{1}, {5}, held(1, 1)}};
|
|
CHECK(drifted.transfer(drifted.last_action() + 1, leak).has_value());
|
|
const auto after_leak =
|
|
std::vector<Inventory>{drifted.balances().begin(), drifted.balances().end()};
|
|
const auto leaked_action = drifted.last_action();
|
|
CHECK(refused(commit_collapse(drifted, empty_registry, plan), CollapseError::stale_plan));
|
|
CHECK(std::vector<Inventory>(drifted.balances().begin(), drifted.balances().end()) ==
|
|
after_leak);
|
|
CHECK(drifted.last_action() == leaked_action);
|
|
CHECK(empty_registry.size() == 0);
|
|
|
|
// A member holding more than was sampled is equally stale: the surplus would
|
|
// stay behind as the same biomass in a second tier.
|
|
auto enriched = world();
|
|
CohortRegistry spare;
|
|
const std::array gift{Transfer{{5}, {1}, held(1, 1)}};
|
|
CHECK(enriched.transfer(enriched.last_action() + 1, gift).has_value());
|
|
CHECK(refused(commit_collapse(enriched, spare, plan), CollapseError::stale_plan));
|
|
CHECK(enriched.balances()[0] == held(11, 101));
|
|
CHECK(spare.size() == 0);
|
|
}
|
|
|
|
void a_destination_holding_anything_is_refused() {
|
|
// Gathering into an occupied reservoir would mix unrelated inventory into the
|
|
// cohort's backing store while the cohort recorded only what it sampled, so
|
|
// its reserve would understate what backs it and the surplus would be owned
|
|
// by nobody. Reservoir 5 already holds something in this fixture.
|
|
auto ledger = world();
|
|
CohortRegistry registry;
|
|
auto elsewhere = request();
|
|
elsewhere.destination = {5};
|
|
const auto offered = members();
|
|
const auto plan = plan_collapse(offered, elsewhere);
|
|
CHECK(plan.has_value());
|
|
CHECK(plan->total() == held(60, 600));
|
|
const auto opening = std::vector<Inventory>{ledger.balances().begin(), ledger.balances().end()};
|
|
const auto action = ledger.last_action();
|
|
CHECK(refused(commit_collapse(ledger, registry, *plan), CollapseError::destination_not_empty));
|
|
// Unfixed this committed, leaving the reservoir holding 67 energy against a
|
|
// cohort recording 60. Rejection must leave both sides exactly as they were.
|
|
CHECK(std::vector<Inventory>(ledger.balances().begin(), ledger.balances().end()) == opening);
|
|
CHECK(ledger.balances()[4] == held(7, 7));
|
|
CHECK(ledger.last_action() == action);
|
|
CHECK(registry.size() == 0);
|
|
// Emptying that reservoir first makes the same plan committable, and then the
|
|
// cohort's reserve is the whole of what backs it.
|
|
const std::array clear{Transfer{{5}, {4}, held(7, 7)}};
|
|
CHECK(ledger.transfer(ledger.last_action() + 1, clear).has_value());
|
|
const auto installed = commit_collapse(ledger, registry, *plan);
|
|
CHECK(installed.has_value());
|
|
CHECK(ledger.balances()[4] == plan->total());
|
|
CHECK(ledger.balances()[4] == installed->reserve());
|
|
}
|
|
|
|
void a_destination_owned_by_another_cohort_is_refused() {
|
|
// An empty reservoir is not an available one. A cohort holding nothing still
|
|
// owns its store, and gathering into it would put inventory there that its own
|
|
// record does not account for. Worse, the shared-reservoir rule would have
|
|
// refused the install only after the transfer, leaving the members emptied and
|
|
// their biomass in a reservoir nothing accounts for.
|
|
auto ledger = world();
|
|
CohortRegistry registry;
|
|
CohortDraft squatter;
|
|
squatter.representation_version = cohort_representation_version;
|
|
squatter.habitat = {7};
|
|
squatter.genome = 99; // A different lineage, so not the habitat/genome guard.
|
|
squatter.owner = {11, 2};
|
|
squatter.last_tick = evo::Tick{900};
|
|
squatter.revision = 1;
|
|
squatter.conversion = 1;
|
|
squatter.reservoir = destination; // The reservoir this collapse would gather into.
|
|
squatter.classes = {{0, 100, 1, Inventory{}, 0}};
|
|
const auto sitting = Cohort::create(squatter);
|
|
CHECK(sitting.has_value());
|
|
CHECK(registry.install(*sitting).has_value());
|
|
const auto plan = planned();
|
|
const auto opening = std::vector<Inventory>{ledger.balances().begin(), ledger.balances().end()};
|
|
const auto action = ledger.last_action();
|
|
CHECK(refused(commit_collapse(ledger, registry, plan), CollapseError::destination_owned));
|
|
CHECK(std::vector<Inventory>(ledger.balances().begin(), ledger.balances().end()) == opening);
|
|
CHECK(ledger.last_action() == action);
|
|
CHECK(registry.size() == 1);
|
|
CHECK(registry.find(HabitatId{7}, 99)->reserve() == Inventory{});
|
|
}
|
|
|
|
void one_plan_cannot_be_committed_twice() {
|
|
auto ledger = world();
|
|
CohortRegistry registry;
|
|
const auto plan = planned();
|
|
CHECK(commit_collapse(ledger, registry, plan).has_value());
|
|
const auto settled = std::vector<Inventory>{ledger.balances().begin(), ledger.balances().end()};
|
|
const auto action = ledger.last_action();
|
|
// The destination is now occupied, so the replay is refused before the ledger
|
|
// is reached and inventory is not moved a second time.
|
|
CHECK(refused(commit_collapse(ledger, registry, plan), CollapseError::destination_occupied));
|
|
CHECK(std::vector<Inventory>(ledger.balances().begin(), ledger.balances().end()) == settled);
|
|
CHECK(ledger.last_action() == action);
|
|
CHECK(registry.size() == 1);
|
|
CHECK(registry.find(HabitatId{7}, 3)->count() == 3);
|
|
// Even into a fresh registry the members are empty now, so the sample that
|
|
// said they held something is stale and the replay still moves nothing.
|
|
CohortRegistry fresh;
|
|
CHECK(refused(commit_collapse(ledger, fresh, plan), CollapseError::stale_plan));
|
|
CHECK(std::vector<Inventory>(ledger.balances().begin(), ledger.balances().end()) == settled);
|
|
CHECK(fresh.size() == 0);
|
|
}
|
|
|
|
void a_moved_from_plan_is_still_a_whole_plan() {
|
|
// A moved-from plan would keep its identities and lose its legs, and
|
|
// committing it would move nothing while reporting a conversion.
|
|
static_assert(std::is_copy_constructible_v<CollapsePlan>);
|
|
static_assert(std::is_copy_assignable_v<CollapsePlan>);
|
|
static_assert(!std::is_nothrow_move_constructible_v<CollapsePlan>);
|
|
auto source = planned();
|
|
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)
|
|
const auto moved = std::move(source);
|
|
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
|
|
CHECK(source == before);
|
|
// NOLINTNEXTLINE(bugprone-use-after-move)
|
|
CHECK(source.legs().size() == 3);
|
|
// NOLINTNEXTLINE(bugprone-use-after-move)
|
|
CHECK(source.cohort().count() == 3);
|
|
CHECK(moved == before);
|
|
// The supposedly moved-from plan still converts everyone it sampled.
|
|
auto ledger = world();
|
|
CohortRegistry registry;
|
|
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
|
|
const auto installed = commit_collapse(ledger, registry, source);
|
|
CHECK(installed.has_value());
|
|
CHECK(installed->count() == 3);
|
|
CHECK(ledger.balances()[destination.value - 1] == held(60, 600));
|
|
}
|
|
} // namespace
|
|
int main() try {
|
|
a_plan_totals_its_members_exactly();
|
|
ages_and_the_distribution_survive_the_move();
|
|
an_ineligible_member_refuses_the_whole_plan();
|
|
a_committed_collapse_conserves_and_empties_the_members();
|
|
every_rejection_leaves_the_world_as_it_was();
|
|
a_destination_holding_anything_is_refused();
|
|
a_destination_owned_by_another_cohort_is_refused();
|
|
one_plan_cannot_be_committed_twice();
|
|
a_moved_from_plan_is_still_a_whole_plan();
|
|
std::cout << "PASS collapse sampling, exact conservation and unchanged-on-rejection\n";
|
|
return 0;
|
|
} catch (...) {
|
|
return 1;
|
|
}
|