feat(ecology): own cells and their local environment together
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

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>
This commit is contained in:
dingo
2026-10-19 16:05:17 -04:00
co-authored by Claude Opus 5.5
parent a898a35e1b
commit 4c70257883
17 changed files with 1335 additions and 6 deletions
@@ -0,0 +1,460 @@
#include "evo/server/lifecycle/cellular_environment.hpp"
#include "evo/core/random.hpp"
#include <algorithm>
#include <limits>
#include <set>
#include <utility>
namespace evo::server {
namespace {
constexpr std::uint64_t magic = 0x314E45434F564541ULL; // "AEVOCEN1"
constexpr std::uint64_t infall_stream = 0x494E46414C4CULL; // "INFALL"
std::uint64_t checksum(std::span<const std::uint8_t> bytes) {
std::uint64_t hash = 14695981039346656037ULL;
for (const auto byte : bytes)
hash = (hash ^ byte) * 1099511628211ULL;
return hash; // Corruption detection; trusted publication must also bind SHA-256.
}
void put(std::vector<std::uint8_t>& bytes, std::uint64_t value, unsigned width) {
for (unsigned i = 0; i < width; ++i) {
bytes.push_back(static_cast<std::uint8_t>(value & 255U));
value >>= 8U;
}
}
void put(std::vector<std::uint8_t>& bytes, const accounting::Inventory& value) {
put(bytes, value.energy.value, 8);
for (const auto& channel : value.matter)
put(bytes, channel.value, 8);
}
class Reader {
public:
explicit Reader(std::span<const std::uint8_t> bytes) : bytes_(bytes) {}
std::uint64_t get(unsigned width) {
std::uint64_t value = 0;
for (unsigned i = 0; i < width; ++i)
value |= std::uint64_t{bytes_[at_++]} << (8U * i);
return value;
}
accounting::Inventory inventory() {
accounting::Inventory value;
value.energy.value = get(8);
for (auto& channel : value.matter)
channel.value = get(8);
return value;
}
[[nodiscard]] std::size_t at() const noexcept {
return at_;
}
private:
std::span<const std::uint8_t> bytes_;
std::size_t at_{};
};
// Channel 0 is energy; 1..4 are C, N, P and organic other.
std::uint64_t& channel(accounting::Inventory& value, std::size_t index) noexcept {
return index == 0 ? value.energy.value : value.matter[index - 1].value;
}
std::uint64_t channel(const accounting::Inventory& value, std::size_t index) noexcept {
return index == 0 ? value.energy.value : value.matter[index - 1].value;
}
bool add(accounting::Inventory& total, const accounting::Inventory& value) noexcept {
for (std::size_t index = 0; index < 5; ++index) {
if (channel(value, index) >
std::numeric_limits<std::uint64_t>::max() - channel(total, index))
return false;
channel(total, index) += channel(value, index);
}
return true;
}
bool within(const accounting::Inventory& part, const accounting::Inventory& whole) noexcept {
for (std::size_t index = 0; index < 5; ++index)
if (channel(part, index) > channel(whole, index))
return false;
return true;
}
std::uint64_t roll(std::uint64_t world, std::uint64_t region, std::uint64_t source,
std::uint64_t tick) noexcept {
std::uint64_t value = world;
for (const auto salt : {region, source, tick}) {
Random random{value};
value = random.next() ^ salt;
}
Random random{value};
return random.next();
}
bool overlaps(const CellularInfallSource& a, const CellularInfallSource& b) noexcept {
return std::uint64_t{a.x_um} < std::uint64_t{b.x_um} + b.width_um &&
std::uint64_t{b.x_um} < std::uint64_t{a.x_um} + a.width_um &&
std::uint64_t{a.y_um} < std::uint64_t{b.y_um} + b.height_um &&
std::uint64_t{b.y_um} < std::uint64_t{a.y_um} + a.height_um;
}
bool supported(const CellularLives& state) noexcept {
return (state.format_version() == cellular_lives_migration_format &&
(state.rules_version() == cellular_lives_foraging_rules ||
state.rules_version() == cellular_lives_maturation_rules)) ||
(state.format_version() == cellular_lives_inheritance_format &&
state.rules_version() == cellular_lives_inheritance_rules);
}
std::expected<world::HabitatMeasure, CellularEnvironmentError>
validate(const CellularLives& state, const CellularEnvironmentConfig& config) {
if (!supported(state))
return std::unexpected(CellularEnvironmentError::unsupported);
if (config.atmosphere_species != 0)
return std::unexpected(CellularEnvironmentError::unsupported);
const auto& box = config.geometry.box;
const auto measure = world::measure_habitat(box);
if (!measure || box.width.value != state.area().width_um ||
box.height.value != state.area().height_um || box.depth.value == 0)
return std::unexpected(CellularEnvironmentError::invalid_geometry);
if (config.sources.size() > max_cellular_infall_sources)
return std::unexpected(CellularEnvironmentError::invalid_source);
for (std::size_t index = 0; index < config.sources.size(); ++index) {
const auto& source = config.sources[index];
const bool stocked = source.per_bubble != accounting::Inventory{};
if (source.id == 0 || (index != 0 && config.sources[index - 1].id >= source.id) ||
source.width_um == 0 || source.height_um == 0 ||
std::uint64_t{source.x_um} + source.width_um > state.area().width_um ||
std::uint64_t{source.y_um} + source.height_um > state.area().height_um ||
source.start_tick >= source.end_tick || source.mean_interval_ticks == 0 ||
source.bubbles_min == 0 || source.bubbles_min > source.bubbles_max ||
source.bubbles_max > max_cellular_infall_bubbles || !stocked)
return std::unexpected(CellularEnvironmentError::invalid_source);
for (std::size_t other = 0; other < index; ++other)
if (overlaps(config.sources[other], source))
return std::unexpected(CellularEnvironmentError::invalid_source);
}
return *measure;
}
} // namespace
struct CellularEnvironment::Exchange {
std::vector<biology::CellularPatch> deposits;
accounting::Picojoules heat_export{};
std::vector<CellularInfallProgress> progress;
CellularEnvironmentTickReport report;
};
CellularEnvironment::CellularEnvironment(std::unique_ptr<CellularPopulation> population,
CellularEnvironmentConfig config)
: population_(std::move(population)), config_(std::move(config)),
progress_(config_.sources.size()) {}
CellularEnvironment::~CellularEnvironment() = default;
std::expected<std::unique_ptr<CellularEnvironment>, CellularEnvironmentError>
CellularEnvironment::create(std::unique_ptr<CellularPopulation> population,
CellularEnvironmentConfig config) {
if (!population)
return std::unexpected(CellularEnvironmentError::unsupported);
const auto measure = validate(population->state(), config);
if (!measure)
return std::unexpected(measure.error());
return std::unique_ptr<CellularEnvironment>(
new CellularEnvironment(std::move(population), std::move(config)));
}
const CellularPopulation& CellularEnvironment::population() const noexcept {
return *population_;
}
const CellularLives& CellularEnvironment::state() const noexcept {
return population_->state();
}
const CellularEnvironmentGeometry& CellularEnvironment::geometry() const noexcept {
return config_.geometry;
}
world::HabitatMeasure CellularEnvironment::measure() const noexcept {
// Validated at creation and restore; the box never changes.
const auto& box = config_.geometry.box;
return {{box.width.value * box.height.value},
{box.width.value * box.height.value * box.depth.value}};
}
const CellularWaterColumn& CellularEnvironment::water() const noexcept {
return config_.water;
}
std::span<const CellularInfallSource> CellularEnvironment::sources() const noexcept {
return config_.sources;
}
std::span<const CellularInfallProgress> CellularEnvironment::infall() const noexcept {
return progress_;
}
accounting::Picojoules CellularEnvironment::radiation_cap() const noexcept {
return config_.radiation_cap;
}
accounting::Inventory CellularEnvironment::imported() const noexcept {
accounting::Inventory total;
for (const auto& source : progress_)
static_cast<void>(add(total, source.imported)); // Bounded by the nested ledger.
return total;
}
accounting::Picojoules CellularEnvironment::exported() const noexcept {
return exported_;
}
std::uint64_t CellularEnvironment::tick() const noexcept {
return population_->state().tick();
}
std::expected<CellularEnvironment::Exchange, CellularEnvironmentError>
CellularEnvironment::plan_exchange(std::uint64_t tick) const {
const auto& state = population_->state();
const auto& habitat = state.habitat();
const auto area = state.area();
Exchange exchange;
exchange.progress = progress_;
exchange.report.tick = tick;
std::set<biology::CellularPatchAddress> taken;
for (std::size_t index = 0; index < config_.sources.size(); ++index) {
const auto& source = config_.sources[index];
auto& progress = exchange.progress[index];
if (tick < source.start_tick || tick >= source.end_tick)
continue;
const auto event = roll(state.world(), state.region(), source.id, tick);
if (event % source.mean_interval_ticks != 0)
continue;
Random stream{event ^ infall_stream};
const auto count =
source.bubbles_min + static_cast<std::uint32_t>(
stream.next() % (source.bubbles_max - source.bubbles_min + 1));
const auto centre_x =
source.x_um + static_cast<std::uint32_t>(stream.next() % source.width_um);
const auto centre_y =
source.y_um + static_cast<std::uint32_t>(stream.next() % source.height_um);
std::vector<std::size_t> stocked;
for (std::size_t slot = 0; slot < 5; ++slot)
if (channel(source.per_bubble, slot) != 0)
stocked.push_back(slot);
const auto first = static_cast<std::size_t>(stream.next() % stocked.size());
bool remaining = false;
for (const auto slot : stocked)
remaining =
remaining || channel(progress.imported, slot) < channel(source.entitlement, slot);
++progress.events;
++exchange.report.events;
if (!remaining)
++progress.exhausted_events;
for (std::uint32_t bubble = 0; bubble < count; ++bubble) {
const auto slot = stocked[(first + bubble) % stocked.size()];
constexpr auto radius = std::int64_t{cellular_infall_clump_radius_um};
std::int64_t dx = 0, dy = 0;
for (unsigned attempt = 0; attempt < 8; ++attempt) {
const auto x = static_cast<std::int64_t>(stream.next() % (2 * radius + 1)) - radius;
const auto y = static_cast<std::int64_t>(stream.next() % (2 * radius + 1)) - radius;
if (x * x + y * y <= radius * radius) {
dx = x;
dy = y;
break;
}
}
const biology::CellularPatchAddress address{
static_cast<std::uint32_t>(std::clamp<std::int64_t>(
std::int64_t{centre_x} + dx, 0, static_cast<std::int64_t>(area.width_um) - 1)),
static_cast<std::uint32_t>(
std::clamp<std::int64_t>(std::int64_t{centre_y} + dy, 0,
static_cast<std::int64_t>(area.height_um) - 1))};
const auto left = channel(source.entitlement, slot) - channel(progress.imported, slot);
const auto amount = std::min(channel(source.per_bubble, slot), left);
if (amount == 0 || habitat.find(address) || taken.contains(address) ||
habitat.patches().size() + exchange.deposits.size() >=
biology::max_cellular_patches) {
++progress.skipped_bubbles;
++exchange.report.skipped_bubbles;
continue;
}
biology::CellularPatch deposit;
deposit.address = address;
deposit.source = source.id;
deposit.radius_um = biology::cellular_mote_radius_um;
deposit.kind = biology::CellularDepositKind::mote;
channel(deposit.stock, slot) = amount;
if (!add(progress.imported, deposit.stock) ||
!add(exchange.report.imported, deposit.stock))
return std::unexpected(CellularEnvironmentError::overflow);
taken.insert(address);
exchange.deposits.push_back(deposit);
++progress.credited_bubbles;
++exchange.report.credited_bubbles;
}
}
exchange.heat_export.value = std::min(state.heat().energy.value, config_.radiation_cap.value);
if (exchange.heat_export.value > std::numeric_limits<std::uint64_t>::max() - exported_.value)
return std::unexpected(CellularEnvironmentError::overflow);
exchange.report.exported = exchange.heat_export;
return exchange;
}
std::expected<CellularEnvironmentTickReport, CellularEnvironmentError>
CellularEnvironment::advance_tick(std::span<const CellularLifeIntent> controlled,
std::span<const CellularMutationSelection> selections) {
if (tick() == std::numeric_limits<std::uint64_t>::max())
return std::unexpected(CellularEnvironmentError::overflow);
auto exchange = plan_exchange(tick() + 1);
if (!exchange)
return std::unexpected(exchange.error());
auto& lives = *population_->state_;
auto savepoint = lives.exchange_boundary(exchange->deposits, exchange->heat_export);
if (!savepoint)
return std::unexpected(savepoint.error() == CellularLivesError::habitat
? CellularEnvironmentError::habitat
: CellularEnvironmentError::conservation);
auto executed = population_->advance_tick(controlled, selections);
if (!executed) {
lives.restore_boundary(std::move(*savepoint));
return std::unexpected(CellularEnvironmentError::biology);
}
progress_ = std::move(exchange->progress);
exported_.value += exchange->heat_export.value;
exchange->report.biology = std::move(*executed);
return std::move(exchange->report);
}
std::expected<std::size_t, CellularEnvironmentError>
CellularEnvironment::collapse(std::uint64_t genome) {
const auto converted = population_->collapse(genome);
if (!converted)
return std::unexpected(CellularEnvironmentError::biology);
return *converted;
}
std::expected<std::size_t, CellularEnvironmentError>
CellularEnvironment::materialize(std::uint64_t genome) {
const auto converted = population_->materialize(genome);
if (!converted)
return std::unexpected(CellularEnvironmentError::biology);
return *converted;
}
std::vector<std::uint8_t> CellularEnvironment::snapshot() const {
const auto nested = population_->snapshot();
const auto& state = population_->state();
const auto& geometry = config_.geometry;
std::vector<std::uint8_t> bytes;
bytes.reserve(cellular_environment_header_bytes +
cellular_infall_source_bytes * config_.sources.size() + nested.size() + 8);
put(bytes, magic, 8);
put(bytes, cellular_environment_format, 4);
put(bytes, cellular_environment_rules, 4);
for (const auto value :
{state.world(), state.region(), state.frame(), state.tick(),
static_cast<std::uint64_t>(geometry.voxel.x),
static_cast<std::uint64_t>(geometry.voxel.y),
static_cast<std::uint64_t>(geometry.voxel.z), geometry.box.x.value, geometry.box.y.value,
geometry.box.z.value, geometry.box.width.value, geometry.box.height.value,
geometry.box.depth.value, config_.water.water.value,
config_.water.dissolved_nitrogen.value, config_.water.dissolved_phosphorus.value,
config_.radiation_cap.value, exported_.value})
put(bytes, value, 8);
put(bytes, config_.sources.size(), 4);
put(bytes, 0, 4);
put(bytes, nested.size(), 8);
for (std::size_t index = 0; index < config_.sources.size(); ++index) {
const auto& source = config_.sources[index];
const auto& progress = progress_[index];
put(bytes, source.id, 8);
for (const auto value : {source.x_um, source.y_um, source.width_um, source.height_um})
put(bytes, value, 4);
put(bytes, source.start_tick, 8);
put(bytes, source.end_tick, 8);
put(bytes, source.mean_interval_ticks, 8);
put(bytes, source.bubbles_min, 4);
put(bytes, source.bubbles_max, 4);
put(bytes, source.per_bubble);
put(bytes, source.entitlement);
put(bytes, progress.imported);
for (const auto value : {progress.events, progress.credited_bubbles,
progress.skipped_bubbles, progress.exhausted_events})
put(bytes, value, 8);
}
bytes.insert(bytes.end(), nested.begin(), nested.end());
put(bytes, checksum(bytes), 8);
return bytes;
}
std::expected<std::unique_ptr<CellularEnvironment>, CellularEnvironmentError>
CellularEnvironment::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
std::uint64_t region, std::uint64_t frame, std::uint64_t tick) {
if (bytes.size() < cellular_environment_header_bytes + 8 ||
bytes.size() > max_cellular_environment_bytes)
return std::unexpected(CellularEnvironmentError::format);
Reader tail(bytes.last(8));
if (tail.get(8) != checksum(bytes.first(bytes.size() - 8)))
return std::unexpected(CellularEnvironmentError::checksum);
Reader in(bytes);
if (in.get(8) != magic)
return std::unexpected(CellularEnvironmentError::format);
if (in.get(4) != cellular_environment_format || in.get(4) != cellular_environment_rules)
return std::unexpected(CellularEnvironmentError::unsupported);
if (in.get(8) != world || in.get(8) != region || in.get(8) != frame || in.get(8) != tick)
return std::unexpected(CellularEnvironmentError::identity);
CellularEnvironmentConfig config;
config.geometry.voxel = {static_cast<std::int64_t>(in.get(8)),
static_cast<std::int64_t>(in.get(8)),
static_cast<std::int64_t>(in.get(8))};
auto& box = config.geometry.box;
box.x.value = in.get(8);
box.y.value = in.get(8);
box.z.value = in.get(8);
box.width.value = in.get(8);
box.height.value = in.get(8);
box.depth.value = in.get(8);
config.water.water.value = in.get(8);
config.water.dissolved_nitrogen.value = in.get(8);
config.water.dissolved_phosphorus.value = in.get(8);
config.radiation_cap.value = in.get(8);
const accounting::Picojoules exported{in.get(8)};
const auto count = in.get(4);
if (in.get(4) != 0 || count > max_cellular_infall_sources)
return std::unexpected(CellularEnvironmentError::format);
const auto nested_bytes = in.get(8);
if (nested_bytes == 0 || nested_bytes > max_cellular_population_bytes ||
bytes.size() != cellular_environment_header_bytes + count * cellular_infall_source_bytes +
nested_bytes + 8)
return std::unexpected(CellularEnvironmentError::format);
std::vector<CellularInfallProgress> progress;
for (std::uint64_t index = 0; index < count; ++index) {
CellularInfallSource source;
source.id = in.get(8);
source.x_um = static_cast<std::uint32_t>(in.get(4));
source.y_um = static_cast<std::uint32_t>(in.get(4));
source.width_um = static_cast<std::uint32_t>(in.get(4));
source.height_um = static_cast<std::uint32_t>(in.get(4));
source.start_tick = in.get(8);
source.end_tick = in.get(8);
source.mean_interval_ticks = in.get(8);
source.bubbles_min = static_cast<std::uint32_t>(in.get(4));
source.bubbles_max = static_cast<std::uint32_t>(in.get(4));
source.per_bubble = in.inventory();
source.entitlement = in.inventory();
CellularInfallProgress done;
done.imported = in.inventory();
done.events = in.get(8);
done.credited_bubbles = in.get(8);
done.skipped_bubbles = in.get(8);
done.exhausted_events = in.get(8);
if (!within(done.imported, source.entitlement))
return std::unexpected(CellularEnvironmentError::conservation);
config.sources.push_back(source);
progress.push_back(done);
}
auto population = CellularPopulation::restore(
bytes.subspan(in.at(), static_cast<std::size_t>(nested_bytes)), world, region, frame, tick);
if (!population)
return std::unexpected(CellularEnvironmentError::format);
auto candidate = create(std::move(*population), std::move(config));
if (!candidate)
return std::unexpected(candidate.error());
(*candidate)->progress_ = std::move(progress);
(*candidate)->exported_ = exported;
// Environmental flows are part of the nested ledger, never in addition to it.
accounting::Inventory flows;
for (const auto& done : (*candidate)->progress_)
if (!add(flows, done.imported))
return std::unexpected(CellularEnvironmentError::conservation);
const auto& ledger = (*candidate)->state().boundary_ledger();
if (!within(flows, ledger.incoming) || exported.value > ledger.outgoing.energy.value)
return std::unexpected(CellularEnvironmentError::conservation);
if (!std::ranges::equal((*candidate)->snapshot(), bytes))
return std::unexpected(CellularEnvironmentError::format);
return candidate;
}
} // namespace evo::server
+71
View File
@@ -800,6 +800,77 @@ CellularLives::migration_replacement(std::vector<CellularOwnedLife> living,
return replacement;
}
std::expected<CellularLives::BoundarySavepoint, CellularLivesError>
CellularLives::exchange_boundary(std::span<const biology::CellularPatch> deposits,
accounting::Picojoules heat_export) {
if (state_->format_version != cellular_lives_migration_format &&
state_->format_version != cellular_lives_inheritance_format)
return std::unexpected(CellularLivesError::version);
if (heat_export.value > state_->heat.energy.value)
return std::unexpected(CellularLivesError::conservation);
auto boundary = state_->boundary;
auto heat = state_->heat;
heat.energy.value -= heat_export.value;
if (heat_export.value >
std::numeric_limits<std::uint64_t>::max() - boundary.outgoing.energy.value)
return std::unexpected(CellularLivesError::overflow);
boundary.outgoing.energy.value += heat_export.value;
if (deposits.empty()) {
// Heat alone: the total falls by exactly the recorded export, so closure holds.
BoundarySavepoint savepoint{nullptr, state_->heat, state_->current_total, state_->boundary};
state_->heat = heat;
state_->current_total.energy.value -= heat_export.value;
state_->boundary = std::move(boundary);
return savepoint;
}
std::unique_ptr<biology::CellularHabitat> habitat;
{
auto config = state_->habitat->config();
if (config.format != biology::cellular_habitat_deposit_format)
return std::unexpected(CellularLivesError::version);
for (auto deposit : deposits) {
if (config.next_deposit == std::numeric_limits<std::uint32_t>::max() ||
deposit.stock == accounting::Inventory{} ||
!add_inventory(boundary.incoming, deposit.stock))
return std::unexpected(CellularLivesError::overflow);
deposit.id = config.next_deposit++;
const auto at = std::ranges::lower_bound(config.patches, deposit.address, {},
&biology::CellularPatch::address);
if (at != config.patches.end() && at->address == deposit.address)
return std::unexpected(CellularLivesError::habitat);
config.patches.insert(at, deposit);
}
auto created = biology::CellularHabitat::create(std::move(config));
if (!created)
return std::unexpected(CellularLivesError::habitat);
habitat = std::move(*created);
}
const auto rules = state_->rules_version;
const auto total = validate_state(
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
*habitat, state_->lives, state_->corpses, state_->archive, state_->nursery, heat,
state_->opening_total, rules >= cellular_lives_engulf_rules,
rules >= cellular_lives_bud_rules, state_->next_bud_sequence,
rules >= cellular_lives_presence_rules, &boundary,
rules == cellular_lives_inheritance_rules ? &state_->offspring_revisions : nullptr);
if (!total)
return std::unexpected(total.error());
BoundarySavepoint savepoint{std::move(state_->habitat), state_->heat, state_->current_total,
state_->boundary};
state_->habitat = std::move(habitat);
state_->heat = heat;
state_->current_total = *total;
state_->boundary = std::move(boundary);
return savepoint;
}
void CellularLives::restore_boundary(BoundarySavepoint savepoint) noexcept {
if (savepoint.habitat)
state_->habitat = std::move(savepoint.habitat);
state_->heat = savepoint.heat;
state_->current_total = savepoint.current_total;
state_->boundary = std::move(savepoint.boundary);
}
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::migration_upgrade_candidate() const {
if (state_->rules_version != cellular_lives_foraging_rules)