Files
aevolution/tests/genome_tests.cpp
T
dingoandClaude Opus 5.5 17fe23e5f0
Foundation / checks (deploy) (push) Successful in 3m32s
Foundation / checks (ecs) (push) Successful in 1m56s
Foundation / checks (client) (push) Successful in 12m56s
Foundation / checks (network) (push) Successful in 13m46s
Foundation / checks (tsan) (push) Successful in 7m59s
Foundation / checks (checks) (push) Successful in 33m36s
Foundation / checks (postgres) (push) Successful in 45m30s
Foundation / postgres-tools (push) Successful in 20s
Foundation / server-image (push) Successful in 25s
Foundation / image (push) Successful in 2m36s
M11.1: genome schema 2 with per-second rates (ADR-0099, segment 2)
Movement and ingestion are stored per second in schema 2 (ranges x20). Schema 1 records
stay valid, are never rewritten, and read as exactly x20 via Genome::per_second; drafts
default to schema 1 so existing literals keep their meaning. Development version 1
converts genome rates at its own 50 ms quantum (round down), so phenotypes are
unchanged. Mutation keeps the parent's schema and step; the lineage archive header names
exactly the highest schema held (all-schema-1 archives keep their bytes); the
development-v1 opening names schema 1. No golden changed; two tests that used 2 as an
unknown schema now use the next one. Refresh the dev session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:16:55 -04:00

405 lines
19 KiB
C++

