Propose mutations without proposing a best build

M3.4 adds the candidate-generation experiment GENOME_MODEL describes: a
static catalog of four effects over the seven capabilities, drawn from a
recorded context with an explicit stream.

The named risk is a hidden best build or offerings biased toward what
would help, so the defence is structural rather than asserted. Nothing is
ranked: candidates are drawn without replacement by rejection sampling,
making every eligible operator 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.

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 development
graph are enforced once, where they were defined. Shedding a capability
another declares as a prerequisite fails that check with no rule written
here to catch it. Range boundaries are refused rather than clamped, since
a clamp would make two operators agree and offer a no-op as a choice.

The draw reads the parent digest and the context and nothing else, so the
same context always returns the same candidates and 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, so a changed
context is rejected rather than answered with a different mutation.

Cost is not invented: a candidate reports the successor's own maintenance
and mass under ADR-0032, and reserves nothing.

The eligible set is pinned by hand from the schema rather than observed,
and the uniformity check is confirmed to fail against a draw that takes
the first eligible operators. The rejection sampling that removes modulo
bias is correct by construction, not test-verified: at this scale the
bias is one part in 10^18. That is recorded rather than claimed.

No organism mutates and no fixture calls any of this. Candidate count,
mutation cost as a game rule, inherited versus acquired expression, NPC
mutation and recombination all remain open, as GENOME_MODEL requires.

Native Release, clang-tidy analysis, ASan and format checks pass 20/20.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-23 15:27:21 -04:00
co-authored by Claude Opus 5
parent fd6faeb7f8
commit 5497f4d74c
11 changed files with 788 additions and 6 deletions
+204
View File
@@ -0,0 +1,204 @@
#include "evo/biology/mutation.hpp"
#include "evo/core/random.hpp"
#include <algorithm>
#include <array>
#include <limits>
#include <optional>
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<MutationOperator, 4 * capability_count> catalog = [] {
std::array<MutationOperator, 4 * capability_count> entries{};
std::uint16_t next = 1;
for (std::size_t index = 0; index < capability_count; ++index) {
const auto kind = static_cast<Capability>(index);
for (const auto effect : {MutationEffect::adjust_up, MutationEffect::adjust_down,
MutationEffect::acquire, MutationEffect::shed}) {
entries[static_cast<std::size_t>(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<std::size_t>(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<std::uint64_t>(context.stream), context.event_index,
static_cast<std::uint64_t>(context.candidate_count),
static_cast<std::uint64_t>(context.growth.realized_per_thousand),
static_cast<std::uint64_t>(context.growth.damage_per_thousand),
static_cast<std::uint64_t>(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<std::uint64_t>::max() -
std::numeric_limits<std::uint64_t>::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<GenomeDraft> 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<std::size_t>(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<const MutationOperator> mutation_catalog() noexcept {
return catalog;
}
std::expected<std::vector<MutationCandidate>, 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<MutationCandidate> 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<std::size_t>(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<Genome, MutationError>
select_mutation(const Genome& genome, const MutationContext& context,
std::span<const MutationCandidate> 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