Files
aevolution/apps/evo-sim/main.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

522 lines
22 KiB
C++

#include "evo/processes/ecosystem.hpp"
#include "evo/processes/ensemble.hpp"
#include "evo/simulation/world.hpp"
#include "evo/telemetry/sinks.hpp"
#include <array>
#include <charconv>
#include <exception>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
namespace {
struct Options {
std::uint64_t seed{123456};
std::uint64_t ticks{1000};
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{};
};
std::expected<std::uint64_t, evo::Error> number(std::string_view text) {
std::uint64_t value{};
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size()) {
return std::unexpected{evo::Error::invalid_arguments};
}
return value;
}
std::expected<void, evo::Error> validate_paths(const Options& options) {
auto paths = std::array{options.load, options.save, options.output, options.metrics};
for (auto& path : paths) {
if (!path.empty()) {
std::error_code error;
path = std::filesystem::weakly_canonical(path, error);
if (error) {
return std::unexpected{evo::Error::io_failure};
}
}
}
for (std::size_t first = 0; first < paths.size(); ++first) {
for (std::size_t second = first + 1; second < paths.size(); ++second) {
if (paths[first].empty() || paths[second].empty()) {
continue;
}
if (paths[first] == paths[second]) {
return std::unexpected{evo::Error::invalid_arguments};
}
std::error_code error;
const auto first_exists = std::filesystem::exists(paths[first], error);
if (error) {
return std::unexpected{evo::Error::io_failure};
}
const auto second_exists = std::filesystem::exists(paths[second], error);
if (error) {
return std::unexpected{evo::Error::io_failure};
}
if (first_exists && second_exists) {
const auto same = std::filesystem::equivalent(paths[first], paths[second], error);
if (error) {
return std::unexpected{evo::Error::io_failure};
}
if (same) {
return std::unexpected{evo::Error::invalid_arguments};
}
}
}
}
return {};
}
std::expected<Options, evo::Error> parse(int argc, char** argv) {
Options options;
bool initial_state_option = false;
bool entities_option = false;
bool ticks_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") {
options.help = true;
continue;
}
if (key == "--verify-replay") {
options.verify_replay = true;
continue;
}
if (key == "--ecosystem") {
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 == "--seeds-per-cell" || key == "--strategies") {
const auto parsed = number(value);
if (!parsed) {
return std::unexpected{parsed.error()};
}
if (key == "--seed") {
options.seed = *parsed;
initial_state_option = true;
} else if (key == "--entities") {
options.entities = *parsed;
initial_state_option = true;
entities_option = true;
} else if (key == "--episodes") {
options.episodes = *parsed;
episodes_option = true;
} else if (key == "--tick-limit") {
options.tick_limit = *parsed;
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;
}
} else if (key == "--load") {
options.load = value;
} else if (key == "--save") {
options.save = value;
} else if (key == "--output") {
options.output = value;
} else if (key == "--metrics") {
options.metrics = value;
} else {
return std::unexpected{evo::Error::invalid_arguments};
}
}
if (options.entities > evo::max_entities || (!options.load.empty() && initial_state_option)) {
return std::unexpected{evo::Error::invalid_arguments};
}
// Every option must belong to the selected mode. An option that is accepted and
// then ignored lets a measurement script succeed while running another workload.
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) {
// 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 (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) {
return std::unexpected{valid.error()};
}
return options;
}
std::expected<evo::SimulationWorld, evo::Error> initial_world(const Options& options) {
if (options.load.empty()) {
evo::SimulationWorld world{options.seed};
for (std::uint64_t index = 0; index < options.entities; ++index) {
const auto created = world.create_entity();
if (!created) {
return std::unexpected{created.error()};
}
}
return world;
}
std::ifstream input{options.load, std::ios::binary | std::ios::ate};
const auto length = input.tellg();
if (!input || length < 0 || length > static_cast<std::streamoff>(evo::max_snapshot_bytes)) {
return std::unexpected{evo::Error::io_failure};
}
evo::Snapshot bytes(static_cast<std::size_t>(length));
input.seekg(0);
if (!bytes.empty()) {
input.read(reinterpret_cast<char*>(bytes.data()),
static_cast<std::streamsize>(bytes.size()));
}
if (!input) {
return std::unexpected{evo::Error::io_failure};
}
return evo::SimulationWorld::restore(bytes);
}
std::expected<void, evo::Error> advance(evo::SimulationWorld& world, std::uint64_t ticks) {
if (ticks > std::numeric_limits<std::uint64_t>::max() - world.current_tick().value) {
return std::unexpected{evo::Error::tick_exhausted};
}
for (std::uint64_t tick = 0; tick < ticks; ++tick) {
if (const auto result = world.tick(); !result) {
return result;
}
}
return {};
}
std::expected<void, evo::Error> write_report(const Options& options, const std::string& text) {
std::ofstream output_file;
if (!options.output.empty()) {
if (const auto valid = validate_paths(options); !valid) {
return valid;
}
output_file.open(options.output);
if (!output_file) {
return std::unexpected{evo::Error::io_failure};
}
}
auto& output = options.output.empty() ? std::cout : output_file;
output << text;
output.flush();
if (!options.output.empty()) {
output_file.close();
}
if (!output) {
return std::unexpected{evo::Error::io_failure};
}
return {};
}
// CLI-local fixture constants. They are measurement inputs, not simulation rules,
// and are deliberately not exported by the library. See ADR-0029.
evo::accounting::Inventory bundle(std::uint64_t value) {
using namespace evo::accounting;
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
}
evo::processes::StrategyConfig grazer() {
return {bundle(20), bundle(3), 900, bundle(30), bundle(20), 50};
}
evo::processes::StrategyConfig forager() {
return {bundle(20), bundle(2), 1000, bundle(24), bundle(16), 70};
}
std::expected<void, evo::Error> run_ecosystem(const Options& options) {
using namespace evo::processes;
const ProducerConfig plants{{{10}, 1}, {2, 1}, 1000, {1}, bundle(1).matter};
const EcosystemConfig config{plants, {100'000}, bundle(200).matter, {bundle(4)},
800, 14, options.tick_limit};
const std::array founders{grazer(), forager()};
std::uint64_t ticks{}, births{}, predation{}, lifespan{}, extinctions{}, survivors{};
std::uint64_t shortest = std::numeric_limits<std::uint64_t>::max(), longest{}, fingerprint{};
for (std::uint64_t index = 0; index < options.episodes; ++index) {
if (options.seed > std::numeric_limits<std::uint64_t>::max() - index) {
return std::unexpected{evo::Error::invalid_arguments};
}
auto episode = EcosystemEpisode::create(config, founders, options.seed + index);
if (!episode) {
return std::unexpected{evo::Error::invalid_arguments};
}
const auto summary = episode->run();
if (!summary) {
return std::unexpected{evo::Error::replay_mismatch};
}
if (summary->ticks > std::numeric_limits<std::uint64_t>::max() - ticks) {
return std::unexpected{evo::Error::tick_exhausted};
}
ticks += summary->ticks;
births += summary->births;
predation += summary->predation_deaths;
lifespan += summary->lifespan_deaths;
extinctions += summary->extinction_tick != 0 ? 1 : 0;
survivors += summary->surviving_lineages;
shortest = std::min(shortest, summary->ticks);
longest = std::max(longest, summary->ticks);
fingerprint ^= summary->fingerprint + 0x9e3779b97f4a7c15ULL + (fingerprint << 6U) +
(fingerprint >> 2U);
}
std::ostringstream report;
report << "{\"rules_version\":" << evo::rules_version
<< ",\"mode\":\"ecosystem\",\"seed\":" << options.seed
<< ",\"episodes\":" << options.episodes << ",\"tick_limit\":" << options.tick_limit
<< ",\"ticks\":" << ticks << ",\"births\":" << births
<< ",\"predation_deaths\":" << predation << ",\"lifespan_deaths\":" << lifespan
<< ",\"extinctions\":" << extinctions << ",\"surviving_lineages\":" << survivors
<< ",\"shortest\":" << shortest << ",\"longest\":" << longest << ",\"fingerprint\":\""
<< std::hex << std::setfill('0') << std::setw(16) << fingerprint << std::dec << "\"}\n";
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<void, evo::Error> 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<std::size_t>(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 << ",\"deaths\":" << outcome.deaths
<< ",\"lived_ticks\":" << outcome.lived_ticks
<< ",\"survivors\":" << outcome.survivors
<< ",\"observed_ticks\":" << outcome.observed_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<void, evo::Error> 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()};
}
auto world = std::move(*loaded);
std::optional<evo::SimulationWorld> replay;
if (options.verify_replay) {
replay = world;
}
if (const auto result = advance(world, options.ticks); !result) {
return result;
}
if (replay) {
const auto half = options.ticks / 2;
if (const auto result = advance(*replay, half); !result) {
return result;
}
auto restored = evo::SimulationWorld::restore(replay->serialize());
if (!restored) {
return std::unexpected{restored.error()};
}
if (const auto result = advance(*restored, options.ticks - half); !result) {
return result;
}
if (restored->serialize() != world.serialize()) {
return std::unexpected{evo::Error::replay_mismatch};
}
}
if (!options.save.empty()) {
const auto bytes = world.serialize();
std::ofstream snapshot{options.save, std::ios::binary | std::ios::trunc};
snapshot.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(bytes.size()));
snapshot.close();
if (!snapshot) {
return std::unexpected{evo::Error::io_failure};
}
}
if (!options.metrics.empty()) {
if (const auto valid = validate_paths(options); !valid) {
return valid;
}
std::ofstream metrics_file{options.metrics};
evo::PrometheusTextSink sink{metrics_file};
sink.observe({world.current_tick(), static_cast<std::uint64_t>(world.entities().size())});
metrics_file.close();
if (!metrics_file) {
return std::unexpected{evo::Error::io_failure};
}
}
std::ofstream output_file;
if (!options.output.empty()) {
if (const auto valid = validate_paths(options); !valid) {
return valid;
}
output_file.open(options.output);
if (!output_file) {
return std::unexpected{evo::Error::io_failure};
}
}
auto& output = options.output.empty() ? std::cout : output_file;
output << "{\"rules_version\":" << evo::rules_version
<< ",\"format_version\":" << evo::format_version << ",\"seed\":" << world.seed()
<< ",\"ticks\":" << world.current_tick().value
<< ",\"entities\":" << world.entities().size() << ",\"state_hash\":\"" << std::hex
<< std::setfill('0') << std::setw(16) << world.state_hash() << std::dec
<< "\",\"replay_verified\":" << (options.verify_replay ? "true" : "false") << "}\n";
output.flush();
if (!options.output.empty()) {
output_file.close();
}
if (!output) {
return std::unexpected{evo::Error::io_failure};
}
return {};
}
} // namespace
int main(int argc, char** argv) try {
try {
const auto options = parse(argc, argv);
if (!options) {
evo::log_error(std::cerr, options.error());
return 2;
}
if (options->help) {
std::cout
<< "evo-sim [--seed N --entities N | --load FILE] --ticks N\n"
" [--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"
"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);
if (!result) {
evo::log_error(std::cerr, result.error());
return 1;
}
return 0;
} catch (const std::exception&) {
evo::log_error(std::cerr, evo::Error::unhandled_exception);
return 1;
}
} catch (...) {
// Last-resort process boundary, including failure of error reporting itself.
return 1;
}