#include "evo/biology/genome.hpp"
#include <algorithm>
#include <iostream>
#include <source_location>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace {
using namespace evo::biology;
void check(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error("genome line " + std::to_string(location.line()));
}
}
#define CHECK(expression) check(static_cast<bool>(expression))
// The three schema-required capabilities, in canonical order.
std::vector<CapabilityRecord> minimal() {
return {{Capability::energy_conversion, 400, 0},
{Capability::membrane, 120, 0},
{Capability::target_size, 5'000, 0}};
}
GenomeDraft founder() {
return {7, 1, 1, {}, minimal()};
}
GenomeDraft descendant() {
auto draft = founder();
draft.id = 8;
draft.origin_event = 2;
draft.parents = {7};
return draft;
}
std::uint32_t bits(std::initializer_list<Capability> kinds) {
std::uint32_t mask{};
for (const auto kind : kinds) {
mask |= capability_bit(kind);
}
return mask;
}
void reject(const GenomeDraft& draft, GenomeError expected,
std::source_location location = std::source_location::current()) {
const auto result = Genome::create(draft);
check(!result && result.error() == expected, location);
}
void founders_and_ancestry() {
const auto first = Genome::create(founder());
CHECK(first);
CHECK(first->id() == 7 && first->origin_event() == 1);
CHECK(first->schema_version() == 1 && first->development_version() == 1);
CHECK(first->parents().empty()); // Zero parents identifies a documented founder.
CHECK(first->capabilities().size() == 3);
CHECK(first->carries(Capability::membrane) && !first->carries(Capability::movement));
CHECK(first->parameter(Capability::membrane) && *first->parameter(Capability::membrane) == 120);
const auto absent = first->parameter(Capability::movement);
CHECK(!absent && absent.error() == GenomeError::missing_capability);
const auto child = Genome::create(descendant());
CHECK(child);
CHECK(child->parents().size() == 1 && child->parents()[0] == 7);
// Identical capabilities from a different origin never share a digest.
CHECK(child->content_digest() != first->content_digest());
CHECK(*child != *first);
// A draft is unordered input; the stored record is canonical.
auto shuffled = founder();
std::ranges::reverse(shuffled.capabilities);
const auto same = Genome::create(shuffled);
CHECK(same && *same == *first && same->encode() == first->encode());
CHECK(std::ranges::is_sorted(same->capabilities(), {}, &CapabilityRecord::kind));
}
void ancestry_rules() {
auto draft = descendant();
draft.id = 0;
reject(draft, GenomeError::invalid_identity);
draft = descendant();
draft.origin_event = 0;
reject(draft, GenomeError::invalid_identity);
draft = descendant();
draft.development_version = 0;
reject(draft, GenomeError::unsupported_version);
draft = descendant();
draft.parents = {0};
reject(draft, GenomeError::invalid_ancestry);
draft = descendant();
draft.parents = {draft.id}; // A genome cannot descend from itself.
reject(draft, GenomeError::invalid_ancestry);
draft = descendant();
draft.parents = {7, 9}; // Reserved in the format, rejected by schema 1.
reject(draft, GenomeError::invalid_ancestry);
draft = descendant();
draft.parents = {7, 7, 7};
reject(draft, GenomeError::invalid_ancestry);
}
void capability_and_range_rules() {
auto draft = founder();
draft.capabilities.clear();
reject(draft, GenomeError::missing_capability);
for (const auto required :
{Capability::energy_conversion, Capability::membrane, Capability::target_size}) {
draft = founder();
std::erase_if(draft.capabilities,
[required](const auto& record) { return record.kind == required; });
reject(draft, GenomeError::missing_capability);
}
draft = founder();
draft.capabilities.push_back({Capability::membrane, 130, 0});
reject(draft, GenomeError::duplicate_capability);
draft = founder();
draft.capabilities.push_back({static_cast<Capability>(capability_count), 1, 0});
reject(draft, GenomeError::unknown_capability);
draft = founder();
draft.capabilities.push_back({Capability::thermal_tolerance, 1, 1U << capability_count});
reject(draft, GenomeError::unknown_capability);
// Every boundary of every declared range, from both sides, in each schema's own table.
for (const auto schema : {genome_schema_v1, genome_schema_version}) {
const auto& table = *capability_schema_for(schema);
const auto fresh = [&] {
auto d = founder();
d.schema_version = schema;
return d;
};
for (std::size_t index = 0; index < capability_count; ++index) {
const auto kind = static_cast<Capability>(index);
const auto& limits = table[index];
for (const auto value : {limits.minimum, limits.maximum}) {
draft = fresh();
std::erase_if(draft.capabilities,
[kind](const auto& record) { return record.kind == kind; });
draft.capabilities.push_back({kind, value, limits.mandates});
const auto accepted = Genome::create(draft);
CHECK(accepted && *accepted->parameter(kind) == value);
}
if (limits.minimum > 0) {
draft = fresh();
std::erase_if(draft.capabilities,
[kind](const auto& record) { return record.kind == kind; });
draft.capabilities.push_back({kind, limits.minimum - 1, limits.mandates});
reject(draft, GenomeError::parameter_out_of_range);
}
draft = fresh();
std::erase_if(draft.capabilities,
[kind](const auto& record) { return record.kind == kind; });
draft.capabilities.push_back({kind, limits.maximum + 1, limits.mandates});
reject(draft, GenomeError::parameter_out_of_range);
}
}
}
void development_graph_rules() {
// Movement and ingestion mandate a membrane, which a founder already carries.
auto draft = founder();
draft.capabilities.push_back({Capability::movement, 250, 0});
draft.capabilities.push_back({Capability::ingestion, 90, 0});
CHECK(Genome::create(draft));
// A declared prerequisite naming a capability the genome does not carry.
draft = founder();
draft.capabilities.push_back(
{Capability::thermal_tolerance, 500, bits({Capability::movement})});
reject(draft, GenomeError::missing_prerequisite);
// In schema 1 every mandated capability is also required, so a mandated
// capability can only be absent when a required one already is. Removing
// membrane reports that, not the mandate.
draft = founder();
std::erase_if(draft.capabilities,
[](const auto& record) { return record.kind == Capability::membrane; });
draft.capabilities.push_back({Capability::movement, 250, 0});
reject(draft, GenomeError::missing_capability);
draft = founder();
draft.capabilities.push_back({Capability::reproduction, 300, 0});
CHECK(Genome::create(draft)); // Reproduction mandates energy conversion, which is present.
// Self, mutual and longer cycles in the declared graph.
draft = founder();
draft.capabilities[1].prerequisites = bits({Capability::membrane});
reject(draft, GenomeError::cyclic_development);
draft = founder();
draft.capabilities[0].prerequisites = bits({Capability::membrane});
draft.capabilities[1].prerequisites = bits({Capability::energy_conversion});
reject(draft, GenomeError::cyclic_development);
draft = founder();
draft.capabilities[0].prerequisites = bits({Capability::membrane});
draft.capabilities[1].prerequisites = bits({Capability::target_size});
draft.capabilities[2].prerequisites = bits({Capability::energy_conversion});
reject(draft, GenomeError::cyclic_development);
// The same three edges without the closing one are a valid ordering.
draft = founder();
draft.capabilities[0].prerequisites = bits({Capability::membrane});
draft.capabilities[1].prerequisites = bits({Capability::target_size});
CHECK(Genome::create(draft));
// A mandated edge can close a cycle a declared edge opened.
draft = founder();
draft.capabilities.push_back({Capability::movement, 250, 0});
draft.capabilities[1].prerequisites = bits({Capability::movement});
reject(draft, GenomeError::cyclic_development);
}
void canonical_encoding() {
auto draft = descendant();
draft.capabilities.push_back({Capability::movement, 250, bits({Capability::membrane})});
draft.capabilities.push_back({Capability::reproduction, 300, 0});
const auto genome = Genome::create(draft);
CHECK(genome);
const auto bytes = genome->encode();
CHECK(bytes.size() <= max_genome_bytes);
const auto restored = Genome::decode(bytes);
CHECK(restored && *restored == *genome);
CHECK(restored->encode() == bytes); // Re-encoding is byte-exact.
CHECK(restored->content_digest() == genome->content_digest());
CHECK(restored->parents().size() == 1 && restored->parents()[0] == 7);
// Truncation at every length, and trailing bytes, are rejected.
for (std::size_t length = 0; length < bytes.size(); ++length) {
CHECK(!Genome::decode(std::span{bytes}.first(length)));
}
auto extended = bytes;
extended.push_back(0);
const auto trailing = Genome::decode(extended);
CHECK(!trailing && trailing.error() == GenomeError::invalid_encoding);
std::vector<std::uint8_t> oversized(max_genome_bytes + 1, 0);
CHECK(!Genome::decode(oversized));
// Every single-byte corruption is caught by the checksum or a later check.
for (std::size_t index = 0; index < bytes.size(); ++index) {
auto damaged = bytes;
damaged[index] = static_cast<std::uint8_t>(damaged[index] ^ 0xffU);
CHECK(!Genome::decode(damaged));
}
auto wrong_magic = bytes;
wrong_magic[0] = 'X';
const auto rejected = Genome::decode(wrong_magic);
CHECK(!rejected && rejected.error() == GenomeError::invalid_encoding);
}
void encoded_record_rules() {
const auto genome = Genome::create(descendant());
CHECK(genome);
auto bytes = genome->encode();
const auto reseal = [](std::vector<std::uint8_t>& raw) {
std::uint64_t hash = 14695981039346656037ULL;
for (std::size_t index = 0; index + 8 < raw.size(); ++index) {
hash = (hash ^ raw[index]) * 1099511628211ULL;
}
for (std::size_t index = 0; index < 8; ++index) {
raw[raw.size() - 8 + index] = static_cast<std::uint8_t>((hash >> (8U * index)) & 0xffU);
}
};
// A rewritten record with a valid checksum still fails the digest check.
auto rewritten = bytes;
rewritten[16] = static_cast<std::uint8_t>(rewritten[16] + 1); // A different genome ID.
reseal(rewritten);
const auto tampered = Genome::decode(rewritten);
CHECK(!tampered && tampered.error() == GenomeError::digest_mismatch);
// An unsupported schema version fails closed before anything else is read.
auto future = bytes;
future[8] = static_cast<std::uint8_t>(genome_schema_version + 1);
reseal(future);
const auto ahead = Genome::decode(future);
CHECK(!ahead && ahead.error() == GenomeError::unsupported_version);
// Non-canonical ordering is rejected even though both kinds are known.
auto unordered = Genome::create(founder())->encode();
const std::size_t first_record = 36 + 4;
const std::size_t second_record = first_record + 9;
std::swap_ranges(unordered.begin() + first_record, unordered.begin() + second_record,
unordered.begin() + second_record);
reseal(unordered);
const auto misordered = Genome::decode(unordered);
CHECK(!misordered && misordered.error() == GenomeError::duplicate_capability);
// A declared count larger than the schema knows about is refused. One parent
// sits between the fixed prefix and the capability count.
auto overcounted = bytes;
overcounted[36 + 8] = static_cast<std::uint8_t>(capability_count + 1);
reseal(overcounted);
const auto excessive = Genome::decode(overcounted);
CHECK(!excessive && excessive.error() == GenomeError::duplicate_capability);
// A parent count beyond the reserved room is refused before any parent is read.
auto crowded = bytes;
crowded[32] = static_cast<std::uint8_t>(max_parents + 1);
reseal(crowded);
const auto overfull = Genome::decode(crowded);
CHECK(!overfull && overfull.error() == GenomeError::invalid_ancestry);
}
// A frozen schema 1 record for the founder above, verified by hand against
// schemas/genome-v1.md. Changing these bytes changes the meaning of every
// existing v1 record: it needs a schema version and a migration, not an edit.
const std::vector<std::uint8_t>& frozen_founder() {
static const std::vector<std::uint8_t> bytes{
0x41, 0x45, 0x56, 0x4f, 0x47, 0x45, 0x4e, 0x31, // magic AEVOGEN1
0x01, 0x00, 0x00, 0x00, // schema version 1
0x01, 0x00, 0x00, 0x00, // development version 1
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // genome ID 7
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // origin event 1
0x00, 0x00, 0x00, 0x00, // no parents: a founder
0x03, 0x00, 0x00, 0x00, // three capabilities
0x00, 0x90, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // conversion 400
0x01, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // membrane 120
0x05, 0x88, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // target size 5000
0x7f, 0xc8, 0x6a, 0xf1, 0xde, 0xde, 0x2c, 0x9b, // content digest
0x0b, 0xb0, 0xaa, 0xf8, 0x3c, 0x76, 0x83, 0xec}; // checksum
return bytes;
}
void frozen_record_compatibility() {
const auto genome = Genome::create(founder());
CHECK(genome);
// The encoder must still produce the bytes a v1 record was written with.
CHECK(genome->encode() == frozen_founder());
CHECK(frozen_founder().size() == 56 + 9 * 3);
CHECK(genome->content_digest() == 0x9b2cdedef16ac87fULL);
// The decoder must still read them, independently of what the encoder does.
const auto restored = Genome::decode(frozen_founder());
CHECK(restored);
CHECK(restored->id() == 7 && restored->origin_event() == 1);
CHECK(restored->schema_version() == 1 && restored->development_version() == 1);
CHECK(restored->parents().empty());
CHECK(restored->capabilities().size() == 3);
CHECK(restored->capabilities()[0] == (CapabilityRecord{Capability::energy_conversion, 400, 0}));
CHECK(restored->capabilities()[1] == (CapabilityRecord{Capability::membrane, 120, 0}));
CHECK(restored->capabilities()[2] == (CapabilityRecord{Capability::target_size, 5'000, 0}));
CHECK(restored->content_digest() == 0x9b2cdedef16ac87fULL);
CHECK(*restored == *genome);
}
// Schema 2 (ADR-0099): rates per second. Schema 1 records stay valid, unrewritten, and
// read as exactly twenty times their per-tick values.
void schema_v2_rates() {
auto v1 = founder();
v1.capabilities.push_back({Capability::movement, 5'000, 0});
v1.capabilities.push_back({Capability::ingestion, 1'000'000, 0}); // Schema 1 maximum.
const auto old = Genome::create(v1);
CHECK(old && old->schema_version() == genome_schema_v1);
CHECK(old->per_second(Capability::movement) == std::uint64_t{100'000});
CHECK(old->per_second(Capability::ingestion) == std::uint64_t{20'000'000});
CHECK(old->per_second(Capability::target_size) == std::uint64_t{5'000}); // Not a rate.
CHECK(!old->per_second(Capability::thermal_tolerance));
auto v2 = v1;
v2.schema_version = genome_schema_version;
v2.capabilities[3].parameter = 100'000; // Movement, per second.
v2.capabilities[4].parameter = 20'000'000;
const auto now = Genome::create(v2);
CHECK(now && now->schema_version() == 2);
CHECK(now->per_second(Capability::movement) == old->per_second(Capability::movement));
CHECK(now->per_second(Capability::ingestion) == old->per_second(Capability::ingestion));
// The same meaning in another schema is another record.
CHECK(now->content_digest() != old->content_digest());
const auto restored = Genome::decode(now->encode());
CHECK(restored && *restored == *now && restored->schema_version() == 2);
// Ranges are per schema: a schema 2 rate may exceed schema 1's per-tick maximum.
v2.capabilities[4].parameter = 20'000'001;
reject(v2, GenomeError::parameter_out_of_range);
v1.capabilities[4].parameter = 1'000'001;
reject(v1, GenomeError::parameter_out_of_range);
auto unknown = founder();
unknown.schema_version = 3;
reject(unknown, GenomeError::unsupported_version);
auto bytes = Genome::create(founder())->encode();
bytes[8] = 3; // Schema field; decode refuses before the checksum matters.
CHECK(!Genome::decode(bytes) &&
Genome::decode(bytes).error() == GenomeError::unsupported_version);
}
void moves_preserve_validity() {
const auto original = Genome::create(founder());
const auto other = Genome::create(descendant());
CHECK(original && other);
// Moves decay to copies, so a moved-from record is still a whole genome
// rather than an identity with no capabilities.
auto source = *original;
// The decay to a copy is the contract under test, so tidy is right that no
// move happens here and wrong that it is a mistake.
// NOLINTNEXTLINE(performance-move-const-arg)
const auto moved = std::move(source);
CHECK(moved == *original);
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
CHECK(source == *original);
CHECK(source.capabilities().size() == 3 && source.id() == 7);
CHECK(Genome::decode(source.encode()));
auto target = *original;
auto donor = *other;
// NOLINTNEXTLINE(performance-move-const-arg)
target = std::move(donor);
CHECK(target == *other);
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
CHECK(donor == *other);
CHECK(Genome::decode(donor.encode()));
static_assert(std::is_copy_constructible_v<Genome>);
static_assert(std::is_copy_assignable_v<Genome>);
}
} // namespace
int main() try {
founders_and_ancestry();
ancestry_rules();
capability_and_range_rules();
development_graph_rules();
canonical_encoding();
encoded_record_rules();
frozen_record_compatibility();
schema_v2_rates();
moves_preserve_validity();
std::cout << "PASS genome schema, ancestry, development graph and canonical encoding\n";
return 0;
} catch (...) {
return 1;
}