Files
aevolution/tests/ensemble_tests.cpp
T
dingoandClaude Opus 5 72ed03f4dd Stop calling the end of watching a death
Three defects from review of 89ad95b.

An organism still alive when an episode stopped was recorded dead. A one-tick
run reported no extinctions while writing terminal records for founders that had
not died, and their watched time was added to the same total as completed
lifetimes. Observation ending is a fact about the run, not about the organism,
and ADR-0034 makes a recorded death terminal, so there was nothing to be
terminal about. Survivors stay living now and are counted apart, with their
watched time as the lower bound it is; lived_ticks and observed_ticks answer
different questions and are never summed together.

A genome without the reproduction capability derives a zero investment, which
the driver refused outright, so seeds 10, 12 and 15 failed the whole run.
Filtering those variants out before sampling would have been the worse repair:
the measured set would then be the fertile subset a guard approved of, and being
unable to reproduce is a result rather than grounds for exclusion. The driver
runs such a strategy and proposes no birth for it. ADR-0029 is amended rather
than quietly contradicted.

A half's thermal shortfall was assigned where it was documented as a total, so
two episodes at 15,000 reported 15,000.

Only configurations the driver already rejected behave differently, so the M2.6
pin 2cd4a15f9fbe9949 was checked rather than assumed and still holds. The
ensemble pin moved because the reported facts changed, not to pass a test; the
reason sits beside it. Each fix was confirmed load-bearing by reverting it alone.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 05:58:22 -04:00

421 lines
19 KiB
C++

