#include "evo/core/random.hpp" #include "evo/processes/environmental_community.hpp" #include "evo/processes/environmental_schedule.hpp" #include #include #include #include #include #include #include #include namespace { using namespace evo::world; using namespace evo::processes; constexpr auto maximum = std::numeric_limits::max(); void check(bool ok, std::source_location at = std::source_location::current()) { if (!ok) throw std::runtime_error("environment qualification line " + std::to_string(at.line())); } #define CHECK(...) check(static_cast(__VA_ARGS__)) constexpr WorldIdentity identity{7, 9}; EnvironmentalConfig config() { EnvironmentalConfig c; c.world = 7; c.frame = 9; c.producer = 1; c.consumer = 2; c.source = 3; c.tick_microseconds = 50000; c.area_um2 = 1; c.irradiance_numerator = 11; c.irradiance_denominator = 3; c.efficiency = 600; c.growth_numerator = 3; c.growth_denominator = 2; c.growth_cost = 1; c.recipe = {1, 2, 1, 1, 1}; c.intake.fill(100); c.assimilation = 600; c.producer_min_mK = c.consumer_min_mK = 270000; c.producer_max_mK = c.consumer_max_mK = 310000; return c; } struct Opening { std::array environment{1000000, 1000000, 1000000, 2000000, 0, 0, 1000000, 0, 10000000, 0}, producer{}, consumer{}; std::uint64_t producer_capacity{100000000}, consumer_capacity{100000000}; }; std::unique_ptr resources(Opening o = {}) { const FieldSite site{{0, 0, -16000}, {{0}, {0}, {0}, {10}, {20}, {3}}, {1}}; std::array opening{}; for (std::size_t k = 0; k < 10; ++k) opening[k] = {static_cast(k), {&o.environment[k], 1}}; const FieldDefaults defaults{{evo::accounting::Femtograms{0}, evo::accounting::Femtograms{maximum}, evo::accounting::Femtograms{0}}}; auto f = FieldStore::create(identity, 1, defaults, {&site, 1}, opening, 2000000); CHECK(f); auto t = ChunkStore::create({}, 1, 2000000, {{VolumeUnits{100}, VolumeUnits{100}}}); CHECK(t); CHECK((*t)->load({0, 0, -1000})); std::array accounts{}; accounts[0].id = {1}; accounts[1].id = {2}; accounts[0].balances = o.producer; accounts[1].balances = o.consumer; accounts[0].capacities.fill(o.producer_capacity); accounts[1].capacities.fill(o.consumer_capacity); auto r = EnvironmentalTransfers::create(identity, std::move(*f), std::move(*t), accounts, 4000000); CHECK(r); return std::move(*r); } auto make(EnvironmentalConfig c = config(), Opening opening = {}) { auto o = EnvironmentalCommunity::create(c, resources(opening), 8000000); CHECK(o); return std::move(*o); } WorldBytes bytes(const EnvironmentalCommunity& o) { auto b = o.snapshot(); CHECK(b); return std::move(*b); } evo::accounting::Inventory audit(const EnvironmentalCommunity& o) { evo::accounting::Inventory sum{}; constexpr std::array map{3, 1, 2, 0, 1, 2, 3}; for (std::size_t k = 0; k < 10; ++k) { auto& v = k < 7 ? sum.matter[map[k]].value : sum.energy.value; auto field = o.resources().fields().read(0, static_cast(k)); CHECK(field); CHECK(*field <= maximum - v); v += *field; for (const auto& a : o.resources().organisms()) { CHECK(a.balances[k] <= maximum - v); v += a.balances[k]; } } return sum; } void put(WorldBytes& b, std::size_t at, std::uint64_t value) { CHECK(at + 8 <= b.size()); for (unsigned i = 0; i < 8; ++i) b[at + i] = static_cast((value >> (8U * i)) & 255U); } std::uint64_t hash(std::span b) { std::uint64_t h = 14695981039346656037ULL; for (auto x : b) h = (h ^ x) * 1099511628211ULL; return h; } void seal(WorldBytes& b) { put(b, b.size() - 8, hash(std::span{b}.first(b.size() - 8))); } void refusals() { for (unsigned which = 0; which < 15; ++which) { auto c = config(); switch (which) { case 0: c.rules = 4; // Unknown: 2 is the M6.6 terminal/decay extension, 3 per second. break; case 1: c.world = 8; break; case 2: c.source = 0; break; case 3: c.tick_microseconds = 0; break; case 4: c.area_um2 = 0; break; case 5: c.irradiance_denominator = 0; break; case 6: c.efficiency = 1001; break; case 7: c.assimilation = 1001; break; case 8: c.growth_denominator = 0; break; case 9: c.growth_cost = 0; break; case 10: c.recipe[2] = 0; break; case 11: c.producer_min_mK = c.producer_max_mK + 1; break; case 12: c.consumer_min_mK = 0; break; case 13: c.producer = 2; break; default: c.area_um2 = 2; c.irradiance_numerator = maximum; break; } CHECK(!EnvironmentalCommunity::create(c, resources(), 8000000)); } auto r = resources(); const auto voxel = r->fields().sites()[0].voxel; auto v = query_environment(r->fields(), r->terrain(), 1, {&voxel, 1}, all_environment_fields); CHECK(v); const EnvironmentalLeg leg{voxel, {1}, Field::water, ResourceDirection::to_organism, 1}; CHECK(r->commit({1, 1, {&leg, 1}}, *v, 1)); CHECK(!EnvironmentalCommunity::create(config(), std::move(r), 8000000)); // Capture is staged before feeding; a late capacity failure must undo it as well. Opening opening; opening.producer[3] = 10; opening.producer[7] = 10; opening.consumer[7] = 1; opening.consumer_capacity = 1; auto o = make(config(), opening); const auto before = bytes(*o); auto failed = o->advance(1, {290000, 1, {1, 0, 0, 0, 2}}); CHECK(!failed && failed.error() == CommunityError::capacity); CHECK(bytes(*o) == before); CHECK(o->advance(1, {290000, 1, {1, 0, 0, 0, 0}})); opening = {}; opening.producer_capacity = 0; o = make(config(), opening); const auto empty = bytes(*o); CHECK(!o->advance(1, {290000, 1, {}})); CHECK(bytes(*o) == empty); // Scalar arithmetic boundaries: first interval succeeds; carried numerator then overflows. for (bool capture : {false, true}) { auto c = config(); c.growth_numerator = 0; Opening large; large.environment = {}; if (capture) { c.irradiance_numerator = maximum; c.irradiance_denominator = 2; c.efficiency = 0; large.environment[8] = maximum; } else { c.growth_numerator = maximum; c.growth_denominator = 2; } auto x = make(c, large); CHECK(x->advance(1, {290000, capture ? 1ULL : 0ULL, {}})); auto b = bytes(*x); auto bad = x->advance(2, {290000, capture ? 1ULL : 0ULL, {}}); CHECK(!bad && bad.error() == CommunityError::overflow); CHECK(bytes(*x) == b); } } void limits() { // Each recipe channel independently limits growth to zero; none can substitute for it. constexpr std::array source{0, 3, 1, 2, 6}; for (auto missing : source) { Opening opening; opening.environment[missing] = 0; opening.producer[7] = 100; auto o = make(config(), opening); auto report = o->advance(1, {290000, 0, {}}); CHECK(report && report->grown == 0 && report->unmet == 1); CHECK(o->resources().organisms()[0].balances[7] == 100); } for (auto efficiency : {std::uint64_t{0}, std::uint64_t{1000}}) { auto c = config(); c.efficiency = efficiency; c.assimilation = efficiency; c.growth_numerator = 0; Opening opening; opening.producer[3] = 10; opening.producer[0] = 1; auto o = make(c, opening); const auto total = audit(*o); auto report = o->advance(1, {290000, 1, {10, 0, 0, 0, 0}}); CHECK(report); CHECK(report->retained == (efficiency == 0 ? 0 : 3)); CHECK(report->assimilated[0] == (efficiency == 0 ? 0 : 10)); CHECK(audit(*o) == total); CHECK(!report->terminal_transition && o->resources().organisms()[0].balances[0] == 1); } // Consumer temperature gates reject entire ticks, including otherwise legal capture. Opening opening; opening.producer[3] = 10; auto c = config(); c.consumer_min_mK = 280000; c.consumer_max_mK = 300000; auto o = make(c, opening); auto before = bytes(*o); CHECK(!o->advance(1, {279999, 1, {1, 0, 0, 0, 0}})); CHECK(bytes(*o) == before); CHECK(o->advance(1, {280000, 1, {1, 0, 0, 0, 0}})); CHECK(o->advance(2, {300000, 1, {1, 0, 0, 0, 0}})); before = bytes(*o); CHECK(!o->advance(3, {300001, 1, {1, 0, 0, 0, 0}})); CHECK(bytes(*o) == before); } void malformed() { auto o = make(); CHECK(o->advance(1, {290000, 1, {}})); const auto b = bytes(*o); // Explicit documented u64 offsets: current progress, anchor, history input and report. const std::array, 13> invalid{{{8, 2}, {16, 1}, {256 + 8, 3}, {256 + 16, 2}, {256 + 24, 1000}, {256 + 32, 2}, {256 + 40, 2}, {304 + 30 * 8 + 40, 1}, {592, 65}, {600, 0}, {608, 2}, {656, 2}, {656 + 6 * 8, 3}}}; for (const auto& [offset, value] : invalid) { auto bad = b; put(bad, offset, value); seal(bad); CHECK(!EnvironmentalCommunity::restore(bad, identity, 8000000)); } auto trailing = b; trailing.push_back(0); put(trailing, 16, trailing.size()); seal(trailing); CHECK(!EnvironmentalCommunity::restore(trailing, identity, 8000000)); evo::Random rng{123456}; std::uint64_t accepted{}; for (unsigned i = 0; i < 512; ++i) { auto bad = b; const auto offset = static_cast(rng.next() % (bad.size() - 8)); bad[offset] ^= static_cast(1U << (rng.next() % 8)); seal(bad); auto restored = EnvironmentalCommunity::restore(bad, identity, 8000000); if (restored) { ++accepted; CHECK(bytes(**restored) == bad); } } std::printf("mutations=512 valid_alternative_states=%llu\n", static_cast(accepted)); CHECK(bytes(*o) == b); } void exhausted_tick() { // A valid no-op trace shifted to the final u64 window; no rules depend on wall time. auto c = config(); c.growth_numerator = 0; auto o = make(c); const EnvironmentalInput input{290000, 0, {}}; for (std::uint64_t t = 1; t <= 64; ++t) CHECK(o->advance(t, input)); auto b = bytes(*o); put(b, 256, maximum); // current progress tick put(b, 304 + 30 * 8, maximum - 64); // audit anchor tick for (std::uint64_t i = 0; i < 64; ++i) put(b, static_cast(600 + i * 200 + 56), maximum - 63 + i); const std::size_t nested_at = 600 + 64 * 200 + 8; WorldBytes nested(b.begin() + static_cast(nested_at), b.end() - 8); put(nested, 32, maximum); // resource adoption watermark auto read32 = [&](std::size_t at) { std::uint64_t v{}; for (unsigned i = 0; i < 4; ++i) v |= std::uint64_t{nested[at + i]} << (8U * i); return static_cast(v); }; const auto field_at = 56 + read32(48), field_length = read32(52); WorldBytes fields(nested.begin() + static_cast(field_at), nested.begin() + static_cast(field_at + field_length)); put(fields, 48, maximum); seal(fields); std::copy(fields.begin(), fields.end(), nested.begin() + static_cast(field_at)); seal(nested); std::copy(nested.begin(), nested.end(), b.begin() + static_cast(nested_at)); seal(b); auto restored = EnvironmentalCommunity::restore(b, identity, 8000000); CHECK(restored); CHECK(bytes(**restored) == b); CHECK((*restored)->advance(maximum, input)); // exact retry remains legal CHECK(!(*restored)->advance(0, input)); // cannot wrap CHECK(!(*restored)->advance(maximum - 64, input)); // outside retained window auto pause = schedule_environment(**restored, {identity, maximum, maximum, 50000, {}}); CHECK(pause && !pause->failure && pause->committed == 0 && pause->last_tick == maximum); auto wrap = schedule_environment(**restored, {identity, maximum, 0, 50000, {&input, 1}}); CHECK(!wrap && wrap.error() == EnvironmentalIntervalError::range); CHECK(bytes(**restored) == b); } void sequences(std::uint64_t ticks) { std::uint64_t capture{}, growth{}, bites{}, fingerprint{}; const auto start = std::chrono::steady_clock::now(); for (std::uint64_t seed = 0; seed < 16; ++seed) { auto c = config(); c.assimilation = (seed % 3) * 500; auto o = make(c); auto continuous = make(c); const auto total = audit(*o); const auto resident = o->resources().accounted_bytes(); evo::Random rng{seed}; for (std::uint64_t t = 1; t <= ticks; ++t) { const auto draw = rng.next(); EnvironmentalInput in{ draw % 17 == 0 ? 269999ULL : 290000ULL, draw % 5 == 0 ? 0ULL : 1ULL, {}}; if (in.temperature_mK == 290000 && draw % 3 == 0) { for (std::size_t k = 0; k < 4; ++k) in.bite[k] = std::min(std::uint64_t{3}, o->resources().organisms()[0].balances[3 + k]); if (std::ranges::any_of(in.bite, [](auto x) { return x != 0; })) ++bites; } auto report = o->advance(t, in); CHECK(report); CHECK(continuous->advance(t, in) == report); capture += report->captured; growth += report->grown; CHECK(audit(*o) == total); CHECK(o->resources().accounted_bytes() == resident); if (t % 997 == 0 || t == ticks) { const auto b = bytes(*o); CHECK(bytes(*continuous) == b); auto restored = EnvironmentalCommunity::restore(b, identity, 8000000); CHECK(restored); CHECK((*restored)->advance(t, in) == report); auto changed = in; changed.source_enabled ^= 1; CHECK(!(*restored)->advance(t, changed)); CHECK(bytes(**restored) == b); o = std::move(*restored); } } fingerprint ^= hash(bytes(*o)); } CHECK(capture > 0 && growth > 0 && bites > 0); const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); std::printf("seeds=16 ticks_per_seed=%llu paired_steps=%llu captured=%llu grown=%llu " "bites=%llu fingerprint=%016llx validation_seconds=%.6f\n", static_cast(ticks), 32ULL * static_cast(ticks), static_cast(capture), static_cast(growth), static_cast(bites), static_cast(fingerprint), elapsed); } struct Slice { EnvironmentalConfig parameters{config()}; Opening opening{}; std::array inputs{}; std::uint64_t consumer_death{}, producer_death{}; }; Slice slice(std::uint64_t seed, unsigned regime) { evo::Random rng{seed}; Slice s; s.parameters.rules = 2; s.parameters.assimilation = 1000; s.parameters.decay.fill(regime == 4 ? 0 : 1); const auto nutrients = 4 + rng.next() % 4; s.opening.environment = {200, regime == 2 ? 0 : nutrients, nutrients, 400, 0, 0, 200, 0, 2000, 0}; s.consumer_death = 32 + rng.next() % 5; s.producer_death = 96 + rng.next() % 7; for (std::size_t i = 0; i < s.inputs.size(); ++i) { const auto tick = i + 1; const auto draw = rng.next(); auto& in = s.inputs[i]; in.temperature_mK = regime == 3 || (tick > 40 && draw % 11 == 0) ? 260000 : 290000; in.source_enabled = regime == 1 || (tick > 40 && draw % 5 == 0) ? 0 : 1; if (tick == 16 && (regime == 0 || regime == 4)) in.bite = {2, 2, 2, 2, 1}; if (tick == s.consumer_death) in.terminal[1] = 1; if (tick == s.producer_death) in.terminal[0] = 1; } return s; } void slice_audit(const EnvironmentalCommunity& o, const evo::accounting::Inventory& total, const Slice& s) { CHECK(audit(o) == total); const auto water = o.resources().fields().read(0, Field::water); if (!water) throw std::runtime_error("missing water"); CHECK(*water + o.resources().organisms()[0].balances[0] + o.resources().organisms()[1].balances[0] == s.opening.environment[0]); const auto p = o.progress(); CHECK(p.source_remainder < s.parameters.irradiance_denominator); CHECK(p.growth_remainder < s.parameters.growth_denominator); CHECK(p.efficiency_remainder < 1000 && p.last_funded <= p.tick); } void integrated(std::uint64_t episodes) { const auto start = std::chrono::steady_clock::now(); for (unsigned regime = 0; regime < 5; ++regime) { std::uint64_t captured{}, grown{}, assimilated_n{}, returned_n{}, regrown{}, fingerprint{}; for (std::uint64_t seed = 0; seed < 16; ++seed) for (std::uint64_t episode = 0; episode < episodes; ++episode) { const auto stream = seed + 16 * episode; const auto s = slice(stream, regime); auto reference = make(s.parameters, s.opening); auto scheduled = make(s.parameters, s.opening); const auto total = audit(*reference); const auto resident = reference->resources().accounted_bytes(); std::array reports{}; std::uint64_t episode_growth{}, episode_regrowth{}, episode_capture{}; for (std::size_t i = 0; i < s.inputs.size(); ++i) { auto r = reference->advance(i + 1, s.inputs[i]); CHECK(r); reports[i] = *r; slice_audit(*reference, total, s); episode_growth += r->grown; episode_capture += r->captured; captured += r->captured; grown += r->grown; assimilated_n += r->assimilated[1]; returned_n += r->decomposed[4]; if (r->tick > s.consumer_death && r->tick < s.producer_death) episode_regrowth += r->grown; if (r->tick == s.consumer_death) { CHECK(r->grown == 0 && r->consumer_transition == 1); if (regime == 0) CHECK(reference->resources().organisms()[1].balances[4] == 1); } if (r->tick >= s.producer_death) CHECK(r->grown == 0 && r->captured == 0); } if (regime == 0) { CHECK(episode_regrowth == 2 && reports[15].assimilated[1] == 2); CHECK(episode_growth == s.opening.environment[1] + 2); } else { CHECK(episode_regrowth == 0); if (regime == 4) CHECK(episode_growth == s.opening.environment[1]); else CHECK(episode_growth == 0); if (regime == 1 || regime == 3) CHECK(episode_capture == 0); } regrown += episode_regrowth; evo::Random batches{stream ^ 0xabcdefULL}; for (std::size_t begin = 0; begin < s.inputs.size();) { auto end = std::min(s.inputs.size(), begin + 1 + static_cast(batches.next() % 16)); // Force checkpoint boundaries around terminal events and history eviction. for (auto cut : {s.consumer_death - 1, s.consumer_death, s.consumer_death + 1, std::uint64_t{64}, s.producer_death - 1, s.producer_death}) if (cut > begin && cut < end) end = static_cast(cut); auto r = schedule_environment( *scheduled, {identity, begin, end, 50000, std::span{s.inputs}.subspan(begin, end - begin)}); CHECK(r && !r->failure && r->committed == end - begin); for (std::size_t j = 0; j < r->committed; ++j) CHECK(r->reports[j] == reports[begin + j]); slice_audit(*scheduled, total, s); CHECK(scheduled->resources().accounted_bytes() == resident); auto b = bytes(*scheduled); auto restored = EnvironmentalCommunity::restore(b, identity, 8000000); CHECK(restored); CHECK(bytes(**restored) == b); CHECK((*restored)->advance(end, s.inputs[end - 1]) == reports[end - 1]); CHECK(bytes(**restored) == b); scheduled = std::move(*restored); begin = end; } CHECK(bytes(*scheduled) == bytes(*reference)); fingerprint = (fingerprint ^ hash(bytes(*reference))) * 1099511628211ULL; } std::printf( "slice regime=%u episodes=%llu ticks=%llu capture=%llu growth=%llu " "assimilated_N=%llu returned_N=%llu regrowth=%llu hash=%016llx\n", regime, 16ULL * static_cast(episodes), 16ULL * 128ULL * static_cast(episodes), static_cast(captured), static_cast(grown), static_cast(assimilated_n), static_cast(returned_n), static_cast(regrown), static_cast(fingerprint)); } std::printf("slice_validation_seconds=%.6f\n", std::chrono::duration(std::chrono::steady_clock::now() - start).count()); } void integrated_cost() { for (unsigned sample = 0; sample < 3; ++sample) { double steps{}, snapshot_ms{}, restore_ms{}; std::size_t snapshot_bytes{}, resource_bytes{}; for (std::uint64_t seed = 0; seed < 100; ++seed) { const auto s = slice(seed, 0); auto o = make(s.parameters, s.opening); auto start = std::chrono::steady_clock::now(); for (std::size_t begin = 0; begin < 128; begin += 64) { auto r = schedule_environment(*o, {identity, begin, begin + 64, 50000, std::span{s.inputs}.subspan(begin, 64)}); CHECK(r && !r->failure && r->committed == 64); } steps += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); start = std::chrono::steady_clock::now(); auto b = bytes(*o); snapshot_ms += std::chrono::duration(std::chrono::steady_clock::now() - start) .count(); start = std::chrono::steady_clock::now(); auto restored = EnvironmentalCommunity::restore(b, identity, 8000000); CHECK(restored); restore_ms += std::chrono::duration(std::chrono::steady_clock::now() - start) .count(); CHECK(bytes(**restored) == b); snapshot_bytes = b.size(); resource_bytes = o->resources().accounted_bytes(); } std::printf("slice_cost sample=%u ticks=12800 seconds=%.6f snapshot_mean_ms=%.6f " "restore_mean_ms=%.6f snapshot_bytes=%zu resource_bytes=%zu owner_bytes=%zu " "interval_result_bytes=%zu\n", sample, steps, snapshot_ms / 100, restore_ms / 100, snapshot_bytes, resource_bytes, sizeof(EnvironmentalCommunity), sizeof(EnvironmentalIntervalResult)); } } void cost() { std::array times{}; for (auto& seconds : times) { auto o = make(); const auto start = std::chrono::steady_clock::now(); for (std::uint64_t t = 1; t <= 100000; ++t) CHECK(o->advance(t, {290000, 1, {}})); seconds = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); auto b = bytes(*o); const auto restore_start = std::chrono::steady_clock::now(); auto restored = EnvironmentalCommunity::restore(b, identity, 8000000); CHECK(restored); const auto restore_ms = std::chrono::duration( std::chrono::steady_clock::now() - restore_start) .count(); std::printf("step_sample_seconds=%.6f resource_bytes=%zu process_bytes=%zu " "snapshot_bytes=%zu restore_ms=%.6f\n", seconds, o->resources().accounted_bytes(), sizeof(EnvironmentalCommunity), b.size(), restore_ms); } std::ranges::sort(times); std::printf("median_100000_steps_seconds=%.6f\n", times[1]); } } // namespace int main(int argc, char** argv) { try { if (argc > 2 || (argc == 2 && std::string_view{argv[1]} != "--long")) return 2; refusals(); limits(); malformed(); exhausted_tick(); sequences(argc == 2 ? 65536 : 4096); integrated(argc == 2 ? 64 : 1); if (argc == 2) { cost(); integrated_cost(); } return 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); return 1; } catch (...) { return 1; } }