From 89ad95bf122bc6fc6a78be94f8e40ce138609c34 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 23 Sep 2026 23:03:52 -0400 Subject: [PATCH] Let a genome decide, and report where each axis actually acts M3.6 joins the M3 pieces: strategy_for derives a StrategyConfig from the metabolic budget, founders are pre-diverged variants admitted to the lineage archive, and evo-sim --ensemble runs them over a resource and temperature grid with every cell's seeds split in half and never merged. ADR-0029's driver is untouched, so the M2.6 fingerprint still holds. Nothing mutates during an episode, so NPC mutation stays open. Three things measurement found, kept rather than smoothed over. The report aggregates were default-initialized, leaving their scalar counters indeterminate. The resource level never reaches strategy derivation at all, so the header now says where each axis acts instead of claiming both shape a strategy. And the resource axis is not monotonic: a sweep peaks near 8000 femtograms and falls away on both sides, because only one consumer may bite a target per tick, so scarcity concentrates mass into individuals that reach the threshold while abundance spreads the same income too thin. The test asserts that an axis moves the outcome and never a direction; an earlier draft asserted a direction that held at two cells and the sweep disproves. Earning a birth at all required pinning the investment fraction to the schema floor, since intake scales with surface and investment with mass. That is a finding about the ADR-0031/0032 cost model, now the second priority in STATUS. Release 33/33, analysis, ASan 33/33 and clang-format all ran and passed here; no Clang or GCC compile happens on this host, so Linux CI is still the first result for this increment. Co-Authored-By: Claude Opus 5 --- CMakeLists.txt | 30 ++- README.md | 14 + apps/evo-sim/main.cpp | 134 +++++++++- docs/ROADMAP.md | 12 +- docs/STATUS.md | 34 ++- docs/adr/0035-genome-ecology-ensembles.md | 135 ++++++++++ docs/adr/README.md | 1 + docs/biology/GENOME_MODEL.md | 30 +++ docs/engineering/VALIDATION.md | 76 ++++++ include/evo/processes/ensemble.hpp | 71 +++++ include/evo/processes/genome_strategy.hpp | 8 + src/processes/ensemble.cpp | 215 ++++++++++++++++ src/processes/genome_strategy.cpp | 16 ++ tests/ensemble_tests.cpp | 299 ++++++++++++++++++++++ 14 files changed, 1063 insertions(+), 12 deletions(-) create mode 100644 docs/adr/0035-genome-ecology-ensembles.md create mode 100644 include/evo/processes/ensemble.hpp create mode 100644 src/processes/ensemble.cpp create mode 100644 tests/ensemble_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f0fd71..0da9628 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,7 +47,7 @@ target_link_libraries(evo_biology PUBLIC evo::accounting) target_compile_features(evo_biology PUBLIC cxx_std_23) evo_owned_target(evo_biology) -add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp src/processes/genome_strategy.cpp) +add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp src/processes/genome_strategy.cpp src/processes/ensemble.cpp) add_library(evo::processes ALIAS evo_processes) target_link_libraries(evo_processes PUBLIC evo::accounting evo::biology) evo_owned_target(evo_processes) @@ -93,6 +93,11 @@ if(BUILD_TESTING) evo_owned_target(evo-lineage-tests) add_test(NAME lineage-contracts COMMAND evo-lineage-tests) set_tests_properties(lineage-contracts PROPERTIES TIMEOUT 120) + add_executable(evo-ensemble-tests tests/ensemble_tests.cpp) + target_link_libraries(evo-ensemble-tests PRIVATE evo::processes) + evo_owned_target(evo-ensemble-tests) + add_test(NAME ensemble-contracts COMMAND evo-ensemble-tests) + set_tests_properties(ensemble-contracts PROPERTIES TIMEOUT 300) add_executable(evo-producer-tests tests/producer_tests.cpp) target_link_libraries(evo-producer-tests PRIVATE evo::processes) evo_owned_target(evo-producer-tests) @@ -123,9 +128,32 @@ if(BUILD_TESTING) add_test(NAME cli-ecosystem-rejects-save COMMAND evo-sim --ecosystem --save episodes.evo) add_test(NAME cli-episodes-require-ecosystem COMMAND evo-sim --episodes 2 --tick-limit 1) add_test(NAME cli-tick-limit-requires-ecosystem COMMAND evo-sim --ticks 10 --tick-limit 1) + add_test(NAME cli-ecosystem-rejects-seeds-per-cell COMMAND evo-sim --ecosystem --seeds-per-cell 4) set_tests_properties(cli-ecosystem-conflict cli-ecosystem-rejects-ticks cli-ecosystem-rejects-entities cli-ecosystem-rejects-save cli-episodes-require-ecosystem cli-tick-limit-requires-ecosystem + cli-ecosystem-rejects-seeds-per-cell + PROPERTIES WILL_FAIL TRUE) + add_test(NAME cli-ensemble COMMAND evo-sim --ensemble --seed 0 --seeds-per-cell 4 + --strategies 3 --tick-limit 400) + set_tests_properties(cli-ensemble PROPERTIES TIMEOUT 120 + PASS_REGULAR_EXPRESSION "c2b96c86101be628") + # The two measurement modes are separate workloads, and neither may borrow the + # other's options: --episodes counts episodes, --seeds-per-cell counts seeds. + add_test(NAME cli-ensemble-conflict COMMAND evo-sim --ensemble --verify-replay) + add_test(NAME cli-ensemble-excludes-ecosystem COMMAND evo-sim --ensemble --ecosystem) + add_test(NAME cli-ensemble-rejects-episodes COMMAND evo-sim --ensemble --episodes 2) + add_test(NAME cli-ensemble-rejects-ticks COMMAND evo-sim --ensemble --ticks 1) + add_test(NAME cli-ensemble-rejects-entities COMMAND evo-sim --ensemble --entities 4) + # Halves need at least one seed each, and the driver caps strategies at four. + add_test(NAME cli-ensemble-rejects-single-seed COMMAND evo-sim --ensemble --seeds-per-cell 1) + add_test(NAME cli-ensemble-rejects-excess-strategies COMMAND evo-sim --ensemble --strategies 5) + add_test(NAME cli-seeds-per-cell-requires-ensemble COMMAND evo-sim --seeds-per-cell 4) + add_test(NAME cli-strategies-requires-ensemble COMMAND evo-sim --strategies 3) + set_tests_properties(cli-ensemble-conflict cli-ensemble-excludes-ecosystem + cli-ensemble-rejects-episodes cli-ensemble-rejects-ticks cli-ensemble-rejects-entities + cli-ensemble-rejects-single-seed cli-ensemble-rejects-excess-strategies + cli-seeds-per-cell-requires-ensemble cli-strategies-requires-ensemble PROPERTIES WILL_FAIL TRUE) add_test(NAME cli-file-integration COMMAND "${CMAKE_COMMAND}" "-DEVO_SIM=$" "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/cli-integration" diff --git a/README.md b/README.md index d83a004..ffdd4d2 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,20 @@ shares no state, snapshot or particle metric with the proof run, and its strateg constants are measurement inputs rather than simulation rules. See [ADR-0029](docs/adr/0029-ecosystem-driver-and-episodes.md) for scope. +```sh +./build/release/evo-sim --ensemble --seed 0 --seeds-per-cell 4 --strategies 3 --tick-limit 400 +``` + +Ensemble mode derives strategies from genomes instead of writing them, then runs +them on that same driver over a resource and temperature gradient. Each cell's +seeds are split in half and both halves are reported separately and never merged, +so a difference that appears in one half only is visible as the seed artifact it +is. Options belong to exactly one mode: `--episodes` counts episodes and is +rejected here, `--seeds-per-cell` counts seeds and is rejected in ecosystem mode. +A cell's numbers are not fitness, adaptation or balance, and the resource axis is +deliberately not monotonic. See +[ADR-0035](docs/adr/0035-genome-ecology-ensembles.md) for scope and for why. + The second command continues saved PRNG/component state. `--verify-replay` compares an uninterrupted run to a midpoint serialization/restore run. JSON reports the seed, ticks, active entities and canonical state hash. Snapshots diff --git a/apps/evo-sim/main.cpp b/apps/evo-sim/main.cpp index 1c98352..ed747e7 100644 --- a/apps/evo-sim/main.cpp +++ b/apps/evo-sim/main.cpp @@ -1,4 +1,5 @@ #include "evo/processes/ecosystem.hpp" +#include "evo/processes/ensemble.hpp" #include "evo/simulation/world.hpp" #include "evo/telemetry/sinks.hpp" @@ -24,9 +25,12 @@ struct Options { std::uint64_t entities{8}; std::uint64_t episodes{1}; std::uint64_t tick_limit{2000}; + std::uint64_t seeds_per_cell{8}; + std::uint64_t strategies{3}; std::filesystem::path load, save, output, metrics; bool verify_replay{}; bool ecosystem{}; + bool ensemble{}; bool help{}; }; @@ -86,7 +90,9 @@ std::expected parse(int argc, char** argv) { bool initial_state_option = false; bool entities_option = false; bool ticks_option = false; - bool episode_option = false; + bool episodes_option = false; + bool tick_limit_option = false; + bool ensemble_option = false; for (int index = 1; index < argc; ++index) { const std::string_view key{argv[index]}; if (key == "--help") { @@ -101,12 +107,16 @@ std::expected parse(int argc, char** argv) { options.ecosystem = true; continue; } + if (key == "--ensemble") { + options.ensemble = true; + continue; + } if (++index >= argc) { return std::unexpected{evo::Error::invalid_arguments}; } const std::string_view value{argv[index]}; if (key == "--seed" || key == "--ticks" || key == "--entities" || key == "--episodes" || - key == "--tick-limit") { + key == "--tick-limit" || key == "--seeds-per-cell" || key == "--strategies") { const auto parsed = number(value); if (!parsed) { return std::unexpected{parsed.error()}; @@ -120,10 +130,16 @@ std::expected parse(int argc, char** argv) { entities_option = true; } else if (key == "--episodes") { options.episodes = *parsed; - episode_option = true; + episodes_option = true; } else if (key == "--tick-limit") { options.tick_limit = *parsed; - episode_option = true; + tick_limit_option = true; + } else if (key == "--seeds-per-cell") { + options.seeds_per_cell = *parsed; + ensemble_option = true; + } else if (key == "--strategies") { + options.strategies = *parsed; + ensemble_option = true; } else { options.ticks = *parsed; ticks_option = true; @@ -148,11 +164,22 @@ std::expected parse(int argc, char** argv) { const bool proof_only = entities_option || ticks_option || options.verify_replay || !options.load.empty() || !options.save.empty() || !options.metrics.empty(); + if (options.ecosystem && options.ensemble) { + return std::unexpected{evo::Error::invalid_arguments}; + } if (options.ecosystem) { - if (proof_only || options.episodes == 0 || options.tick_limit == 0) { + // Ensemble mode counts seeds per cell, not episodes, so --episodes here + // would name a quantity this mode does not have. + if (proof_only || ensemble_option || options.episodes == 0 || options.tick_limit == 0) { return std::unexpected{evo::Error::invalid_arguments}; } - } else if (episode_option) { + } else if (options.ensemble) { + if (proof_only || episodes_option || options.tick_limit == 0 || + options.seeds_per_cell < 2 || options.strategies == 0 || + options.strategies > evo::processes::max_strategies) { + return std::unexpected{evo::Error::invalid_arguments}; + } + } else if (episodes_option || tick_limit_option || ensemble_option) { return std::unexpected{evo::Error::invalid_arguments}; } if (const auto valid = validate_paths(options); !valid) { @@ -283,10 +310,98 @@ std::expected run_ecosystem(const Options& options) { return write_report(options, report.str()); } +// The ensemble fixture, again CLI-local measurement input rather than a rule. The +// ancestor's investment fraction sits at the schema floor because intake scales +// with surface while investment scales with mass: at any larger fraction no +// organism in this world can fund a birth from feeding within an episode, and the +// resource axis would measure nothing. See ADR-0035. +evo::biology::GenomeDraft ensemble_ancestor() { + using evo::biology::Capability; + evo::biology::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; +} + +std::expected run_ensemble_mode(const Options& options) { + using namespace evo::processes; + constexpr std::uint32_t reference_temperature = 293'150U; + const auto ancestor = evo::biology::Genome::create(ensemble_ancestor()); + if (!ancestor) { + return std::unexpected{evo::Error::invalid_arguments}; + } + const auto founders = + diverge_founders(*ancestor, static_cast(options.strategies), options.seed); + if (!founders) { + return std::unexpected{evo::Error::invalid_arguments}; + } + const ProducerConfig plants{{{50}, 1}, {50, 1}, 1000, {1}, bundle(1).matter}; + const EcosystemConfig world{plants, {10'000'000}, bundle(200).matter, {bundle(4)}, + 800, 10, options.tick_limit}; + const EnsembleConfig plan{{{reference_temperature - 15'000U, 1'000}, + {reference_temperature, 1'000}, + {reference_temperature + 15'000U, 1'000}, + {reference_temperature, 8'000}}, + options.seeds_per_cell, + options.tick_limit, + 300, + 10}; + evo::biology::LineageArchive archive; + const auto measured = run_ensemble(archive, *founders, world, plan, options.seed); + if (!measured) { + return std::unexpected{evo::Error::invalid_arguments}; + } + std::ostringstream report; + report << "{\"rules_version\":" << evo::rules_version + << ",\"mode\":\"ensemble\",\"seed\":" << options.seed + << ",\"strategies\":" << founders->size() + << ",\"seeds_per_cell\":" << options.seeds_per_cell + << ",\"tick_limit\":" << options.tick_limit << ",\"episodes\":" << measured->episodes + << ",\"ticks\":" << measured->ticks + << ",\"archived_genomes\":" << measured->archived_genomes + << ",\"archived_organisms\":" << measured->archived_organisms << ",\"cells\":["; + for (std::size_t index = 0; index < measured->cells.size(); ++index) { + const auto& cell = measured->cells[index]; + report << (index == 0 ? "" : ",") + << "{\"temperature_millikelvin\":" << cell.cell.temperature_millikelvin + << ",\"nutrients\":" << cell.cell.nutrients << ",\"ticks\":" << cell.ticks + << ",\"extinctions\":" << cell.extinctions << ",\"halves\":["; + // Both halves are reported, never merged: a difference that shows in one + // and not the other is an artifact of the seeds. See ADR-0035. + const std::array halves{&cell.first_half, &cell.second_half}; + for (std::size_t half = 0; half < halves.size(); ++half) { + report << (half == 0 ? "[" : ",["); + for (std::size_t which = 0; which < halves[half]->size(); ++which) { + const auto& outcome = (*halves[half])[which]; + report << (which == 0 ? "" : ",") << "{\"genome\":" << outcome.genome + << ",\"episodes\":" << outcome.episodes << ",\"births\":" << outcome.births + << ",\"organisms\":" << outcome.organisms + << ",\"lived_ticks\":" << outcome.lived_ticks + << ",\"thermal_shortfall\":" << outcome.thermal_shortfall + << ",\"scheduled_lifespan\":" << outcome.scheduled_lifespan << "}"; + } + report << "]"; + } + report << "]}"; + } + report << "],\"fingerprint\":\"" << std::hex << std::setfill('0') << std::setw(16) + << measured->fingerprint << std::dec << "\"}\n"; + return write_report(options, report.str()); +} + std::expected run(const Options& options) { if (options.ecosystem) { return run_ecosystem(options); } + if (options.ensemble) { + return run_ensemble_mode(options); + } auto loaded = initial_world(options); if (!loaded) { return std::unexpected{loaded.error()}; @@ -378,9 +493,14 @@ int main(int argc, char** argv) try { " [--verify-replay] [--save FILE] [--output JSON] [--metrics FILE]\n" "evo-sim --ecosystem [--seed N] [--episodes N] [--tick-limit N]\n" " [--output JSON]\n" + "evo-sim --ensemble [--seed N] [--seeds-per-cell N] [--strategies N]\n" + " [--tick-limit N] [--output JSON]\n" "Synthetic proof. When loading, ticks are additional.\n" "Ecosystem mode measures seeded bounded episodes; it shares no state,\n" - "snapshot or particle metric with the proof run.\n"; + "snapshot or particle metric with the proof run.\n" + "Ensemble mode runs genome-derived strategies over a resource and\n" + "temperature gradient, reporting each cell's two seed halves\n" + "separately. Its numbers describe that fixture and nothing wider.\n"; return 0; } const auto result = run(*options); diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 7547d96..0691057 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -83,7 +83,7 @@ composition, maintenance, movement, construction, intake and reproduction investment, each derived from a different phenotype quantity so one parameter moves some budgets and not others. `consumer_for` is the first path from a genome into the M2 fixtures, and mass splits conserve exactly so a derived body can be -spent through the ledger. No existing fixture reads genomes yet; that is M3.6. M3.4 now proposes successors +spent through the ledger. M3.4 now proposes successors (ADR-0033): a bounded operator catalog whose eligibility is the M3.1 validation itself, drawn uniformly without replacement from a recorded context and returned in canonical order with nothing ranked. Selection regenerates the offer and @@ -96,6 +96,16 @@ that carried it, ancestry and descendants resolve through dead links, and a lineage with no living carrier is reported absent and never extinct, because terminal extinction needs a reconciled watermark this type cannot see. NPC mutation stays undecided: the archive records an origin event and never an actor. +M3.6 closes M3 by making the pieces meet (ADR-0035): `strategy_for` turns a genome +into the `StrategyConfig` the M2.6 driver already takes, founders are pre-diverged +variants of one ancestor admitted to the archive, and `evo-sim --ensemble` runs +them over a resource and temperature grid with every cell's seeds split in half and +reported separately. The driver is untouched, so the M2.6 fingerprint still holds. +Two findings are recorded rather than smoothed over: resource level never reaches +strategy derivation, because a mature founder has an empty construction transition, +and the resource axis is not monotonic, because feeding caps community income at +one producer bite per tick. Nothing mutates during an episode, so NPC mutation +stays open. ## M3 — Genome v0.1 diff --git a/docs/STATUS.md b/docs/STATUS.md index 1c2e37d..3511bdf 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged. ## Completed implementation - Vision, architectural pillars, risks, open-question register, architecture - diagrams, biological contracts, engineering constitution and 34 ADRs. + diagrams, biological contracts, engineering constitution and 35 ADRs. Proposed/deferred choices remain distinct from accepted proof decisions. - M0–M4 task breakdowns with dependencies, acceptance evidence and risks, plus M5–M14 gates in [ROADMAP.md](ROADMAP.md). @@ -61,8 +61,8 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M3.6 genome ecology ensembles | Strategies compared under resource and temperature gradients, with conservation and a diversity report; closes M3 | -| 2 | M4.1 cohort state and ownership | Genome, lineage, counts, age, reserves, residuals and ownership made explicit | +| 1 | M4.1 cohort state and ownership | Genome, lineage, counts, age, reserves, residuals and ownership made explicit | +| 2 | Revisit the ADR-0031/0032 reproduction cost model | Reproduction is affordable only at the genome schema's floor; decide whether that is intended before M4 builds cohorts on it | | Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes | M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md): @@ -242,6 +242,34 @@ archive records an origin event and never an actor. Nothing is serialized, so durable retention and migration remain M7 and M8. Native Release, analysis, ASan and formatting passed 21/21; Linux CI has not run yet. +M3.6 closes M3 by making the M3 pieces meet (ADR-0035). `strategy_for` derives a +`StrategyConfig` from ADR-0032's budget, so a strategy is what the genome already +implies rather than a second description of the same organism, and a parent +reproduces once it holds what it would invest. Founders are variants of one +ancestor diverged by ADR-0033's draw before any episode starts and admitted to +ADR-0034's archive with their parent links; every birth and death is recorded as +it happens, so the diversity a run reports has a provenance. Nothing mutates +during an episode, because autonomous divergence would settle NPC mutation, which +stays open. `evo-sim --ensemble` runs the grid and reports each cell's seeds in +two halves that are never merged. ADR-0029's driver is untouched and the M2.6 +fingerprint still holds. + +Two findings are recorded rather than smoothed over. Resource level never reaches +strategy derivation: founders are derived fully grown, so their construction +transition is empty and ADR-0031's per-channel `available` cannot move intake, +assimilation or investment; the resource level acts only as the nutrient pool +bounding producer growth. And the resource axis is not monotonic, so no test +asserts a direction. A sweep peaks near 8000 femtograms and falls away on both +sides, because ADR-0026 lets only one consumer bite a target per tick: the +community's income is capped at one producer bite regardless of the pool, scarcity +drives predation that concentrates mass into individuals that reach the threshold, +and abundance spreads the same income too thin to fund a birth. Separately, the +fixture's reproduction investment is pinned to the genome schema's floor because +intake scales with surface while investment scales with mass; at any larger +fraction nothing can earn a birth within a lifespan and both axes measure nothing. +That is a finding about the ADR-0031/0032 cost model, not a fixture detail. Native +Release, analysis, ASan and formatting passed 33/33; Linux CI has not run yet. + Before biology, resolve the relevant heredity and energetic contracts rather than treating proof particles as organisms. Exact game tick rate, NPC mutation, logout treatment, species/extinction rules and multicellular transition remain diff --git a/docs/adr/0035-genome-ecology-ensembles.md b/docs/adr/0035-genome-ecology-ensembles.md new file mode 100644 index 0000000..604f025 --- /dev/null +++ b/docs/adr/0035-genome-ecology-ensembles.md @@ -0,0 +1,135 @@ +# ADR-0035: Genome-derived strategies over an environment gradient + +## Status + +Adopted for M3.6, which closes M3. Nothing mutates during an episode: autonomous +divergence would settle NPC mutation, which OPEN_QUESTIONS leaves open until M12. +No simulation contract changes, and ADR-0029's episode driver is untouched. + +## Context + +Every piece of M3 exists and none of them meet. Genomes validate, phenotypes +derive, budgets are charged, candidates are drawn and lineages are retained, but +the M2 fixtures still run on hand-written constants. M3.6 is where a genome +finally decides how something behaves in an ecosystem, measured across a gradient +rather than at one point. + +The named risk is tuning one seed until it looks good. A single run of a seeded +ecosystem says almost nothing: the question is whether a difference between +strategies survives being measured again on seeds nobody chose. + +## Decision + +Derive a `StrategyConfig` from a genome rather than writing one. Intake, +assimilation and reproduction investment all come from ADR-0032's budget, so a +strategy is what the genome already implies and not a second description of the +same organism. A parent reproduces once it holds what it would invest, which +avoids inventing a separate margin. + +Run those strategies over a grid of resource levels and temperatures, many seeds +per cell, on ADR-0029's existing episode driver. The driver does not change, so +the M2.6 fingerprint still holds and the ecology under test is the one already +validated. + +The two axes reach a run by different routes, and implementation showed the +routes are not symmetric. Founders are derived fully grown, so their construction +transition is empty and ADR-0031's per-channel `available` cannot move intake, +assimilation or reproduction investment. The resource level therefore does not +enter strategy derivation at all; it reaches a run only as the nutrient pool an +episode starts with, which bounds producer growth. Temperature is the opposite: it +enters only the derivation, through thermal shortfall, and reaches the ecology +through the scheduling rule below. Saying the resource level shapes a strategy +would have been false, so this ADR says instead exactly where each axis acts. + +Temperature has to be made consequential or the axis is decoration: ADR-0031 +derives thermal shortfall but deliberately lets it change no budget. The harness +therefore shortens a strategy's scheduled lifespan in proportion to its shortfall. +That is an extension of the lifespan rule ADR-0029 already owns, which is a +fixture scheduling device and explicitly not biology. It is not a mortality model, +it lives in the harness rather than in any contract, and a genome carrying thermal +tolerance simply keeps more of its scheduled life at the extremes. + +Founders are pre-diverged variants of one ancestor, produced by ADR-0033's +candidate draw before any episode starts and admitted to ADR-0034's archive with +their parent links. Every organism's birth and death is recorded as it happens, so +the diversity a run reports comes from retained records rather than from counters +the harness kept for itself. Nothing mutates mid-episode, because an organism +diverging on its own is exactly the NPC-mutation question that remains open. + +The report is distributional. Per strategy and per cell it carries episodes, +births, survivals, lifetime and mean thermal shortfall, so a reader sees a spread +rather than an outcome. To make overfitting visible rather than merely warned +against, the seeds of every cell are split in half and the two halves reported +separately: a difference that appears in one half and not the other is an artifact +of the seeds, and the tests assert the halves agree. + +## Alternatives Considered + +Mutating during an episode would exercise more of M3 and would settle NPC mutation +by implication, which ADR-0034 was careful not to do. Teaching the episode driver +about genomes would change a tested fixture and break a pinned fingerprint for no +gain, since a derived `StrategyConfig` is the same shape the driver already takes. +Letting thermal shortfall reduce a budget would put a mortality rule inside a +contract that says it is not one. Reporting one number per cell would hide exactly +the variance the named risk is about. Deriving lifespan from body size would be an +allometric claim this project has no basis for; it stays a harness constant +applied to every strategy alike. + +## Benefits + +A genome now determines behaviour end to end, through code that was already tested +at every step. Both axes are consequential, so strategies can be compared rather +than merely listed. Split halves make an overfitted conclusion fail a test instead +of surviving in a report, and the archive gives the diversity figures a provenance. + +## Costs + +The grid is small and the seed count modest, so the report describes this fixture +and nothing wider. The thermal penalty, the lifespan base and the grid bounds are +chosen constants. Recording every birth and death costs a scan of the slots each +tick. Founders diverge once, before the run, so the ensemble compares a fixed set +of strategies rather than an evolving population. + +## Risks + +Do not read a cell's numbers as fitness, adaptation or balance: a strategy that +produces more offspring here is doing so under constants this ADR chose. The +thermal penalty is a scheduling rule and is not a claim that heat kills. + +The resource axis is emphatically not monotonic, and no test asserts that it is. +Sweeping the fixture, organisms rise to a peak near 8000 femtograms and fall away +on both sides. The mechanism is a property of ADR-0026's feeding rules, not of +ecology: a target may be bitten by only one consumer per tick, so the community's +income is capped at one producer bite however much is in the pool. Scarcity +empties the producer, consumers then bite each other, and that concentrates mass +into individuals that reach the reproduction threshold; abundance spreads the same +income across more feeders, and none of them accumulates enough to fund a birth. +Reading "more resource supports more life" out of a cell would be reading past the +rules that produced it. + +The fixture's reproduction investment sits at the genome schema's floor of one +per thousand. That is forced, not chosen for taste: intake scales with surface and +investment with body mass, so the ticks needed to fund a birth grow as the cube +root of mass and exceed any plausible lifespan at every larger fraction. At the +previous constants no organism could earn a birth at all, every birth came from +the opening endowment, and both axes measured nothing. A cost model in which +reproduction is affordable only at the schema floor is a finding about ADR-0031 +and ADR-0032 worth revisiting, not a fixture detail. Agreement +between seed halves shows a measurement is reproducible, not that it is +ecologically meaningful, and conservation holding across the grid remains +arithmetic rather than plausibility. No organism mutates, no population is +modelled, and nothing here is persistent. + +## Consequences + +Test that a derived strategy matches the genome's own budget, that conservation +holds at every tick of every cell, that the archive ends holding exactly the +founders and every organism that lived, that lineage status reflects the carriers, +that the two seed halves agree within a stated band for every strategy and cell, +that each axis alone changes outcomes rather than leaving cells identical, that a +thermally tolerant strategy keeps more of its life at the extremes than an +intolerant one, and that a repeated run reproduces the report exactly. The gradient +test asserts only that an axis moves the outcome, never a direction, because the +direction is not a property of this model. `evo-sim --ensemble` reports every cell +with its two halves separate and never merges them. No genome schema, mutation +catalog, archive, ledger, episode driver, renderer or deployment changes. diff --git a/docs/adr/README.md b/docs/adr/README.md index 0bebf52..fdf3fc8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -27,6 +27,7 @@ Each record has the eight required sections. 0032 derives non-uniform metabolic budgets and the first genome/ledger path. 0033 adopts the bounded mutation catalog and uniform seeded candidate draws. 0034 adopts the permanent lineage archive and absence that is never extinction. +0035 derives strategies from genomes and measures them over a split-half gradient. Every dependency adoption records exact version/commit and integrity hash, transitive license obligations, maintenance/security review, owner and removal diff --git a/docs/biology/GENOME_MODEL.md b/docs/biology/GENOME_MODEL.md index 44f9b8c..da1c2aa 100644 --- a/docs/biology/GENOME_MODEL.md +++ b/docs/biology/GENOME_MODEL.md @@ -262,3 +262,33 @@ not deleting; a silent drop would be. Durable storage, retention tiers and cross-version migration are M7 and M8 work, and nothing here is serialized. NPC mutation stays undecided, because the archive records an origin event and never an actor. + +## What a genome decides, end to end + +A genome now determines behaviour all the way into an ecosystem. `strategy_for` +turns a genome, a growth state and an environment into the same `StrategyConfig` +the episode driver already took, with intake, assimilation and reproduction +investment all read from the metabolic budget. A strategy is therefore what the +genome already implies, not a second description of the same organism, and a +parent reproduces once it holds what it would invest rather than clearing an +invented margin. + +Where an environment acts is narrower than it first appears. Temperature enters +the derivation, through the phenotype's thermal shortfall. Resource level does +not enter it at all: an organism derived fully grown has an empty construction +transition, so the per-channel `available` inventory has nothing to bound, and +intake, assimilation and investment are unchanged by how much material surrounds +it. The resource level acts only on the ecology, as the nutrient pool bounding +what producers can build. + +Reproduction is expensive in a specific, structural way. Intake scales with +surface area and investment with body mass, so the time to fund a birth by +feeding falls only as the cube root of mass and rises with the investment +fraction. Across the sizes the schema permits, a birth can be earned within a +plausible lifespan only near the schema's floor of one per thousand. That is a +property of the development and metabolism rules, not of any fixture, and whether +it is intended is an open question rather than a settled model. + +Nothing in this path mutates an organism. Variants are diverged before a run and +compared as a fixed set, because an organism diverging on its own would settle NPC +mutation, which remains open. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 66a2640..f507b25 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -720,3 +720,79 @@ migration are M7 and M8, and NPC mutation remains undecided. Golden `d61ad5bf0c928c76`, ecosystem fingerprint `2cd4a15f9fbe9949` and the frozen genome fixture are unchanged. No deployment manifest or image pin changed. Linux validation is pending; no Gitea result is claimed since `b01a824`. + +## M3.6 genome ecology ensembles + +Executed on this Windows host (2026-09-23): Release configure, build and `ctest` +33/33; the analysis preset (clang-tidy 19, warnings as errors) built clean; the +ASan preset configured, built and ran 33/33; `clang-format` 19.1.5 reported no +violations after the new files were formatted. All four checks ran and passed on +the committed tree. No Clang or GCC compile happens on this host, so the standing +gap recorded for `29ce255` is unchanged and Linux CI remains the first Clang and +GCC result for this increment. + +`evo-ensemble-tests` covers eight properties: that a derived strategy carries +exactly ADR-0032's budget quantities and invents no margin, that divergence is +reproducible and refuses its bounds rather than truncating, that conservation +holds at every tick of every cell, that a run is reproducible and a different seed +is not, that the archive ends holding exactly the founders and every organism that +lived with no living carriers, that the two seed halves agree within the stated +band, that each gradient axis alone changes the outcome, and that a thermally +tolerant strategy keeps more scheduled life at the extremes. `evo-sim --ensemble` +is pinned by fingerprint `c2b96c86101be628`, confirmed stable across three runs +and distinct from a different seed's `8f88e72cf2715eac`. + +Three defects were found and fixed during implementation, all by measurement +rather than by review. `EnsembleReport` and `CellReport` were default-initialized +rather than value-initialized: both are aggregates whose vector members give them +a non-trivial default constructor, which leaves the scalar counters indeterminate, +and the episode total read as garbage. Both are now `{}`. + +The other two are findings about the model, and are recorded in ADR-0035 rather +than tuned away. The header claimed the resource level entered both the derived +strategies and the episode's nutrient pool. It does not enter the derivation at +all: founders are derived fully grown, so their construction transition is empty +and ADR-0031's per-channel `available` cannot reach intake, assimilation or +reproduction investment. The comment was corrected rather than the code, because +the code was right and the claim was false. + +The resource axis was then measured to be decorative at the original constants and +non-monotonic once it was not. A ten-point sweep at the original fixture returned +41 to 45 organisms across three orders of magnitude of nutrients with identical +tick totals and eight extinctions everywhere: every birth came from the opening +endowment, because a body of 353,600,000 fg needed 73,776,000 fg of carbon to +reproduce while feeding supplied 8,000 fg per tick before assimilation, or roughly +23,000 ticks against a 60-tick lifespan. Rescaling so a birth can be earned +required pinning the investment fraction to the genome schema's floor of one per +thousand, because intake scales with surface and investment with body mass, so +the ticks needed to fund a birth fall only as the cube root of mass. That a +reproduction is affordable only at the schema floor is a finding about the +ADR-0031/0032 cost model and is now the second priority in STATUS.md. + +After rescaling, a sweep of 200 to 200,000 femtograms gave 45, 45, 45, 51, 61, 81, +44, 44, 42 and 42 organisms: a peak near 8,000 and a fall away on both sides. The +mechanism is ADR-0026's feeding rule that a target may be bitten by only one +consumer per tick, which caps community income at one producer bite however large +the pool; scarcity empties the producer, consumers bite each other, and that +concentrates mass into individuals that reach the threshold, while abundance +spreads the same income too thin to fund a birth. The gradient test therefore +asserts only that an axis moves the outcome, never a direction. An earlier draft +of that test asserted `rich_organisms > lean_organisms`; that assertion held at +the two chosen cells but implied a monotonicity the sweep disproves, so it was +replaced rather than satisfied by picking two cells that flattered it. + +Coverage limits. The grid is four cells and the tests use eight seeds per cell, so +every number describes this fixture and nothing wider. The split-half band +(`high * 2 <= low * 3 + 2`) is a chosen tolerance, not a derived one. No organism +mutates during an episode, so nothing here exercises in-episode divergence and NPC +mutation stays open. The thermal penalty lives in the harness and no contract +knows about it, so no contract test covers it. Nothing is serialized. + +The eleven new CLI tests are new-behaviour tests for a new mode, not regressions +of a fixed defect; only the M2.6 bidirectional mode check they extend was ever a +regression. They were confirmed to fail the run, which is what `WILL_FAIL` +asserts, but each one was not separately confirmed to fail through the branch it +names, so a rejection arriving from a different branch would still pass. Golden `d61ad5bf0c928c76`, ecosystem fingerprint `2cd4a15f9fbe9949` and the +frozen genome fixture are unchanged, and ADR-0029's episode driver was not +touched. No deployment manifest or image pin changed. Linux validation is pending; +no Gitea result is claimed since `b01a824`. diff --git a/include/evo/processes/ensemble.hpp b/include/evo/processes/ensemble.hpp new file mode 100644 index 0000000..d4a097e --- /dev/null +++ b/include/evo/processes/ensemble.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "evo/biology/lineage.hpp" +#include "evo/biology/mutation.hpp" +#include "evo/processes/genome_strategy.hpp" + +namespace evo::processes { +// One point of the gradient. The two axes reach a run by different routes, and +// neither route is the other's. Temperature enters the derivation: it sets the +// phenotype's thermal shortfall, which reaches the ecology through the scheduling +// rule below. Resource level does not enter the derivation at all. Founders are +// derived fully grown, so their construction transition is empty and +// `EnvironmentState::available` cannot move `intake_limit`, assimilation or +// reproduction investment; the resource level reaches a run only as the nutrient +// pool an episode starts with, which bounds producer growth. +struct GradientCell { + std::uint32_t temperature_millikelvin; + std::uint64_t nutrients; + auto operator<=>(const GradientCell&) const = default; +}; +struct EnsembleConfig { + std::vector gradient; + std::uint64_t seeds_per_cell; + std::uint64_t tick_limit; + std::uint32_t base_lifespan; + // Ticks of scheduled life lost per kelvin of thermal shortfall. This extends + // ADR-0029's lifespan rule, which is a harness scheduling device and not + // biology. It is not a mortality model and no contract knows about it. + std::uint32_t lifespan_lost_per_kelvin; +}; +// What one strategy did in one half of one cell's seeds. Reported per half so an +// effect that only appears in one of them is visible as the artifact it is. +struct StrategyOutcome { + std::uint64_t genome; + std::uint64_t episodes; + std::uint64_t births; + std::uint64_t organisms; + std::uint64_t lived_ticks; + std::uint64_t thermal_shortfall; // summed over the episodes of this half + std::uint32_t scheduled_lifespan; + auto operator<=>(const StrategyOutcome&) const = default; +}; +struct CellReport { + GradientCell cell; + std::vector first_half; + std::vector second_half; + std::uint64_t ticks; + std::uint64_t extinctions; + auto operator<=>(const CellReport&) const = default; +}; +struct EnsembleReport { + std::vector cells; + std::uint64_t episodes; + std::uint64_t ticks; + std::uint64_t archived_genomes; + std::uint64_t archived_organisms; + std::uint64_t fingerprint; + auto operator<=>(const EnsembleReport&) const = default; +}; + +// Produces the founder strategies by diverging one ancestor before any episode +// runs. Nothing mutates during an episode: an organism diverging on its own is +// the NPC-mutation question that remains open. +[[nodiscard]] std::expected, EcosystemError> +diverge_founders(const biology::Genome& ancestor, std::size_t wanted, std::uint64_t seed); +// Runs the grid, recording every birth and death in the archive as it happens, so +// the diversity a report carries comes from retained records. +[[nodiscard]] std::expected +run_ensemble(biology::LineageArchive& archive, std::span founders, + const EcosystemConfig& base, const EnsembleConfig& plan, std::uint64_t seed); +} // namespace evo::processes diff --git a/include/evo/processes/genome_strategy.hpp b/include/evo/processes/genome_strategy.hpp index 6c10c34..33d69d5 100644 --- a/include/evo/processes/genome_strategy.hpp +++ b/include/evo/processes/genome_strategy.hpp @@ -1,6 +1,7 @@ #pragma once #include "evo/biology/metabolism.hpp" +#include "evo/processes/ecosystem.hpp" #include "evo/processes/feeding.hpp" namespace evo::processes { @@ -10,4 +11,11 @@ namespace evo::processes { [[nodiscard]] std::expected consumer_for(const biology::Genome& genome, biology::GrowthState growth, biology::EnvironmentState environment, accounting::Inventory opening); +// The same budget as an episode strategy. A parent reproduces once it holds what +// it would invest, so no separate margin is invented. Lifespan stays the +// harness's own scheduling constant rather than a trait read from the genome. +[[nodiscard]] std::expected +strategy_for(const biology::Genome& genome, biology::GrowthState growth, + biology::EnvironmentState environment, accounting::Inventory opening, + std::uint32_t lifespan); } // namespace evo::processes diff --git a/src/processes/ensemble.cpp b/src/processes/ensemble.cpp new file mode 100644 index 0000000..0bc8aad --- /dev/null +++ b/src/processes/ensemble.cpp @@ -0,0 +1,215 @@ +#include "evo/processes/ensemble.hpp" + +#include "evo/biology/mutation.hpp" + +#include + +namespace evo::processes { +namespace { +using biology::Genome; + +constexpr std::uint32_t millikelvin_per_kelvin = 1000U; +// Founders diverge once, under one reference environment, so every cell of the +// gradient compares the same set of strategies rather than a set the cell shaped. +constexpr std::uint32_t reference_temperature = 293'150U; +constexpr std::uint64_t reference_material = 1'000'000'000U; + +accounting::Inventory pooled(std::uint64_t value) noexcept { + return {{value}, + {accounting::Femtograms{value}, accounting::Femtograms{value}, + accounting::Femtograms{value}, accounting::Femtograms{value}}}; +} +std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept { + return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U)); +} +biology::EnvironmentState conditions(const GradientCell& cell) noexcept { + return {cell.temperature_millikelvin, pooled(cell.nutrients)}; +} +} // namespace + +std::expected, EcosystemError> +diverge_founders(const Genome& ancestor, std::size_t wanted, std::uint64_t seed) { + if (wanted == 0 || wanted > biology::max_candidates + 1) { + return std::unexpected{EcosystemError::invalid_config}; + } + std::vector founders{ancestor}; + if (wanted == 1) { + return founders; + } + const biology::MutationContext context{ + seed, 1, + 1, static_cast(wanted - 1), + {1000, 0}, {reference_temperature, pooled(reference_material)}}; + const auto offer = biology::mutation_candidates(ancestor, context); + if (!offer || offer->candidates.size() + 1 < wanted) { + return std::unexpected{EcosystemError::invalid_config}; + } + for (std::size_t index = 0; index + 1 < wanted; ++index) { + const auto successor = biology::select_mutation( + ancestor, context, *offer, offer->candidates[index].operator_id, + ancestor.id() + index + 1, ancestor.origin_event() + index + 1); + if (!successor) { + return std::unexpected{EcosystemError::invalid_config}; + } + founders.push_back(*successor); + } + return founders; +} + +std::expected +run_ensemble(biology::LineageArchive& archive, std::span founders, + const EcosystemConfig& base, const EnsembleConfig& plan, std::uint64_t seed) { + if (founders.empty() || founders.size() > max_strategies || plan.gradient.empty() || + plan.seeds_per_cell < 2 || plan.tick_limit == 0 || plan.base_lifespan == 0) { + return std::unexpected{EcosystemError::invalid_config}; + } + for (const auto& genome : founders) { + if (!archive.admit(genome)) { + return std::unexpected{EcosystemError::invalid_config}; + } + } + EnsembleReport report{}; + std::uint64_t organism_identity = 0; + std::uint64_t ordinal = 0; + for (const auto& cell : plan.gradient) { + const auto environment = conditions(cell); + CellReport measured{}; + measured.cell = cell; + std::vector strategies; + for (const auto& genome : founders) { + const auto phenotype = biology::derive_phenotype(genome, {1000, 0}, environment); + if (!phenotype) { + return std::unexpected{EcosystemError::invalid_config}; + } + // The harness shortens scheduled life under thermal stress, which is + // what makes the temperature axis consequential. A scheduling rule, + // not a mortality model, and no contract knows about it. + const auto lost = phenotype->thermal_shortfall / millikelvin_per_kelvin * + plan.lifespan_lost_per_kelvin; + const auto lifespan = lost >= plan.base_lifespan ? 1U : plan.base_lifespan - lost; + // An explicit experimental budget, as ADR-0026 requires, scaled so no + // strategy is excluded from acting by the size of the handout. + const auto budget = biology::metabolic_budget(genome, {1000, 0}, environment); + if (!budget) { + return std::unexpected{EcosystemError::invalid_config}; + } + const auto strategy = strategy_for(genome, {1000, 0}, environment, + budget->reproduction_investment, lifespan); + if (!strategy) { + return std::unexpected{EcosystemError::invalid_config}; + } + strategies.push_back(*strategy); + StrategyOutcome blank{}; + blank.genome = genome.id(); + blank.scheduled_lifespan = lifespan; + blank.thermal_shortfall = phenotype->thermal_shortfall; + measured.first_half.push_back(blank); + measured.second_half.push_back(blank); + } + for (std::uint64_t index = 0; index < plan.seeds_per_cell; ++index) { + auto config = base; + config.tick_limit = plan.tick_limit; + config.nutrients = pooled(cell.nutrients).matter; + auto episode = EcosystemEpisode::create(config, strategies, seed + ordinal); + if (!episode) { + return std::unexpected{episode.error()}; + } + ++ordinal; + auto& half = + index * 2 < plan.seeds_per_cell ? measured.first_half : measured.second_half; + const auto slots = static_cast(founders.size() + config.capacity + 1); + std::vector identity(slots + 1U); + std::vector born_at(slots + 1U); + std::vector living(slots + 1U, false); + for (std::uint32_t slot = 2; slot <= slots; ++slot) { + const auto exists = episode->community().born(slot); + if (!exists || !*exists) { + continue; + } + identity[slot] = ++organism_identity; + living[slot] = true; + const auto strategy = static_cast(slot - 2); + if (!archive.record_birth(identity[slot], founders[strategy].id(), Tick{0})) { + return std::unexpected{EcosystemError::invalid_config}; + } + ++half[strategy].organisms; + } + for (auto& outcome : half) { + ++outcome.episodes; + } + while (true) { + const auto stepped = episode->step(); + if (!stepped) { + return std::unexpected{stepped.error()}; + } + const auto tick = episode->community().progress().tick; + for (std::uint32_t slot = 2; slot <= slots; ++slot) { + const auto exists = episode->community().born(slot); + const auto alive = episode->community().active(slot); + // An unallocated slot has no lineage, so skip it before any + // index is derived from one. + if (!exists || !*exists || !alive) { + continue; + } + const auto strategy = static_cast(episode->lineage(slot) - 2); + if (identity[slot] == 0) { + identity[slot] = ++organism_identity; + born_at[slot] = tick.value; + living[slot] = true; + if (!archive.record_birth(identity[slot], founders[strategy].id(), tick)) { + return std::unexpected{EcosystemError::invalid_config}; + } + ++half[strategy].births; + ++half[strategy].organisms; + } else if (living[slot] && !*alive) { + living[slot] = false; + if (!archive.record_death(identity[slot], tick)) { + return std::unexpected{EcosystemError::invalid_config}; + } + half[strategy].lived_ticks += tick.value - born_at[slot]; + } + } + if (!*stepped) { + break; + } + } + const auto summary = episode->report(); + // Anything still alive lived to the end of the episode. + for (std::uint32_t slot = 2; slot <= slots; ++slot) { + if (living[slot]) { + const auto strategy = static_cast(episode->lineage(slot) - 2); + half[strategy].lived_ticks += summary.ticks - born_at[slot]; + if (!archive.record_death(identity[slot], Tick{summary.ticks})) { + return std::unexpected{EcosystemError::invalid_config}; + } + } + } + measured.ticks += summary.ticks; + measured.extinctions += summary.extinction_tick != 0 ? 1 : 0; + report.ticks += summary.ticks; + ++report.episodes; + } + report.cells.push_back(measured); + } + report.archived_genomes = archive.archived(); + report.archived_organisms = archive.recorded(); + std::uint64_t hash = mix(0, report.episodes); + hash = mix(hash, report.ticks); + for (const auto& cell : report.cells) { + hash = mix(hash, cell.ticks); + hash = mix(hash, cell.extinctions); + for (const auto* half : {&cell.first_half, &cell.second_half}) { + for (const auto& outcome : *half) { + for (const auto value : + {outcome.genome, outcome.episodes, outcome.births, outcome.organisms, + outcome.lived_ticks, outcome.thermal_shortfall, + static_cast(outcome.scheduled_lifespan)}) { + hash = mix(hash, value); + } + } + } + } + report.fingerprint = hash; + return report; +} +} // namespace evo::processes diff --git a/src/processes/genome_strategy.cpp b/src/processes/genome_strategy.cpp index 87ff6eb..571a4a1 100644 --- a/src/processes/genome_strategy.cpp +++ b/src/processes/genome_strategy.cpp @@ -10,4 +10,20 @@ consumer_for(const biology::Genome& genome, biology::GrowthState growth, } return ConsumerConfig{opening, budget->intake_limit, budget->assimilation_per_thousand}; } + +std::expected +strategy_for(const biology::Genome& genome, biology::GrowthState growth, + biology::EnvironmentState environment, accounting::Inventory opening, + std::uint32_t lifespan) { + const auto budget = biology::metabolic_budget(genome, growth, environment); + if (!budget) { + return std::unexpected{budget.error()}; + } + return StrategyConfig{opening, + budget->intake_limit, + budget->assimilation_per_thousand, + budget->reproduction_investment, + budget->reproduction_investment, + lifespan}; +} } // namespace evo::processes diff --git a/tests/ensemble_tests.cpp b/tests/ensemble_tests.cpp new file mode 100644 index 0000000..4c78a02 --- /dev/null +++ b/tests/ensemble_tests.cpp @@ -0,0 +1,299 @@ +#include "evo/processes/ensemble.hpp" + +#include +#include +#include +#include +#include +#include +#include + +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(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 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()); + for (const auto& genome : set) { + CHECK(archive.find(genome.id())); + // Every episode ended, so nothing is still carrying anything. + CHECK(*archive.status(genome.id()) == LineageStatus::absent); + CHECK(*archive.living_carriers(genome.id()) == 0); + } + // 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 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. + CHECK(at_extreme.first_half[0].thermal_shortfall == 30'000); + CHECK(at_extreme.first_half[1].thermal_shortfall == 10'000); + 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 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(); + invalid_plans_are_refused(); + std::cout << "PASS genome-derived strategies, gradient ensembles and split-half agreement\n"; + return 0; +} catch (...) { + return 1; +}