#include "evo/server/lifecycle/cellular_environment.hpp" #include "fixtures/cellular_ecology.hpp" #include #include #include namespace { using namespace evo; using namespace evo::server; using namespace evo::fixture; using Environment = std::unique_ptr; std::vector controlled(const CellularLives& state, bool bud = false) { std::vector 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::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 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'; } // A full habitat refuses new deposits: bubbles are counted skipped, never deferred. void capacity() { auto value = environment(founders(), config({source(1, 0, 1, energy_and_carbon(1ULL << 40, 1ULL << 40))})); for (unsigned tick = 0; tick < 1'000 && value->state().habitat().patches().size() < biology::max_cellular_patches; ++tick) step(*value); require(value->state().habitat().patches().size() == biology::max_cellular_patches, "every-tick infall did not reach the deposit limit"); const auto before = value->imported(); const auto report = checked(value->advance_tick(controlled(value->state())), "full tick"); require(report.events == 1 && report.skipped_bubbles > 0 && report.credited_bubbles + report.skipped_bubbles >= cellular_infall_trial_bubbles_min && value->state().habitat().patches().size() <= biology::max_cellular_patches, "full habitat accepted or lost infall bubbles"); require(report.credited_bubbles > 0 || value->imported() == before, "skipped bubbles were imported"); audit(*value); } // Unattended joint intervals: recording equals live joint ticks, encoding is canonical, // replay re-derives every flow and refuses tampered evidence. CellularBatchHeader header(const CellularEnvironment& value, std::uint64_t ticks) { CellularBatchHeader made{ value.state().world(), value.state().region(), value.state().frame(), {}, {}, value.tick(), value.tick() + ticks}; made.predecessor.fill(7); made.predecessor_digest.fill(9); return made; } std::vector frozen(const CellularLives& state) { auto inputs = controlled(state); for (auto& input : inputs) input.intent.frozen = true; return inputs; } // Budding founders until real wildlife exists; returns its genome (zero if none). std::uint64_t first_wildlife(CellularEnvironment& value) { for (unsigned tick = 0; tick < 30'000; ++tick) { step(value, true); for (const auto& life : value.state().lives()) if (life.account == LifeAccount{}) return life.identity.genome; } return 0; } void traces() { // A closed probe finds when wildlife first exists; the traced source starts after it, // so infall neither changes that history nor fills the habitat beforehand. auto probe = environment(founders(), config()); const auto genome = first_wildlife(*probe); require(genome != 0, "no wildlife for joint traces"); auto value = environment( founders(), config({source(1, 0, 15, energy_and_carbon(1ULL << 40, 1ULL << 40), probe->tick() + 1)}, 13)); require(first_wildlife(*value) == genome && value->tick() == probe->tick(), "a not-yet-active source changed the region's history"); require(!prepare_environment_interval(*value, header(*value, 8)), "active controlled cells entered an unattended interval"); for (unsigned tick = 0; tick < cellular_linger_ticks + 10; ++tick) checked(value->advance_tick(frozen(value->state())), "suspend controlled"); require(population_interval_safe(value->state()), "controlled cells did not suspend"); const auto base = value->snapshot(); auto prepared = checked(prepare_environment_interval(*value, header(*value, 64)), "record"); require(value->snapshot() == base, "recording changed its source"); auto live = copy(*value); for (std::uint64_t tick = 0; tick < 64; ++tick) checked(live->advance_tick(frozen(live->state())), "live joint tick"); require(live->snapshot() == prepared.state->snapshot(), "recorded interval differs from live joint ticks"); const auto bytes = checked(encode_environment_batch(prepared.batch), "encode"); const auto decoded = checked(decode_environment_batch(bytes), "decode"); require(decoded == prepared.batch, "batch round trip changed evidence"); const auto replayed = checked(replay_environment_batch(*value, decoded), "replay"); require(replayed->snapshot() == prepared.state->snapshot(), "replay diverged"); Inventory crossed{}; std::uint64_t radiated = 0; for (const auto& flow : prepared.batch.flows) { crossed.energy.value += flow.imported.energy.value; crossed.matter[0].value += flow.imported.matter[0].value; radiated += flow.exported.value; } require(crossed.energy.value + value->imported().energy.value == prepared.state->imported().energy.value && radiated + value->exported().value == prepared.state->exported().value && crossed != Inventory{} && radiated > 0, "flows are not the interval's complete crossing"); auto forged = decoded; forged.flows[3].exported.value += 1; require(replay_environment_batch(*value, forged).error() == CellularEnvironmentError::conservation, "forged radiation accepted"); forged = decoded; forged.population.boundaries[5].sequence += 1; require(!replay_environment_batch(*value, forged), "forged population boundary accepted"); forged = decoded; forged.flows.pop_back(); require(!encode_environment_batch(forged) && !replay_environment_batch(*value, forged), "missing flow accepted"); require(replay_environment_batch(*prepared.state, decoded).error() == CellularEnvironmentError::identity, "batch replayed from the wrong cut"); auto truncated = bytes; truncated.pop_back(); require(!decode_environment_batch(truncated), "truncated batch accepted"); auto future = bytes; future[8] = 2; require(decode_environment_batch(future).error() == CellularEnvironmentError::unsupported, "future batch accepted"); // Whole-group conversion, then a cohort interval that matches the individual one. auto conversion = checked( prepare_environment_conversion(*prepared.state, header(*prepared.state, 0), {genome, true}), "record conversion"); require(conversion.batch.flows.empty() && conversion.state->population().members().size() > 0 && conversion.state->state().snapshot() == prepared.state->state().snapshot(), "conversion changed biology or crossed the boundary"); const auto converted = checked(replay_environment_batch( *prepared.state, checked(decode_environment_batch(checked( encode_environment_batch(conversion.batch), "c")), "decode conversion")), "replay conversion"); require(converted->snapshot() == conversion.state->snapshot(), "conversion replay diverged"); auto individual = checked(prepare_environment_interval(*prepared.state, header(*prepared.state, 64)), "individual interval"); auto cohort = checked(prepare_environment_interval(*conversion.state, header(*conversion.state, 64)), "cohort interval"); require(cohort.state->state().snapshot() == individual.state->state().snapshot() && cohort.batch.flows == individual.batch.flows && cohort.batch.population.biology == individual.batch.population.biology, "cohort interval changed biology or environmental flows"); std::cout << "traces: " << bytes.size() << " bytes for 64 ticks, imported " << crossed.energy.value << " pJ, radiated " << radiated << " pJ, cohort " << conversion.state->population().members().size() << " members\n"; } std::vector resealed(std::vector 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(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& bytes) { std::ofstream out(path, std::ios::binary); out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); require(out.good(), "write failed"); } std::vector read(const char* path) { std::ifstream in(path, std::ios::binary); return {std::istreambuf_iterator(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(); capacity(); traces(); 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; } }