diff --git a/CMakeLists.txt b/CMakeLists.txt index 710e0d0..dd2f85e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,7 +40,7 @@ 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 src/biology/development.cpp src/biology/metabolism.cpp) +add_library(evo_biology STATIC src/biology/genome.cpp src/biology/development.cpp src/biology/metabolism.cpp src/biology/mutation.cpp) add_library(evo::biology ALIAS evo_biology) target_include_directories(evo_biology PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(evo_biology PUBLIC evo::accounting) @@ -83,6 +83,11 @@ if(BUILD_TESTING) evo_owned_target(evo-metabolism-tests) add_test(NAME metabolism-contracts COMMAND evo-metabolism-tests) set_tests_properties(metabolism-contracts PROPERTIES TIMEOUT 60) + add_executable(evo-mutation-tests tests/mutation_tests.cpp) + target_link_libraries(evo-mutation-tests PRIVATE evo::biology) + evo_owned_target(evo-mutation-tests) + add_test(NAME mutation-contracts COMMAND evo-mutation-tests) + set_tests_properties(mutation-contracts PROPERTIES TIMEOUT 120) add_executable(evo-producer-tests tests/producer_tests.cpp) target_link_libraries(evo-producer-tests PRIVATE evo::processes) evo_owned_target(evo-producer-tests) diff --git a/README.md b/README.md index fa2330e..f064c23 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,8 @@ 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. `src/biology` holds the immutable genome record, the deterministic development that derives a phenotype from it and -the metabolic budgets that give capability a cost. No fixture reads a genome yet. +the metabolic budgets that give capability a cost, and the seeded mutation +catalog that proposes successors. No fixture reads a genome yet. `apps/evo-sim` owns CLI/file I/O and reporting. `tests` holds contract, fuzz and measurement programs. Future biology, world, networking and persistence diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a1af766..d275431 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -83,7 +83,13 @@ composition, maintenance, movement, construction, intake and reproduction investment, each derived from a different phenotype quantity so one parameter moves some budgets and not others. `consumer_for` is the first path from a genome into the M2 fixtures, and mass splits conserve exactly so a derived body can be -spent through the ledger. No existing fixture reads genomes yet; that is M3.6. +spent through the ledger. No existing fixture reads genomes yet; that is M3.6. M3.4 now proposes successors +(ADR-0033): a bounded operator catalog whose eligibility is the M3.1 validation +itself, drawn uniformly without replacement from a recorded context and returned +in canonical order with nothing ranked. Selection regenerates the offer and +refuses a changed context rather than substituting. Candidate count, mutation +cost as a game rule, inherited versus acquired expression, NPC mutation and +recombination stay open, and no organism mutates yet. ## M3 — Genome v0.1 diff --git a/docs/STATUS.md b/docs/STATUS.md index b2db624..6ff90bf 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged. ## Completed implementation - Vision, architectural pillars, risks, open-question register, architecture - diagrams, biological contracts, engineering constitution and 32 ADRs. + diagrams, biological contracts, engineering constitution and 33 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.4 seeded mutation candidates | Bounded reproducible candidates conditioned by recorded context, with prerequisite, cost and fixed-seed tests | -| 2 | M3.5 heredity and divergence history | Reproduction persists parent/child links and genome identity survives death | +| 1 | M3.5 heredity and divergence history | Reproduction persists parent/child links; genome identity survives death; extinct genomes are never deleted | +| 2 | M3.6 genome ecology ensembles | Strategies compared under resource and temperature gradients, with conservation and a diversity report | | 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): @@ -208,6 +208,23 @@ derived consumer is shown driving a real feeding tick with the ledger conserving No existing fixture reads genomes yet and no organism spends any budget. Native Release, analysis, ASan and formatting passed 19/19; Linux CI has not run yet. +M3.4 proposes successors (ADR-0033). A static catalog of four effects over the +seven capabilities is filtered by the M3.1 validation itself, so eligibility is +not a second rulebook: shedding a capability another declares as a prerequisite +fails without a rule written for it. Candidates are drawn without replacement by +rejection sampling on an explicit stream, so every eligible operator is exactly as +likely as any other, and the result is returned in canonical order with no score +anywhere in the record. The draw reads only the parent digest and a recorded +context, so the same context always returns the same candidates and a retry cannot +reroll, while a new event index earns a new draw. Selection regenerates the offer +and refuses a changed context outright rather than answering it with a different +mutation. A candidate reports what ADR-0032 would charge its successor and +reserves nothing. The uniformity test was confirmed to fail against a draw that +took the first eligible operators. Candidate count, mutation cost as a game rule, +inherited versus acquired expression, NPC mutation and recombination stay open; +no organism mutates. Native Release, analysis, ASan and formatting passed 20/20; +Linux CI has not run yet. + Before biology, resolve the relevant heredity and energetic contracts rather than treating proof particles as organisms. Exact game tick rate, NPC mutation, logout treatment, species/extinction rules and multicellular transition remain diff --git a/docs/adr/0033-seeded-mutation-candidates.md b/docs/adr/0033-seeded-mutation-candidates.md new file mode 100644 index 0000000..ba7b051 --- /dev/null +++ b/docs/adr/0033-seeded-mutation-candidates.md @@ -0,0 +1,111 @@ +# ADR-0033: Seeded mutation candidates over a bounded operator catalog + +## Status + +Adopted for M3.4 as the candidate-generation experiment GENOME_MODEL describes. +It settles none of the rules that document leaves open: candidate count, context +window, mutation costs as a game rule, inherited versus acquired expression, NPC +mutation and recombination all remain undecided. Heredity history is M3.5. + +## Context + +M3.3 gave capability a cost, but every genome is still authored by hand. Before +lineages can diverge, something has to propose a successor, and GENOME_MODEL is +specific about how: a constrained catalog of operators over capability records, +filtered by prerequisites, sorted by stable operator ID, sampled from a recorded +genome and context with an explicit stream, with no wall clock, no `std::hash` +and no implementation-defined distribution. + +The named risk is a hidden deterministic best build, or offerings biased toward +what would help. Either would turn mutation into a progression tree wearing a +biological costume. + +## Decision + +Add `evo::biology::mutation_candidates` and `select_mutation` over a static +catalog. Each operator has a stable ID and one of four effects on one capability: +adjust its parameter up or down, acquire a capability the genome lacks, or shed +one it carries. The adjustment step is one rule rather than a constant per +capability: a hundredth of that capability's declared range, at least one. + +Eligibility is not a second rulebook. An operator is eligible when its own +precondition holds and the genome it would produce passes the M3.1 validation +unchanged. Prerequisites, required capabilities, ranges and the acyclic +development graph are therefore enforced exactly once, where they were defined. +Shedding a capability another one declares as a prerequisite fails that check by +itself, with no rule written here to catch it. + +Nothing is ranked. Candidates are drawn without replacement from the eligible set +by rejection sampling on a SplitMix64 stream, so each eligible operator is exactly +equally likely, and the result is returned sorted by operator ID. Position carries +no meaning, there is no score anywhere in the record, and nothing about an +organism's situation makes a helpful mutation more likely to be offered. Whether +offerings should ever be environment-conditioned is a game-design question +GENOME_MODEL leaves open, and this implementation does not open it. + +The draw is seeded from the recorded context alone: the parent's content digest, +an explicit seed and stream, the eligible event index, the organism's growth and +environment, and the requested count. Two calls with the same context return +identical candidates, so a retry cannot reroll; a new event index is what earns a +new draw. Because the functions read nothing but the genome and that context, +events elsewhere in a world cannot move a candidate set. + +A candidate reports what the successor would be and what it would cost, and +reserves nothing. Cost is not invented here: it is the successor's own maintenance +and mass under ADR-0032, derived from the same rules as the parent's, so a +candidate carries a consequence rather than a price this ADR made up. + +`select_mutation` takes the candidates that were offered, regenerates them from +the context, and refuses unless the whole list still matches. A changed context is +rejected outright rather than silently answered with a different mutation. Only +then is the immutable successor built, with a caller-allocated identity, the +parent recorded, and M3.1 validating it once more. + +## Alternatives Considered + +Scoring or ordering candidates by any derived quantity would be the best-build +failure directly, however it was labelled. Conditioning the draw on what an +organism needs would make mutation anticipate its environment, which GENOME_MODEL +explicitly refuses to claim. Re-implementing prerequisite checks in the catalog +would let the two rulebooks drift. Clamping an adjustment at a range boundary +would make two operators produce one result and offer no-ops as real choices. +Plain modulo on the stream would bias the draw very slightly toward low operator +IDs, which is exactly the accusation this increment must be able to refute. +Letting selection substitute a still-valid candidate when the context moved would +mean an organism mutating into something nobody was shown. + +## Benefits + +Divergence becomes possible without a progression tree. Every offer is legitimate +by the same validation that defines legitimacy, uniformity is exact rather than +asymptotic, retries are stable, and a changed context fails loudly. The cost +shown is the cost the rest of the system would charge. + +## Costs + +Four effects over seven capabilities is a small catalog, and the shared +range-fraction step means a capability's granularity follows its range rather than +any biology. Eligibility runs validation once per operator per call, which is +cheap here but is a full genome construction each time. Regenerating the whole +list to select is deliberate duplicated work. + +## Risks + +Do not read a candidate's reported maintenance or mass as a recommendation, a +score or a price; it is what ADR-0032 would charge either way. Uniform offering is +not a claim about real mutation rates, and the catalog is not a claim about which +mutations are possible in biology. Nothing here decides whether NPCs mutate, +whether acquired state is ever inherited, what a mutation should cost a player, or +how often events occur. No organism mutates yet, and no fixture calls any of this. + +## Consequences + +Test that the same context always yields the same candidates and a new event index +yields a new draw, that offers are uniform across the eligible set over many seeds +and cover it completely, that the returned order is always canonical, that every +offered candidate produces a genome M3.1 accepts, that ineligible operators are +never offered, that shedding a declared prerequisite is refused, that boundary +adjustments are refused rather than clamped, that selection rejects an unknown +candidate and any changed context, and that a successor records its parent and +survives encoding. No genome schema, ledger, fixture, renderer or deployment +changes. diff --git a/docs/adr/README.md b/docs/adr/README.md index 9976213..fdf0173 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -25,6 +25,7 @@ Each record has the eight required sections. 0030 adopts the immutable genome v1 record, validation and canonical encoding. 0031 adopts deterministic development, derived phenotype and bounded plans. 0032 derives non-uniform metabolic budgets and the first genome/ledger path. +0033 adopts the bounded mutation catalog and uniform seeded candidate draws. Every dependency adoption records exact version/commit and integrity hash, transitive license obligations, maintenance/security review, owner and removal diff --git a/docs/biology/GENOME_MODEL.md b/docs/biology/GENOME_MODEL.md index 1836696..4a1a165 100644 --- a/docs/biology/GENOME_MODEL.md +++ b/docs/biology/GENOME_MODEL.md @@ -188,3 +188,46 @@ budgets differing by orders of magnitude make every tradeoff invisible. That is legibility choice for tests, not tuning, and must be re-derived before balancing. A budget is a derived quantity, not a rule: nothing here decides starvation, death or repair, and no organism spends any of it yet. + +## Implemented M3.4 mutation candidates + +[ADR-0033](../adr/0033-seeded-mutation-candidates.md) implements the +candidate-generation experiment this document describes, and only that. Four +effects over the seven capabilities give a static catalog with stable IDs: +adjust a parameter up or down by a hundredth of its declared range, acquire a +capability the genome lacks, or shed one it carries. + +Eligibility is not a second rulebook. An operator is eligible when the genome it +would produce passes the M3.1 validation unchanged, so prerequisites, required +capabilities, ranges and the acyclic graph are enforced once, where they were +defined. Shedding a capability another declares as a prerequisite fails that check +without a rule written for it. + +Nothing is ranked. Candidates are drawn without replacement by rejection sampling +on an explicit SplitMix64 stream, so every eligible operator is exactly as likely +as any other, and the result is returned sorted by operator ID. No score exists in +the record, position carries no meaning, and nothing about an organism's situation +makes a helpful mutation more likely to be offered. + +The draw reads the parent's content digest, a seed, a stream, an eligible event +index, growth, environment and the requested count, and nothing else. The same +context always returns the same candidates, so a retry cannot reroll; a new event +index is what earns a new draw. `select_mutation` regenerates the offer and +refuses unless it still matches exactly, so a changed context is rejected rather +than answered with a different mutation. A candidate reports the successor's own +maintenance and mass under ADR-0032 and reserves nothing. + +| Contract | Status after M3.4 | +|---|---| +| ValidateGenome | Implemented for schema 1, and reused as the eligibility filter | +| PlanDevelopment | Implemented: a proposal, narrowed by the composition layer | +| ApplyDevelopment | Half: the transfer still does not exist | +| DerivePhenotype | Implemented for rule version 1 | +| GenerateMutationCandidates | Implemented: uniform, canonical, context-recorded | +| SelectMutation | Implemented: revalidates and refuses a changed context | + +Uniform offering is not a claim about real mutation rates, and the catalog is not +a claim about which mutations are possible in biology. Candidate count, context +window, mutation cost as a game rule, inherited versus acquired expression, NPC +mutation and recombination all remain open, exactly as stated above. No organism +mutates, no fixture calls any of this, and heredity history is M3.5. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 87113b0..9411c90 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -583,3 +583,46 @@ chosen for legible magnitudes, not balance. Golden `d61ad5bf0c928c76`, ecosystem fingerprint `2cd4a15f9fbe9949` and the frozen genome fixture are unchanged. No deployment manifest or image pin changed. Linux validation is pending its first pushed run; no Gitea result is claimed for any increment since `b01a824`. + +## M3.4 seeded mutation candidates (2026-09-23) + +Native Release, analysis and MSVC ASan each passed 20/20 CTests; formatting +passed. Commands: `tools/windows-check.ps1 -Preset +-Action check` and debug `-Action format`. `mutation-contracts` is the one new +CTest case, in the existing `evo::biology` library. No existing suite changed. + +The eligible set for the founder fixture is pinned by hand rather than observed: +nine operators, derived from the schema by the rules that make them eligible. +Energy conversion and membrane can adjust either way, movement, ingestion, +reproduction and thermal tolerance can be acquired, target size can adjust up but +not down because its 9,999,999 step would fall below the minimum from 8,000,000, +and no required capability can be shed. Over 2,000 seeds the offers are exactly +that set and nothing else. + +Uniformity is checked to within a fifth of each operator's exact share, about six +standard deviations for 8,000 offers across nine operators. That test was +confirmed to fail when the draw was replaced by taking the first eligible +operators, which is the shape a biased offering would take. The rejection +sampling that removes modulo bias is correct by construction rather than +test-verified: over nine bins with 64-bit draws the bias it removes is about one +part in 10^18 and no test at this scale could observe it. That is recorded rather +than claimed as covered. + +Stability is checked both ways: the same context always returns the same +candidates, while a new event index, seed, stream or growth state returns a +different draw. Selection is checked to refuse an operator that was never offered, +a moved event index, a changed growth state, a tampered offer and a different +parent genome, each with its own error. Boundary operators are checked to be +absent rather than clamped at both ends of a range, and a capability another one +declares as a prerequisite is checked to be unsheddable while the dependent +capability itself remains sheddable. Every offered candidate is selected in turn +and its successor checked to validate, to record parent 7, and to survive a +decode; the reported maintenance and mass are checked to equal what +`metabolic_budget` charges that successor. + +No organism mutates and no fixture calls any of this. Candidate count, context +window, mutation cost as a game rule, inherited versus acquired expression, NPC +mutation and recombination remain open and are not settled here. Golden +`d61ad5bf0c928c76`, ecosystem fingerprint `2cd4a15f9fbe9949` and the frozen genome +fixture are unchanged. No deployment manifest or image pin changed. Linux +validation is pending; no Gitea result is claimed since `b01a824`. diff --git a/include/evo/biology/mutation.hpp b/include/evo/biology/mutation.hpp new file mode 100644 index 0000000..0aac9ab --- /dev/null +++ b/include/evo/biology/mutation.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include "evo/biology/metabolism.hpp" + +namespace evo::biology { +enum class MutationEffect : std::uint8_t { adjust_up, adjust_down, acquire, shed }; +// One entry of the static catalog. The ID is stable: it orders candidates and +// names them across calls, and it carries no ranking. +struct MutationOperator { + std::uint16_t id; + Capability target; + MutationEffect effect; + auto operator<=>(const MutationOperator&) const = default; +}; +// What the recorded context is. The draw reads this and the parent genome and +// nothing else, so events elsewhere in a world cannot move a candidate set. +struct MutationContext { + std::uint64_t seed; + std::uint32_t stream; // explicit stream identity, never a shared global + std::uint64_t event_index; // a new event earns a new draw; a retry does not + std::uint16_t candidate_count; + GrowthState growth; + EnvironmentState environment; + auto operator<=>(const MutationContext&) const = default; +}; +// A proposal. It reserves nothing. Maintenance and mass are what ADR-0032 would +// charge for the successor, not a price invented here and not a score. +struct MutationCandidate { + std::uint16_t operator_id; + Capability target; + MutationEffect effect; + std::uint32_t parameter; // the successor's value; zero when shed + std::uint64_t maintenance; + std::uint64_t total_mass; + auto operator<=>(const MutationCandidate&) const = default; +}; +enum class MutationError : std::uint8_t { + invalid_context, + no_candidates, + unknown_candidate, + context_changed, + invalid_successor +}; +inline constexpr std::size_t max_candidates = 8; + +[[nodiscard]] std::span mutation_catalog() noexcept; +// Identical inputs always yield identical candidates, sorted by operator ID. +// The order is canonical and means nothing: nothing here is ranked. +[[nodiscard]] std::expected, MutationError> +mutation_candidates(const Genome& genome, const MutationContext& context); +// Regenerates the offer and refuses unless it still matches exactly, so a changed +// context is rejected rather than answered with a different mutation. +[[nodiscard]] std::expected +select_mutation(const Genome& genome, const MutationContext& context, + std::span offered, std::uint16_t chosen, + std::uint64_t successor_id, std::uint64_t origin_event); +} // namespace evo::biology diff --git a/src/biology/mutation.cpp b/src/biology/mutation.cpp new file mode 100644 index 0000000..d1140ff --- /dev/null +++ b/src/biology/mutation.cpp @@ -0,0 +1,204 @@ +#include "evo/biology/mutation.hpp" + +#include "evo/core/random.hpp" + +#include +#include +#include +#include + +namespace evo::biology { +namespace { +// Four effects over seven capabilities. IDs are stable and carry no ranking; +// they exist to order candidates canonically and to name one across calls. +constexpr std::array catalog = [] { + std::array entries{}; + std::uint16_t next = 1; + for (std::size_t index = 0; index < capability_count; ++index) { + const auto kind = static_cast(index); + for (const auto effect : {MutationEffect::adjust_up, MutationEffect::adjust_down, + MutationEffect::acquire, MutationEffect::shed}) { + entries[static_cast(next - 1)] = {next, kind, effect}; + ++next; + } + } + return entries; +}(); + +// One rule rather than a constant per capability: a hundredth of the declared +// range, at least one. Granularity follows the range, which is a stated model +// choice and not a claim about biology. +constexpr std::uint32_t adjustment_step(Capability kind) noexcept { + const auto& limits = capability_schema[static_cast(kind)]; + const auto span = limits.maximum - limits.minimum; + return span / 100 == 0 ? 1 : span / 100; +} + +std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept { + // Non-cryptographic combiner. No wall clock and no std::hash enters this. + return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U)); +} +std::uint64_t context_digest(const Genome& genome, const MutationContext& context) noexcept { + std::uint64_t hash = genome.content_digest(); + for (const auto value : + {context.seed, static_cast(context.stream), context.event_index, + static_cast(context.candidate_count), + static_cast(context.growth.realized_per_thousand), + static_cast(context.growth.damage_per_thousand), + static_cast(context.environment.temperature_millikelvin), + context.environment.available.energy.value}) { + hash = mix(hash, value); + } + for (const auto& mass : context.environment.available.matter) { + hash = mix(hash, mass.value); + } + return hash; +} +// Exactly uniform below bound. Plain modulo would lean very slightly toward low +// operator IDs, which is precisely the bias this increment must be able to deny. +std::uint64_t bounded(Random& stream, std::uint64_t bound) noexcept { + const auto limit = std::numeric_limits::max() - + std::numeric_limits::max() % bound; + auto draw = stream.next(); + while (draw >= limit) { + draw = stream.next(); + } + return draw % bound; +} + +// Applies one operator, or reports that it does not apply at all. Validity is +// left entirely to Genome::create: prerequisites, required capabilities, ranges +// and the development graph are enforced once, where they were defined. +std::optional apply(const Genome& genome, const MutationOperator& entry, + std::uint64_t id, std::uint64_t origin_event) { + GenomeDraft draft; + draft.id = id; + draft.origin_event = origin_event; + draft.development_version = genome.development_version(); + draft.parents = {genome.id()}; + draft.capabilities.assign(genome.capabilities().begin(), genome.capabilities().end()); + const auto& limits = capability_schema[static_cast(entry.target)]; + const auto carried = + std::ranges::find(draft.capabilities, entry.target, &CapabilityRecord::kind); + const auto present = carried != draft.capabilities.end(); + switch (entry.effect) { + case MutationEffect::adjust_up: { + if (!present) { + return std::nullopt; + } + const auto step = adjustment_step(entry.target); + // Refused rather than clamped: a clamp would make two operators agree + // and would offer a no-op as a real choice. + if (carried->parameter > limits.maximum - step) { + return std::nullopt; + } + carried->parameter += step; + break; + } + case MutationEffect::adjust_down: { + if (!present) { + return std::nullopt; + } + const auto step = adjustment_step(entry.target); + if (carried->parameter < limits.minimum + step) { + return std::nullopt; + } + carried->parameter -= step; + break; + } + case MutationEffect::acquire: + if (present) { + return std::nullopt; + } + draft.capabilities.push_back({entry.target, limits.minimum, 0}); + break; + case MutationEffect::shed: + if (!present) { + return std::nullopt; + } + draft.capabilities.erase(carried); + break; + } + return draft; +} +} // namespace + +std::span mutation_catalog() noexcept { + return catalog; +} + +std::expected, MutationError> +mutation_candidates(const Genome& genome, const MutationContext& context) { + if (context.candidate_count == 0 || context.candidate_count > max_candidates) { + return std::unexpected{MutationError::invalid_context}; + } + // Eligibility is whatever M3.1 accepts, so there is no second rulebook. + std::vector eligible; + for (const auto& entry : catalog) { + // Any valid placeholder identity: eligibility and the reported budget + // depend on capabilities, never on which ID a successor would be given. + const auto draft = apply(genome, entry, genome.id() == 1 ? 2 : 1, 1); + if (!draft) { + continue; + } + const auto successor = Genome::create(*draft); + if (!successor) { + continue; + } + const auto budget = metabolic_budget(*successor, context.growth, context.environment); + if (!budget) { + continue; + } + const auto parameter = successor->parameter(entry.target); + eligible.push_back({entry.id, entry.target, entry.effect, parameter ? *parameter : 0U, + budget->maintenance.value, budget->phenotype.total_mass}); + } + if (eligible.empty()) { + return std::unexpected{MutationError::no_candidates}; + } + // Draw without replacement. Every eligible operator is exactly as likely as + // every other: nothing about the organism makes a helpful one more probable. + Random stream{mix(context_digest(genome, context), context.stream)}; + const auto wanted = std::min(context.candidate_count, eligible.size()); + for (std::size_t index = 0; index < wanted; ++index) { + const auto pick = index + bounded(stream, eligible.size() - index); + std::swap(eligible[index], eligible[pick]); + } + eligible.resize(wanted); + // Canonical order. Position carries no meaning; nothing here is ranked. + std::ranges::sort(eligible, {}, &MutationCandidate::operator_id); + return eligible; +} + +std::expected +select_mutation(const Genome& genome, const MutationContext& context, + std::span offered, std::uint16_t chosen, + std::uint64_t successor_id, std::uint64_t origin_event) { + const auto current = mutation_candidates(genome, context); + if (!current) { + return std::unexpected{current.error()}; + } + // A changed context is refused outright. Answering it with a still-valid but + // different mutation would mutate an organism into something nobody saw. + if (!std::ranges::equal(*current, offered)) { + return std::unexpected{MutationError::context_changed}; + } + const auto picked = std::ranges::find(*current, chosen, &MutationCandidate::operator_id); + if (picked == current->end()) { + return std::unexpected{MutationError::unknown_candidate}; + } + const auto entry = std::ranges::find(catalog, chosen, &MutationOperator::id); + if (entry == catalog.end()) { + return std::unexpected{MutationError::unknown_candidate}; + } + const auto draft = apply(genome, *entry, successor_id, origin_event); + if (!draft) { + return std::unexpected{MutationError::invalid_successor}; + } + auto successor = Genome::create(*draft); + if (!successor) { + return std::unexpected{MutationError::invalid_successor}; + } + return *successor; +} +} // namespace evo::biology diff --git a/tests/mutation_tests.cpp b/tests/mutation_tests.cpp new file mode 100644 index 0000000..92d6400 --- /dev/null +++ b/tests/mutation_tests.cpp @@ -0,0 +1,294 @@ +#include "evo/biology/mutation.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::biology; +using namespace evo::accounting; +void check(bool condition, std::source_location location = std::source_location::current()) { + if (!condition) { + throw std::runtime_error("mutation line " + std::to_string(location.line())); + } +} +#define CHECK(expression) check(static_cast(expression)) +constexpr Inventory pooled(std::uint64_t value) { + return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}}; +} +constexpr EnvironmentState temperate{293'150, pooled(1'000'000'000)}; +GenomeDraft draft() { + return {7, + 1, + 1, + {}, + {{Capability::energy_conversion, 400, 0}, + {Capability::membrane, 120, 0}, + {Capability::target_size, 8'000'000, 0}}}; +} +Genome build(const GenomeDraft& source) { + const auto genome = Genome::create(source); + check(genome.has_value()); + return *genome; +} +MutationContext context(std::uint64_t seed, std::uint16_t count = 4) { + return {seed, 1, 1, count, {1000, 0}, temperate}; +} + +void the_same_context_always_offers_the_same_candidates() { + const auto genome = build(draft()); + const auto first = mutation_candidates(genome, context(99)); + const auto again = mutation_candidates(genome, context(99)); + CHECK(first && again && *first == *again); // A retry is not a reroll. + CHECK(first->size() == 4); + // A new event earns a new draw; the seed and the stream do too. + auto later = context(99); + later.event_index = 2; + const auto next_event = mutation_candidates(genome, later); + CHECK(next_event && *next_event != *first); + auto elsewhere = context(99); + elsewhere.stream = 2; + CHECK(mutation_candidates(genome, elsewhere)); + CHECK(*mutation_candidates(genome, elsewhere) != *first); + CHECK(*mutation_candidates(genome, context(100)) != *first); + // Context that changes the organism changes the draw as well. + auto grown = context(99); + grown.growth = {500, 0}; + CHECK(*mutation_candidates(genome, grown) != *first); +} + +void offers_are_canonical_and_unranked() { + const auto genome = build(draft()); + bool ever_unsorted_by_cost = false; + for (std::uint64_t seed = 0; seed < 64; ++seed) { + const auto offered = mutation_candidates(genome, context(seed)); + CHECK(offered && offered->size() == 4); + // Canonical order, so position cannot encode a preference. Strictly + // increasing, because a draw without replacement never repeats one. + for (std::size_t index = 1; index < offered->size(); ++index) { + CHECK((*offered)[index - 1].operator_id < (*offered)[index].operator_id); + } + if (!std::ranges::is_sorted(*offered, {}, &MutationCandidate::maintenance)) { + ever_unsorted_by_cost = true; + } + } + // Offers are not arranged by their reported cost either, so no position in + // the list is the cheap one or the good one. + CHECK(ever_unsorted_by_cost); +} + +// The operators a founder genome with conversion, membrane and target size can +// legitimately reach. Derived by hand from the schema: required capabilities +// cannot be shed, absent ones cannot be adjusted, present ones cannot be +// acquired, and target size cannot step down from 8e6 by its 9,999,999 step. +std::vector> expected_eligible() { + return {{Capability::energy_conversion, MutationEffect::adjust_up}, + {Capability::energy_conversion, MutationEffect::adjust_down}, + {Capability::membrane, MutationEffect::adjust_up}, + {Capability::membrane, MutationEffect::adjust_down}, + {Capability::movement, MutationEffect::acquire}, + {Capability::ingestion, MutationEffect::acquire}, + {Capability::reproduction, MutationEffect::acquire}, + {Capability::target_size, MutationEffect::adjust_up}, + {Capability::thermal_tolerance, MutationEffect::acquire}}; +} + +void every_eligible_operator_is_offered_and_none_is_favoured() { + const auto genome = build(draft()); + constexpr std::uint64_t trials = 2000; + constexpr std::uint64_t drawn = 4; + std::map offers; + for (std::uint64_t seed = 0; seed < trials; ++seed) { + const auto offered = mutation_candidates(genome, context(seed)); + CHECK(offered && offered->size() == drawn); + for (const auto& candidate : *offered) { + ++offers[candidate.operator_id]; + } + } + // The set that was offered is exactly the set the schema permits, no more. + const auto permitted = expected_eligible(); + CHECK(offers.size() == permitted.size()); + for (const auto& [kind, effect] : permitted) { + const auto entry = std::ranges::find_if(mutation_catalog(), [&](const auto& candidate) { + return candidate.target == kind && candidate.effect == effect; + }); + CHECK(entry != mutation_catalog().end() && offers.contains(entry->id)); + } + // Each is offered within a fifth of its exact share. The draw is uniform by + // construction, so this is about six standard deviations wide; a draw that + // favoured any operator would be the biased-adaptation failure. + const auto share = trials * drawn / permitted.size(); + for (const auto& [id, count] : offers) { + CHECK(count * 5 > share * 4); + CHECK(count * 4 < share * 5); + } +} + +void only_legitimate_operators_are_offered() { + const auto genome = build(draft()); + const auto offered = mutation_candidates(genome, context(5, 8)); + CHECK(offered); + for (const auto& candidate : *offered) { + // A required capability can never be shed, however it is drawn. + const auto& limits = capability_schema[static_cast(candidate.target)]; + CHECK(!(candidate.effect == MutationEffect::shed && limits.required)); + // Acquiring only ever applies to something the parent lacks, and + // adjusting only to something it carries. + if (candidate.effect == MutationEffect::acquire) { + CHECK(!genome.carries(candidate.target)); + CHECK(candidate.parameter == limits.minimum); + } else if (candidate.effect != MutationEffect::shed) { + CHECK(genome.carries(candidate.target)); + CHECK(candidate.parameter >= limits.minimum && candidate.parameter <= limits.maximum); + } + // Every offer produces a genome the schema accepts. + const auto successor = + select_mutation(genome, context(5, 8), *offered, candidate.operator_id, 99, 42); + CHECK(successor); + CHECK(successor->id() == 99 && successor->origin_event() == 42); + CHECK(successor->parents().size() == 1 && successor->parents()[0] == 7); + CHECK(Genome::decode(successor->encode())); + } +} + +void boundaries_are_refused_rather_than_clamped() { + // At the top of its range, adjusting a capability up is not on offer at all. + auto source = draft(); + source.capabilities[1].parameter = 10'000; // membrane at its maximum + const auto topped = build(source); + const auto offers = mutation_candidates(topped, context(3, 8)); + CHECK(offers); + for (const auto& candidate : *offers) { + CHECK(!(candidate.target == Capability::membrane && + candidate.effect == MutationEffect::adjust_up)); + } + // The same at the bottom. + source.capabilities[1].parameter = 1; + const auto floored = build(source); + const auto low = mutation_candidates(floored, context(3, 8)); + CHECK(low); + for (const auto& candidate : *low) { + CHECK(!(candidate.target == Capability::membrane && + candidate.effect == MutationEffect::adjust_down)); + } + // A capability another one declares as a prerequisite cannot be shed, and no + // rule here says so: the schema's own validation refuses it. + source = draft(); + source.capabilities[1].parameter = 120; + source.capabilities.push_back({Capability::thermal_tolerance, 500, 0}); + source.capabilities.push_back( + {Capability::movement, 250, capability_bit(Capability::thermal_tolerance)}); + const auto dependent = build(source); + const auto guarded = mutation_candidates(dependent, context(11, 8)); + CHECK(guarded); + for (const auto& candidate : *guarded) { + CHECK(!(candidate.target == Capability::thermal_tolerance && + candidate.effect == MutationEffect::shed)); + } + // Shedding the dependent capability itself is still legitimate. + const auto sheddable = std::ranges::find_if(*guarded, [](const auto& candidate) { + return candidate.target == Capability::movement && candidate.effect == MutationEffect::shed; + }); + if (sheddable != guarded->end()) { + const auto successor = + select_mutation(dependent, context(11, 8), *guarded, sheddable->operator_id, 99, 42); + CHECK(successor && !successor->carries(Capability::movement)); + } +} + +void selection_refuses_a_changed_context_or_an_unknown_choice() { + const auto genome = build(draft()); + const auto offered = mutation_candidates(genome, context(7)); + CHECK(offered); + const auto chosen = offered->front().operator_id; + CHECK(select_mutation(genome, context(7), *offered, chosen, 99, 42)); + // An operator that was never offered is refused even though it is valid. + std::uint16_t absent = 0; + for (const auto& entry : mutation_catalog()) { + if (std::ranges::find(*offered, entry.id, &MutationCandidate::operator_id) == + offered->end()) { + absent = entry.id; + break; + } + } + CHECK(absent != 0); + const auto unknown = select_mutation(genome, context(7), *offered, absent, 99, 42); + CHECK(!unknown && unknown.error() == MutationError::unknown_candidate); + // A context that moved is rejected outright, never answered with a + // different mutation that happens to still be valid. + auto moved = context(7); + moved.event_index = 5; + const auto stale = select_mutation(genome, moved, *offered, chosen, 99, 42); + CHECK(!stale && stale.error() == MutationError::context_changed); + auto regrown = context(7); + regrown.growth = {250, 0}; + const auto shifted = select_mutation(genome, regrown, *offered, chosen, 99, 42); + CHECK(!shifted && shifted.error() == MutationError::context_changed); + // A tampered offer is a changed context too. + auto edited = *offered; + edited.front().maintenance += 1; + const auto forged = select_mutation(genome, context(7), edited, chosen, 99, 42); + CHECK(!forged && forged.error() == MutationError::context_changed); + // A different parent genome cannot be answered with this offer. + auto other = draft(); + other.capabilities[0].parameter = 401; + const auto cousin = build(other); + const auto mismatched = select_mutation(cousin, context(7), *offered, chosen, 99, 42); + CHECK(!mismatched && mismatched.error() == MutationError::context_changed); +} + +void reported_cost_is_what_the_budget_charges() { + const auto genome = build(draft()); + const auto offered = mutation_candidates(genome, context(13, 8)); + CHECK(offered); + for (const auto& candidate : *offered) { + const auto successor = + select_mutation(genome, context(13, 8), *offered, candidate.operator_id, 99, 42); + CHECK(successor); + // The candidate showed exactly what ADR-0032 would charge; nothing here + // invents a price, and nothing was reserved by displaying it. + const auto budget = metabolic_budget(*successor, {1000, 0}, temperate); + CHECK(budget && budget->maintenance.value == candidate.maintenance); + CHECK(budget->phenotype.total_mass == candidate.total_mass); + } + // The parent is untouched by every one of those proposals. + CHECK(genome == build(draft())); +} + +void invalid_contexts_are_refused() { + const auto genome = build(draft()); + for (const std::uint16_t count : + {std::uint16_t{0}, static_cast(max_candidates + 1)}) { + const auto refused = mutation_candidates(genome, context(1, count)); + CHECK(!refused && refused.error() == MutationError::invalid_context); + } + // An unsupported development version leaves no eligible operator at all, + // because every successor fails to derive a budget. + auto source = draft(); + source.development_version = 4; + const auto future = build(source); + const auto empty = mutation_candidates(future, context(1)); + CHECK(!empty && empty.error() == MutationError::no_candidates); + CHECK(mutation_catalog().size() == 4 * capability_count); +} +} // namespace +int main() try { + the_same_context_always_offers_the_same_candidates(); + offers_are_canonical_and_unranked(); + only_legitimate_operators_are_offered(); + boundaries_are_refused_rather_than_clamped(); + selection_refuses_a_changed_context_or_an_unknown_choice(); + reported_cost_is_what_the_budget_charges(); + invalid_contexts_are_refused(); + every_eligible_operator_is_offered_and_none_is_favoured(); + std::cout << "PASS mutation catalog, uniform seeded offers and guarded selection\n"; + return 0; +} catch (...) { + return 1; +}