#include "evo/server/lifecycle/primitive_lives.hpp" #include #include #include #include #include namespace evo::server { struct PrimitiveLives::State { NurseryConfig config; accounting::Ledger ledger; biology::LineageArchive archive; std::vector lives; }; PrimitiveLives::PrimitiveLives(std::unique_ptr state) : state_{std::move(state)} {} PrimitiveLives::~PrimitiveLives() = default; std::expected, LifeError> PrimitiveLives::create(NurseryConfig config) { if (config.world == 0 || config.region == 0 || config.frame == 0 || config.source == 0 || config.sites.empty() || config.sites.size() > max_primitive_lives || !std::ranges::is_sorted(config.sites)) return std::unexpected{LifeError::invalid}; const auto founder = biology::primitive_founder(1, 1); if (!founder) return std::unexpected{LifeError::biology}; const auto phenotype = biology::derive_phenotype(*founder, {1000, 0}, {}); if (!phenotype) return std::unexpected{LifeError::biology}; for (std::size_t i = 0; i < config.sites.size(); ++i) { const auto site = config.sites[i]; if (site.x_um < -spawn_coordinate_limit_um || site.x_um > spawn_coordinate_limit_um || site.y_um < -spawn_coordinate_limit_um || site.y_um > spawn_coordinate_limit_um) return std::unexpected{LifeError::invalid}; for (std::size_t j = 0; j < i; ++j) { const auto dx = std::abs(std::int64_t{site.x_um} - config.sites[j].x_um); const auto dy = std::abs(std::int64_t{site.y_um} - config.sites[j].y_um); if (dx < phenotype->extent && dy < phenotype->extent) return std::unexpected{LifeError::occupied}; } } std::vector opening(2 + 2 * config.sites.size()); opening[0] = config.funding; // Source 1, heat 2; body/reserve pairs follow. auto ledger = accounting::Ledger::create(opening); if (!ledger) return std::unexpected{LifeError::overflow}; auto state = std::make_unique(State{std::move(config), std::move(*ledger), {}, {}}); return std::unique_ptr{new PrimitiveLives{std::move(state)}}; } std::expected PrimitiveLives::spawn(LifeRequest request, LifeAllocation allocation) { if (request.action == 0 || std::ranges::all_of(request.account, [](auto b) { return b == 0; })) return std::unexpected{LifeError::invalid}; for (const auto& life : state_->lives) { if (life.request == request) return life; if (life.request.account == request.account) return std::unexpected{LifeError::existing_life}; } if (allocation.life == 0 || allocation.organism == 0 || allocation.genome == 0 || allocation.event == 0) return std::unexpected{LifeError::invalid}; for (const auto& life : state_->lives) { const auto& old = life.identity; if (old.life == allocation.life || old.organism == allocation.organism || old.genome == allocation.genome || old.event == allocation.event) return std::unexpected{LifeError::identity_conflict}; } const auto slot = state_->lives.size(); if (slot == state_->config.sites.size()) return std::unexpected{LifeError::capacity}; const auto endowed = biology::primitive_endowment(); const auto genome = biology::primitive_founder(allocation.genome, allocation.event); if (!endowed || !genome) return std::unexpected{LifeError::biology}; const auto body = accounting::ReservoirId{static_cast(3 + 2 * slot)}; const auto reserve = accounting::ReservoirId{body.value + 1}; const PrimitiveLife life{ request, allocation, state_->config.source, state_->config.sites[slot], endowed->growth, body, reserve}; // Detached candidate: all fallible work, including allocations and archive // admission, precedes the single noexcept pointer swap. auto next = std::make_unique(*state_); const std::array legs{accounting::Transfer{{1}, body, endowed->body}, accounting::Transfer{{1}, reserve, endowed->reserve}, accounting::Transfer{{1}, {2}, {endowed->construction, {}}}}; const auto paid = next->ledger.transfer(slot + 1, legs); if (!paid) return std::unexpected{paid.error() == accounting::LedgerError::insufficient_inventory ? LifeError::insufficient_funding : LifeError::overflow}; if (!next->archive.admit(*genome) || !next->archive.record_birth(allocation.organism, allocation.genome, allocation.born)) return std::unexpected{LifeError::archive}; next->lives.push_back(life); state_.swap(next); return life; } const NurseryConfig& PrimitiveLives::config() const noexcept { return state_->config; } std::span PrimitiveLives::lives() const noexcept { return state_->lives; } std::span PrimitiveLives::balances() const noexcept { return state_->ledger.balances(); } accounting::Inventory PrimitiveLives::totals() const noexcept { return state_->ledger.conserved_totals(); } const biology::LineageArchive& PrimitiveLives::archive() const noexcept { return state_->archive; } namespace { constexpr std::uint64_t life_magic = 0x314546494C4F5645ULL; // "EVOLIFE1" constexpr std::size_t life_header_bytes = 112; constexpr std::size_t life_record_bytes = 96; std::uint64_t checksum(std::span bytes) noexcept { std::uint64_t value = 14695981039346656037ULL; for (const auto byte : bytes) value = (value ^ byte) * 1099511628211ULL; return value; } class Writer { public: explicit Writer(std::vector& bytes) : bytes_{bytes} {} void put(std::uint64_t value, unsigned width = 8) { for (unsigned i = 0; i < width; ++i, value >>= 8U) bytes_[at_++] = static_cast(value & 255U); } void inventory(accounting::Inventory value) { put(value.energy.value); for (const auto mass : value.matter) put(mass.value); } void site(SpawnSite value) { put(std::bit_cast(value.x_um), 4); put(std::bit_cast(value.y_um), 4); } void raw(std::span value) { for (const auto b : value) put(b, 1); } private: std::vector& bytes_; std::size_t at_{}; }; // Only constructed after exact sizes/counts have been checked, except for the // fixed header, whose minimum length is checked before reading any byte. class Reader { public: explicit Reader(std::span bytes) : bytes_{bytes} {} std::uint64_t get(unsigned width = 8) { std::uint64_t value{}; for (unsigned i = 0; i < width; ++i) value |= std::uint64_t{bytes_[at_++]} << (8U * i); return value; } accounting::Inventory inventory() { accounting::Inventory out{}; out.energy.value = get(); for (auto& mass : out.matter) mass.value = get(); return out; } SpawnSite site() { const auto x = static_cast(get(4)); const auto y = static_cast(get(4)); return {std::bit_cast(x), std::bit_cast(y)}; } std::span raw(std::size_t size) { const auto result = bytes_.subspan(at_, size); at_ += size; return result; } private: std::span bytes_; std::size_t at_{}; }; } // namespace std::vector PrimitiveLives::snapshot() const { const auto& c = state_->config; const auto history = state_->archive.encode(); std::vector bytes(life_header_bytes + 8 * c.sites.size() + life_record_bytes * state_->lives.size() + 40 * balances().size() + history.size() + 8); Writer out{bytes}; out.put(life_magic); out.put(primitive_lives_format, 4); out.put(biology::founder_life_rules, 4); out.put(c.world); out.put(c.region); out.put(c.frame); out.put(c.source); out.put(50'000); // Ratified M10 quantum; no biological stepping in format 1. out.inventory(c.funding); out.put(c.sites.size(), 4); out.put(state_->lives.size(), 4); out.put(history.size(), 4); out.put(0, 4); for (const auto site : c.sites) out.site(site); for (const auto& life : state_->lives) { out.raw(life.request.account); out.put(life.request.action); const auto& id = life.identity; out.put(id.life); out.put(id.organism); out.put(id.genome); out.put(id.event); out.put(id.born.value); out.put(life.source); out.site(life.site); out.put(life.growth.realized_per_thousand, 4); out.put(life.growth.damage_per_thousand, 4); out.put(life.body.value, 4); out.put(life.reserve.value, 4); } for (const auto inventory : balances()) out.inventory(inventory); out.raw(history); out.put(checksum(std::span{bytes}.first(bytes.size() - 8))); return bytes; } std::expected, LifeCodecError> PrimitiveLives::restore(std::span bytes, std::uint64_t world, std::uint64_t region, std::uint64_t frame) { if (bytes.size() < life_header_bytes + 8 || bytes.size() > max_primitive_lives_bytes) return std::unexpected{LifeCodecError::format}; Reader tail{bytes.last(8)}; if (checksum(bytes.first(bytes.size() - 8)) != tail.get()) return std::unexpected{LifeCodecError::checksum}; Reader in{bytes}; if (in.get() != life_magic) return std::unexpected{LifeCodecError::format}; if (in.get(4) != primitive_lives_format || in.get(4) != biology::founder_life_rules) return std::unexpected{LifeCodecError::version}; NurseryConfig c; c.world = in.get(); c.region = in.get(); c.frame = in.get(); c.source = in.get(); if (c.world != world || c.region != region || c.frame != frame) return std::unexpected{LifeCodecError::closure}; if (in.get() != 50'000) return std::unexpected{LifeCodecError::version}; c.funding = in.inventory(); const auto sites = in.get(4), count = in.get(4), archive_bytes = in.get(4); if (in.get(4) != 0 || sites == 0 || sites > max_primitive_lives || count > sites || archive_bytes > biology::max_archive_legacy_bytes || bytes.size() != life_header_bytes + 8 * sites + life_record_bytes * count + 40 * (2 + 2 * sites) + archive_bytes + 8) return std::unexpected{LifeCodecError::format}; for (std::uint64_t i = 0; i < sites; ++i) c.sites.push_back(in.site()); auto restored = create(std::move(c)); if (!restored) return std::unexpected{LifeCodecError::closure}; for (std::uint64_t i = 0; i < count; ++i) { PrimitiveLife saved{}; std::ranges::copy(in.raw(16), saved.request.account.begin()); saved.request.action = in.get(); auto& id = saved.identity; id.life = in.get(); id.organism = in.get(); id.genome = in.get(); id.event = in.get(); id.born.value = in.get(); saved.source = in.get(); saved.site = in.site(); saved.growth.realized_per_thousand = static_cast(in.get(4)); saved.growth.damage_per_thousand = static_cast(in.get(4)); saved.body.value = static_cast(in.get(4)); saved.reserve.value = static_cast(in.get(4)); const auto actual = (*restored)->spawn(saved.request, saved.identity); if (!actual || *actual != saved || (*restored)->lives().size() != i + 1) return std::unexpected{LifeCodecError::closure}; } for (const auto actual : (*restored)->balances()) if (actual != in.inventory()) return std::unexpected{LifeCodecError::closure}; const auto archive = in.raw(static_cast(archive_bytes)); if (!std::ranges::equal(archive, (*restored)->archive().encode()) || !std::ranges::equal(bytes, (*restored)->snapshot())) return std::unexpected{LifeCodecError::closure}; return std::move(*restored); } } // namespace evo::server