Refuse the whole conversion rather than drop the inconvenient member
M4.2 moves individuals into the M4.1 record and does only that: no advance, no materialization back, no transfer between habitats, no persistence. Collapse is two phases over one sample. plan_collapse reads the members once and returns an immutable plan that already carries a validated cohort; commit applies exactly that plan and derives nothing, so replaying a committed sample cannot resample, and a record that would not validate fails during planning rather than after the ledger has moved. A controlled, suspended, dead or unsettled member refuses the whole plan instead of being skipped. Filtering would let a caller obtain a plan by omitting whoever was inconvenient, and the result would be indistinguishable from an honest conversion, which is the adversarial selection the model forbids. Ages are carried into declared classes and a member fitting none refuses the plan, so nobody is quietly moved or dropped for having nowhere to go. Reserves are summed per class and never redistributed, so the distribution M4.1 exists to keep survives the move. Conservation runs through the ledger rather than beside it: one atomic transaction, one leg per member, each moving that member's entire reserve, so the conserved total is unchanged by construction. Dual representation is closed from both ends. A member must be emptied exactly, and a reservoir holding anything other than what was sampled makes the plan stale rather than partly applicable. The destination is proved available before anything moves, so no rejection can strand biomass in a reservoir nothing owns. Reversing that order is detected by the tests, which is the point: the ordering prevents the failure rather than a comment claiming it cannot happen. Two gaps are stated rather than implied covered. This cannot tell whether the members offered were all there were, so completeness is the caller's obligation. And emptying a reservoir is not withdrawing the right to use it, because the ledger has no removal. ReservoirId and Transfer gain the defaulted comparisons every other value type here already has, so a plan's legs can be compared. Additive, and ADR-0037 says so rather than claiming no M1 change. All ten guards were confirmed load-bearing by removing each and rerunning. One of my own expectations was wrong rather than the code: a replayed commit reported stale_plan where I expected destination_occupied. Both are pure checks made before anything moves, so only the diagnosis differed; the destination check runs first now, because "this already happened" says more about a replay. Release 35/35, analysis, ASan 35/35 and clang-format all ran and passed here. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,341 @@
|
||||
#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());
|
||||
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 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();
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user