#include "evo/core/random.hpp" #include "evo/processes/environmental_community.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 = 3; // Rules 2 are the M6.6 terminal/decay extension. 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 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), static_cast(32 * ticks), static_cast(capture), static_cast(growth), static_cast(bites), static_cast(fingerprint), elapsed); } 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); if (argc == 2) cost(); return 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); return 1; } catch (...) { return 1; } }