Add the immutable genome v1 record and its canonical encoding
Open M3 with the record that development and mutation will read, in a new evo::biology library that nothing else links yet. A genome is validated once at construction and exposes no mutator, so an invalid one cannot exist at runtime and callers never revalidate. A draft carries unvalidated input; create and decode apply identical semantic checks, so a decoded record is never less validated than a constructed one. Schema 1 fixes the seven v0.1 capability kinds. Each has a unit, an inclusive range, whether every genome must carry it, and the capabilities it mandates, all held as schema facts rather than record data, so no record can contradict its own units. A capability adds one parameter and a bitmask of declared developmental edges; the union of declared and mandated edges must be acyclic, which seven nodes make exact and bounded. Identity is a nonzero world-scoped genome ID distinct from every runtime identity, a nonzero origin event, and zero or one parent. Zero parents identifies a documented founder. The format reserves room for a second so recombination needs a schema version rather than a layout change. The encoding follows ADR-0008: explicit little endian, bounded before any allocation, an exact length match so trailing bytes are rejected, records strictly ascending by kind so the bytes are canonical and duplicates fall out of the same comparison, a stored digest recomputed on decode, and a trailing checksum. The digest covers identity and ancestry, so identical capabilities from different origins never share one. Neither value is an authenticity claim. Unknown schema versions fail closed. Tests cover ancestry rules, every declared range boundary from both sides, self, mutual and three-node cycles, a cycle closed by a mandated edge, truncation at every length, trailing and oversized buffers, every single-byte corruption, and three resealed edits that reach the digest, version and ordering checks rather than stopping at the checksum. One branch is recorded as uncovered rather than given a test that cannot fail: in schema 1 every mandated capability is also required. No genome affects any simulation. Native Release, clang-tidy analysis, ASan and format checks pass 17/17; golden d61ad5bf0c928c76 and ecosystem fingerprint 2cd4a15f9fbe9949 are unchanged. Linux CI has not run yet. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,6 +40,12 @@ target_include_directories(evo_accounting PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in
|
||||
target_compile_features(evo_accounting PUBLIC cxx_std_23)
|
||||
evo_owned_target(evo_accounting)
|
||||
|
||||
add_library(evo_biology STATIC src/biology/genome.cpp)
|
||||
add_library(evo::biology ALIAS evo_biology)
|
||||
target_include_directories(evo_biology PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
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)
|
||||
add_library(evo::processes ALIAS evo_processes)
|
||||
target_link_libraries(evo_processes PUBLIC evo::accounting)
|
||||
@@ -61,6 +67,11 @@ if(BUILD_TESTING)
|
||||
evo_owned_target(evo-ecosystem-tests)
|
||||
add_test(NAME ecosystem-contracts COMMAND evo-ecosystem-tests)
|
||||
set_tests_properties(ecosystem-contracts PROPERTIES TIMEOUT 300)
|
||||
add_executable(evo-genome-tests tests/genome_tests.cpp)
|
||||
target_link_libraries(evo-genome-tests PRIVATE evo::biology)
|
||||
evo_owned_target(evo-genome-tests)
|
||||
add_test(NAME genome-contracts COMMAND evo-genome-tests)
|
||||
set_tests_properties(genome-contracts PROPERTIES TIMEOUT 60)
|
||||
add_executable(evo-producer-tests tests/producer_tests.cpp)
|
||||
target_link_libraries(evo-producer-tests PRIVATE evo::processes)
|
||||
evo_owned_target(evo-producer-tests)
|
||||
|
||||
@@ -22,6 +22,7 @@ network service. Dev verification manifests are separate from the simulation.
|
||||
- [Sequential command scheduling and recovery](docs/architecture/SCHEDULER_CONTRACT.md)
|
||||
- [Local periodic spatial queries](docs/architecture/SPATIAL_CONTRACT.md)
|
||||
- [Energy/matter model and implemented ledger boundary](docs/biology/ENERGY_MODEL.md)
|
||||
- [Genome model and implemented v1 record](docs/biology/GENOME_MODEL.md)
|
||||
|
||||
Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are
|
||||
authoritative over implementation. No external runtime library is needed for
|
||||
@@ -92,7 +93,8 @@ restore. See [testing strategy](docs/engineering/TEST_STRATEGY.md) and
|
||||
codec. `src/accounting` provides the independent finite-inventory ledger;
|
||||
it is not yet part of particle snapshots. `src/processes` holds the synthetic
|
||||
producer, feeding, reproduction and episode fixtures built on that ledger; they
|
||||
are bounded experiments, not organism biology. `apps/evo-sim` owns CLI/file I/O
|
||||
are bounded experiments, not organism biology. `src/biology` holds the immutable
|
||||
genome record; nothing reads it yet. `apps/evo-sim` owns CLI/file I/O
|
||||
and reporting. `tests` holds contract,
|
||||
fuzz and measurement programs. Future biology, world, networking and persistence
|
||||
modules are documented boundaries; they are added when they have real behavior.
|
||||
|
||||
+4
-1
@@ -71,7 +71,10 @@ mean one community is not a population, and with no maintenance cost an uneaten
|
||||
consumer never dies. It therefore measures many bounded episodes, with mortality
|
||||
from predation and a configured lifespan, rather than one continuous run. Over a
|
||||
million ticks conserve exactly, which demonstrates arithmetic, not ecology.
|
||||
M3 replaces duplicated strategies with heritable developmental capabilities.
|
||||
M3.1 now supplies that record (ADR-0030): seven versioned capability kinds with
|
||||
units, ranges, declared and mandated developmental edges, immutable ancestry and
|
||||
a canonical bounded encoding. It is validated once at the boundary and coupled to
|
||||
nothing; development, phenotype derivation and mutation remain M3.2 to M3.4.
|
||||
|
||||
## M3 — Genome v0.1
|
||||
|
||||
|
||||
+18
-3
@@ -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 29 ADRs.
|
||||
diagrams, biological contracts, engineering constitution and 30 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.1 immutable genome schema and ancestry | Versioned developmental capability data replacing M2.6's duplicated founder strategies |
|
||||
| 2 | M3.2 development pipeline | Same genome and environment yield the same explicit phenotype parameters |
|
||||
| 1 | M3.2 development pipeline | Same genome and environment yield the same explicit phenotype parameters, with material and capability prerequisites |
|
||||
| 2 | M3.3 derive energetic components | Size, membrane and movement tradeoffs affect several budgets; connects the genome to the M2 fixtures |
|
||||
| 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):
|
||||
@@ -159,6 +159,21 @@ demonstrates arithmetic and turnover, not ecological plausibility; strategy
|
||||
constants are chosen inputs and must not become gameplay by having been measured.
|
||||
Native Release, analysis, ASan and formatting passed; Linux CI has not run yet.
|
||||
|
||||
M3.1 opens M3 with the immutable genome record (ADR-0030) in a new `evo::biology`
|
||||
library that nothing else links yet. A genome is validated once at construction
|
||||
and exposes no mutator, so an invalid one cannot exist at runtime; `decode`
|
||||
applies identical checks, so a decoded record is never less validated than a
|
||||
constructed one. Schema 1 fixes the seven v0.1 capability kinds with units,
|
||||
inclusive ranges, required flags and mandated developmental edges as schema facts
|
||||
rather than record data. Identity is a nonzero world-scoped genome ID distinct
|
||||
from every runtime identity, a nonzero origin event and zero or one parent, with
|
||||
room reserved for recombination. The encoding is canonical, bounded and exact:
|
||||
strict ascending order, a stored digest that is recomputed on decode, and a
|
||||
trailing checksum, with the byte layout in schemas/genome-v1.md. No genome
|
||||
affects any simulation; the M2 fixtures still duplicate founder strategies.
|
||||
Development, phenotype, mutation and heredity remain M3.2 to M3.5. Native
|
||||
Release, analysis, ASan and formatting passed; 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
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# ADR-0030: Immutable genome v1 record and canonical encoding
|
||||
|
||||
## Status
|
||||
|
||||
Adopted for M3.1. Development, phenotype derivation, mutation candidates,
|
||||
heredity operations and any coupling to the M2 process fixtures are out of scope
|
||||
and remain M3.2 through M3.5. No gameplay balance is selected.
|
||||
|
||||
## Context
|
||||
|
||||
M2 closed with founder strategies duplicated verbatim from parent to child, so
|
||||
nothing heritable exists and lineages differ only by their founder. Before
|
||||
development or mutation can be written, the record they read must exist: a
|
||||
versioned, validated, immutable description of developmental capability, with
|
||||
ancestry that outlives its organisms and an encoding that is canonical enough to
|
||||
compare across platforms and reject malformed input.
|
||||
|
||||
GENOME_MODEL fixes the shape of that record and the two failure modes to avoid:
|
||||
literal DNA, and an Animal/Plant/Fungus style inheritance hierarchy. It also
|
||||
leaves mutation, recombination, NPC divergence and multi-parent heredity open.
|
||||
|
||||
## Decision
|
||||
|
||||
Add an `evo::biology` library holding one value type, `Genome`, constructed only
|
||||
through validation and exposing no mutator. A `GenomeDraft` carries unvalidated
|
||||
input; `Genome::create` either returns a validated record or an error, and
|
||||
`decode` applies the identical semantic checks to bytes. There is no way to hold
|
||||
an invalid `Genome`, so callers never revalidate.
|
||||
|
||||
Genome v1 fixes seven capability kinds, matching the v0.1 list in GENOME_MODEL:
|
||||
energy conversion, membrane, movement, ingestion, reproduction, target size and
|
||||
thermal tolerance. These are capabilities, not genes, organs or species. A static
|
||||
schema table gives each kind its unit, inclusive parameter range, whether every
|
||||
genome must carry it, and the capabilities it mandates being present. The unit is
|
||||
a schema fact and is never encoded, so no record can contradict its own units.
|
||||
Energy conversion, membrane and target size are required in every v1 genome.
|
||||
|
||||
A capability record is a kind, one u32 parameter and a u32 bitmask of declared
|
||||
prerequisites. Declared prerequisites are developmental ordering the genome
|
||||
asserts; mandated prerequisites are schema facts. Validation rejects an unknown
|
||||
capability bit or kind, a duplicate kind, a parameter outside its declared range,
|
||||
a prerequisite naming a capability the genome does not carry, a missing required
|
||||
or mandated capability, and any cycle in the union of declared and mandated
|
||||
edges. Seven nodes make that closure exact and bounded.
|
||||
|
||||
Ancestry is immutable and separate from every runtime identity. A genome carries
|
||||
a nonzero world-scoped ID distinct from the process and entity IDs of earlier
|
||||
increments, a nonzero origin event explaining founder, mutation or reproduction
|
||||
origin, and zero or one parent. The format reserves room for two so later
|
||||
recombination needs a schema version rather than a layout change; v1 rejects more
|
||||
than one. A parent may be neither zero, nor the genome itself, nor repeated.
|
||||
|
||||
The encoding follows ADR-0008: explicit little endian, an `AEVOGEN1` magic, fixed
|
||||
u32 schema and development versions, the identity and ancestry fields, then
|
||||
capability records sorted strictly ascending by kind, a content digest and a
|
||||
trailing FNV-1a checksum. Strict ascending order makes the encoding canonical and
|
||||
rejects duplicates in the same comparison. Sizes and counts are validated against
|
||||
`max_genome_bytes` before any allocation, and an exact length match is required,
|
||||
so trailing bytes are rejected rather than ignored.
|
||||
|
||||
The content digest covers the whole body, identity and ancestry included, so two
|
||||
genomes with identical capabilities but different origins never share a digest.
|
||||
It is an integrity and deduplication aid, never a content-identity key across
|
||||
origins. It is stored and also recomputed on decode, and a mismatch is rejected:
|
||||
the digest and the checksum answer different questions, record consistency and
|
||||
accidental corruption, and neither is an authenticity claim.
|
||||
|
||||
Unknown schema versions fail closed. A genome is never migrated in place.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
Literal nucleotide sequences would need an expression model no contract defines
|
||||
and would make every range check meaningless. A capability class hierarchy would
|
||||
bake the taxonomy GENOME_MODEL forbids into the type system. Deriving the digest
|
||||
on demand instead of storing it would lose the record-consistency check that
|
||||
catches a hand-edited or partially migrated record. Typed accounting units in the
|
||||
parameters would couple the genome to the ledger before M3.3 has decided how
|
||||
capability maps to energetic cost. A general graph with arbitrary node counts
|
||||
would make cycle detection unbounded for no v1 benefit.
|
||||
|
||||
## Benefits
|
||||
|
||||
An invalid genome cannot exist at runtime. Capability, range and dependency
|
||||
errors are caught once, at the boundary, with a named reason. Ancestry survives
|
||||
encoding and is independent of every runtime identity. The bytes are canonical,
|
||||
bounded and comparable across platforms, so later development and mutation work
|
||||
starts from a record whose validity is already established.
|
||||
|
||||
## Costs
|
||||
|
||||
Seven fixed kinds and one u32 parameter each cannot express a capability with
|
||||
several dimensions; that needs a schema version. The required set and the ranges
|
||||
are chosen constants. Storing the digest costs eight bytes and one consistency
|
||||
rule. Multi-parent heredity is reserved but not implemented.
|
||||
|
||||
## Risks
|
||||
|
||||
Do not read capability parameters as balance, stats or a power score: fitness is
|
||||
an outcome. A parameter within range is not a viable organism, and validation
|
||||
proves neither developmental feasibility nor biological plausibility. The schema
|
||||
ranges must not become gameplay tuning by having been written down. Nothing here
|
||||
decides mutation operators, inherited versus acquired expression, NPC divergence
|
||||
or recombination, and no genome yet affects any simulation.
|
||||
|
||||
## Consequences
|
||||
|
||||
Test canonical round trips, byte-exact encoding stability, strict ordering,
|
||||
truncation, trailing bytes, corrupted checksums, digest mismatch, unsupported and
|
||||
zero versions, unknown capability kinds and prerequisite bits, duplicates,
|
||||
every range boundary, missing required and mandated capabilities, self and mutual
|
||||
and longer prerequisite cycles, and every ancestry rule. No snapshot format,
|
||||
process fixture, database, renderer or deployment changes. The M1 particle codec
|
||||
does not serialize genomes, and M3.2 development must not mutate this record.
|
||||
@@ -22,6 +22,7 @@ Each record has the eight required sections.
|
||||
0027 adds terminal inventory ownership and budgeted nutrient return for M2.4.
|
||||
0028 adopts funded reproduction, bounded slot capacity and retained lineage IDs.
|
||||
0029 scopes the deterministic ecosystem driver and bounded measured episodes.
|
||||
0030 adopts the immutable genome v1 record, validation and canonical encoding.
|
||||
|
||||
Every dependency adoption records exact version/commit and integrity hash,
|
||||
transitive license obligations, maintenance/security review, owner and removal
|
||||
|
||||
@@ -76,3 +76,42 @@ records/provenance and are tested on cloned worlds. Unknown required capabilitie
|
||||
fail closed. Tests cover canonical round trips, prerequisites, resource-limited
|
||||
development, deterministic candidates, stream independence, retry stability,
|
||||
bounded graph expansion, ancestry-preserving migration and material tradeoffs.
|
||||
|
||||
## Implemented M3.1 genome record
|
||||
|
||||
[ADR-0030](../adr/0030-immutable-genome-record.md) implements the record this
|
||||
document proposes, and nothing that reads it. `evo::biology::Genome` is validated
|
||||
once at construction and exposes no mutator, so an invalid genome cannot exist at
|
||||
runtime and callers never revalidate. `GenomeDraft` carries unvalidated input;
|
||||
`create` and `decode` apply identical semantic checks, so a decoded record is
|
||||
never less validated than a constructed one.
|
||||
|
||||
Schema 1 fixes the seven v0.1 capability kinds. Each has a unit, an inclusive
|
||||
parameter range, whether every genome must carry it, and the capabilities it
|
||||
mandates, all held as schema facts rather than record data, so no genome can
|
||||
contradict its own units. Energy conversion, membrane and target size are
|
||||
required. A capability record adds one u32 parameter and a bitmask of declared
|
||||
developmental edges; the union of declared and mandated edges must be acyclic.
|
||||
|
||||
Identity is a nonzero world-scoped genome ID distinct from every runtime identity,
|
||||
a nonzero origin event, and zero or one parent. Zero parents identifies a
|
||||
documented founder. The format reserves room for a second parent so recombination
|
||||
needs a schema version rather than a layout change. The byte layout, validation
|
||||
rules and digest semantics are in [genome-v1.md](../../schemas/genome-v1.md).
|
||||
|
||||
| Contract | Status after M3.1 |
|
||||
|---|---|
|
||||
| ValidateGenome | Implemented for schema 1, at construction and at decode |
|
||||
| PlanDevelopment | Not started; M3.2 |
|
||||
| ApplyDevelopment | Not started; M3.2 |
|
||||
| DerivePhenotype | Not started; M3.2 |
|
||||
| GenerateMutationCandidates | Not started; M3.4 |
|
||||
| SelectMutation | Not started; M3.4 |
|
||||
|
||||
No genome affects any simulation. The M2 process fixtures still duplicate founder
|
||||
strategies verbatim and do not read this record; M3.3 connects capability to
|
||||
energetic cost. Nothing here decides mutation operators, inherited versus acquired
|
||||
expression, NPC divergence or recombination. A parameter within range is not a
|
||||
viable organism: validation proves neither developmental feasibility nor
|
||||
biological plausibility, and the schema ranges are expressible bounds rather than
|
||||
balance. Fitness remains an outcome, not a score held in the record.
|
||||
|
||||
@@ -362,3 +362,50 @@ not serialized, allocation failure is not injected, and no population abstractio
|
||||
exists. Golden `d61ad5bf0c928c76` and every earlier suite are unchanged. No
|
||||
deployment manifest or image pin changed. Linux validation is pending its first
|
||||
pushed run; no Gitea result or cross-platform fingerprint agreement is claimed yet.
|
||||
|
||||
## M3.1 immutable genome record (2026-09-22)
|
||||
|
||||
Native Release, analysis and MSVC ASan each passed 17/17 CTests; formatting
|
||||
passed. Commands: `tools/windows-check.ps1 -Preset <release|analysis|asan>
|
||||
-Action check` and debug `-Action format`. Formatting rejected three wrapped
|
||||
declarations on the first run; clang-format 19.1.5 rewrote them and Release was
|
||||
rebuilt and rerun. `genome-contracts` is the one new CTest case, covering a new
|
||||
`evo::biology` library that nothing else links.
|
||||
|
||||
Tests cover founder and descendant records, unordered drafts producing byte-equal
|
||||
canonical records, digests differing for identical capabilities from different
|
||||
origins, and every ancestry rule: zero identity, zero origin, zero development
|
||||
version, a zero parent, a self parent, two parents and a repeated parent. Schema
|
||||
rules cover an empty record, each of the three required capabilities removed in
|
||||
turn, a duplicate kind, an unknown kind, an unknown prerequisite bit, and both
|
||||
inclusive boundaries of all seven declared ranges accepted with one below and one
|
||||
above each rejected. Graph rules cover a declared prerequisite naming an absent
|
||||
capability, self, mutual and three-node cycles, a valid ordering using the same
|
||||
edges without the closing one, and a cycle closed by a mandated rather than a
|
||||
declared edge.
|
||||
|
||||
Encoding tests cover the round trip, byte-exact re-encoding, truncation at every
|
||||
length from zero to one byte short, one trailing byte, an oversized buffer, a
|
||||
corrupted magic, and every single-byte corruption of the full record. Three cases
|
||||
reseal the checksum after editing so the later checks are reached rather than
|
||||
masked: a rewritten genome ID is caught by the digest, a future schema version
|
||||
fails closed, and non-canonical record order is caught as a duplicate kind. A
|
||||
parent count beyond the reserved room and a capability count beyond the schema
|
||||
are both refused before the corresponding region is read.
|
||||
|
||||
Coverage limitation: in schema 1 every mandated capability is also a required
|
||||
one, so the presence half of the mandate check is reachable only through declared
|
||||
prerequisites, which is tested. The mandated edges do take part in the cycle
|
||||
closure, which is tested. A later schema that mandates a capability without
|
||||
requiring it would exercise the remaining branch; this is recorded rather than
|
||||
covered by a test that could not fail.
|
||||
|
||||
No genome affects any simulation, and nothing links the new library except its
|
||||
own tests. The M2 process fixtures still duplicate founder strategies and do not
|
||||
read the record. Development, phenotype derivation, mutation, recombination,
|
||||
multi-parent heredity, migration between schema versions and any persistent
|
||||
genome archive are not implemented. The encoding is a local record format, not a
|
||||
network protocol or durable storage, and neither the digest nor the checksum is
|
||||
an authenticity claim. Golden `d61ad5bf0c928c76` and the ecosystem fingerprint
|
||||
`2cd4a15f9fbe9949` are unchanged. No deployment manifest or image pin changed.
|
||||
Linux validation is pending its first pushed run; no Gitea result is claimed yet.
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace evo::biology {
|
||||
// Evolvable developmental capabilities, not genes, organs, species or DNA.
|
||||
enum class Capability : std::uint8_t {
|
||||
energy_conversion,
|
||||
membrane,
|
||||
movement,
|
||||
ingestion,
|
||||
reproduction,
|
||||
target_size,
|
||||
thermal_tolerance
|
||||
};
|
||||
inline constexpr std::size_t capability_count = 7;
|
||||
// The unit is a schema fact per kind and is never encoded, so no record can
|
||||
// contradict its own units.
|
||||
enum class Unit : std::uint8_t {
|
||||
per_thousand,
|
||||
micrometres,
|
||||
micrometres_per_tick,
|
||||
femtograms,
|
||||
femtograms_per_tick,
|
||||
millikelvin
|
||||
};
|
||||
struct CapabilitySpec {
|
||||
Unit unit;
|
||||
std::uint32_t minimum;
|
||||
std::uint32_t maximum;
|
||||
bool required;
|
||||
// Capabilities the schema mandates be present; developmental edges as well.
|
||||
std::uint32_t mandates;
|
||||
};
|
||||
[[nodiscard]] constexpr std::uint32_t capability_bit(Capability kind) noexcept {
|
||||
return 1U << static_cast<std::uint8_t>(kind);
|
||||
}
|
||||
// Chosen schema constants, reviewable as a unit. These are ranges of expressible
|
||||
// capability, not balance, stats or a power score.
|
||||
inline constexpr std::array<CapabilitySpec, capability_count> capability_schema{
|
||||
CapabilitySpec{Unit::per_thousand, 1, 1000, true, 0},
|
||||
CapabilitySpec{Unit::micrometres, 1, 10'000, true, 0},
|
||||
CapabilitySpec{Unit::micrometres_per_tick, 0, 100'000, false,
|
||||
capability_bit(Capability::membrane)},
|
||||
CapabilitySpec{Unit::femtograms_per_tick, 0, 1'000'000, false,
|
||||
capability_bit(Capability::membrane)},
|
||||
CapabilitySpec{Unit::per_thousand, 1, 1000, false,
|
||||
capability_bit(Capability::energy_conversion)},
|
||||
CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0},
|
||||
CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}};
|
||||
|
||||
struct CapabilityRecord {
|
||||
Capability kind{};
|
||||
std::uint32_t parameter{};
|
||||
// Declared developmental ordering, over and above what the schema mandates.
|
||||
std::uint32_t prerequisites{};
|
||||
auto operator<=>(const CapabilityRecord&) const = default;
|
||||
};
|
||||
// Unvalidated input. Only Genome::create turns one into a record.
|
||||
struct GenomeDraft {
|
||||
std::uint64_t id{};
|
||||
std::uint64_t origin_event{};
|
||||
std::uint32_t development_version{};
|
||||
std::vector<std::uint64_t> parents;
|
||||
std::vector<CapabilityRecord> capabilities;
|
||||
};
|
||||
enum class GenomeError : std::uint8_t {
|
||||
unsupported_version,
|
||||
unknown_capability,
|
||||
missing_capability,
|
||||
duplicate_capability,
|
||||
parameter_out_of_range,
|
||||
missing_prerequisite,
|
||||
cyclic_development,
|
||||
invalid_identity,
|
||||
invalid_ancestry,
|
||||
digest_mismatch,
|
||||
invalid_encoding
|
||||
};
|
||||
inline constexpr std::uint32_t genome_schema_version = 1;
|
||||
inline constexpr std::size_t max_parents = 2;
|
||||
inline constexpr std::size_t max_genome_bytes = 256;
|
||||
|
||||
// Immutable once constructed: validation happens exactly once, at the boundary.
|
||||
class Genome {
|
||||
public:
|
||||
[[nodiscard]] static std::expected<Genome, GenomeError> create(const GenomeDraft& draft);
|
||||
[[nodiscard]] static std::expected<Genome, GenomeError>
|
||||
decode(std::span<const std::uint8_t> bytes);
|
||||
[[nodiscard]] std::vector<std::uint8_t> encode() const;
|
||||
[[nodiscard]] std::uint64_t id() const noexcept {
|
||||
return id_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t origin_event() const noexcept {
|
||||
return origin_event_;
|
||||
}
|
||||
[[nodiscard]] std::uint32_t schema_version() const noexcept {
|
||||
return genome_schema_version;
|
||||
}
|
||||
[[nodiscard]] std::uint32_t development_version() const noexcept {
|
||||
return development_version_;
|
||||
}
|
||||
// Zero parents identifies a documented founder; v1 permits at most one.
|
||||
[[nodiscard]] std::span<const std::uint64_t> parents() const noexcept {
|
||||
return parents_;
|
||||
}
|
||||
// Sorted strictly ascending by kind, so the record is canonical.
|
||||
[[nodiscard]] std::span<const CapabilityRecord> capabilities() const noexcept {
|
||||
return capabilities_;
|
||||
}
|
||||
[[nodiscard]] bool carries(Capability kind) const noexcept;
|
||||
[[nodiscard]] std::expected<std::uint32_t, GenomeError>
|
||||
parameter(Capability kind) const noexcept;
|
||||
// Covers identity and ancestry, so distinct origins never share a digest.
|
||||
// An integrity and deduplication aid, never a content key and never authenticity.
|
||||
[[nodiscard]] std::uint64_t content_digest() const noexcept {
|
||||
return digest_;
|
||||
}
|
||||
auto operator<=>(const Genome&) const = default;
|
||||
|
||||
private:
|
||||
Genome() = default;
|
||||
[[nodiscard]] std::vector<std::uint8_t> body() const;
|
||||
std::uint64_t id_{};
|
||||
std::uint64_t origin_event_{};
|
||||
std::uint32_t development_version_{};
|
||||
std::vector<std::uint64_t> parents_;
|
||||
std::vector<CapabilityRecord> capabilities_;
|
||||
std::uint64_t digest_{};
|
||||
};
|
||||
} // namespace evo::biology
|
||||
@@ -0,0 +1,71 @@
|
||||
# Genome record, schema version 1
|
||||
|
||||
Scope: the immutable developmental record defined by
|
||||
[ADR-0030](../docs/adr/0030-immutable-genome-record.md) and shaped by
|
||||
[GENOME_MODEL.md](../docs/biology/GENOME_MODEL.md). Its encoder/decoder is
|
||||
`src/biology/genome.cpp`.
|
||||
|
||||
Not a network protocol, authenticated archive, event journal, production world
|
||||
format or durable storage implementation. It is not literal DNA, not a taxonomy
|
||||
and not a balance table. A future schema must preserve or explicitly migrate
|
||||
supported historical versions; unknown versions fail closed and no record is
|
||||
migrated in place.
|
||||
|
||||
## Layout
|
||||
|
||||
All integers are little endian. Offsets assume `P` parents and `N` capability
|
||||
records. `P` is 0 or 1 in schema 1, with room reserved for 2. `N` is 1 to 7.
|
||||
|
||||
| Offset | Size | Field |
|
||||
|---|---|---|
|
||||
| 0 | 8 | magic `AEVOGEN1` |
|
||||
| 8 | 4 | schema version, 1 |
|
||||
| 12 | 4 | development rule version, nonzero and opaque to this schema |
|
||||
| 16 | 8 | genome ID, nonzero and distinct from every runtime identity |
|
||||
| 24 | 8 | origin event ID, nonzero |
|
||||
| 32 | 4 | parent count `P` |
|
||||
| 36 | 8·P | parent genome IDs |
|
||||
| 36+8P | 4 | capability record count `N` |
|
||||
| 40+8P | 9·N | capability records, strictly ascending by kind |
|
||||
| 40+8P+9N | 8 | content digest |
|
||||
| 48+8P+9N | 8 | FNV-1a checksum over every preceding byte |
|
||||
|
||||
Each capability record is a u8 kind, a u32 parameter and a u32 prerequisite
|
||||
bitmask, in that order. Total size is `56 + 8P + 9N` bytes: 83 for a founder
|
||||
carrying the three required capabilities, 135 at the maximum, and never more
|
||||
than `max_genome_bytes` (256).
|
||||
|
||||
## Capabilities
|
||||
|
||||
Kinds are ordered 0 to 6: energy conversion, membrane, movement, ingestion,
|
||||
reproduction, target size, thermal tolerance. The unit, inclusive range, whether
|
||||
every genome must carry the kind, and the capabilities it mandates are schema
|
||||
facts held in `capability_schema` and are never encoded, so no record can
|
||||
contradict its own units. Energy conversion, membrane and target size are
|
||||
required in schema 1. A prerequisite bit outside the known kinds is rejected.
|
||||
|
||||
## Validation
|
||||
|
||||
Decoding applies the same semantic checks as construction, so a decoded record is
|
||||
never less validated than a constructed one. Sizes and counts are bounded before
|
||||
any allocation, and the length must match exactly, so trailing bytes are rejected
|
||||
rather than ignored.
|
||||
|
||||
Rejected: unknown schema version, unknown capability kind or prerequisite bit, a
|
||||
missing required capability, duplicate or non-ascending kinds, a parameter
|
||||
outside its range, a prerequisite naming an absent capability, any cycle in the
|
||||
union of declared and mandated developmental edges, a zero identity or origin, a
|
||||
zero development version, more than one parent, and a parent that is zero,
|
||||
repeated or the genome itself.
|
||||
|
||||
## Digest and checksum
|
||||
|
||||
The digest covers the whole body, identity and ancestry included, so two genomes
|
||||
with identical capabilities but different origins never share one. It is an
|
||||
integrity and deduplication aid, never a content-identity key across origins. It
|
||||
is stored and recomputed on decode, and a mismatch is rejected, which catches a
|
||||
record edited in place or partially migrated.
|
||||
|
||||
The trailing checksum detects accidental corruption only. Neither value is a
|
||||
cryptographic or authenticity claim, and neither substitutes for the other: they
|
||||
answer record consistency and transport corruption respectively.
|
||||
@@ -0,0 +1,288 @@
|
||||
#include "evo/biology/genome.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;
|
||||
|
||||
const CapabilitySpec& spec(Capability kind) noexcept {
|
||||
return capability_schema[static_cast<std::size_t>(kind)];
|
||||
}
|
||||
|
||||
std::expected<void, GenomeError> validate(std::uint64_t id, std::uint64_t origin,
|
||||
std::uint32_t development,
|
||||
std::span<const std::uint64_t> parents,
|
||||
std::span<const CapabilityRecord> capabilities) {
|
||||
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 (capability_schema[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, genome_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.id, draft.origin_event, draft.development_version,
|
||||
draft.parents, ordered);
|
||||
!valid) {
|
||||
return std::unexpected{valid.error()};
|
||||
}
|
||||
Genome genome;
|
||||
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()));
|
||||
if (reader.read(4) != genome_schema_version) {
|
||||
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(id, origin, development, parents, capabilities); !valid) {
|
||||
return std::unexpected{valid.error()};
|
||||
}
|
||||
Genome genome;
|
||||
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};
|
||||
}
|
||||
} // namespace evo::biology
|
||||
@@ -0,0 +1,285 @@
|
||||
#include "evo/biology/genome.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#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.
|
||||
for (std::size_t index = 0; index < capability_count; ++index) {
|
||||
const auto kind = static_cast<Capability>(index);
|
||||
const auto& limits = capability_schema[index];
|
||||
for (const auto value : {limits.minimum, limits.maximum}) {
|
||||
draft = founder();
|
||||
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 = founder();
|
||||
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 = founder();
|
||||
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] = 2;
|
||||
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);
|
||||
}
|
||||
} // namespace
|
||||
int main() try {
|
||||
founders_and_ancestry();
|
||||
ancestry_rules();
|
||||
capability_and_range_rules();
|
||||
development_graph_rules();
|
||||
canonical_encoding();
|
||||
encoded_record_rules();
|
||||
std::cout << "PASS genome schema, ancestry, development graph and canonical encoding\n";
|
||||
return 0;
|
||||
} catch (...) {
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user