Files
aevolution/src/processes/ecosystem.cpp
T
dingoandClaude Opus 5 eaf58f2b85 Drive the energy cycle with measured ecosystem episodes
Close M2 with a deterministic driver that owns one community and one
seeded stream, holds no inventory and emits only the terminal, feeding
and reproduction intents the earlier increments already accept. No
simulation contract changed to make the cycle run unattended.

Two limits shaped the design. Identities are never reused and slots are
capped, so one community supports a bounded number of consumer lifetimes
and is not a population. No maintenance cost exists, so a consumer that
is never eaten never dies, and inventing a starvation rule here would
settle a question ENERGY_MODEL leaves open inside a measurement harness.
The harness therefore measures many bounded episodes, taking mortality
from predation and from a configured lifespan delivered as an ADR-0027
host terminal fact. Lifespan bounds an episode; it is not senescence.

The driver must never submit a batch the community rejects, so it probes
a discarded copy each tick to size bites against the state feeding will
actually see, claims each target for one feeder, and excludes a bitten
consumer from acting. A rejected tick is reported as a driver defect
rather than absorbed as ecology.

Across 64 seeds the suite steps tick by tick, requiring exact conserved
totals at every tick and an identical report on replay, and covers both
mortality paths, slot exhaustion, tick-limit termination, lineage
attribution, episode independence and configuration rejection.
evo-sim --ecosystem reports seeded ensembles: 3,000 episodes advanced
1,093,007 ticks, all reaching extinction, with deaths reconciling exactly
against founders plus births. That demonstrates arithmetic and turnover,
not ecological plausibility; strategy constants are chosen inputs.

Native Release, clang-tidy analysis, ASan and format checks pass 11/11;
golden d61ad5bf0c928c76 is unchanged. Linux CI has not run yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 17:38:34 -04:00

309 lines
12 KiB
C++