#include "evo/processes/ensemble.hpp"
#include <algorithm>
#include <array>
#include <iostream>
#include <source_location>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo::processes;
using namespace evo::biology;
using namespace evo::accounting;
void check(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error("ensemble line " + std::to_string(location.line()));
}
}
#define CHECK(expression) check(static_cast<bool>(expression))
constexpr Inventory pooled(std::uint64_t value) {
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
}
constexpr std::uint32_t reference_temperature = 293'150U;
GenomeDraft ancestor_draft() {
GenomeDraft source;
source.id = 1;
source.origin_event = 1;
source.development_version = 1;
source.capabilities = {{Capability::energy_conversion, 400, 0},
{Capability::membrane, 120, 0},
{Capability::target_size, 2'000, 0},
{Capability::ingestion, 1'000'000, 0},
{Capability::reproduction, 1, 0}};
return source;
}
Genome ancestor() {
const auto genome = Genome::create(ancestor_draft());
check(genome.has_value());
return *genome;
}
EcosystemConfig base_world() {
const ProducerConfig plants{{{50}, 1},
{50, 1},
1000,
{1},
{Femtograms{1}, Femtograms{1}, Femtograms{1}, Femtograms{1}}};
return {plants, {10'000'000}, pooled(200).matter, {pooled(4)}, 800, 10, 400};
}
EnsembleConfig plan() {
return {{{reference_temperature - 15'000U, 1'000},
{reference_temperature, 1'000},
{reference_temperature + 15'000U, 1'000},
{reference_temperature, 8'000}},
8,
400,
300,
10};
}
std::vector<Genome> founders(std::size_t wanted = 3) {
const auto diverged = diverge_founders(ancestor(), wanted, 5);
check(diverged.has_value());
return *diverged;
}
void a_strategy_is_what_the_genome_already_implies() {
const auto genome = ancestor();
const EnvironmentState environment{reference_temperature, pooled(1'000'000)};
const auto budget = metabolic_budget(genome, {1000, 0}, environment);
CHECK(budget);
const auto strategy =
strategy_for(genome, {1000, 0}, environment, budget->reproduction_investment, 60);
CHECK(strategy);
// Nothing is a second description of the same organism.
CHECK(strategy->intake_limit == budget->intake_limit);
CHECK(strategy->assimilation_per_thousand == budget->assimilation_per_thousand);
CHECK(strategy->investment == budget->reproduction_investment);
// A parent reproduces once it holds what it would invest; no margin invented.
CHECK(strategy->reproduction_threshold == strategy->investment);
CHECK(strategy->lifespan == 60); // The harness's constant, not a genome trait.
// A genome that cannot reproduce yields nothing to invest, and the episode
// driver refuses such a strategy rather than inventing a default.
auto barren = ancestor();
const auto without = strategy_for(barren, {1000, 0}, environment, pooled(10), 60);
CHECK(without && without->investment == budget->reproduction_investment);
}
void founders_diverge_once_before_any_episode() {
const auto set = founders(3);
CHECK(set.size() == 3);
CHECK(set[0] == ancestor()); // The ancestor itself is the first strategy.
for (std::size_t index = 1; index < set.size(); ++index) {
CHECK(set[index].parents().size() == 1 && set[index].parents()[0] == 1);
CHECK(set[index] != set[0]);
CHECK(Genome::decode(set[index].encode())); // Every variant is a valid genome.
}
CHECK(set[1] != set[2]);
// Divergence is itself reproducible, and a different seed gives a different set.
CHECK(*diverge_founders(ancestor(), 3, 5) == set);
CHECK(*diverge_founders(ancestor(), 3, 6) != set);
// Bounds are refused rather than truncated.
CHECK(!diverge_founders(ancestor(), 0, 5));
CHECK(!diverge_founders(ancestor(), max_candidates + 2, 5));
CHECK(diverge_founders(ancestor(), 1, 5)->size() == 1);
}
void the_run_is_reproducible_and_archived() {
LineageArchive archive;
const auto set = founders();
const auto report = run_ensemble(archive, set, base_world(), plan(), 11);
CHECK(report);
CHECK(report->cells.size() == plan().gradient.size());
CHECK(report->episodes == plan().gradient.size() * plan().seeds_per_cell);
CHECK(report->ticks > 0);
// Every founder is archived, and so is every organism that ever lived.
CHECK(report->archived_genomes == set.size());
CHECK(report->archived_organisms > report->episodes * set.size());
// A death is recorded only where one was observed. An organism whose episode
// stopped while it was alive stays living in the archive, so a lineage is
// reported absent exactly when every one of its carriers was seen to die.
std::uint64_t survivors = 0, deaths = 0;
for (const auto& cell : report->cells) {
for (const auto* which : {&cell.first_half, &cell.second_half}) {
for (const auto& outcome : *which) {
survivors += outcome.survivors;
deaths += outcome.deaths;
}
}
}
CHECK(deaths > 0 && survivors > 0); // Both paths occur in this fixture.
CHECK(deaths + survivors == report->archived_organisms);
std::uint64_t carried = 0;
for (const auto& genome : set) {
CHECK(archive.find(genome.id()));
carried += *archive.living_carriers(genome.id());
CHECK(*archive.status(genome.id()) == (*archive.living_carriers(genome.id()) == 0
? LineageStatus::absent
: LineageStatus::living));
}
CHECK(carried == survivors);
// A repeated run reproduces the whole report.
LineageArchive again;
const auto repeated = run_ensemble(again, set, base_world(), plan(), 11);
CHECK(repeated && *repeated == *report);
CHECK(again.recorded() == archive.recorded());
// A different seed does not.
LineageArchive other;
const auto elsewhere = run_ensemble(other, set, base_world(), plan(), 12);
CHECK(elsewhere && elsewhere->fingerprint != report->fingerprint);
}
void every_cell_conserves_at_every_tick() {
const auto set = founders();
const auto environment = EnvironmentState{reference_temperature, pooled(400)};
for (const auto& cell : plan().gradient) {
std::vector<StrategyConfig> strategies;
for (const auto& genome : set) {
const auto budget = metabolic_budget(genome, {1000, 0}, environment);
CHECK(budget);
const auto strategy =
strategy_for(genome, {1000, 0}, environment, budget->reproduction_investment, 60);
CHECK(strategy);
strategies.push_back(*strategy);
}
auto config = base_world();
config.nutrients = pooled(cell.nutrients).matter;
config.tick_limit = 200;
auto episode = EcosystemEpisode::create(config, strategies, 3);
CHECK(episode);
const auto opening = episode->report().conserved;
while (true) {
const auto stepped = episode->step();
CHECK(stepped);
if (!*stepped) {
break;
}
// Genome-derived configs conserve exactly, as hand-written ones did.
CHECK(episode->report().conserved == opening);
}
}
}
void the_two_seed_halves_agree() {
LineageArchive archive;
const auto report = run_ensemble(archive, founders(), base_world(), plan(), 21);
CHECK(report);
std::uint64_t compared = 0;
for (const auto& cell : report->cells) {
CHECK(cell.first_half.size() == cell.second_half.size());
for (std::size_t index = 0; index < cell.first_half.size(); ++index) {
const auto& first = cell.first_half[index];
const auto& second = cell.second_half[index];
CHECK(first.genome == second.genome);
CHECK(first.episodes == second.episodes);
// Independent seed sets must agree. A difference that shows in one
// half and not the other is an artifact of the seeds, which is what
// tuning against a single seed would produce.
const auto low = std::min(first.organisms, second.organisms);
const auto high = std::max(first.organisms, second.organisms);
CHECK(high > 0);
CHECK(high * 2 <= low * 3 + 2); // within half again of each other
++compared;
}
}
CHECK(compared == report->cells.size() * 3);
}
void the_gradient_changes_the_outcome() {
LineageArchive archive;
const auto report = run_ensemble(archive, founders(), base_world(), plan(), 31);
CHECK(report);
// Cells 0..2 share a resource level and vary temperature; cell 3 shares the
// reference temperature with cell 1 and varies the resource level. So each
// comparison below moves exactly one axis.
const auto& lean = report->cells[1];
const auto& rich = report->cells[3];
CHECK(lean.cell.temperature_millikelvin == rich.cell.temperature_millikelvin);
CHECK(lean.cell.nutrients < rich.cell.nutrients);
std::uint64_t lean_organisms = 0, rich_organisms = 0;
for (std::size_t index = 0; index < lean.first_half.size(); ++index) {
lean_organisms += lean.first_half[index].organisms + lean.second_half[index].organisms;
rich_organisms += rich.first_half[index].organisms + rich.second_half[index].organisms;
}
// The resource axis is consequential, not decorative: changing only the
// nutrient pool changes how many organisms lived and whether the communities
// died out. Deliberately no directional claim. A sweep of this fixture peaks
// near 8000 femtograms and falls away on both sides, because community income
// is capped at one producer bite per tick: scarcity drives predation, which
// concentrates mass into individuals that reach the reproduction threshold,
// while abundance spreads the same income too thin to fund a birth. That is a
// property of this fixture's rules, not a claim about ecology, so the test
// asserts only that the axis moves the outcome.
CHECK(lean_organisms != rich_organisms);
CHECK(lean.extinctions != rich.extinctions);
// The temperature axis is consequential too, at a fixed resource level.
CHECK(report->cells[0].ticks != report->cells[1].ticks);
CHECK(report->cells[0].first_half[0].scheduled_lifespan <
report->cells[1].first_half[0].scheduled_lifespan);
}
void tolerance_keeps_more_life_at_the_extremes() {
// Two strategies differing only in thermal tolerance, compared at the
// reference and at an extreme. The harness shortens scheduled life under
// shortfall, so the tolerant one keeps more of it away from the reference.
auto source = ancestor_draft();
source.id = 2;
source.origin_event = 2;
source.capabilities.push_back({Capability::thermal_tolerance, 20'000, 0});
const auto tolerant = Genome::create(source);
CHECK(tolerant);
const std::array pair{ancestor(), *tolerant};
LineageArchive archive;
auto gradient = plan();
gradient.gradient = {{reference_temperature, 1'000}, {reference_temperature + 30'000U, 1'000}};
gradient.lifespan_lost_per_kelvin = 20;
const auto report = run_ensemble(archive, pair, base_world(), gradient, 41);
CHECK(report && report->cells.size() == 2);
const auto& at_reference = report->cells[0];
const auto& at_extreme = report->cells[1];
// At the reference neither is stressed, so the schedule is identical.
CHECK(at_reference.first_half[0].thermal_shortfall == 0);
CHECK(at_reference.first_half[1].thermal_shortfall == 0);
CHECK(at_reference.first_half[0].scheduled_lifespan ==
at_reference.first_half[1].scheduled_lifespan);
// At the extreme the intolerant one is stressed more and scheduled shorter.
// Shortfall is a total across the half's episodes, so it scales with them.
const auto episodes = at_extreme.first_half[0].episodes;
CHECK(episodes > 1); // Otherwise a sum and a single reading look alike.
CHECK(at_extreme.first_half[1].episodes == episodes);
CHECK(at_extreme.first_half[0].thermal_shortfall == 30'000 * episodes);
CHECK(at_extreme.first_half[1].thermal_shortfall == 10'000 * episodes);
CHECK(at_extreme.first_half[0].scheduled_lifespan == 1); // The loss floors it.
CHECK(at_extreme.first_half[1].scheduled_lifespan == 300U - 10U * 20U);
CHECK(at_extreme.first_half[1].scheduled_lifespan >
at_extreme.first_half[0].scheduled_lifespan);
// Tolerance costs nothing at the reference and helps only where it applies.
CHECK(at_reference.first_half[0].scheduled_lifespan == 300);
}
void ending_observation_is_not_death() {
// A single tick stops every episode with its founders alive. None of them
// died, so none may be recorded dead, and the run must say so.
LineageArchive archive;
const auto set = founders();
auto brief = plan();
brief.tick_limit = 1;
brief.seeds_per_cell = 2;
const auto report = run_ensemble(archive, set, base_world(), brief, 11);
CHECK(report);
std::uint64_t survivors = 0, deaths = 0, observed = 0, lived = 0;
for (const auto& cell : report->cells) {
CHECK(cell.extinctions == 0); // Nothing died out in one tick.
for (const auto* which : {&cell.first_half, &cell.second_half}) {
for (const auto& outcome : *which) {
survivors += outcome.survivors;
deaths += outcome.deaths;
observed += outcome.observed_ticks;
lived += outcome.lived_ticks;
}
}
}
CHECK(deaths == 0); // The defect recorded a death for every founder.
CHECK(lived == 0); // And charged each one a completed lifetime.
CHECK(survivors > 0); // They are survivors, counted as such.
// Each founder was watched for exactly its one tick. Anything born during
// that tick is also a survivor, watched for none of it, so observed time is
// a lower bound and not a lifetime.
CHECK(observed == report->episodes * set.size());
CHECK(survivors >= report->episodes * set.size());
// The archive agrees: nothing was observed to die, so every lineage lives.
for (const auto& genome : set) {
CHECK(*archive.status(genome.id()) == LineageStatus::living);
CHECK(*archive.living_carriers(genome.id()) > 0);
}
}
void a_strategy_that_cannot_reproduce_is_still_measured() {
// A mutation may legitimately drop reproduction. Such a genome yields a zero
// investment, which the driver once refused outright, so the whole ensemble
// failed on the seeds that happened to draw one. It now runs and simply never
// reproduces; excluding it would have made the measured set a subset chosen
// by a guard rather than by the draw.
auto source = ancestor_draft();
source.capabilities.erase(
std::remove_if(source.capabilities.begin(), source.capabilities.end(),
[](const auto& record) { return record.kind == Capability::reproduction; }),
source.capabilities.end());
const auto barren = Genome::create(source);
CHECK(barren);
CHECK(!barren->carries(Capability::reproduction));
const EnvironmentState where{reference_temperature, pooled(1'000)};
const auto budget = metabolic_budget(*barren, {1000, 0}, where);
CHECK(budget && budget->reproduction_investment == Inventory{});
const auto strategy = strategy_for(*barren, {1000, 0}, where, Inventory{}, 60);
CHECK(strategy && strategy->investment == Inventory{});
// The driver accepts it rather than rejecting the configuration.
auto config = base_world();
config.tick_limit = 120;
const std::array only{*strategy};
auto episode = EcosystemEpisode::create(config, only, 3);
CHECK(episode);
const auto summary = episode->run();
CHECK(summary && summary->births == 0); // It lives, and it leaves nothing.
// And the seeds that previously failed now produce a whole run.
for (const std::uint64_t seed : {10U, 12U, 15U}) {
LineageArchive archive;
const auto set = diverge_founders(ancestor(), 3, seed);
CHECK(set);
auto brief = plan();
brief.seeds_per_cell = 2;
brief.tick_limit = 60;
CHECK(run_ensemble(archive, *set, base_world(), brief, seed));
}
}
void thermal_shortfall_is_summed_over_episodes() {
// The field is a total across a half's episodes, not one episode's reading.
LineageArchive archive;
const auto set = founders();
auto stressed = plan();
stressed.gradient = {{reference_temperature + 15'000U, 1'000}};
stressed.seeds_per_cell = 4;
stressed.tick_limit = 40;
const auto report = run_ensemble(archive, set, base_world(), stressed, 11);
CHECK(report && report->cells.size() == 1);
const auto& cell = report->cells[0];
for (const auto* which : {&cell.first_half, &cell.second_half}) {
for (const auto& outcome : *which) {
CHECK(outcome.episodes == 2);
// Two episodes at 15,000 millikelvin of shortfall total 30,000; the
// defect reported 15,000, the value of a single episode.
CHECK(outcome.thermal_shortfall == 30'000);
}
}
}
void invalid_plans_are_refused() {
LineageArchive archive;
const auto set = founders();
const auto world = base_world();
for (auto broken : {0U, 1U, 2U, 3U}) {
auto spoiled = plan();
if (broken == 0) {
spoiled.gradient.clear();
} else if (broken == 1) {
spoiled.seeds_per_cell = 1; // Halves need at least one seed each.
} else if (broken == 2) {
spoiled.tick_limit = 0;
} else {
spoiled.base_lifespan = 0;
}
LineageArchive fresh;
const auto refused = run_ensemble(fresh, set, world, spoiled, 1);
CHECK(!refused && refused.error() == EcosystemError::invalid_config);
CHECK(fresh.archived() == 0); // Nothing was admitted on a refusal.
}
CHECK(!run_ensemble(archive, {}, world, plan(), 1));
// Admitting the same founders twice is refused by the archive itself.
CHECK(run_ensemble(archive, set, world, plan(), 1));
const auto again = run_ensemble(archive, set, world, plan(), 1);
CHECK(!again && again.error() == EcosystemError::invalid_config);
}
} // namespace
int main() try {
a_strategy_is_what_the_genome_already_implies();
founders_diverge_once_before_any_episode();
every_cell_conserves_at_every_tick();
the_run_is_reproducible_and_archived();
the_two_seed_halves_agree();
the_gradient_changes_the_outcome();
tolerance_keeps_more_life_at_the_extremes();
ending_observation_is_not_death();
a_strategy_that_cannot_reproduce_is_still_measured();
thermal_shortfall_is_summed_over_episodes();
invalid_plans_are_refused();
std::cout << "PASS genome-derived strategies, gradient ensembles and split-half agreement\n";
return 0;
} catch (...) {
return 1;
}