Files
aevolution/tests/cellular_environment_tests.cpp
T
dingoandClaude Opus 5.5 4c70257883
Foundation / checks (ecs) (push) Successful in 2m28s
Foundation / checks (deploy) (push) Successful in 4m59s
Foundation / checks (network) (push) Successful in 20m56s
Foundation / checks (client) (push) Successful in 22m1s
Foundation / checks (tsan) (push) Successful in 45m41s
Foundation / checks (postgres) (push) Successful in 1h13m35s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (checks) (push) Canceled after 1h20m34s
feat(ecology): own cells and their local environment together
ADR-0172 records the maintainer's M12.5 ownership decision: one owner per
patch of space for cells and their local environment, reserves belonging
to the biological individual, and an open planet boundary whose every
crossing is a recorded import or export.

The portable CellularEnvironment owner (envelope AEVOCEN1) holds an exact
population with tagged water and dissolved compartments, refuses declared
atmosphere, imports infall from finite per-source entitlements (ADR-0136
step B) and radiates retained heat. Each tick's exchange is a validated
swap on the nested owner, undone if the biological tick refuses. Closed
and source-off regions keep their biology byte for byte; raw and cohort
representations agree under infall. No existing format, trace, golden,
default opening or live version changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:05:17 -04:00

388 lines
18 KiB
C++