#include "evo/processes/ecosystem.hpp"
#include <algorithm>
#include <limits>
#include <utility>
namespace evo::processes {
namespace {
constexpr std::size_t slot_limit = max_consumers + 2;
std::size_t balance_index(std::uint32_t actor) noexcept {
return actor == 1 ? 2 : static_cast<std::size_t>(actor) + 2;
}
bool covers(const accounting::Inventory& need, const accounting::Inventory& have) noexcept {
if (need.energy > have.energy) {
return false;
}
for (std::size_t index = 0; index < 4; ++index) {
if (need.matter[index] > have.matter[index]) {
return false;
}
}
return true;
}
// Cumulative diagnostics saturate; they are reported totals, not owned inventory.
void accumulate(accounting::Inventory& total, const accounting::Inventory& amount) noexcept {
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
total.energy.value = amount.energy.value > maximum - total.energy.value
? maximum
: total.energy.value + amount.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
total.matter[index].value = amount.matter[index].value > maximum - total.matter[index].value
? maximum
: total.matter[index].value + amount.matter[index].value;
}
}
// Non-cryptographic combiner, used only to compare results across platforms.
std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept {
return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U));
}
} // namespace
EcosystemEpisode::EcosystemEpisode(FeedingCommunity community, std::vector<StrategyConfig> founders,
EcosystemConfig config, std::uint64_t seed)
: community_{std::move(community)}, founders_{std::move(founders)}, config_{config},
random_{seed}, seed_{seed} {}
std::expected<EcosystemEpisode, EcosystemError>
EcosystemEpisode::create(EcosystemConfig config, std::span<const StrategyConfig> founders,
std::uint64_t seed) {
if (founders.empty() || founders.size() > max_strategies || config.tick_limit == 0) {
return std::unexpected{EcosystemError::invalid_config};
}
for (const auto& founder : founders) {
// A zero lifespan would retire a founder before it ever acted; a zero
// investment would request a birth the community rejects outright.
if (founder.lifespan == 0 || founder.investment == accounting::Inventory{} ||
founder.assimilation_per_thousand > 1000) {
return std::unexpected{EcosystemError::invalid_config};
}
}
std::vector<ConsumerConfig> consumers;
consumers.reserve(founders.size());
for (const auto& founder : founders) {
consumers.push_back(
{founder.opening, founder.intake_limit, founder.assimilation_per_thousand});
}
auto community = FeedingCommunity::create(
config.producer, config.source, config.nutrients, consumers, config.decomposition,
{config.capacity, config.construction_per_thousand, {}});
if (!community) {
return std::unexpected{EcosystemError::invalid_config};
}
return EcosystemEpisode{
std::move(*community), {founders.begin(), founders.end()}, config, seed};
}
std::uint32_t EcosystemEpisode::lineage(std::uint32_t id) const noexcept {
if (id < 2) {
return 0;
}
// A child always occupies a higher slot than its parent, so this terminates.
auto current = id;
while (true) {
const auto exists = community_.born(current);
if (!exists || !*exists) {
return 0;
}
const auto ancestor = community_.parent(current);
if (!ancestor) {
return 0;
}
if (*ancestor == 0) {
return current;
}
current = *ancestor;
}
}
const StrategyConfig& EcosystemEpisode::strategy(std::uint32_t id) const noexcept {
const auto root = lineage(id);
// Every born consumer descends from a founder; index zero is a safe fallback.
const auto offset = root >= 2 && static_cast<std::size_t>(root - 2) < founders_.size()
? static_cast<std::size_t>(root - 2)
: 0U;
return founders_[offset];
}
std::expected<bool, EcosystemError> EcosystemEpisode::step() {
if (finished_) {
return false;
}
const auto slots = static_cast<std::uint32_t>(founders_.size() + config_.capacity + 1);
const auto tick = community_.progress().tick.value + 1;
// Lifespan retirement is decided from age alone, before any activity this tick.
std::vector<TerminalEvent> terminal;
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto alive = community_.active(id);
const auto born = community_.origin(id);
if (!alive || !*alive || !born) {
continue;
}
if (tick - born->value >= strategy(id).lifespan) {
terminal.push_back({id});
}
}
// Probe a discarded copy so bites are sized against the state feeding will see:
// terminal facts and producer capture/growth both land before any feeding.
auto probe = community_;
if (!probe.advance(Tick{tick}, {}, terminal)) {
return std::unexpected{EcosystemError::community_failure};
}
std::array<std::uint32_t, slot_limit> target{};
std::array<bool, slot_limit> claimed{};
for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) {
const auto alive = probe.active(consumer);
// A consumer that cannot bite must not claim a target away from one that can.
if (!alive || !*alive || strategy(consumer).intake_limit == accounting::Inventory{}) {
continue;
}
std::array<std::uint32_t, slot_limit> available{};
std::size_t count = 0;
for (std::uint32_t candidate = 1; candidate <= slots; ++candidate) {
const auto living = probe.active(candidate);
if (candidate == consumer || claimed[candidate] || !living || !*living) {
continue;
}
if (probe.balances()[balance_index(candidate)] == accounting::Inventory{}) {
continue;
}
available[count++] = candidate;
}
if (count == 0) {
continue;
}
// One feeder per target removes contention rejection from the batch.
const auto chosen = available[random_.next() % count];
target[consumer] = chosen;
claimed[chosen] = true;
}
// A consumer bitten this tick may be retired by that bite, so it does not act.
for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) {
if (target[consumer] != 0 && claimed[consumer]) {
target[consumer] = 0;
}
}
claimed.fill(false);
std::vector<FeedIntent> meals;
for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) {
if (target[consumer] == 0) {
continue;
}
const auto& cap = strategy(consumer).intake_limit;
const auto& balance = probe.balances()[balance_index(target[consumer])];
accounting::Inventory bite{};
bite.energy.value = std::min(cap.energy.value, balance.energy.value);
for (std::size_t channel = 0; channel < 4; ++channel) {
bite.matter[channel].value =
std::min(cap.matter[channel].value, balance.matter[channel].value);
}
if (bite == accounting::Inventory{}) {
continue;
}
claimed[target[consumer]] = true;
meals.push_back(
{static_cast<std::uint64_t>(meals.size()) + 1, consumer, target[consumer], bite});
}
std::size_t free_slots = 0;
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto exists = probe.born(id);
if (exists && !*exists) {
++free_slots;
}
}
std::vector<ReproduceIntent> newborn;
for (std::uint32_t parent = 2; parent <= slots && newborn.size() < free_slots; ++parent) {
const auto alive = probe.active(parent);
if (!alive || !*alive || claimed[parent]) {
continue;
}
const auto& plan = strategy(parent);
const auto& balance = probe.balances()[balance_index(parent)];
// Feeding only adds to an unbitten parent, so this bound stays valid.
if (!covers(plan.reproduction_threshold, balance) || !covers(plan.investment, balance)) {
continue;
}
newborn.push_back(
{static_cast<std::uint64_t>(newborn.size()) + 1, parent, plan.investment});
}
const auto receipts = community_.advance(Tick{tick}, meals, terminal, newborn);
if (!receipts) {
return std::unexpected{EcosystemError::community_failure};
}
lifespan_deaths_ += terminal.size();
for (const auto& receipt : *receipts) {
if (receipt.target_depleted) {
++predation_deaths_;
}
}
births_ += community_.last_births().size();
accumulate(decomposed_, community_.last_decomposed());
bool surviving = false;
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto alive = community_.active(id);
if (alive && *alive) {
surviving = true;
break;
}
}
if (!surviving) {
extinction_tick_ = tick;
finished_ = true;
} else if (tick >= config_.tick_limit) {
finished_ = true;
}
return true;
}
std::expected<EcosystemReport, EcosystemError> EcosystemEpisode::run() {
while (true) {
const auto stepped = step();
if (!stepped) {
return std::unexpected{stepped.error()};
}
if (!*stepped) {
return report();
}
}
}
EcosystemReport EcosystemEpisode::report() const noexcept {
const auto slots = static_cast<std::uint32_t>(founders_.size() + config_.capacity + 1);
EcosystemReport summary{};
summary.seed = seed_;
summary.ticks = community_.progress().tick.value;
summary.births = births_;
summary.predation_deaths = predation_deaths_;
summary.lifespan_deaths = lifespan_deaths_;
summary.extinction_tick = extinction_tick_;
summary.founders = static_cast<std::uint32_t>(founders_.size());
std::array<bool, slot_limit> represented{};
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto alive = community_.active(id);
if (!alive || !*alive) {
continue;
}
const auto root = lineage(id);
if (root != 0 && !represented[root]) {
represented[root] = true;
++summary.surviving_lineages;
}
}
summary.decomposed = decomposed_;
// The ledger validated at creation that every channel total fits u64.
for (const auto& balance : community_.balances()) {
summary.conserved.energy.value += balance.energy.value;
for (std::size_t channel = 0; channel < 4; ++channel) {
summary.conserved.matter[channel].value += balance.matter[channel].value;
}
}
std::uint64_t hash = 0;
for (const auto value : {summary.ticks, summary.births, summary.predation_deaths,
summary.lifespan_deaths, summary.extinction_tick}) {
hash = mix(hash, value);
}
for (const auto& balance : community_.balances()) {
hash = mix(hash, balance.energy.value);
for (const auto& mass : balance.matter) {
hash = mix(hash, mass.value);
}
}
for (std::uint32_t id = 1; id <= slots; ++id) {
const auto exists = community_.born(id);
const auto alive = community_.active(id);
hash = mix(hash, (exists && *exists ? 2U : 0U) + (alive && *alive ? 1U : 0U));
hash = mix(hash, lineage(id));
}
summary.fingerprint = hash;
return summary;
}
} // namespace evo::processes