Files
aevolution/experiments/resolution/cellular_reference.cpp
T
dingo bee57e5829
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 2m47s
Foundation / checks (tsan) (push) Successful in 13m32s
Foundation / checks (client) (push) Failing after 17m9s
Foundation / checks (network) (push) Successful in 19m58s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (postgres) (push) Canceled after 20m34s
Foundation / checks (checks) (push) Canceled after 20m49s
M12.2c: qualify the current cellular reference instrument
2026-10-17 11:44:00 -04:00

363 lines
18 KiB
C++

// ADR-0138: current cellular exact control; no aggregate model or runtime policy.
#include "evo/server/lifecycle/cellular_batch.hpp"
#include "evo/server/lifecycle/cellular_play_summary.hpp"
#include "evo/server/lifecycle/wildlife_controller.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <expected>
#include <iostream>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace {
using namespace evo;
using namespace evo::server;
using accounting::Inventory;
using Owner = std::unique_ptr<CellularLives>;
using Clock = std::chrono::steady_clock;
void require(bool condition, const char* message) {
if (!condition)
throw std::runtime_error(message);
}
template <typename T, typename E> T checked(std::expected<T, E> result, const char* message) {
if (!result)
throw std::runtime_error(std::string{message} + ": " +
std::to_string(static_cast<unsigned>(result.error())));
return std::move(*result);
}
Owner restore(const CellularLives& state) {
return checked(CellularLives::restore(state.snapshot(), state.world(), state.region(),
state.frame(), state.tick()),
"reference restore");
}
std::uint64_t fingerprint(const CellularLives& state) {
std::uint64_t value = 14695981039346656037ULL;
for (const auto byte : state.snapshot())
value = (value ^ byte) * 1099511628211ULL;
return value; // Reproducibility fingerprint only, never an authenticity proof.
}
Owner opening(std::uint64_t seed, bool rich) {
constexpr std::uint32_t side = 6'000;
const auto world = 200 + seed;
const auto endowment = checked(biology::primitive_endowment(biology::primitive_founder_v3),
"reference founder endowment");
auto funding = endowment.body;
funding.energy.value = 4 * (endowment.reserve.energy.value + endowment.construction.value);
for (auto& channel : funding.matter)
channel.value *= 4;
const std::vector<SpawnSite> sites{
{1'000, 1'000}, {1'000, 4'000}, {4'000, 1'000}, {4'000, 4'000}};
auto primitive =
checked(PrimitiveLives::create({world, 1, 1, 17, funding, sites}), "reference nursery");
std::vector<biology::CellularPatch> pools;
for (const auto& site : sites) {
biology::CellularPatch pool;
pool.address = {static_cast<std::uint32_t>(site.x_um),
static_cast<std::uint32_t>(site.y_um)};
pool.radius_um = 500;
pool.source = 18;
pool.stock.energy.value = rich ? 1'000'000'000'000ULL : 0;
for (auto& channel : pool.stock.matter)
channel.value = rich ? 1'000'000'000'000ULL : 1'000;
pools.push_back(pool);
}
Inventory amount{{rich ? 1'000'000ULL : 10'000ULL}, {}};
for (auto& channel : amount.matter)
channel.value = rich ? 100'000 : 10;
auto config = checked(
biology::scatter_deposits({world, 1, 1, side, side, {}}, pools, {64, 19, amount, seed}),
"reference deposits");
if (rich) {
// Explicit finite contact food on each founding site. It is not a reserve grant
// or replenishment; the owner must acquire and spend it through real biology.
for (const auto& site : sites)
for (std::uint32_t channel = 0; channel < 5; ++channel) {
biology::CellularPatch mote;
mote.address = {static_cast<std::uint32_t>(site.x_um) + 10 + channel * 2,
static_cast<std::uint32_t>(site.y_um) + 10};
mote.source = 20;
mote.id = config.next_deposit++;
mote.radius_um = biology::cellular_mote_radius_um;
mote.kind = biology::CellularDepositKind::mote;
if (channel == 0)
mote.stock.energy.value = 1'000'000'000'000ULL;
else
mote.stock.matter[channel - 1].value = 1'000'000'000'000ULL;
config.patches.push_back(mote);
}
std::ranges::sort(config.patches, {}, &biology::CellularPatch::address);
}
auto habitat =
checked(biology::CellularHabitat::create(std::move(config)), "reference habitat");
auto state =
checked(CellularLives::create(*primitive, std::move(habitat), {{side, side}, 0, 293'150},
CellularLivesProfile::foraging),
"reference cellular owner");
require(state->advance_tick(std::span<const CellularLifeIntent>{}).has_value(),
"reference genesis tick");
for (std::uint64_t index = 0; index < 4; ++index) {
LifeRequest request{};
request.account.back() = static_cast<std::uint8_t>(index + 1);
request.action = 1;
const auto identity = 100 + index;
state = checked(state->birth_candidate(
request, {identity, identity, identity, identity, {state->tick()}}),
"reference funded birth");
}
require(state->rules_version() == cellular_lives_foraging_rules &&
state->habitat().config().format == biology::cellular_habitat_deposit_format,
"reference version bundle");
return state;
}
CellularTickIntents inputs(const CellularLives& state, std::uint64_t seed,
const std::set<std::uint64_t>& mutated) {
CellularTickIntents tick;
const auto wildlife = checked(wildlife_intents(state, state.tick() + 1), "reference wildlife");
for (const auto& life : state.lives()) {
CellularLifeIntent intent{life.identity.life, {}};
if (life.account == LifeAccount{}) {
const auto found =
std::ranges::find(wildlife, life.identity.life, &CellularLifeIntent::life_id);
require(found != wildlife.end(), "reference missing wildlife intention");
intent = *found;
} else {
const auto phase = (state.tick() + 1) % 1024;
intent.intent.frozen = life.identity.life == 100 && phase >= 128 && phase < 384;
if (!intent.intent.frozen) {
// Fixture players request real actions; the owner alone admits/funds them.
if ((state.tick() + 1 + life.identity.life) % 100 == 0)
intent.intent.bud = true;
else if ((state.tick() + 1) % 197 == 0)
intent.intent.engulf = true;
else if (state.tick() >= 4096) {
const auto direction = (state.tick() / 64 + life.identity.life + seed) % 4;
constexpr std::array<biology::CellularIntent, 4> directions{
{{1'000, 0}, {0, 1'000}, {-1'000, 0}, {0, -1'000}}};
intent.intent.movement = directions[direction];
}
}
if (!intent.intent.frozen && life.presence == CellularPresence::active &&
!mutated.contains(life.identity.life) && life.mutation.offer) {
const auto genome =
checked(state.archive().find(life.identity.genome), "reference offered genome");
const auto& offer = *life.mutation.offer;
for (std::size_t offset = 0; offset < offer.candidates.size(); ++offset) {
const auto& choice =
offer.candidates[(offset + seed) % offer.candidates.size()];
const auto successor = 1'000'000 + state.tick() * 4 + life.identity.life - 100;
const auto funded =
biology::fund_mutation(genome, offer.context, offer, choice.operator_id,
successor, successor, life.reserve);
if (funded) {
tick.mutations.push_back({life.identity.life, life.mutation.event_index,
life.mutation.offer_tick, successor,
choice.operator_id});
break;
}
}
}
}
tick.lives.push_back(intent);
}
return tick;
}
struct Replay {
std::uint64_t width{};
Owner state;
CellularBatch batch;
std::uint64_t elapsed_ns{}, intervals{}, restores{};
};
void flush(Replay& replay, const CellularLives& reference, bool timing) {
if (replay.batch.ticks.empty())
return;
const auto start = timing ? Clock::now() : Clock::time_point{};
replay.batch.header.world = replay.state->world();
replay.batch.header.region = replay.state->region();
replay.batch.header.frame = replay.state->frame();
replay.batch.header.begin_tick = replay.state->tick();
replay.batch.header.end_tick = reference.tick();
// Stand-in trusted predecessor identities for this in-memory, non-storage instrument.
replay.batch.header.predecessor.fill(1);
replay.batch.header.predecessor_digest.fill(2);
const auto bytes = checked(encode_cellular_batch(replay.batch), "reference trace encode");
const auto decoded = checked(decode_cellular_batch(bytes), "reference trace decode");
require(decoded == replay.batch, "reference trace round trip");
replay.state = checked(replay_cellular_batch(*replay.state, decoded), "reference trace replay");
if (timing)
replay.elapsed_ns += static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count());
require(replay.state->snapshot() == reference.snapshot(), "reference replay state mismatch");
require(replay.state->current_total() == replay.state->opening_total(),
"reference replay conservation");
++replay.intervals;
if (reference.tick() % 128 == 1) {
auto resumed = restore(*replay.state);
require(resumed->snapshot() == replay.state->snapshot(), "reference restart mismatch");
replay.state = std::move(resumed);
++replay.restores;
}
replay.batch.ticks.clear();
}
std::uint64_t profiles(const CellularLives& state) {
std::vector<std::vector<biology::CapabilityRecord>> distinct;
for (const auto& life : state.lives()) {
const auto genome = checked(state.archive().find(life.identity.genome), "reference census");
std::vector<biology::CapabilityRecord> signature{genome.capabilities().begin(),
genome.capabilities().end()};
if (std::ranges::find(distinct, signature) == distinct.end())
distinct.push_back(std::move(signature));
}
return distinct.size();
}
CellularPlaySummary run(std::uint64_t seed, bool rich, std::uint64_t ticks, bool timing) {
auto state = opening(seed, rich);
require(state->lives().size() == 4, "reference must start with four funded founders");
std::array<Replay, 3> replays{{{1, restore(*state), {}, 0, 0, 0},
{16, restore(*state), {}, 0, 0, 0},
{64, restore(*state), {}, 0, 0, 0}}};
std::set<std::uint64_t> mutated;
std::uint64_t direct_ns = 0, frozen_ticks = 0, suspended_ticks = 0, blocked = 0;
std::uint64_t peak_lives = state->lives().size(), peak_bytes = state->snapshot().size();
std::uint64_t max_profiles = profiles(*state);
for (std::uint64_t step = 0; step < ticks; ++step) {
const auto tick = inputs(*state, seed, mutated);
// Retain exact offline biology; presence/linger ticks may change, biology may not.
std::vector<CellularOwnedLife> frozen;
for (const auto& intent : tick.lives)
if (intent.intent.frozen) {
const auto found =
std::ranges::find(state->lives(), intent.life_id,
[](const auto& life) { return life.identity.life; });
require(found != state->lives().end(), "reference frozen identity");
frozen.push_back(*found);
++frozen_ticks;
}
const auto start = timing ? Clock::now() : Clock::time_point{};
const auto executed =
checked(state->advance_tick_with_mutations(tick.lives, tick.mutations),
"reference biological tick");
if (timing)
direct_ns += static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count());
for (const auto& mutation : executed.mutations)
if (mutation.result == CellularMutationResult::applied)
mutated.insert(mutation.life_id);
for (const auto& before : frozen) {
const auto found =
std::ranges::find(state->lives(), before.identity.life,
[](const auto& life) { return life.identity.life; });
if (found != state->lives().end())
require(found->identity == before.identity && found->growth == before.growth &&
found->position == before.position && found->body == before.body &&
found->reserve == before.reserve && found->mutation == before.mutation,
"reference offline biology progressed");
}
for (const auto& feedback : state->last_tick_feedback()) {
suspended_ticks += feedback.presence == CellularPresence::suspended ? 1 : 0;
blocked += feedback.resume_blocked ? 1 : 0;
}
require(state->current_total() == state->opening_total(), "reference conservation");
peak_lives = std::max(peak_lives, static_cast<std::uint64_t>(state->lives().size()));
peak_bytes = std::max(peak_bytes, static_cast<std::uint64_t>(state->snapshot().size()));
max_profiles = std::max(max_profiles, profiles(*state));
for (auto& replay : replays) {
replay.batch.ticks.push_back(tick);
if (replay.batch.ticks.size() == replay.width || step + 1 == ticks)
flush(replay, *state, timing);
}
}
const auto summary = checked(summarize_cellular_play(*state), "reference history summary");
require(state->tick() == ticks + 1, "reference did not complete every requested tick");
if (rich)
require(frozen_ticks > 0 && suspended_ticks > 0 && summary.mutations > 0 &&
max_profiles > 1,
"reference rich fixture missed mutation/offline coverage");
Inventory living_body{};
for (const auto& life : state->lives())
for (std::size_t channel = 0; channel < living_body.matter.size(); ++channel)
living_body.matter[channel].value += life.body.matter[channel].value;
std::cout << "{\"kind\":\"cellular_reference\",\"seed\":" << seed << ",\"split\":\""
<< (seed < 2 ? "development" : "holdout") << "\",\"regime\":\""
<< (rich ? "rich" : "scarce") << "\",\"ticks\":" << ticks
<< ",\"exact_replay\":true,\"conservation\":true,\"offline_frozen_ticks\":"
<< frozen_ticks << ",\"suspended_life_ticks\":" << suspended_ticks
<< ",\"resume_blocked_ticks\":" << blocked << ",\"peak_lives\":" << peak_lives
<< ",\"peak_snapshot_bytes\":" << peak_bytes
<< ",\"max_capability_profiles\":" << max_profiles
<< ",\"living_genome_ids\":" << summary.living_genomes
<< ",\"final_owned\":" << summary.owned << ",\"final_wildlife\":" << summary.wildlife
<< ",\"buds\":" << summary.buds << ",\"mutations\":" << summary.mutations
<< ",\"deaths\":" << summary.deaths << ",\"engulfed\":" << summary.engulfed
<< ",\"living_body_matter_fg\":[" << living_body.matter[0].value << ','
<< living_body.matter[1].value << ',' << living_body.matter[2].value << ','
<< living_body.matter[3].value << ']'
<< ",\"final_state_fnv64\":" << fingerprint(*state)
<< ",\"direct_step_ns\":" << direct_ns << "}\n";
for (const auto& replay : replays)
std::cout << "{\"kind\":\"replay_partition\",\"seed\":" << seed << ",\"regime\":\""
<< (rich ? "rich" : "scarce") << "\",\"width\":" << replay.width
<< ",\"compared_boundaries\":" << replay.intervals
<< ",\"checkpoint_restores\":" << replay.restores
<< ",\"codec_and_replay_ns\":" << replay.elapsed_ns << "}\n";
return summary;
}
} // namespace
int main(int argc, char** argv) try {
if (argc > 2 || (argc == 2 && std::string_view{argv[1]} != "--verify")) {
std::fputs("usage: evo-cellular-reference [--verify]\n", stderr);
return 2;
}
const bool timing = argc == 1;
std::cout << "{\"kind\":\"metadata\",\"instrument\":\"cellular-reference-1\","
"\"rules\":8,\"owner_format\":6,\"habitat_format\":2,\"genome_schema\":4,"
"\"development\":4,\"trace_format\":3,\"tick_microseconds\":50000,"
"\"aggregate_qualified\":false,\"compiler\":\""
#if defined(__clang__)
<< "Clang " << __clang_version__
#elif defined(_MSC_VER)
<< "MSVC " << _MSC_VER
#else
<< "GCC " << __VERSION__
#endif
<< "\",\"build\":\""
#if defined(NDEBUG)
<< "release"
#else
<< "debug"
#endif
<< "\"}\n";
std::uint64_t buds = 0, deaths = 0;
for (std::uint64_t seed = 0; seed < 4; ++seed)
for (const bool rich : {true, false}) {
const auto summary = run(seed, rich, timing ? 8192 : 512, timing);
buds += summary.buds;
deaths += summary.deaths;
}
if (timing)
require(buds > 0 && deaths > 0, "reference long suite missed birth/death coverage");
return 0;
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}