Files
aevolution/src/biology/genome.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

317 lines
13 KiB
C++

#include "evo/biology/genome.hpp"
#include "evo/accounting/rates.hpp"
#include <algorithm>
namespace evo::biology {
namespace {
constexpr std::array<std::uint8_t, 8> magic{'A', 'E', 'V', 'O', 'G', 'E', 'N', '1'};
// Magic, versions, identity, origin and parent count.
constexpr std::size_t fixed_prefix = 36;
constexpr std::size_t parent_size = 8;
constexpr std::size_t record_size = 9;
constexpr std::size_t digest_size = 8;
constexpr std::size_t checksum_size = 8;
// Accidental-corruption detection only, per ADR-0008. Not authenticity.
std::uint64_t checksum(std::span<const std::uint8_t> bytes) noexcept {
std::uint64_t hash = 14695981039346656037ULL;
for (const auto byte : bytes) {
hash = (hash ^ byte) * 1099511628211ULL;
}
return hash;
}
// Record digest, deliberately a different function from the checksum: the two
// answer different questions and neither is a cryptographic claim.
std::uint64_t digest_of(std::span<const std::uint8_t> bytes) noexcept {
std::uint64_t hash = 0x9e3779b97f4a7c15ULL;
for (const auto byte : bytes) {
hash ^= byte;
hash *= 0xff51afd7ed558ccdULL;
hash ^= hash >> 29U;
}
return hash;
}
void append(std::vector<std::uint8_t>& bytes, std::uint64_t value, std::size_t width) {
for (std::size_t index = 0; index < width; ++index) {
bytes.push_back(static_cast<std::uint8_t>(value & 0xffU));
value >>= 8U;
}
}
// Private reader: callers validate the whole bounded region before reading.
// Widths below are constants, not input-controlled values.
class Reader {
public:
explicit Reader(std::span<const std::uint8_t> bytes) noexcept : bytes_{bytes} {}
std::uint64_t read(std::size_t width) noexcept {
std::uint64_t value{};
for (std::size_t index = 0; index < width; ++index) {
value |= static_cast<std::uint64_t>(bytes_[offset_++]) << (8U * index);
}
return value;
}
private:
std::span<const std::uint8_t> bytes_;
std::size_t offset_{};
};
constexpr std::uint32_t every_capability = (1U << capability_count) - 1U;
std::expected<void, GenomeError> validate(std::uint32_t schema, std::uint64_t id,
std::uint64_t origin, std::uint32_t development,
std::span<const std::uint64_t> parents,
std::span<const CapabilityRecord> capabilities) {
const auto* table = capability_schema_for(schema);
if (table == nullptr) {
return std::unexpected{GenomeError::unsupported_version};
}
const auto spec = [table](Capability kind) -> const CapabilitySpec& {
return (*table)[static_cast<std::size_t>(kind)];
};
if (id == 0 || origin == 0) {
return std::unexpected{GenomeError::invalid_identity};
}
if (development == 0) {
return std::unexpected{GenomeError::unsupported_version};
}
// The format reserves room for recombination; schema 1 admits one parent.
if (parents.size() > 1) {
return std::unexpected{GenomeError::invalid_ancestry};
}
for (std::size_t index = 0; index < parents.size(); ++index) {
if (parents[index] == 0 || parents[index] == id) {
return std::unexpected{GenomeError::invalid_ancestry};
}
for (std::size_t other = index + 1; other < parents.size(); ++other) {
if (parents[index] == parents[other]) {
return std::unexpected{GenomeError::invalid_ancestry};
}
}
}
if (capabilities.empty()) {
return std::unexpected{GenomeError::missing_capability};
}
if (capabilities.size() > capability_count) {
return std::unexpected{GenomeError::duplicate_capability};
}
std::uint32_t present{};
for (std::size_t index = 0; index < capabilities.size(); ++index) {
const auto& record = capabilities[index];
if (static_cast<std::size_t>(record.kind) >= capability_count) {
return std::unexpected{GenomeError::unknown_capability};
}
// Strictly ascending order is canonical and rejects duplicates at once.
if (index > 0 && !(capabilities[index - 1].kind < record.kind)) {
return std::unexpected{GenomeError::duplicate_capability};
}
if ((record.prerequisites & ~every_capability) != 0) {
return std::unexpected{GenomeError::unknown_capability};
}
const auto& limits = spec(record.kind);
if (record.parameter < limits.minimum || record.parameter > limits.maximum) {
return std::unexpected{GenomeError::parameter_out_of_range};
}
present |= capability_bit(record.kind);
}
for (std::size_t index = 0; index < capability_count; ++index) {
const auto kind = static_cast<Capability>(index);
if ((*table)[index].required && (present & capability_bit(kind)) == 0) {
return std::unexpected{GenomeError::missing_capability};
}
}
std::array<std::uint32_t, capability_count> edges{};
for (const auto& record : capabilities) {
// In schema 1 every mandated capability is also a required one, so this
// presence check fires only for declared prerequisites. Mandated edges
// still take part in the cycle closure below, and a later schema may
// mandate a capability that is not required.
const auto required = record.prerequisites | spec(record.kind).mandates;
if ((required & ~present) != 0) {
return std::unexpected{GenomeError::missing_prerequisite};
}
edges[static_cast<std::size_t>(record.kind)] = required;
}
// Seven nodes make the transitive closure exact and bounded.
for (std::size_t round = 0; round < capability_count; ++round) {
for (std::size_t node = 0; node < capability_count; ++node) {
std::uint32_t reached = edges[node];
for (std::size_t other = 0; other < capability_count; ++other) {
if ((edges[node] & (1U << other)) != 0) {
reached |= edges[other];
}
}
edges[node] = reached;
}
}
for (std::size_t node = 0; node < capability_count; ++node) {
if ((edges[node] & (1U << node)) != 0) {
return std::unexpected{GenomeError::cyclic_development};
}
}
return {};
}
} // namespace
std::vector<std::uint8_t> Genome::body() const {
std::vector<std::uint8_t> bytes;
bytes.reserve(max_genome_bytes);
bytes.insert(bytes.end(), magic.begin(), magic.end());
append(bytes, schema_version_, 4);
append(bytes, development_version_, 4);
append(bytes, id_, 8);
append(bytes, origin_event_, 8);
append(bytes, parents_.size(), 4);
for (const auto parent : parents_) {
append(bytes, parent, 8);
}
append(bytes, capabilities_.size(), 4);
for (const auto& record : capabilities_) {
append(bytes, static_cast<std::uint64_t>(record.kind), 1);
append(bytes, record.parameter, 4);
append(bytes, record.prerequisites, 4);
}
return bytes;
}
std::vector<std::uint8_t> Genome::encode() const {
auto bytes = body();
append(bytes, digest_, digest_size);
append(bytes, checksum(bytes), checksum_size);
return bytes;
}
std::expected<Genome, GenomeError> Genome::create(const GenomeDraft& draft) {
// A draft is unordered input; the stored record is canonical.
std::vector<CapabilityRecord> ordered{draft.capabilities.begin(), draft.capabilities.end()};
std::ranges::sort(ordered, {}, &CapabilityRecord::kind);
if (draft.parents.size() > max_parents) {
return std::unexpected{GenomeError::invalid_ancestry};
}
if (const auto valid = validate(draft.schema_version, draft.id, draft.origin_event,
draft.development_version, draft.parents, ordered);
!valid) {
return std::unexpected{valid.error()};
}
Genome genome;
genome.schema_version_ = draft.schema_version;
genome.id_ = draft.id;
genome.origin_event_ = draft.origin_event;
genome.development_version_ = draft.development_version;
genome.parents_ = draft.parents;
genome.capabilities_ = std::move(ordered);
genome.digest_ = digest_of(genome.body());
return genome;
}
std::expected<Genome, GenomeError> Genome::decode(std::span<const std::uint8_t> bytes) {
if (bytes.size() < fixed_prefix + 4 + digest_size + checksum_size ||
bytes.size() > max_genome_bytes) {
return std::unexpected{GenomeError::invalid_encoding};
}
if (!std::equal(magic.begin(), magic.end(), bytes.begin())) {
return std::unexpected{GenomeError::invalid_encoding};
}
Reader reader{bytes};
static_cast<void>(reader.read(magic.size()));
const auto schema = static_cast<std::uint32_t>(reader.read(4));
if (capability_schema_for(schema) == nullptr) {
return std::unexpected{GenomeError::unsupported_version};
}
const auto development = static_cast<std::uint32_t>(reader.read(4));
const auto id = reader.read(8);
const auto origin = reader.read(8);
const auto parent_count = reader.read(4);
if (parent_count > max_parents) {
return std::unexpected{GenomeError::invalid_ancestry};
}
// Bound the record region before reading any of it.
const auto counted = fixed_prefix + static_cast<std::size_t>(parent_count) * parent_size + 4;
if (bytes.size() < counted + digest_size + checksum_size) {
return std::unexpected{GenomeError::invalid_encoding};
}
std::vector<std::uint64_t> parents;
parents.reserve(static_cast<std::size_t>(parent_count));
for (std::uint64_t index = 0; index < parent_count; ++index) {
parents.push_back(reader.read(parent_size));
}
const auto record_count = reader.read(4);
if (record_count > capability_count) {
return std::unexpected{GenomeError::duplicate_capability};
}
// An exact length match rejects trailing bytes rather than ignoring them.
const auto expected = counted + static_cast<std::size_t>(record_count) * record_size +
digest_size + checksum_size;
if (bytes.size() != expected) {
return std::unexpected{GenomeError::invalid_encoding};
}
const auto stored = Reader{bytes.subspan(expected - checksum_size)}.read(checksum_size);
if (stored != checksum(bytes.first(expected - checksum_size))) {
return std::unexpected{GenomeError::invalid_encoding};
}
std::vector<CapabilityRecord> capabilities;
capabilities.reserve(static_cast<std::size_t>(record_count));
for (std::uint64_t index = 0; index < record_count; ++index) {
const auto kind = reader.read(1);
if (kind >= capability_count) {
return std::unexpected{GenomeError::unknown_capability};
}
const auto parameter = static_cast<std::uint32_t>(reader.read(4));
const auto prerequisites = static_cast<std::uint32_t>(reader.read(4));
capabilities.push_back({static_cast<Capability>(kind), parameter, prerequisites});
}
if (const auto valid = validate(schema, id, origin, development, parents, capabilities);
!valid) {
return std::unexpected{valid.error()};
}
Genome genome;
genome.schema_version_ = schema;
genome.id_ = id;
genome.origin_event_ = origin;
genome.development_version_ = development;
genome.parents_ = std::move(parents);
genome.capabilities_ = std::move(capabilities);
// The body must reproduce exactly, so a rewritten record is rejected.
const auto digest = digest_of(genome.body());
if (digest != reader.read(digest_size)) {
return std::unexpected{GenomeError::digest_mismatch};
}
genome.digest_ = digest;
return genome;
}
bool Genome::carries(Capability kind) const noexcept {
return std::ranges::any_of(capabilities_,
[kind](const auto& record) { return record.kind == kind; });
}
std::expected<std::uint32_t, GenomeError> Genome::parameter(Capability kind) const noexcept {
for (const auto& record : capabilities_) {
if (record.kind == kind) {
return record.parameter;
}
}
return std::unexpected{GenomeError::missing_capability};
}
std::expected<std::uint64_t, GenomeError> Genome::per_second(Capability kind) const noexcept {
const auto stored = parameter(kind);
if (!stored) {
return std::unexpected{stored.error()};
}
const auto unit = capability_schema_v1[static_cast<std::size_t>(kind)].unit;
const bool per_tick = unit == Unit::micrometres_per_tick || unit == Unit::femtograms_per_tick;
if (schema_version_ == genome_schema_v1 && per_tick) {
// Exact: a 50 ms tick is a twentieth of a second (ADR-0099).
const auto rate =
accounting::per_second_from_per_tick(*stored, schema_v1_tick_microseconds);
if (!rate) {
return std::unexpected{GenomeError::parameter_out_of_range};
}
return *rate;
}
return std::uint64_t{*stored};
}
} // namespace evo::biology