From 6fd553c84b90554fd7de34a1098cc827015b988d Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 27 Sep 2026 13:57:01 -0400 Subject: [PATCH] Qualify M6.5 environmental fixture with boundary and long-run tests --- CMakeLists.txt | 5 + README.md | 5 + docs/ROADMAP.md | 5 + docs/STATUS.md | 16 +- .../0055-environmental-process-contract.md | 5 + docs/biology/ENVIRONMENTAL_PROCESS.md | 6 +- .../ENVIRONMENTAL_QUALIFICATION.md | 88 ++++ docs/engineering/VALIDATION.md | 26 ++ tests/environmental_qualification.cpp | 441 ++++++++++++++++++ 9 files changed, 595 insertions(+), 2 deletions(-) create mode 100644 docs/engineering/ENVIRONMENTAL_QUALIFICATION.md create mode 100644 tests/environmental_qualification.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 84dbdb7..9f4978e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,6 +72,11 @@ evo_owned_target(evo-sim) include(CTest) if(BUILD_TESTING) + add_executable(evo-environmental-qualification tests/environmental_qualification.cpp) + target_link_libraries(evo-environmental-qualification PRIVATE evo::processes) + evo_owned_target(evo-environmental-qualification) + add_test(NAME environmental-qualification COMMAND evo-environmental-qualification) + set_tests_properties(environmental-qualification PROPERTIES TIMEOUT 120) add_executable(evo-environmental-community-tests tests/environmental_community_tests.cpp) target_link_libraries(evo-environmental-community-tests PRIVATE evo::processes) evo_owned_target(evo-environmental-community-tests) diff --git a/README.md b/README.md index 8566714..9ebb47b 100644 --- a/README.md +++ b/README.md @@ -150,3 +150,8 @@ is next (M6.5); coupled snapshot/recovery remains M6.8. M6.5c: [persisted producer/consumer fixture](docs/biology/ENVIRONMENTAL_PROCESS.md), with finite source capture, tagged growth/feeding and complete rate/lifecycle snapshots. It is a library/test fixture; existing CLI modes and M2/M3 rules are unchanged. + +For the M6.5 boundary/seeded suite and local cost report, run +`build/release/evo-environmental-qualification --long` (add `.exe` on Windows). +See [environmental qualification](docs/engineering/ENVIRONMENTAL_QUALIFICATION.md) +for parameters, coverage and limitations. The shorter suite runs through CTest. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 1751f85..79ccdaf 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -456,3 +456,8 @@ M6.5c implemented: complete process envelope and atomic environmental fixture. Source rates, residuals, last funded interval, lifecycle and exact retry reports now restore together; retained history is replay-validated against an audit anchor. Next M6.5d: broader boundary/long-run qualification; M6.5 remains open until it passes. + +M6.5d native qualification complete: [report](engineering/ENVIRONMENTAL_QUALIFICATION.md) +records boundary/malformed-state tests, 16-seed paired restore runs, more than a +million logical ticks and cost evidence. M6.5 is implemented and natively qualified; +Linux CI is separately pending verification. Next: M6.6 corpse/decay integration. diff --git a/docs/STATUS.md b/docs/STATUS.md index 969cae0..33c31b9 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -61,7 +61,7 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M6.5d qualify persisted producer/consumer fixture | Broader adversarial bounds, long-run seeds, restored replay and cost evidence | +| 1 | M6.6 return dead biomass to environment | Terminal actors cannot act; bounded, conserved decay with persistent residuals and retry safety | | Research | Improve aggregate fidelity and measure Linux/target-host costs | M4.6 found no qualifying width; see the aggregate budget report | | 2 | Revisit the ADR-0031/0032 reproduction cost model | Reproduction is affordable only at the genome schema's floor; decide whether that is intended before M4 builds cohorts on it | | Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes | @@ -708,3 +708,17 @@ Native validation is recorded separately from Linux CI verification. Next: M6.5d broader qualification (boundary/adversarial cases, long-run seeds and cost evidence). M6.5 as a whole is not yet marked complete; no deployment changed. + +## M6.5d native qualification (2026-09-27) + +M6.5a-d are implemented and qualified natively. Added boundary/malformed-state +coverage and a deterministic long-run/cost harness. The extended run compared +1048576 logical ticks against continuous controls, including 329231 feeding +requests; balances and restored bytes matched. See the +[qualification report](engineering/ENVIRONMENTAL_QUALIFICATION.md) for evidence and +limits. Native Release/analysis/ASan suites passed 54/54; Linux CI remains a separate +required delivery check, not an observed pass. + +Next: M6.6 terminal events, retained corpse biomass and bounded decomposition. +No maintenance, reproduction, player progression, simulation version or deployment +changed in this qualification segment. diff --git a/docs/adr/0055-environmental-process-contract.md b/docs/adr/0055-environmental-process-contract.md index 2113de2..45f3a8d 100644 --- a/docs/adr/0055-environmental-process-contract.md +++ b/docs/adr/0055-environmental-process-contract.md @@ -77,3 +77,8 @@ the private checkpoint validates accounting before nonthrowing publication. The complete envelope includes an audit anchor that permits deterministic replay of the retained process receipts on restore. See schemas/environmental-community.md and the process contract for bounds. M6.5d remains the broader qualification gate. + +M6.5d native qualification completed 2026-09-27; see +[the qualification report](../engineering/ENVIRONMENTAL_QUALIFICATION.md). +No fixture rules changed. Linux CI and deployment performance remain separately +verified gates; this does not claim persistent ecology or live-player readiness. diff --git a/docs/biology/ENVIRONMENTAL_PROCESS.md b/docs/biology/ENVIRONMENTAL_PROCESS.md index b2d3919..3c76f8d 100644 --- a/docs/biology/ENVIRONMENTAL_PROCESS.md +++ b/docs/biology/ENVIRONMENTAL_PROCESS.md @@ -1,7 +1,7 @@ # M6.5 environmental process contract v1 Authority: ADR-0055, ADR-0054, environmental units (ADR-0050), and the scoped -producer/feeding rules (ADRs 0025/0026). **Implemented in M6.5c; broader qualification remains M6.5d.** M6.5b is a +producer/feeding rules (ADRs 0025/0026). **Implemented in M6.5c; natively qualified in M6.5d.** M6.5b is a contract segment. M6.5c implements the runtime and complete buffer codec together. Coefficients below are fixture inputs, not game rules. @@ -214,3 +214,7 @@ compares all reports and final state. The anchor is not spendable. The consumer always active in rules v1 (no consumer-death operation exists); producer terminal state is serialized explicitly. Frame/site, account IDs, source identity and primitive rate config come from the complete envelope, never missing-state defaults. + +M6.5d now provides [native qualification and cost evidence](../engineering/ENVIRONMENTAL_QUALIFICATION.md). +The report distinguishes verified synthetic conservation/replay from ecological +stability, gameplay mortality and deployment capacity. No rules changed in M6.5d. diff --git a/docs/engineering/ENVIRONMENTAL_QUALIFICATION.md b/docs/engineering/ENVIRONMENTAL_QUALIFICATION.md new file mode 100644 index 0000000..75ea727 --- /dev/null +++ b/docs/engineering/ENVIRONMENTAL_QUALIFICATION.md @@ -0,0 +1,88 @@ +# M6.5 environmental qualification and cost report + +Recorded 2026-09-27. Scope: ADR-0055's synthetic, one-site/two-actor fixture. +M6.5a-d are implemented and qualified natively. Linux CI remains an independent +required delivery check; no unobserved CI success is claimed. + +## Reproduce + +```powershell +.\tools\windows-check.ps1 -Preset release -Action check +.\build\release\evo-environmental-qualification.exe --long +``` + +CTest runs 16 seeds with 4096 ticks each; `--long` uses 65536 ticks per seed and +adds three 100000-step timing samples. Linux uses the same executable without +`.exe`. The qualification target is part of ordinary CI tests, with a 120-second +cap. Timing is informational, never a noisy portable pass/fail threshold. + +## Evidence + +| Check | Result | +|---|---| +| Closed energy/C/N/P/other balance | Independent checked sums after every seeded tick | +| Continuous versus restored process | Reports and canonical bytes match; restore every 997 ticks and at run end | +| Source/progress | Disabled/unfunded source, frozen residuals, overflow with carried numerator, no heat recycling (existing contract tests) | +| Limiting resources | Water, C, N, P and organic-other each independently block growth when absent | +| Conversion endpoints | 0/1000 capture and assimilation, retained water cannot become edible biomass | +| Rollback | Late consumer capacity failure undoes prior capture/growth and partial staged bite | +| Input/config admission | Wrong rules/world/IDs, zero source/duration/area/denominators/recipe/cost, invalid efficiencies and temperature limits | +| Temperature | Producer limits in contract suite; consumer inside/outside inclusive endpoints with whole-tick rejection | +| Codec | 13 targeted malformed outer states, trailing bytes, 512 bit mutations with recomputed checksum; accepted alternatives must round-trip canonically | +| Tick exhaustion | Synthesized valid no-op trace ending at u64 max; retry succeeds, wrap/expired input rejects, bytes unchanged | +| Memory | Accounted owned resource bytes remain constant throughout seeded runs | + +The 512 mutations produced 3 valid alternative states. That is not an authentication +failure: the format has a corruption checksum, and cannot distinguish a legitimate +alternative state from someone intentionally rewriting and resealing it. Invalid +states reject; accepted states must satisfy canonical restore/replay validation. +The mutation driver is a bounded fuzz-style smoke test, not a coverage-guided fuzzer. + +Final extended run: + +```text +seeds=16 ticks_per_seed=65536 paired_steps=2097152 +captured=2891204 grown=1479838 bites=329231 +fingerprint=93a9f9b296caac36 validation_seconds=1.132057 +``` + +There are 1048576 logical ticks and an uninterrupted comparison branch for each, +so 2097152 actual advances. Seeded inputs use the repository's explicit SplitMix64 +stream, including source on/off, temperature gates and affordable matter bites. +Assimilation varies across 0, 500 and 1000. Energy bites are separately tested in +the contract/rollback cases. Fingerprint is a diagnostic XOR of final-state hashes, +not an authentication token or replacement for the per-seed byte comparisons. +No new golden or simulation law was changed to obtain these results. + +## Local cost sample + +Windows x64, MSVC 19.44 Release, AMD Ryzen 7 9800X3D, 8 cores / 16 logical CPUs. +Not a controlled benchmark host and not the deployment R730xd. The step sample +uses one producer/consumer fixture, source enabled, fixed eligible temperature, +no feeding, and includes normal retry-window/anchor maintenance. The separate +seeded qualification above includes feeding, repeated audits and restore work. + +| Metric | Observed | +|---|---| +| 100000 steps, three samples | 0.027525 / 0.026734 / 0.026783 seconds | +| Median step batch | 0.026783 seconds | +| Accounted resources | 390216 bytes | +| sizeof process owner (includes retry array and anchor) | 13400 bytes | +| Two reserved 64KiB scratch allowances | 131072 bytes | +| Combined minimum admitted budget | 534688 bytes | +| Final complete snapshot | 30615 bytes | +| Restore including retained-history replay | 0.197700 / 0.240200 / 0.197300 ms | + +Accounted bytes are not RSS: allocator headers, stack beyond documented scratch, +and caller-owned query/output buffers are excluded. Snapshot construction requires +the separate bounded output allowance documented by the schema. Small cache-hot +fixtures do not predict MMO tick capacity, networking cost or ecology-worker scale. +No optimization or performance SLA is justified by this measurement alone. + +## Remaining scope + +M6.6: terminal events with retained corpse resources and bounded decomposition. +M6.7: scheduling intervals/catch-up. M6.8: the full death/nutrient/regrowth slice and +longer ecological/cost analysis. This gate does not prove ecological stability, +starvation mortality, player logout fairness, crash-safe publication or host-loss +recovery. M2/M3 maintenance and reproduction rules remain unchanged. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 7807f85..f97e751 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1891,3 +1891,29 @@ Executed native analysis, Release and ASan builds plus the targeted and git diff --check passed. Full suites were not repeated for this test-only fix. Linux clang-tidy/libstdc++ confirmation remains with the next Gitea run; native analysis is not claimed as a reproduction of the Linux diagnostics. + +## M6.5d environmental qualification - 2026-09-27 + +Added the environmental-qualification CTest and optional `--long` driver. It tests +admission/capacity/overflow boundaries, each missing recipe resource, efficiency +endpoints, consumer temperature gates, recomputed-checksum mutations, a u64-max +trace and deterministic paired continuous/restored simulations. No runtime change. +See [ENVIRONMENTAL_QUALIFICATION.md](ENVIRONMENTAL_QUALIFICATION.md) for detailed +coverage, exact commands, long-run output, machine and measured memory/timing. + +Executed Windows checks: + +- Release configure/build/check: 54/54 CTests passed. +- Analysis configure/build/check: clang-tidy/warnings-as-errors and 54/54 passed. +- ASan configure/build/check: 54/54 passed, including tick exhaustion. +- After adding the final tick-exhaustion case, Release and analysis rebuilt and + environmental-qualification passed again. A constant-expression integer-width + diagnostic in the new test was corrected before that final analysis run. +- Release format and git diff --check passed. +- Final Release `evo-environmental-qualification.exe --long`: 16 x 65536 logical + ticks and paired continuous branches passed; 2097152 advances, 329231 bites, + matching snapshots and conserved totals. Reported fingerprint 93a9f9b296caac36. + +Native M6.5 qualification is complete; no new Linux/UBSan/TSan or R730xd/cluster +run was available locally. CI must confirm the committed test on its toolchains. +No source-rule, schema, golden or deployment change. diff --git a/tests/environmental_qualification.cpp b/tests/environmental_qualification.cpp new file mode 100644 index 0000000..c93f864 --- /dev/null +++ b/tests/environmental_qualification.cpp @@ -0,0 +1,441 @@ +#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 = 2; + 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; + } +}