#include "evo/server/lifecycle/cellular_environment.hpp"
#include "fixtures/cellular_ecology.hpp"
#include <cstring>
#include <fstream>
#include <iterator>
namespace {
using namespace evo;
using namespace evo::server;
using namespace evo::fixture;
using Environment = std::unique_ptr<CellularEnvironment>;
std::vector<CellularLifeIntent> controlled(const CellularLives& state, bool bud = false) {
std::vector<CellularLifeIntent> result;
for (const auto& life : state.lives())
if (life.account != LifeAccount{}) {
CellularLifeIntent input{life.identity.life, {}};
input.intent.bud = bud;
result.push_back(input);
}
return result;
}
// A real rules-9/owner-7 region: four funded founders on finite contact food.
Owner founders(std::uint64_t seed = 7) {
auto state = opening(seed, true);
state = checked(state->migration_upgrade_candidate(), "boundary upgrade");
return checked(state->maturation_upgrade_candidate(), "maturation upgrade");
}
Inventory energy_and_carbon(std::uint64_t energy, std::uint64_t carbon) {
Inventory value{{energy}, {}};
value.matter[0].value = carbon;
return value;
}
CellularInfallSource source(std::uint64_t id, std::uint32_t x, std::uint64_t interval,
Inventory entitlement, std::uint64_t start = 1,
std::uint64_t end = std::numeric_limits<std::uint64_t>::max()) {
CellularInfallSource made;
made.id = id;
made.x_um = x;
made.y_um = 0;
made.width_um = 3'000;
made.height_um = 6'000;
made.start_tick = start;
made.end_tick = end;
made.mean_interval_ticks = interval;
made.per_bubble = energy_and_carbon(400'000, 40'000);
made.entitlement = entitlement;
return made;
}
CellularEnvironmentConfig config(std::vector<CellularInfallSource> sources = {},
std::uint64_t radiation = 0) {
CellularEnvironmentConfig made;
made.geometry.voxel = {3, -2, 5};
made.geometry.box = {{1'000}, {2'000}, {0}, {6'000}, {6'000}, {10}};
made.water = {{5'000'000}, {70'000}, {9'000}};
made.sources = std::move(sources);
made.radiation_cap = {radiation};
return made;
}
Environment environment(Owner state, CellularEnvironmentConfig made) {
auto population =
checked(CellularPopulation::create(std::move(state), {false, 900, 1'600}), "population");
return checked(CellularEnvironment::create(std::move(population), std::move(made)),
"environment");
}
Environment copy(const CellularEnvironment& value) {
return checked(CellularEnvironment::restore(value.snapshot(), value.state().world(),
value.state().region(), value.state().frame(),
value.tick()),
"environment copy");
}
void step(CellularEnvironment& value, bool bud = false) {
checked(value.advance_tick(controlled(value.state(), bud)), "joint tick");
}
// Every channel: current == opening + incoming - outgoing, and the environment's own
// flows are the complete ledger here (no migration).
void audit(const CellularEnvironment& value) {
const auto& state = value.state();
const auto& ledger = state.boundary_ledger();
auto expected = state.opening_total();
expected.energy.value += ledger.incoming.energy.value;
expected.energy.value -= ledger.outgoing.energy.value;
for (std::size_t channel = 0; channel < expected.matter.size(); ++channel)
expected.matter[channel].value +=
ledger.incoming.matter[channel].value - ledger.outgoing.matter[channel].value;
require(state.current_total() == expected, "joint owner broke open-boundary closure");
require(ledger.incoming == value.imported() &&
ledger.outgoing == Inventory{value.exported(), {}},
"environment flows differ from the nested boundary ledger");
for (std::size_t index = 0; index < value.sources().size(); ++index) {
const auto& made = value.sources()[index];
const auto& done = value.infall()[index];
require(done.imported.energy <= made.entitlement.energy &&
done.imported.matter[0] <= made.entitlement.matter[0],
"infall exceeded its entitlement");
}
require(value.water() == CellularWaterColumn{{5'000'000}, {70'000}, {9'000}},
"rules 1 changed tagged water or dissolved nutrients");
}
// Source-off and closed regions keep the original biology exactly; a plain population
// advanced without the composite agrees byte for byte.
void closed_and_source_off() {
auto closed = environment(founders(), config());
const auto next = founders()->tick() + 1;
auto off = environment(
founders(), config({source(1, 0, 1, energy_and_carbon(1 << 30, 1 << 30), next, next + 1)}));
auto plain =
checked(CellularPopulation::create(founders(), {false, 900, 1'600}), "plain population");
// Tick 1 is inside the off source's interval; advance past it first without events.
for (unsigned tick = 0; tick < 1'000; ++tick) {
step(*closed, tick % 100 == 0);
if (tick == 0) {
const auto report = off->advance_tick(controlled(off->state(), true));
require(report && report->events == 1 && report->credited_bubbles > 0,
"every-tick source missed its only active tick");
} else {
step(*off, tick % 100 == 0);
}
checked(plain->advance_tick(controlled(plain->state(), tick % 100 == 0)), "plain tick");
audit(*closed);
audit(*off);
require(closed->population().snapshot() == plain->snapshot(),
"closed joint owner changed biology");
}
require(closed->imported() == Inventory{} && closed->exported().value == 0 &&
closed->state().current_total() == closed->state().opening_total(),
"closed region crossed its boundary");
require(off->infall()[0].events == 1 && off->imported() != Inventory{} &&
off->state().current_total() != off->state().opening_total(),
"source interval did not end after one tick");
}
// Open infall exhausts a finite entitlement exactly, then imports nothing.
void exhaustion() {
const auto entitlement = energy_and_carbon(4'000'000, 400'000); // Ten bubbles each.
auto open = environment(founders(), config({source(1, 0, 40, entitlement)}));
std::uint64_t exhausted_at = 0;
for (unsigned tick = 0; tick < 2'000; ++tick) {
step(*open, tick % 100 == 0);
audit(*open);
if (exhausted_at == 0 && open->imported() == entitlement)
exhausted_at = open->tick();
}
const auto& done = open->infall()[0];
require(exhausted_at != 0 && open->imported() == entitlement && done.exhausted_events > 0 &&
done.credited_bubbles == 20 && done.skipped_bubbles > 0,
"finite infall entitlement was not consumed exactly once");
std::cout << "exhaustion: entitlement consumed at tick " << exhausted_at << ", events "
<< done.events << ", credited " << done.credited_bubbles << ", skipped "
<< done.skipped_bubbles << ", exhausted events " << done.exhausted_events << '\n';
const auto after = open->imported();
for (unsigned tick = 0; tick < 500; ++tick)
step(*open);
require(open->imported() == after, "exhausted source imported more stock");
}
// Radiative export removes retained heat only: biology is unchanged against closed.
void radiation() {
auto closed = environment(founders(), config());
auto radiating = environment(founders(), config({}, 50));
for (unsigned tick = 0; tick < 1'500; ++tick) {
step(*closed, tick % 100 == 0);
step(*radiating, tick % 100 == 0);
audit(*radiating);
const auto& a = closed->state();
const auto& b = radiating->state();
require(std::ranges::equal(a.lives(), b.lives()) &&
std::ranges::equal(a.corpses(), b.corpses()) &&
a.habitat().snapshot() == b.habitat().snapshot() &&
a.heat().energy.value == b.heat().energy.value + radiating->exported().value,
"radiated heat changed biology or was not removed exactly");
}
require(radiating->exported().value > 0, "no heat was radiated");
std::cout << "radiation: exported " << radiating->exported().value << " pJ, retained "
<< radiating->state().heat().energy.value << " of "
<< closed->state().heat().energy.value << " pJ closed\n";
}
// A refused tick on an infall tick changes nothing; restore continues exactly.
void atomic_and_restore() {
// Every tick of the first 25 imports, so the refused tick carries an exchange.
const auto next = founders()->tick() + 1;
auto value = environment(
founders(),
config({source(1, 0, 1, energy_and_carbon(1 << 30, 1 << 30), next, next + 25)}, 7));
for (unsigned tick = 0; tick < 20; ++tick)
step(*value);
const auto before = value->snapshot();
const auto patches = value->state().habitat().patches().size();
require(!value->advance_tick({}).has_value() && value->snapshot() == before &&
value->state().habitat().patches().size() == patches,
"refused joint tick kept a torn exchange");
auto restored = copy(*value);
require(restored->snapshot() == before, "restore changed the joint envelope");
const auto retried = checked(value->advance_tick(controlled(value->state())), "retried tick");
require(retried.credited_bubbles > 0 && retried.imported != Inventory{},
"the refused tick carried no exchange");
step(*restored);
require(value->snapshot() == restored->snapshot(), "retry differed from the restored owner");
for (unsigned tick = 0; tick < 200; ++tick) {
step(*value, tick % 50 == 0);
step(*restored, tick % 50 == 0);
require(value->snapshot() == restored->snapshot(), "restored owner diverged");
}
audit(*restored);
}
// Exact cohorts of real wildlife see the same environment and biology as individuals.
void raw_and_cohort() {
auto raw = environment(
founders(), config({source(1, 0, 60, energy_and_carbon(1ULL << 40, 1ULL << 40))}, 20));
std::uint64_t genome = 0;
for (unsigned tick = 0; tick < 30'000 && genome == 0; ++tick) {
step(*raw, true);
for (const auto& life : raw->state().lives())
if (life.account == LifeAccount{})
genome = life.identity.genome;
}
require(genome != 0, "no real wildlife for cohort comparison");
auto cohort = copy(*raw);
require(checked(cohort->collapse(genome), "collapse wildlife") > 0, "empty cohort");
for (unsigned tick = 0; tick < 1'500; ++tick) {
const auto a = checked(raw->advance_tick(controlled(raw->state(), tick % 40 == 0)), "raw");
const auto b =
checked(cohort->advance_tick(controlled(cohort->state(), tick % 40 == 0)), "cohort");
require(a.imported == b.imported && a.exported == b.exported &&
a.biology.buds == b.biology.buds &&
raw->state().snapshot() == cohort->state().snapshot(),
"cohort and individual representations diverged");
}
audit(*cohort);
require(raw->infall()[0].events > 0, "comparison saw no infall");
std::cout << "raw/cohort: " << cohort->population().members().size() << " tagged of "
<< raw->state().lives().size() << " lives, infall events " << raw->infall()[0].events
<< ", imported energy " << raw->imported().energy.value << " pJ, radiated "
<< raw->exported().value << " pJ at tick " << raw->tick() << '\n';
}
std::vector<std::uint8_t> resealed(std::vector<std::uint8_t> bytes) {
std::uint64_t hash = 14695981039346656037ULL;
for (std::size_t i = 0; i + 8 < bytes.size(); ++i)
hash = (hash ^ bytes[i]) * 1099511628211ULL;
for (std::size_t i = 0; i < 8; ++i)
bytes[bytes.size() - 8 + i] = static_cast<std::uint8_t>(hash >> (8U * i));
return bytes;
}
void refusals() {
auto value = environment(founders(), config({source(1, 0, 1, energy_and_carbon(800'000, 1))}));
for (unsigned tick = 0; tick < 5; ++tick)
step(*value);
const auto bytes = value->snapshot();
const auto world = value->state().world(), region = value->state().region(),
frame = value->state().frame(), tick = value->tick();
auto corrupt = bytes;
corrupt[200] ^= 1U;
require(CellularEnvironment::restore(corrupt, world, region, frame, tick).error() ==
CellularEnvironmentError::checksum,
"corruption accepted");
require(CellularEnvironment::restore(bytes, world, region, frame, tick + 1).error() ==
CellularEnvironmentError::identity,
"wrong tick accepted");
auto version = bytes;
version[8] = 2;
require(CellularEnvironment::restore(resealed(version), world, region, frame, tick).error() ==
CellularEnvironmentError::unsupported,
"future envelope accepted");
// The first source's cumulative energy import (after id, rect, ticks, interval,
// bubble bounds, per-bubble and entitlement) above its entitlement.
auto excess = bytes;
const auto imported = cellular_environment_header_bytes + 8 + 16 + 24 + 8 + 40 + 40;
excess[imported + 7] = 0x7F;
require(CellularEnvironment::restore(resealed(excess), world, region, frame, tick).error() ==
CellularEnvironmentError::conservation,
"import above entitlement accepted");
auto nested = bytes;
nested[cellular_environment_header_bytes - 8] ^= 1U; // Nested length.
require(!CellularEnvironment::restore(resealed(nested), world, region, frame, tick),
"nested length accepted");
const auto refused = [](CellularEnvironmentConfig made, CellularEnvironmentError error,
Owner state = founders()) {
auto population = checked(CellularPopulation::create(std::move(state), {false, 900, 1'600}),
"refusal population");
const auto result = CellularEnvironment::create(std::move(population), std::move(made));
return !result && result.error() == error;
};
auto atmosphere = config();
atmosphere.atmosphere_species = 1;
require(refused(atmosphere, CellularEnvironmentError::unsupported),
"atmosphere treated as zero or unlimited");
auto flat = config();
flat.geometry.box.depth = {0};
require(refused(flat, CellularEnvironmentError::invalid_geometry), "zero depth accepted");
auto camera = config();
camera.geometry.box.width = {5'000};
require(refused(camera, CellularEnvironmentError::invalid_geometry),
"box disagreed with the cellular area");
auto outside = config();
outside.geometry.box.x = {996'000};
require(refused(outside, CellularEnvironmentError::invalid_geometry),
"habitat crossed its voxel");
const auto plenty = energy_and_carbon(1 << 20, 1 << 20);
require(refused(config({source(1, 0, 1, plenty), source(2, 2'000, 1, plenty)}),
CellularEnvironmentError::invalid_source),
"overlapping entitlements accepted");
require(refused(config({source(2, 0, 1, plenty), source(1, 3'000, 1, plenty)}),
CellularEnvironmentError::invalid_source),
"unsorted sources accepted");
auto empty = source(1, 0, 1, plenty);
empty.per_bubble = {};
require(refused(config({empty}), CellularEnvironmentError::invalid_source),
"stockless source accepted");
require(
refused(config({source(1, 4'000, 1, plenty)}), CellularEnvironmentError::invalid_source),
"source outside the habitat accepted");
require(refused(config(), CellularEnvironmentError::unsupported, opening(7, true)),
"owner without a boundary ledger accepted");
}
constexpr std::uint64_t restart_ticks = 400;
Environment restart_fixture() {
auto value =
environment(founders(), config({source(1, 0, 25, energy_and_carbon(1ULL << 40, 1ULL << 40)),
source(4, 3'000, 30, energy_and_carbon(1ULL << 40, 9))},
11));
for (std::uint64_t tick = 0; tick < restart_ticks; ++tick)
step(*value, tick % 50 == 0);
return value;
}
void write(const char* path, const std::vector<std::uint8_t>& bytes) {
std::ofstream out(path, std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(bytes.size()));
require(out.good(), "write failed");
}
std::vector<std::uint8_t> read(const char* path) {
std::ifstream in(path, std::ios::binary);
return {std::istreambuf_iterator<char>(in), {}};
}
void continue_fixture(CellularEnvironment& value) {
for (std::uint64_t tick = 0; tick < restart_ticks; ++tick)
step(value, tick % 50 == 0);
}
} // namespace
int main(int argc, char** argv) {
try {
if (argc == 4 && std::strcmp(argv[1], "--checkpoint") == 0) {
auto value = restart_fixture();
write(argv[2], value->snapshot());
continue_fixture(*value);
audit(*value);
write(argv[3], value->snapshot());
return 0;
}
if (argc == 4 && std::strcmp(argv[1], "--resume") == 0) {
const auto bytes = read(argv[2]);
// Identity is trusted input, never taken from the envelope it checks.
const auto origin = founders();
auto value = checked(CellularEnvironment::restore(bytes, origin->world(),
origin->region(), origin->frame(),
origin->tick() + restart_ticks),
"fresh-process restore");
continue_fixture(*value);
write(argv[3], value->snapshot());
return 0;
}
closed_and_source_off();
exhaustion();
radiation();
atomic_and_restore();
raw_and_cohort();
refusals();
auto value = restart_fixture();
audit(*value);
require(value->infall()[0].events > 0 && value->infall()[1].events > 0 &&
value->exported().value > 0,
"restart fixture crossed no boundary");
std::cout << "cellular environment contracts passed\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}