// Profile-4 publication and recovery against the migration-backed PostgreSQL adapter. #include "evo/persistence/account_control_store.hpp" #include "evo/persistence/checkpoint_store.hpp" #include "evo/persistence/life_reservation_store.hpp" #include "evo/persistence/sha256.hpp" #include "evo/server/cellular_region_host.hpp" #ifdef EVO_POSTGRES_M10 #include "evo/server/cellular_session_batch.hpp" #endif #include #include #include #include #include #include #include #include #include #include void run_cellular_publication_tests(); namespace { using namespace evo::persistence; using namespace evo::server; using namespace std::chrono_literals; void check(bool value, std::source_location at = std::source_location::current()) { if (!value) throw std::runtime_error("cellular publication test line " + std::to_string(at.line())); } #define CHECK(...) check(static_cast(__VA_ARGS__)) template const T& checked_value(const std::optional& value) { if (!value.has_value()) throw std::runtime_error("cellular publication test expected an optional value"); return *value; } template const T& checked_value(const std::expected& value) { if (!value.has_value()) throw std::runtime_error("cellular publication test expected a successful result"); return *value; } std::string env(const char* name) { const auto* value = std::getenv(name); if (!value) throw std::runtime_error("missing PostgreSQL test environment"); return value; } auto connect_as(const std::string& user) { auto db = Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), user, {}, {}}, 5s); CHECK(db); return std::move(*db); } template std::array filled(std::uint8_t value) { std::array out{}; out.fill(value); return out; } // Commit ids are unique across the whole store; other suites use uniform-byte ids, so // these mix bytes. Uuid distinct_commit(std::uint8_t tag) { auto id = filled<16>(0xC3); id[1] = 0x5E; id[15] = tag; return id; } std::string hex(std::span bytes) { constexpr char digits[] = "0123456789abcdef"; std::string out = "\\x"; for (const auto byte : bytes) { out.push_back(digits[byte >> 4U]); out.push_back(digits[byte & 15U]); } return out; } void refresh_cellular_checksum(std::vector& bytes) { std::uint64_t value = 14695981039346656037ULL; for (const auto byte : std::span{bytes}.first(bytes.size() - 8)) value = (value ^ byte) * 1099511628211ULL; for (unsigned index = 0; index < 8; ++index) bytes[bytes.size() - 8 + index] = static_cast(value >> (index * 8U)); } } // namespace namespace { void cellular_birth_publication_is_durable() { using namespace evo::biology; constexpr RegionKey key{9758, 1}; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(0xD9); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('d9',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowed = primitive_endowment(); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); auto habitat = CellularHabitat::create({key.world, key.region, 1, 1'000, 1'000, {}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 0, 293'150}); CHECK(opening && (*opening)->lives().empty()); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); const auto genesis = provision_cellular_region(*owner, **objects, key, 1, **opening, filled<16>(0x30), build, 5s); CHECK(genesis); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9758,1000)", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto authority = host->authority(); CHECK(authority); const auto& authority_value = checked_value(authority); const auto committed = host->committed(); CHECK(committed); const auto& committed_value = checked_value(committed); const auto account = filled<16>(0x47); const auto control = claim_account_control(*runtime, key, authority_value, account, 1, 1, 20'000ms, 5s); CHECK(control); const auto requested = host->create_primitive_life(account, control->generation, 7); CHECK(requested.result == evo::network::PrimitiveLifeResult::pending && requested.life_identity != 0 && host->queued_births().size() == 1); const auto retried = host->create_primitive_life(account, control->generation, 7); CHECK(retried == requested && host->queued_births().size() == 1); const auto reservation = host->queued_births().front(); CellularBatch batch; const auto predecessor_digest = sha256(committed_value.manifest); CHECK(predecessor_digest); batch.header = { key.world, key.region, 1, committed_value.head.commit, checked_value(predecessor_digest), 0, 1}; CellularTickIntents tick; tick.births.push_back(reservation); batch.ticks.push_back(tick); auto candidate = replay_cellular_batch(*host->state(), batch); CHECK(candidate && (*candidate)->lives().size() == 1 && (*candidate)->lives()[0].identity.life == reservation.identity); auto published = host->publish(batch); if (!published) { const auto& failure = published.error(); auto message = "cellular host publish failed, error=" + std::to_string(static_cast(failure.kind)); if (failure.publication) message += ", publication=" + std::to_string(static_cast(*failure.publication)); if (failure.store) { message += ", store=" + std::to_string(static_cast(failure.store->kind)); const auto& state = failure.store->cause.sqlstate; if (state[0] != '\0') message += ", sqlstate=" + std::string(state.data(), 5); } if (failure.object) message += ", object=" + std::to_string(static_cast(*failure.object)); throw std::runtime_error(message); } CHECK(published->committed.head.sequence == 1); CHECK(host->state()->snapshot() == (*candidate)->snapshot()); CHECK(host->queued_births().empty()); const auto host_outcome = host->query_primitive_life(account, control->generation, 7); CHECK(host_outcome.result == evo::network::PrimitiveLifeResult::born && host_outcome.life_identity == reservation.identity && host_outcome.commit_sequence == 1); const auto outcome = query_primitive_life(*runtime, key, authority_value, account, control->generation, 7, 5s); CHECK(outcome && outcome.value().has_value()); const auto& outcome_value = checked_value(outcome.value()); CHECK(outcome_value.published.has_value()); const auto& published_value = checked_value(outcome_value.published); CHECK(published_value.identity == reservation.identity && published_value.born == 1); host->drain(); host.reset(); auto restarted_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(restarted_objects); auto restarted_made = CellularRegionHost::create(config(), connect, std::move(*restarted_objects)); CHECK(restarted_made); auto restarted = std::move(*restarted_made); CHECK(restarted->step().ready && restarted->state()->tick() == 1 && restarted->state()->snapshot() == (*candidate)->snapshot()); restarted->drain(); } void cellular_profile_migration_is_durable_and_recovers_without_a_tick() { using namespace evo::biology; constexpr RegionKey key{9759, 1}; auto owner = connect_as(env("PGUSER")); const auto build = filled<32>(0xD9); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('d9',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowment = primitive_endowment(); CHECK(endowment); auto funding = endowment->body; funding.energy.value += endowment->reserve.energy.value + endowment->construction.value; for (std::size_t index = 0; index < funding.matter.size(); ++index) funding.matter[index].value += endowment->reserve.matter[index].value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); auto habitat = CellularHabitat::create({key.world, key.region, 1, 1'000, 1'000, {}}); CHECK(habitat); auto current = CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 0, 293'150}); CHECK(current && (*current)->lives().empty()); auto legacy_bytes = (*current)->snapshot(); constexpr std::uint64_t legacy_magic = 0x3130564C43564541ULL; for (unsigned index = 0; index < 8; ++index) legacy_bytes[index] = static_cast(legacy_magic >> (index * 8U)); legacy_bytes[8] = 1; legacy_bytes[9] = legacy_bytes[10] = legacy_bytes[11] = 0; legacy_bytes[12] = 1; legacy_bytes[13] = legacy_bytes[14] = legacy_bytes[15] = 0; refresh_cellular_checksum(legacy_bytes); auto legacy = CellularLives::restore(legacy_bytes, key.world, key.region, 1, 0); CHECK(legacy && (*legacy)->format_version() == cellular_lives_legacy_format); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); auto genesis_commit = filled<16>(0x50); genesis_commit[0] = 0x51; auto provisioned = provision_cellular_region(*owner, **objects, key, 1, **legacy, genesis_commit, build, 5s); CHECK(provisioned); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9759,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto migration_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(migration_objects); auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto authority = host->authority(); CHECK(authority); const auto& authority_value = checked_value(authority); const auto predecessor = host->committed(); CHECK(predecessor); const auto& predecessor_value = checked_value(predecessor); CHECK(predecessor_value.head.sequence == 0); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto account = filled<16>(0x5A); const auto control = claim_account_control(*runtime, key, authority_value, account, 1, 1, 20'000ms, 5s); CHECK(control); const auto requested = host->create_primitive_life(account, control->generation, 9); CHECK(requested.result == evo::network::PrimitiveLifeResult::pending && requested.life_identity != 0 && host->queued_births().size() == 1); CellularBatch batch; const auto predecessor_digest = sha256(predecessor_value.manifest); CHECK(predecessor_digest); batch.header = { key.world, key.region, 1, predecessor_value.head.commit, checked_value(predecessor_digest), 0, 1}; CellularTickIntents tick; tick.births.push_back(host->queued_births().front()); batch.ticks.push_back(tick); const auto published = host->publish(batch); CHECK(published && published->committed.head.sequence == 1); CHECK(host->state()->lives().size() == 1 && host->state()->lives().front().identity.born.value == 1); auto migrated = migrate_cellular_profile_to_v2(*owner, **migration_objects, authority_value, published->committed, filled<16>(0x51), build, 5s); CHECK(migrated && migrated->head.sequence == 2 && migrated->head.end_tick == 1); CHECK( retry_cellular_profile_migration(*owner, {key, filled<16>(0x51), migrated->manifest}, 5s)); auto revision_migrated = migrate_cellular_profile_to_v3( *owner, **migration_objects, authority_value, *migrated, filled<16>(0x52), build, 5s); CHECK(revision_migrated && revision_migrated->head.sequence == 3 && revision_migrated->head.end_tick == 1); CHECK(retry_cellular_profile_migration( *owner, {key, filled<16>(0x52), revision_migrated->manifest}, 5s)); host->drain(); host.reset(); auto recovery_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(recovery_objects); const auto target_manifest = decode_manifest(revision_migrated->manifest); CHECK(target_manifest); const auto target_payload = (*recovery_objects)->get({target_manifest->payload_sha256, target_manifest->payload_bytes}); CHECK(target_payload); auto restarted_made = CellularRegionHost::create(config(), connect, std::move(*recovery_objects)); CHECK(restarted_made); auto restarted = std::move(*restarted_made); CHECK(restarted->step().ready); const auto restarted_committed = restarted->committed(); CHECK(restarted_committed); const auto& restarted_committed_value = checked_value(restarted_committed); CHECK(restarted_committed_value.head.sequence == 3 && restarted_committed_value.head.end_tick == 1 && restarted->state()->tick() == 1 && restarted->state()->format_version() == cellular_lives_revision_format && restarted->state()->snapshot() == *target_payload); restarted->drain(); } // ADR-0121 (schema v35): a reserved mutation choice publishes with its checkpoint, the // bound result is the replay's, recovery reloads choice and result, and a restarted host // resumes at the same state. void cellular_mutation_publication_binds_results() { using namespace evo::biology; constexpr RegionKey key{9764, 1}; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(0xD9); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('d9',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowed = primitive_endowment(); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); // A stocked patch under the spawn site feeds the cell to its first offer. constexpr std::uint64_t stock = 100'000'000; auto habitat = CellularHabitat::create( {key.world, key.region, 1, 1'000, 1'000, {{{0, 0}, 29, {{stock}, {{{stock}, {stock}, {stock}, {stock}}}}}}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 0, 293'150}, CellularLivesProfile::engulf); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(0x9A), build, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9764,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto authority = checked_value(host->authority()); const auto account = filled<16>(0x64); const auto control = claim_account_control(*runtime, key, authority, account, 1, 1, 60'000ms, 5s); CHECK(control); CHECK(host->create_primitive_life(account, control->generation, 11).result == evo::network::PrimitiveLifeResult::pending); // Each batch starts at the host's committed head. const auto header = [&](std::uint64_t ticks) { const auto& committed = checked_value(host->committed()); const auto digest = sha256(committed.manifest); CHECK(digest); return CellularBatchHeader{key.world, key.region, 1, committed.head.commit, checked_value(digest), host->state()->tick(), host->state()->tick() + ticks}; }; CellularBatch birth; birth.header = header(1); birth.ticks.push_back({{}, {host->queued_births().front()}, {}}); CHECK(host->publish(birth)); const auto life_id = host->state()->lives().front().identity.life; for (int round = 0; round < 4 && !host->state()->lives().front().mutation.offer; ++round) { CHECK(host->step().ready); CellularBatch feeding; feeding.header = header(64); CellularStepIntent feed{}; feed.intake_target = CellularPatchAddress{0, 0}; for (int tick = 0; tick < 64; ++tick) feeding.ticks.push_back({{{life_id, feed}}, {}, {}}); CHECK(host->publish(feeding)); } const auto& life = host->state()->lives().front(); CHECK(life.mutation.offer.has_value()); const auto offer = checked_value(life.mutation.offer); CellularMutationActionRecord choice; choice.account = account; choice.action_id = 21; choice.tick = host->state()->tick() + 1; choice.input = {life_id, life.mutation.event_index, life.mutation.offer_tick, offer.candidates.front().operator_id}; const auto reservation = reserve_cellular_mutation(*runtime, key, authority, account, control->generation, choice.action_id, encode_cellular_mutation_input(choice), 5s); CHECK(reservation); CellularBatch mutation; mutation.header = header(1); mutation.ticks.push_back({{{life_id, {}}}, {}, {{life_id, choice.input.event_index, choice.input.offer_tick, reservation->successor_identity, choice.input.operator_id}}}); auto candidate = replay_cellular_batch(*host->state(), mutation); CHECK(candidate); auto mutation_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(mutation_objects); const std::array choices{choice}; // Publishing without the mutation block is refused: only the block binds the choice. CHECK(!publish_cellular_batch(*runtime, **mutation_objects, authority, checked_value(host->committed()), mutation, **candidate, distinct_commit(0x9B), build, 5s)); const auto published = publish_cellular_batch( *runtime, **mutation_objects, authority, checked_value(host->committed()), mutation, **candidate, distinct_commit(0x9B), build, 5s, {}, {}, choices); CHECK(published && published->mutation_results.size() == 1); const auto result = published->mutation_results.front(); // Applied exactly when the replayed life now carries the reserved successor genome. const bool applied = (*candidate)->lives().front().identity.genome == reservation->successor_identity; CHECK(result == (applied ? CellularMutationResult::applied : CellularMutationResult::insufficient_funding)); auto recovery_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(recovery_objects); const std::array retained{build}; auto recovered = recover_cellular_checkpoint(*runtime, **recovery_objects, key, authority, retained, 5s); CHECK(recovered && recovered->mutation_actions == std::vector{choice} && recovered->mutation_results == std::vector{result} && recovered->state->snapshot() == (*candidate)->snapshot()); host->drain(); host.reset(); auto restarted_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(restarted_objects); auto restarted_made = CellularRegionHost::create(config(), connect, std::move(*restarted_objects)); CHECK(restarted_made); auto restarted = std::move(*restarted_made); CHECK(restarted->step().ready && restarted->state()->snapshot() == (*candidate)->snapshot()); restarted->drain(); } // ADR-0121 11.4c-2: the host admits an exact choice of the outstanding offer, reserves it for // the next tick, keeps it across a restart, refuses a checkpoint that skips it, publishes it // with that tick and answers a repeat with the final outcome. void cellular_host_admits_mutation_choices() { using namespace evo::biology; constexpr RegionKey key{9765, 1}; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(0xDA); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('da',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowed = primitive_endowment(); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); constexpr std::uint64_t stock = 100'000'000; auto habitat = CellularHabitat::create( {key.world, key.region, 1, 1'000, 1'000, {{{0, 0}, 29, {{stock}, {{{stock}, {stock}, {stock}, {stock}}}}}}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 0, 293'150}, CellularLivesProfile::engulf); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(0x9C), build, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9765,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto account = filled<16>(0x74); const auto control = claim_account_control(*runtime, key, checked_value(host->authority()), account, 1, 1, 60'000ms, 5s); CHECK(control); CHECK(host->create_primitive_life(account, control->generation, 11).result == evo::network::PrimitiveLifeResult::pending); const auto header = [&](const CellularRegionHost& at, std::uint64_t ticks) { const auto& committed = checked_value(at.committed()); const auto digest = sha256(committed.manifest); CHECK(digest); return CellularBatchHeader{key.world, key.region, 1, committed.head.commit, checked_value(digest), at.state()->tick(), at.state()->tick() + ticks}; }; CellularBatch birth; birth.header = header(*host, 1); birth.ticks.push_back({{}, {host->queued_births().front()}, {}}); CHECK(host->publish(birth)); const auto life_id = host->state()->lives().front().identity.life; for (int round = 0; round < 4 && !host->state()->lives().front().mutation.offer; ++round) { CHECK(host->step().ready); CellularBatch feeding; feeding.header = header(*host, 64); CellularStepIntent feed{}; feed.intake_target = CellularPatchAddress{0, 0}; for (int tick = 0; tick < 64; ++tick) feeding.ticks.push_back({{{life_id, feed}}, {}, {}}); CHECK(host->publish(feeding)); } const auto& life = host->state()->lives().front(); const auto offer = checked_value(life.mutation.offer); const CellularMutationActionInput choice{life_id, life.mutation.event_index, life.mutation.offer_tick, offer.candidates.front().operator_id}; const auto next = host->state()->tick() + 1; // 11.4d: the owner's view lists the same candidates in operator order. const auto view = offer_view(*host->state(), life, next - 1); CHECK(view.life_identity == life_id && view.event_index == choice.event_index && view.offer_tick == choice.offer_tick && view.candidates.size() == offer.candidates.size() && std::ranges::is_sorted(view.candidates, {}, &evo::network::CellularOfferedCandidate::operator_id)); // ADR-0129: a candidate is affordable by its shown cost exactly when the owner would // fund it from the current reserve. const auto parent_genome = host->state()->archive().find(life.identity.genome); CHECK(parent_genome.has_value()); for (const auto& shown : view.candidates) { bool covered = life.reserve.energy.value >= shown.cost_energy_pj; for (std::size_t c = 0; c < shown.cost_matter_fg.size(); ++c) covered = covered && life.reserve.matter[c].value >= shown.cost_matter_fg[c]; const auto funded = parent_genome ? fund_mutation(*parent_genome, offer.context, offer, shown.operator_id, 999'999, 999'999, life.reserve) : std::unexpected{MutationError::development}; CHECK(covered == funded.has_value()); } auto wrong = choice; wrong.operator_id = 0xFFFF; CHECK(host->select_mutation(account, control->generation, 31, wrong).status == CellularMutationAdmission::invalid); auto stale = choice; ++stale.event_index; CHECK(host->select_mutation(account, control->generation, 31, stale).status == CellularMutationAdmission::invalid); const auto admitted = host->select_mutation(account, control->generation, 31, choice); CHECK(admitted.status == CellularMutationAdmission::admitted && admitted.tick == next); const auto repeated = host->select_mutation(account, control->generation, 31, choice); CHECK(repeated.status == CellularMutationAdmission::admitted && repeated.tick == next); CHECK(host->select_mutation(account, control->generation, 32, choice).status == CellularMutationAdmission::busy); CHECK(host->queued_mutations().size() == 1); const auto reservation = host->queued_mutations().front(); // A restarted host reloads the reserved choice for the same next tick. host->drain(); host.reset(); auto reopened = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(reopened); auto restarted_made = CellularRegionHost::create(config(), connect, std::move(*reopened)); CHECK(restarted_made); host = std::move(*restarted_made); CHECK(host->step().ready && host->state()->tick() + 1 == next); CHECK(host->queued_mutations().size() == 1 && host->queued_mutations().front() == reservation); // A checkpoint for that tick without the choice is refused; the queue survives it. CellularBatch skipped; skipped.header = header(*host, 1); skipped.ticks.push_back({{{life_id, {}}}, {}, {}}); CHECK(!host->publish(skipped)); CHECK(host->step().ready && host->queued_mutations().size() == 1); CellularBatch chosen; chosen.header = header(*host, 1); chosen.ticks.push_back({{{life_id, {}}}, {}, {{life_id, choice.event_index, choice.offer_tick, reservation.successor_identity, choice.operator_id}}}); const std::array records{CellularMutationActionRecord{account, 31, next, choice}}; const auto published = host->publish(chosen, {}, records); CHECK(published && published->mutation_results.size() == 1); CHECK(host->queued_mutations().empty()); const auto finalized = host->take_finalized_mutations(); CHECK(finalized.size() == 1 && finalized.front().account == account && finalized.front().action_id == 31 && finalized.front().tick == next && finalized.front().result == published->mutation_results.front() && finalized.front().commit_sequence == published->committed.head.sequence); const auto outcome = action_outcome(finalized.front()); CHECK(outcome.action_id == 31 && outcome.tick == next && outcome.result == (finalized.front().result == CellularMutationResult::applied ? evo::network::ActionResult::committed : evo::network::ActionResult::committed_no_effect)); // A repeat after publication answers with the same final outcome. const auto final_repeat = host->select_mutation(account, control->generation, 31, choice); CHECK(final_repeat.status == CellularMutationAdmission::final && final_repeat.outcome && *final_repeat.outcome == finalized.front()); CHECK(admit_status(final_repeat.status) == evo::network::AdmitStatus::duplicate); // ADR-0120 amendment (schema v40): feed until the next offer, then decline it. The // decline reserves and publishes like a choice, with result 3; the offer is consumed // and the genome is unchanged. for (int round = 0; round < 8 && !host->state()->lives().front().mutation.offer; ++round) { CellularBatch feeding; feeding.header = header(*host, 64); CellularStepIntent feed{}; feed.intake_target = CellularPatchAddress{0, 0}; for (int tick = 0; tick < 64; ++tick) feeding.ticks.push_back({{{life_id, feed}}, {}, {}}); CHECK(host->publish(feeding)); } // A live session renews its control every 5 s; this long test lets it lapse, so it // claims control again with a newer grant serial, as a reconnecting client would. CHECK(host->step().ready); // Renews the region lease after the feeding publications. const auto reclaimed = claim_account_control(*runtime, key, checked_value(host->authority()), account, 2, 2, 60'000ms, 5s); CHECK(reclaimed); const auto decline_generation = checked_value(reclaimed).generation; const auto& offered = host->state()->lives().front(); CHECK(offered.identity.life == life_id && offered.mutation.offer.has_value()); const auto genome_before = offered.identity.genome; const CellularMutationActionInput decline{life_id, offered.mutation.event_index, offered.mutation.offer_tick, 0}; const auto decline_tick = host->state()->tick() + 1; const auto declined = host->select_mutation(account, decline_generation, 33, decline); CHECK(declined.status == CellularMutationAdmission::admitted && declined.tick == decline_tick && host->queued_mutations().size() == 1); const auto decline_reservation = host->queued_mutations().front(); CellularBatch decline_batch; decline_batch.header = header(*host, 1); decline_batch.ticks.push_back({{{life_id, {}}}, {}, {{life_id, decline.event_index, decline.offer_tick, decline_reservation.successor_identity, 0}}}); const std::array decline_records{ CellularMutationActionRecord{account, 33, decline_tick, decline}}; const auto decline_published = host->publish(decline_batch, {}, decline_records); CHECK(decline_published && decline_published->mutation_results.size() == 1 && decline_published->mutation_results.front() == CellularMutationResult::declined); const auto& after_decline = host->state()->lives().front(); CHECK(!after_decline.mutation.offer && after_decline.identity.genome == genome_before); const auto decline_final = host->take_finalized_mutations(); CHECK(decline_final.size() == 1 && decline_final.front().result == CellularMutationResult::declined && action_outcome(decline_final.front()).result == evo::network::ActionResult::committed); CHECK(owner ->query("SELECT 1 FROM evolution.cellular_mutation_action_publications " "WHERE action_id = 33 AND result = 3", {}, 5s) ->size() == 1); host->drain(); } // ADR-0125 (schema v36): a rules-4 region publishes a bud with its tick; the wildlife // descendant, its identity and the parent's debit recover after a restart. // 2026-10-15 balance (schema v41): a rules-6 region publishes a founder of genome schema 3 // and development 3 on the v7 bundle, and a restarted host recovers it. ADR-0137 (schema // v42): likewise a rules-7 region, founder 3 (schema 4, development 4) on the v8 bundle. struct FoundingCase { RegionKey key; CellularLivesProfile profile; evo::biology::FounderVersion founder; std::uint32_t rules; evo::persistence::CellularVersionBundle bundle; std::uint8_t build_byte, commit_byte, account_byte; }; void cellular_balance_region_founds_and_recovers(const FoundingCase& c) { using namespace evo::biology; const RegionKey key = c.key; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(c.build_byte); { std::string hex; for (const auto byte : build) { constexpr std::string_view digits = "0123456789abcdef"; hex += digits[byte >> 4U]; hex += digits[byte & 15U]; } CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode('" + hex + "','hex')) ON CONFLICT DO NOTHING", {}, 5s)); } auto endowed = primitive_endowment(c.founder); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); constexpr std::uint64_t stock = 10'000'000'000; auto habitat = CellularHabitat::create( {key.world, key.region, 1, 3'000, 2'000, {{{0, 0}, 29, {{stock}, {{{stock}, {stock}, {stock}, {stock}}}}}}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 0, 293'150}, c.profile); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(c.commit_byte), build, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(" + std::to_string(key.world) + ",1000) ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready && host->state()->rules_version() == c.rules); const auto account = filled<16>(c.account_byte); const auto control = claim_account_control(*runtime, key, checked_value(host->authority()), account, 1, 1, 60'000ms, 5s); CHECK(control); CHECK(host->create_primitive_life(account, control->generation, 11).result == evo::network::PrimitiveLifeResult::pending); const auto& committed = checked_value(host->committed()); const auto digest = sha256(committed.manifest); CHECK(digest); CellularBatch birth; birth.header = {key.world, key.region, 1, committed.head.commit, checked_value(digest), host->state()->tick(), host->state()->tick() + 1}; birth.ticks.push_back({{}, {host->queued_births().front()}, {}}); CHECK(host->publish(birth)); const auto life = host->state()->lives().front(); const auto genome = host->state()->archive().find(life.identity.genome); CHECK(genome && genome->schema_version() == c.founder.genome_schema && genome->development_version() == c.founder.development_version); const auto manifest = decode_manifest(checked_value(host->committed()).manifest); CHECK(manifest && manifest->cellular_versions == c.bundle); // A restarted host recovers the state from its checkpoint. host->drain(); host.reset(); auto reopened = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(reopened); auto restarted = CellularRegionHost::create(config(), connect, std::move(*reopened)); CHECK(restarted); host = std::move(*restarted); CHECK(host->step().ready && host->state()->rules_version() == c.rules && host->state()->lives().size() == 1 && host->state()->lives().front().identity == life.identity); host->drain(); } void cellular_bud_publishes_and_recovers() { using namespace evo::biology; constexpr RegionKey key{9767, 1}; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(0xDB); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('db',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowed = primitive_endowment(); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); constexpr std::uint64_t stock = 10'000'000'000; auto habitat = CellularHabitat::create( {key.world, key.region, 1, 3'000, 2'000, {{{0, 0}, 29, {{stock}, {{{stock}, {stock}, {stock}, {stock}}}}}}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 0, 293'150}, CellularLivesProfile::budding); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(0x9D), build, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9767,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto account = filled<16>(0x84); const auto control = claim_account_control(*runtime, key, checked_value(host->authority()), account, 1, 1, 60'000ms, 5s); CHECK(control); CHECK(host->create_primitive_life(account, control->generation, 11).result == evo::network::PrimitiveLifeResult::pending); const auto header = [&](std::uint64_t ticks) { const auto& committed = checked_value(host->committed()); const auto digest = sha256(committed.manifest); CHECK(digest); return CellularBatchHeader{key.world, key.region, 1, committed.head.commit, checked_value(digest), host->state()->tick(), host->state()->tick() + ticks}; }; CellularBatch birth; birth.header = header(1); birth.ticks.push_back({{}, {host->queued_births().front()}, {}}); CHECK(host->publish(birth)); const auto parent = host->state()->lives().front().identity.life; CellularStepIntent feed{}; feed.intake_target = CellularPatchAddress{0, 0}; CellularStepIntent bud{}; bud.bud = true; // Feed for 63 ticks, then ask to bud on the batch's last tick, until it buds. for (int round = 0; round < 200 && host->state()->lives().size() == 1; ++round) { CHECK(host->step().ready); CellularBatch batch; batch.header = header(64); for (int tick = 0; tick < 63; ++tick) batch.ticks.push_back({{{parent, feed}}, {}, {}}); batch.ticks.push_back({{{parent, bud}}, {}, {}}); CHECK(host->publish(batch)); } CHECK(host->state()->lives().size() == 2); const auto expected_bud = cellular_bud_identity(key.region, 1); const auto& wildlife = host->state()->lives()[1]; CHECK(wildlife.identity.life == expected_bud && wildlife.parent_life == parent && wildlife.account == LifeAccount{} && host->state()->next_bud_sequence() == 2); const auto snapshot = host->state()->snapshot(); host->drain(); host.reset(); auto reopened = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(reopened); auto restarted = CellularRegionHost::create(config(), connect, std::move(*reopened)); CHECK(restarted); CHECK((*restarted)->step().ready && (*restarted)->state()->snapshot() == snapshot); (*restarted)->drain(); } #ifdef EVO_POSTGRES_M10 // Write-behind commits (evo-server's rules-12 loop): each batch commits on the host's worker // thread while the next one builds on its candidate under a provisional head, rebased when // the commit lands; recovery reloads exactly the chained state. void cellular_write_behind_commits_chain_and_recover() { using namespace evo::biology; constexpr RegionKey key{9778, 1}; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(0xDB); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('db',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowed = primitive_endowment(); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); constexpr std::uint64_t stock = 10'000'000'000; auto habitat = CellularHabitat::create( {key.world, key.region, 1, 3'000, 2'000, {{{0, 0}, 29, {{stock}, {{{stock}, {stock}, {stock}, {stock}}}}}}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 0, 293'150}, CellularLivesProfile::budding); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(0x9E), build, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9778,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto account = filled<16>(0x85); const auto control = claim_account_control(*runtime, key, checked_value(host->authority()), account, 1, 1, 60'000ms, 5s); CHECK(control); CHECK(host->create_primitive_life(account, control->generation, 11).result == evo::network::PrimitiveLifeResult::pending); const auto& committed = checked_value(host->committed()); const auto digest = sha256(committed.manifest); CHECK(digest); CellularBatch birth; birth.header = {key.world, key.region, 1, committed.head.commit, checked_value(digest), host->state()->tick(), host->state()->tick() + 1}; birth.ticks.push_back({{}, {host->queued_births().front()}, {}}); CHECK(host->publish(birth)); CellularStepIntent feed{}; feed.intake_target = CellularPatchAddress{0, 0}; const std::array baseline{ CellularLifeIntent{host->state()->lives().front().identity.life, feed}}; auto created = CellularSessionBatchBuilder::create(*host->state(), checked_value(host->committed()).head); CHECK(created); std::optional open{std::move(*created)}; const auto fill = [&](int ticks) { for (int i = 0; i < ticks; ++i) CHECK(open->append(open->candidate().tick() + 1, baseline, {})); }; fill(20); for (int round = 0; round < 3; ++round) { const auto& candidate = open->candidate(); const auto end = candidate.tick(); RegionHead provisional{ candidate.frame(), checked_value(host->committed()).head.sequence + 1, {}, {}, end}; provisional.commit.fill(0xFF); provisional.digest.fill(0xFF); auto next = CellularSessionBatchBuilder::create(candidate, provisional); CHECK(next); const auto batch = open->batch(); CHECK(host->begin_publish(batch, {}, {}, open->take_candidate())); // One commit at a time; the synchronous path waits too. CHECK(host->commit_in_flight() && !host->publish(batch) && !host->begin_publish(batch, {}, {}, nullptr)); open.emplace(std::move(*next)); fill(20); // Simulation continues while the commit runs. std::optional> landed; for (int wait = 0; wait < 1'000 && !landed; ++wait) { landed = host->poll_publish(); if (!landed) std::this_thread::sleep_for(10ms); } CHECK(landed && *landed && !host->commit_in_flight() && host->state()->tick() == end && checked_value(host->committed()).head.sequence == provisional.sequence); CHECK(open->rebase(checked_value(host->committed()).head) && host->step().ready); } const auto snapshot = host->state()->snapshot(); const auto tick = host->state()->tick(); host->drain(); host.reset(); auto reopened = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(reopened); auto restarted = CellularRegionHost::create(config(), connect, std::move(*reopened)); CHECK(restarted); CHECK((*restarted)->step().ready && (*restarted)->state()->tick() == tick && (*restarted)->state()->snapshot() == snapshot); (*restarted)->drain(); } #endif // ADR-0127 (schema v37): a dead life stays dead, its corpse stays, and its account starts // a new primitive life with a new identity; the first life's history is unchanged. void cellular_death_is_final_and_account_restarts() { using namespace evo::biology; constexpr RegionKey key{9768, 1}; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto build = filled<32>(0xDC); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('dc',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); auto endowed = primitive_endowment(); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; funding.energy.value *= 2; for (auto& channel : funding.matter) channel.value *= 2; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}, {2'000, 0}}}); CHECK(primitive); auto habitat = CellularHabitat::create({key.world, key.region, 1, 3'000, 2'000, {}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 0, 293'150}, CellularLivesProfile::engulf); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(0x9F), build, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9768,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); CHECK(host->step().ready); const auto account = filled<16>(0x94); const auto control = claim_account_control(*runtime, key, checked_value(host->authority()), account, 1, 1, 60'000ms, 5s); CHECK(control); const auto header = [&](std::uint64_t ticks) { const auto& committed = checked_value(host->committed()); const auto digest = sha256(committed.manifest); CHECK(digest); return CellularBatchHeader{key.world, key.region, 1, committed.head.commit, checked_value(digest), host->state()->tick(), host->state()->tick() + ticks}; }; const auto born = [&](std::uint64_t request) { CHECK(host->create_primitive_life(account, control->generation, request).result == evo::network::PrimitiveLifeResult::pending); CellularBatch birth; birth.header = header(1); std::vector idle; for (const auto& life : host->state()->lives()) idle.push_back({life.identity.life, {}}); birth.ticks.push_back({idle, {host->queued_births().front()}, {}}); CHECK(host->publish(birth)); const auto outcome = host->query_primitive_life(account, control->generation, request); CHECK(outcome.result == evo::network::PrimitiveLifeResult::born); return outcome.life_identity; }; const auto first = born(11); // Unfed in an empty habitat, the founder starves. A batch that runs past the death // names a dead life and is refused by replay, so near the end publish single ticks. for (int round = 0; round < 4'000 && !host->state()->lives().empty(); ++round) { CHECK(host->step().ready); const auto idle = [&](std::uint64_t ticks) { CellularBatch batch; batch.header = header(ticks); for (std::uint64_t tick = 0; tick < ticks; ++tick) batch.ticks.push_back({{{first, {}}}, {}, {}}); return batch; }; if (!host->publish(idle(32))) CHECK(host->publish(idle(1))); } CHECK(host->state()->lives().empty() && host->state()->corpses().size() == 1 && host->state()->corpses().front().life_id == first); CHECK(host->step().ready); // Records any ending a failed flush left behind. const auto owner_region = primitive_life_owner(*runtime, key, checked_value(host->authority()), account, 5s); CHECK(owner_region && !*owner_region); // No active life anywhere. // The same account starts a new primitive life; the first one is history. const auto second = born(12); CHECK(second != first && host->state()->lives().size() == 1 && host->state()->lives().front().identity.life == second && host->state()->corpses().size() == 1); CHECK(host->query_primitive_life(account, control->generation, 11).result == evo::network::PrimitiveLifeResult::born); // While the second life lives, a third request is an existing-life refusal. CHECK(host->create_primitive_life(account, control->generation, 13).result == evo::network::PrimitiveLifeResult::existing_life); // A fresh account still cannot create energy from an exhausted nursery. The // expected refusal must not stall the living cell's tick or stay pending forever. const auto newcomer = filled<16>(0x95); const auto newcomer_control = claim_account_control( *runtime, key, checked_value(host->authority()), newcomer, 1, 2, 60'000ms, 5s); CHECK(newcomer_control); CHECK(host->create_primitive_life(newcomer, newcomer_control->generation, 21).result == evo::network::PrimitiveLifeResult::pending); const auto before_tick = host->state()->tick(); const std::array refusals{CellularBirthRefusal{host->queued_births().front(), CellularLivesError::insufficient_funding}}; CellularBatch continued; continued.header = header(1); continued.ticks.push_back({{{second, {}}}, {}, {}}); CHECK(host->publish(continued)); host->refuse_births(refusals); CHECK(host->state()->tick() == before_tick + 1 && host->queued_births().empty()); CHECK(host->query_primitive_life(newcomer, newcomer_control->generation, 21).result == evo::network::PrimitiveLifeResult::insufficient_funding); CHECK(host->create_primitive_life(newcomer, newcomer_control->generation, 21).result == evo::network::PrimitiveLifeResult::insufficient_funding); const auto snapshot = host->state()->snapshot(); host->drain(); host.reset(); auto reopened = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(reopened); auto restarted = CellularRegionHost::create(config(), connect, std::move(*reopened)); CHECK(restarted); CHECK((*restarted)->step().ready && (*restarted)->state()->snapshot() == snapshot); (*restarted)->drain(); } } // namespace void run_cellular_publication_tests() { cellular_birth_publication_is_durable(); cellular_profile_migration_is_durable_and_recovers_without_a_tick(); cellular_mutation_publication_binds_results(); cellular_host_admits_mutation_choices(); cellular_bud_publishes_and_recovers(); #ifdef EVO_POSTGRES_M10 cellular_write_behind_commits_chain_and_recover(); #endif cellular_balance_region_founds_and_recovers({{9771, 1}, CellularLivesProfile::balance, evo::biology::primitive_founder_v2, cellular_lives_balance_rules, cellular_v7_versions, 0xDC, 0xA7, 0x85}); cellular_balance_region_founds_and_recovers({{9772, 1}, CellularLivesProfile::reproduction, evo::biology::primitive_founder_v3, cellular_lives_reproduction_rules, cellular_v8_versions, 0xDE, 0xB3, 0x87}); cellular_death_is_final_and_account_restarts(); auto owner = connect_as(env("PGUSER")); const auto build = filled<32>(0xD9); CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " "(decode(repeat('d9',32),'hex')) ON CONFLICT DO NOTHING", {}, 5s)); constexpr RegionKey empty_key{9757, 1}; auto empty_nursery = PrimitiveLives::create({empty_key.world, empty_key.region, 1, 17, {}, {{0, 0}}}); CHECK(empty_nursery); auto empty_habitat = evo::biology::CellularHabitat::create( {empty_key.world, empty_key.region, 1, 1'000, 1'000, {{{0, 0}, 19, {{12'000}, {{{10}, {20}, {30}, {40}}}}}}}); CHECK(empty_habitat); auto empty_opening = CellularLives::create(**empty_nursery, std::move(*empty_habitat), {{1'000, 1'000}, 0, 293'150}); CHECK(empty_opening && (*empty_opening)->lives().empty()); auto empty_objects = FilesystemObjectStore::open(env("PGHOST"), empty_key, max_cellular_lives_bytes); CHECK(empty_objects); const auto empty_commit = filled<16>(0x20); auto provisioned = provision_cellular_region(*owner, **empty_objects, empty_key, 1, **empty_opening, empty_commit, build, 5s); CHECK(provisioned && provisioned->head.sequence == 0 && provisioned->head.end_tick == 0); auto empty_manifest = decode_manifest(provisioned->manifest); CHECK(empty_manifest && empty_manifest->profile == CheckpointProfile::cellular_lives_v1 && empty_manifest->cellular_versions == cellular_v2_versions && empty_manifest->payload_bytes == (*empty_opening)->snapshot().size()); auto genesis_payload = (*empty_objects)->get({empty_manifest->payload_sha256, empty_manifest->payload_bytes}); CHECK(genesis_payload); auto restored_genesis = restore_cellular_payload(*genesis_payload, *empty_manifest); CHECK(restored_genesis && (*restored_genesis)->lives().empty() && (*restored_genesis)->nursery() == (*empty_opening)->nursery() && (*restored_genesis)->habitat().snapshot() == (*empty_opening)->habitat().snapshot()); auto exact_retry = provision_cellular_region(*owner, **empty_objects, empty_key, 1, **empty_opening, empty_commit, build, 5s); CHECK(exact_retry && exact_retry->manifest == provisioned->manifest); CHECK(!provision_cellular_region(*owner, **empty_objects, empty_key, 1, **empty_opening, filled<16>(0x22), build, 5s)); constexpr RegionKey key{9756, 1}; auto endowment = evo::biology::primitive_endowment(); CHECK(endowment); auto funding = endowment->body; funding.energy.value = endowment->reserve.energy.value + endowment->construction.value; auto primitive = PrimitiveLives::create({key.world, key.region, 1, 17, funding, {{0, 0}}}); CHECK(primitive); auto habitat = evo::biology::CellularHabitat::create({key.world, key.region, 1, 1'000, 1'000, {}}); CHECK(habitat); auto opening = CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 0, 293'150}); CHECK(opening && (*opening)->lives().empty()); const auto payload = (*opening)->snapshot(); const auto payload_digest = sha256(payload); CHECK(payload_digest); auto genesis = genesis_manifest(key, 1, filled<16>(0x21), 50'000, build, payload.size(), *payload_digest, CheckpointProfile::cellular_lives_v1); CHECK(genesis); genesis->cellular_versions = cellular_v2_versions; const auto genesis_bytes = encode_manifest(*genesis); CHECK(genesis_bytes); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects && (*objects)->put(payload)); CHECK(owner->query("SELECT evolution.provision_region_checkpoint($1::bytea)", std::array{hex(*genesis_bytes)}, 5s)); CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9756,1000) " "ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), {}, env("PGPORT"), env("PGDATABASE"), env("EVO_PG_RUNTIME_USER"), {}, {}}, 5s); }; // A fresh value per host: copying the config trips a GCC 14 -O3 array-bounds false positive. const auto config = [&] { return CellularHostConfig{key, 1, {}, build, {build}}; }; auto made_host = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made_host); auto host = std::move(*made_host); CHECK(host->step().ready); const auto authority = host->authority(); CHECK(authority); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); const auto account = filled<16>(0x43); const auto control = claim_account_control(*runtime, key, checked_value(authority), account, 1, 1, 20'000ms, 5s); CHECK(control); const auto requested = host->create_primitive_life(account, control->generation, 7); CHECK(requested.result == evo::network::PrimitiveLifeResult::pending && requested.life_identity != 0 && host->queued_births().size() == 1); const auto committed = host->committed(); CHECK(committed); const auto& committed_value = checked_value(committed); CellularBatch batch; const auto predecessor_digest = sha256(committed_value.manifest); CHECK(predecessor_digest); batch.header = { key.world, key.region, 1, committed_value.head.commit, checked_value(predecessor_digest), 0, 1}; batch.ticks.resize(1); batch.ticks.front().births.push_back(host->queued_births().front()); const auto birth_replay = replay_cellular_batch(*host->state(), batch); CHECK(birth_replay); const auto birth_publication = host->publish(batch); CHECK(birth_publication && birth_publication->committed.head.sequence == 1 && birth_publication->committed.head.end_tick == 1 && host->state()->snapshot() == (**birth_replay).snapshot()); const auto action_predecessor = host->committed(); CHECK(action_predecessor); const auto& action_predecessor_value = checked_value(action_predecessor); const auto action_predecessor_digest = sha256(action_predecessor_value.manifest); CHECK(action_predecessor_digest); batch = {}; batch.header = {key.world, key.region, 1, action_predecessor_value.head.commit, checked_value(action_predecessor_digest), 1, 2}; batch.ticks.resize(1); batch.ticks.front().lives.push_back({requested.life_identity, {}}); CellularActionRecord action; action.account = account; action.action_id = 77; action.input[0] = 2; // Tick 2, neutral movement, no patch target. const std::array actions{action}; const auto replay = replay_cellular_batch(*host->state(), batch); CHECK(replay); auto published = host->publish(batch, actions); CHECK(published && published->committed.head.sequence == 2 && published->committed.head.end_tick == 2 && host->state()->snapshot() == (**replay).snapshot()); CHECK(host->take_finalized_actions() == std::vector{{action, 2}}); host->drain(); host.reset(); auto restarted_objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(restarted_objects); auto made_restarted = CellularRegionHost::create(config(), connect, std::move(*restarted_objects)); CHECK(made_restarted); auto restarted = std::move(*made_restarted); CHECK(restarted->step().ready); const auto restarted_committed = restarted->committed(); CHECK(restarted_committed); const auto& restarted_committed_value = checked_value(restarted_committed); CHECK(restarted->state()->tick() == 2 && restarted->state()->snapshot() == (**replay).snapshot() && restarted_committed_value.head.sequence == 2); restarted->drain(); }