diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 79ccdaf..fa3791a 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -461,3 +461,11 @@ M6.5d native qualification complete: [report](engineering/ENVIRONMENTAL_QUALIFIC 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. + +M6.6 implemented (2026-09-27): [ADR-0056](adr/0056-environmental-terminal-decay.md) +adds explicit terminal facts, retained corpse accounts, shared integer decay caps, +N/P mineralization and organic-energy heat release. Rules/envelope v2 restore +partial inventory, lifecycle and retry reports together; v1 stays byte-compatible. +Tests cover rollback, water headroom, shared caps, restored exact retries, history +eviction, malformed v2 envelopes and next-tick nutrient-fed growth. Next: M6.7 +fixed environment interval scheduling; M6.8 retains the full integration proof. diff --git a/docs/STATUS.md b/docs/STATUS.md index 33c31b9..6a607e5 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged. ## Completed implementation - Vision, architectural pillars, risks, open-question register, architecture - diagrams, biological contracts, engineering constitution and 55 ADRs (including the accepted M6.5 persistence and process contracts). + diagrams, biological contracts, engineering constitution and 56 ADRs (including the accepted M6.6 terminal/decay contract). Proposed/deferred choices remain distinct from accepted proof decisions. - M0–M4 task breakdowns with dependencies, acceptance evidence and risks, plus M5–M14 gates in [ROADMAP.md](ROADMAP.md). @@ -61,7 +61,7 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M6.6 return dead biomass to environment | Terminal actors cannot act; bounded, conserved decay with persistent residuals and retry safety | +| 1 | M6.7 schedule local environment intervals | Explicit fixed intervals and phase order, bounded catch-up, pause/resume and stale boundary refusal | | 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 | @@ -722,3 +722,9 @@ 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. + +M6.6 now retains corpse resources and lifecycle in opt-in rules/envelope v2. +Partial bounded decay conserves matter and energy, restores with exact retry +history, and can supply the surviving producer on a later tick. V1 compatibility +is retained. See ADR-0056 and VALIDATION.md for scope and evidence. This does not +add mortality causes, decomposer kinetics, durable publication or player sessions. diff --git a/docs/adr/0056-environmental-terminal-decay.md b/docs/adr/0056-environmental-terminal-decay.md new file mode 100644 index 0000000..50cb4f6 --- /dev/null +++ b/docs/adr/0056-environmental-terminal-decay.md @@ -0,0 +1,60 @@ +# ADR-0056: Retained environmental corpses and bounded decay + +## Status +Accepted for the M6.6 synthetic fixture, 2026-09-27. Rules 2 extend ADR-0055; +rules 1 and their canonical envelope remain supported without reinterpretation. + +## Context +Death must not erase inventory or permit further feeding/growth. Lifecycle, +remaining corpse balances and retries must commit together. ADR-0027 establishes +retained accounts and bounded decay for M2; M6 requires tagged destinations. + +## Decision +Input carries two terminal flags, producer then consumer, each 0/1. These are +trusted host facts, not client kill requests or a mortality model. Reject a flag +for an already terminal account on a new tick. Retained exact retries still return +their original report. Apply facts before capture/growth and feeding. A bite +involving either terminal actor rejects the entire tick, including pending deaths. +Emptying a producer by feeding still terminates it. + +Keep the original account and capacities, including after it empties. There is no +new spendable corpse copy or resurrection. Read-only balances plus terminal flags +identify corpse inventory. Ten explicit integer per-tick decay caps, default zero, +use field order and are shared across corpses in ascending ID order (producer, +consumer). Unused quota expires; unprocessed inventory survives. These are whole +bounded transfers, not fractional kinetics. There is no decay backlog or fractional +clock. Source/growth rational residuals retain their existing meaning. + +Decay runs last. Source fields 0..9 return to environment fields +0,1,2,3,1,2,6,9,8,9 respectively: organic N/P mineralize; organic energy becomes +heat; other compartments keep their tags. Carbon remains prepaid organic carbon. +Water return is additionally bounded by habitat water headroom; residual water +stays in the corpse. Source-channel caps are independent. This gate does not decay +environmental waste or imply decomposer kinetics/reactants. Returned nutrients +become available to growth on the following tick. + +Reports include consumer transition and ten summed corpse debits in source field +order. Publish via the existing atomic resource checkpoint. Envelope v2 records +caps, both lifecycle states, terminal inputs and decay reports in its replay audit. +Format must match rules. No in-place migration or automatic organism replacement. + +## Alternatives Considered +Deleting accounts loses matter. Separate corpse inventories duplicate ownership. +Fractional rates add state without a selected kinetic model. Reinterpreting v1 +silently changes physics. Integer caps follow the existing scoped M2 contract. + +## Benefits +Exact conservation, bounded work, recoverable partial decay and unchanged v1 bytes. + +## Costs +Two scoped rules/codec versions and larger bounded receipt storage. + +## Risks +Synthetic mineralization is not complete chemistry. ID priority is a fixture +policy, not a fairness rule. Terminal facts need future host validation. Retaining +empty accounts remains bounded to two actors. + +## Consequences +Test pending-death rollback, inactive actors, shared caps, water blocking, partial +decay/restore, retries, malformed envelopes, history eviction and nutrient-fed +regrowth. Durable publication remains M7; M6.7 schedules intervals. diff --git a/docs/adr/README.md b/docs/adr/README.md index 4d54fce..915bcee 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,5 +1,7 @@ # Architecture decision records +- [ADR-0056: Environmental terminal decay](0056-environmental-terminal-decay.md) - accepted for M6.6 retained corpses, bounded decay and rules/envelope v2. + Locked requirements outrank these records. Review architecture, ADRs, public contracts, tests, then implementation. Stop expanding implementation on conflict. diff --git a/docs/biology/ENVIRONMENTAL_PROCESS.md b/docs/biology/ENVIRONMENTAL_PROCESS.md index 3c76f8d..384bc90 100644 --- a/docs/biology/ENVIRONMENTAL_PROCESS.md +++ b/docs/biology/ENVIRONMENTAL_PROCESS.md @@ -1,5 +1,13 @@ # M6.5 environmental process contract v1 +M6.6 adds opt-in rules 2 under [ADR-0056](../adr/0056-environmental-terminal-decay.md). +The public config adds decay[10] in fg/pJ per tick; input adds terminal[2] flags +in actor order. Progress adds consumer_terminal; reports add consumer_transition +and decomposed[10] source-channel totals. Terminal facts precede capture/growth, +then feeding, then bounded corpse decay. Original accounts retain remaining +inventory. All phases share one rollback and persisted retry boundary. The v1 +contract below and its bytes remain unchanged. See the envelope schema for v2. + Authority: ADR-0055, ADR-0054, environmental units (ADR-0050), and the scoped 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. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index f97e751..70fbff0 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1917,3 +1917,35 @@ Executed Windows checks: 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. + +## M6.6 retained corpse resources - 2026-09-27 + +Rules/envelope v2 now support trusted terminal facts for either fixture actor, +retained corpse inventory and bounded tagged decay. This is an in-memory process +checkpoint, not durable region publication or gameplay mortality. Rule v1 and its +canonical bytes are preserved; no golden was replaced. Config/input extensions +are rejected under v1 rather than silently omitted. + +New tests cover pending death plus feeding rollback, terminal actor rejection, +shared per-channel caps in ID order, exact transfer destinations, partial decay, +zero caps, water headroom, restored duplicate/conflicting/stale requests, permanent +terminal state, consumer-corpse nutrients feeding a surviving producer next tick, +every v2 byte truncation, and checksum-repaired invalid lifecycle/history fields. +Eight 90-tick cases compare retained balances against independent cumulative-quota +formulas, with restore at ticks 17, 65 and 90 and exact conservation every tick. + +Commands: tools/windows-check.ps1 -Preset release/analysis/asan -Action check; +-Preset release -Action format; git diff --check. The initial suites found the +older negative test's rules=2 was now valid; it now rejects unsupported rules=3. +Final results are recorded below after all processes complete. + +Release long qualification again ran 16 x 65536 logical ticks, 2097152 paired +advances, and produced unchanged v1 fingerprint 93a9f9b296caac36. Snapshot size +remains 30615 bytes in that v1 case. Owner size is now 20152 bytes (formerly13400), +including bounded extension receipts; budget admission uses sizeof dynamically. +No new Linux/UBSan/TSan or R730xd measurement is claimed. Linux CI remains a +separate verification step; local Docker Linux engine/toolchain is unavailable. + +Final native validation: Release 54/54 (3.66s), clang-tidy analysis 54/54 (13.37s), +ASan 54/54 (46.72s), format check and git diff --check passed. M6.6 is natively +qualified; the next gate is M6.7 interval scheduling. No deployment was changed. diff --git a/include/evo/processes/environmental_community.hpp b/include/evo/processes/environmental_community.hpp index cd03e11..18d4ead 100644 --- a/include/evo/processes/environmental_community.hpp +++ b/include/evo/processes/environmental_community.hpp @@ -9,22 +9,27 @@ struct EnvironmentalConfig { std::array recipe{}, intake{}; std::uint64_t assimilation{}, producer_min_mK{}, producer_max_mK{}, consumer_min_mK{}, consumer_max_mK{}; + std::array decay{}; // Rules 2: shared source-channel caps per tick. auto operator<=>(const EnvironmentalConfig&) const = default; }; struct EnvironmentalInput { std::uint64_t temperature_mK{}, source_enabled{}; std::array bite{}; + std::array terminal{}; // Rules 2: trusted host facts, actor order. auto operator<=>(const EnvironmentalInput&) const = default; }; struct EnvironmentalProgress { std::uint64_t tick{}, source_remainder{}, last_funded{}, efficiency_remainder{}, growth_remainder{}, producer_terminal{}; + std::uint64_t consumer_terminal{}; auto operator<=>(const EnvironmentalProgress&) const = default; }; struct EnvironmentalReport { std::uint64_t tick{}, captured{}, retained{}, capture_heat{}, grown{}, unmet{}, source_status{}; std::array assimilated{}, waste{}; std::uint64_t terminal_transition{}; + std::uint64_t consumer_transition{}; + std::array decomposed{}; auto operator<=>(const EnvironmentalReport&) const = default; }; enum class CommunityError : std::uint8_t { diff --git a/schemas/environmental-community.md b/schemas/environmental-community.md index d746235..98614be 100644 --- a/schemas/environmental-community.md +++ b/schemas/environmental-community.md @@ -1,5 +1,21 @@ # Environmental community envelope v1 (M6.5c) +## Version 2 extension (M6.6, ADR-0056) + +Format 2 requires rules 2; format 1 requires rules 1. The v1 layout below is +unchanged. In v2 append decay[10] to config (39 u64 total), consumer_terminal +to each progress (7 u64; anchor 37 u64), terminal[2] after each input's bite, +and consumer_transition plus decomposed[10] after each report's terminal_transition. +Each v2 receipt is 38 u64 (304 bytes). Fixed overhead is 712 bytes plus receipts +and nested resource bytes. Lifecycle flags are 0/1; decomposed uses source field +order. Both versions replay their own rules. V1 rejects nonzero extension fields +at creation/input validation; they are not silently omitted. No conversion API. +Terminal accounts may retain balances in v2; v1 retains its empty-terminal rule. +Caps are whole fg/pJ per tick, not rates requiring fractional carry. Remaining +corpse inventory resides in nested resource accounts, never duplicated here. + +## Version 1 layout + Authority ADR-0055. All integers little-endian, no native struct serialization. Header u64 magic 0x3150434f564541, u64 format=1, u64 total bytes. Maximum 1 MiB. Then config, current progress, audit anchor, u64 receipt count, chronological diff --git a/src/processes/environmental_codec.cpp b/src/processes/environmental_codec.cpp index 2207fbd..a20b04c 100644 --- a/src/processes/environmental_codec.cpp +++ b/src/processes/environmental_codec.cpp @@ -38,7 +38,7 @@ struct Reader { return v; } }; -template void config_io(T& c, IO& io) { +template void config_io(T& c, IO& io, bool extended) { io(c.rules); io(c.world); io(c.frame); @@ -62,29 +62,37 @@ template void config_io(T& c, IO& io) { io(c.producer_max_mK); io(c.consumer_min_mK); io(c.consumer_max_mK); + if (extended) + for (auto& v : c.decay) + io(v); } -template void progress_io(T& p, IO& io) { +template void progress_io(T& p, IO& io, bool extended) { io(p.tick); io(p.source_remainder); io(p.last_funded); io(p.efficiency_remainder); io(p.growth_remainder); io(p.producer_terminal); + if (extended) + io(p.consumer_terminal); } -template void state_io(T& s, IO& io) { +template void state_io(T& s, IO& io, bool extended) { for (auto& v : s.environment) io(v); for (auto& v : s.producer) io(v); for (auto& v : s.consumer) io(v); - progress_io(s.progress, io); + progress_io(s.progress, io, extended); } -template void history_io(T& h, IO& io) { +template void history_io(T& h, IO& io, bool extended) { io(h.input.temperature_mK); io(h.input.source_enabled); for (auto& v : h.input.bite) io(v); + if (extended) + for (auto& v : h.input.terminal) + io(v); auto& r = h.report; io(r.tick); io(r.captured); @@ -98,27 +106,32 @@ template void history_io(T& h, IO& io) { for (auto& v : r.waste) io(v); io(r.terminal_transition); + if (extended) { + io(r.consumer_transition); + for (auto& v : r.decomposed) + io(v); + } } } // namespace std::expected EnvironmentalCommunity::snapshot() const { auto resource = resources_->snapshot(); if (!resource) return std::unexpected{CommunityError::resources}; - const auto length = - 24 + 29 * 8 + 6 * 8 + 36 * 8 + 8 + count_ * 25 * 8 + 8 + resource->size() + 8; + const bool extended = config_.rules == 2; + const auto length = (extended ? 712 : 616) + count_ * (extended ? 304 : 200) + resource->size(); if (length > max_snapshot_bytes) return std::unexpected{CommunityError::budget}; Writer w; w.bytes.resize(length); w(magic); - w(1); + w(config_.rules); w(length); - config_io(config_, w); - progress_io(progress_, w); - state_io(anchor_, w); + config_io(config_, w, extended); + progress_io(progress_, w, extended); + state_io(anchor_, w, extended); w(count_); for (std::size_t i = 0; i < count_; ++i) - history_io(history_[(next_ + history_limit - count_ + i) % history_limit], w); + history_io(history_[(next_ + history_limit - count_ + i) % history_limit], w, extended); w(resource->size()); std::copy(resource->begin(), resource->end(), w.bytes.begin() + static_cast(w.at)); @@ -136,7 +149,9 @@ EnvironmentalCommunity::restore(std::span bytes, world::Worl Reader r{bytes.first(bytes.size() - 8)}, tail{bytes.last(8)}; if (r.get() != magic) return std::unexpected{CommunityError::format}; - if (r.get() != 1) + const auto version = r.get(); + const bool extended = version == 2; + if (version != 1 && version != 2) return std::unexpected{CommunityError::version}; if (r.get() != bytes.size()) return std::unexpected{CommunityError::format}; @@ -145,16 +160,18 @@ EnvironmentalCommunity::restore(std::span bytes, world::Worl if (budget < sizeof(EnvironmentalCommunity) + scratch_bytes) return std::unexpected{CommunityError::budget}; auto o = std::unique_ptr(new EnvironmentalCommunity); - config_io(o->config_, r); - progress_io(o->progress_, r); - state_io(o->anchor_, r); + config_io(o->config_, r, extended); + if (o->config_.rules != version) + return std::unexpected{CommunityError::version}; + progress_io(o->progress_, r, extended); + state_io(o->anchor_, r, extended); const auto count = r.get(); if (!r.ok || count != std::min(o->progress_.tick, std::uint64_t{history_limit}) || o->anchor_.progress.tick != o->progress_.tick - count || - count * 200 > r.bytes.size() - r.at) + count * (extended ? 304 : 200) > r.bytes.size() - r.at) return std::unexpected{CommunityError::format}; for (std::size_t i = 0; i < count; ++i) { - history_io(o->history_[i], r); + history_io(o->history_[i], r, extended); if (o->history_[i].report.tick != o->anchor_.progress.tick + i + 1) return std::unexpected{CommunityError::format}; } diff --git a/src/processes/environmental_community.cpp b/src/processes/environmental_community.cpp index 8d532f6..0e558df 100644 --- a/src/processes/environmental_community.cpp +++ b/src/processes/environmental_community.cpp @@ -15,7 +15,9 @@ std::uint64_t portion(std::uint64_t x, std::uint64_t a) { } // namespace bool EnvironmentalCommunity::configuration(const EnvironmentalConfig& c, const world::EnvironmentalTransfers& r) noexcept { - if (c.rules != 1 || c.world == 0 || c.frame == 0 || + if ((c.rules != 1 && c.rules != 2) || + (c.rules == 1 && std::ranges::any_of(c.decay, [](auto v) { return v != 0; })) || + c.world == 0 || c.frame == 0 || r.fields().identity() != world::WorldIdentity{c.world, c.frame} || c.source == 0 || c.tick_microseconds == 0 || c.area_um2 == 0 || c.irradiance_denominator == 0 || c.growth_denominator == 0 || c.efficiency > 1000 || c.assimilation > 1000 || @@ -51,10 +53,12 @@ bool EnvironmentalCommunity::valid(const State& s) const noexcept { if ((p.last_funded == 0 && (p.source_remainder != 0 || p.efficiency_remainder != 0)) || p.source_remainder >= config_.irradiance_denominator || p.growth_remainder >= config_.growth_denominator || p.efficiency_remainder >= 1000 || - p.last_funded > p.tick || p.producer_terminal > 1 || + p.last_funded > p.tick || p.producer_terminal > 1 || p.consumer_terminal > 1 || + (config_.rules == 1 && p.consumer_terminal != 0) || (p.tick == 0 && p != EnvironmentalProgress{})) return false; - if (p.producer_terminal && std::ranges::any_of(s.producer, [](auto v) { return v != 0; })) + if (config_.rules == 1 && p.producer_terminal && + std::ranges::any_of(s.producer, [](auto v) { return v != 0; })) return false; if (s.environment[0] > resources_->fields().water_capacity(0)->value) return false; @@ -98,6 +102,18 @@ EnvironmentalCommunity::step(State& s, std::uint64_t tick, const auto& c = config_; EnvironmentalReport report{}; report.tick = tick; + if (input.terminal[0] > 1 || input.terminal[1] > 1 || + (c.rules == 1 && (input.terminal[0] || input.terminal[1])) || + (input.terminal[0] && p.producer_terminal) || (input.terminal[1] && p.consumer_terminal)) + return std::unexpected{CommunityError::input}; + if (input.terminal[0]) { + p.producer_terminal = 1; + report.terminal_transition = 1; + } + if (input.terminal[1]) { + p.consumer_terminal = 1; + report.consumer_transition = 1; + } const bool eligible = !p.producer_terminal && input.temperature_mK >= c.producer_min_mK && input.temperature_mK <= c.producer_max_mK; if (eligible && input.source_enabled) { @@ -150,8 +166,8 @@ EnvironmentalCommunity::step(State& s, std::uint64_t tick, report.unmet = quota->amount.value - grown; } if (any(input.bite)) { - if (p.producer_terminal || input.temperature_mK < c.consumer_min_mK || - input.temperature_mK > c.consumer_max_mK) + if (p.producer_terminal || p.consumer_terminal || + input.temperature_mK < c.consumer_min_mK || input.temperature_mK > c.consumer_max_mK) return std::unexpected{CommunityError::input}; for (std::size_t j = 0; j < 5; ++j) { const auto amount = input.bite[j], k = food[j]; @@ -173,6 +189,25 @@ EnvironmentalCommunity::step(State& s, std::uint64_t tick, report.terminal_transition = 1; } } + if (c.rules == 2) { + constexpr std::array destination{0, 1, 2, 3, 1, 2, 6, 9, 8, 9}; + auto remaining = c.decay; + for (std::size_t actor = 0; actor < 2; ++actor) { + if (!(actor == 0 ? p.producer_terminal : p.consumer_terminal)) + continue; + auto& corpse = actor == 0 ? s.producer : s.consumer; + for (std::size_t k = 0; k < 10; ++k) { + auto amount = std::min(remaining[k], corpse[k]); + if (k == 0) + amount = std::min(amount, resources_->fields().water_capacity(0)->value - + s.environment[0]); + corpse[k] -= amount; + s.environment[destination[k]] += amount; + remaining[k] -= amount; + report.decomposed[k] += amount; + } + } + } p.tick = tick; if (!valid(s)) return std::unexpected{CommunityError::resources}; diff --git a/tests/environmental_community_tests.cpp b/tests/environmental_community_tests.cpp index 1b5d6b4..c062f52 100644 --- a/tests/environmental_community_tests.cpp +++ b/tests/environmental_community_tests.cpp @@ -34,7 +34,7 @@ EnvironmentalConfig config() { } std::unique_ptr resources(std::array e = {100, 100, 100, 100, 0, 0, 100, 0, 10, 0}, - std::array p = {}) { + std::array p = {}, std::array consumer = {}) { 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) @@ -50,6 +50,7 @@ resources(std::array e = {100, 100, 100, 100, 0, 0, 100, 0, 1 accounts[0].id = {1}; accounts[1].id = {2}; accounts[0].balances = p; + accounts[1].balances = consumer; for (auto& a : accounts) a.capacities.fill(1000); auto r = @@ -233,12 +234,187 @@ void codec_replay() { CHECK(!EnvironmentalCommunity::restore(corrupted, identity, 8000000)); CHECK(o->snapshot() == saved); } +void terminal_decay() { + auto c = config(); + c.rules = 2; + c.decay.fill(3); + const std::array stock{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; + auto created = EnvironmentalCommunity::create(c, resources({}, stock, stock), 8000000); + CHECK(created); + auto o = std::move(*created); + const auto total = audit(*o); + const auto before = o->snapshot(); + CHECK(before); + // A pending terminal fact invalidates feeding and rolls back the entire tick. + for (auto facts : {std::array{1, 0}, std::array{0, 1}}) { + CHECK(!o->advance(1, {290000, 1, {1, 0, 0, 0, 0}, facts})); + CHECK(o->snapshot() == before); + } + CHECK(!o->advance(1, {290000, 0, {}, {2, 0}})); + const EnvironmentalInput death{290000, 1, {}, {1, 1}}; + auto report = o->advance(1, death); + CHECK(report); + CHECK(report->terminal_transition == 1 && report->consumer_transition == 1); + CHECK(report->captured == 0 && report->grown == 0); + for (std::size_t k = 0; k < 10; ++k) { + CHECK(report->decomposed[k] == 3); + CHECK(o->resources().organisms()[0].balances[k] == 2); + CHECK(o->resources().organisms()[1].balances[k] == 5); + } + const std::array returned{3, 6, 6, 3, 0, 0, 3, 0, 3, 6}; + for (std::size_t k = 0; k < 10; ++k) + CHECK(o->resources().fields().read(0, static_cast(k)) == returned[k]); + CHECK(audit(*o) == total); + auto saved = o->snapshot(); + CHECK(saved); + auto restored = EnvironmentalCommunity::restore(*saved, identity, 8000000); + CHECK(restored); + CHECK((*restored)->snapshot() == saved); + CHECK((*restored)->advance(1, death) == report); + CHECK(!(*restored)->advance(1, {290000, 0, {}, {1, 1}})); + CHECK(!(*restored)->advance(2, death)); // repeated death on a fresh tick + CHECK(!(*restored)->advance(2, {290000, 0, {1, 0, 0, 0, 0}})); + CHECK((*restored)->snapshot() == saved); + for (std::uint64_t t = 2; t <= 70; ++t) { + const EnvironmentalInput input{290000, 1, {}}; + auto r = o->advance(t, input); + CHECK(r && (*restored)->advance(t, input) == r); + CHECK(audit(*o) == total); + CHECK(o->snapshot() == (*restored)->snapshot()); + for (auto debit : r->decomposed) + CHECK(debit == (t < 4 ? 3 : t == 4 ? 1 : 0)); + if (t == 2) { + CHECK(o->resources().organisms()[0].balances == std::array{}); + CHECK(o->resources().organisms()[1].balances[4] == 4); + } + } + saved = o->snapshot(); + CHECK(saved); + restored = EnvironmentalCommunity::restore(*saved, identity, 8000000); + CHECK(restored && (*restored)->snapshot() == saved); + CHECK(!(*restored)->advance(1, death)); // retired receipt cannot decay again + CHECK((*restored)->progress().producer_terminal == 1 && + (*restored)->progress().consumer_terminal == 1); + + // Full water destination leaves corpse water intact; zero caps freeze all inventory. + c.decay.fill(0); + auto frozen = EnvironmentalCommunity::create(c, resources({}, stock), 8000000); + CHECK(frozen && (*frozen)->advance(1, {290000, 0, {}, {1, 0}})); + CHECK((*frozen)->resources().organisms()[0].balances == stock); + c.decay.fill(100); + auto blocked = EnvironmentalCommunity::create( + c, resources({999, 0, 0, 0, 0, 0, 0, 0, 0, 0}, stock), 8000000); + CHECK(blocked); + auto r = (*blocked)->advance(1, {290000, 0, {}, {1, 0}}); + CHECK(r && r->decomposed[0] == 1); + CHECK((*blocked)->resources().organisms()[0].balances[0] == 4); + r = (*blocked)->advance(2, {290000, 0, {}}); + CHECK(r && r->decomposed[0] == 0); + saved = (*blocked)->snapshot(); + CHECK(saved); + restored = EnvironmentalCommunity::restore(*saved, identity, 8000000); + CHECK(restored && (*restored)->resources().organisms()[0].balances[0] == 4); + + // Consumer corpse supplies missing N/P; growth cannot spend it until the next tick. + c.growth_numerator = 1; + auto regrow = EnvironmentalCommunity::create(c, + resources({10, 0, 0, 20, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 9, 0, 0}, + {0, 0, 0, 0, 2, 2, 0, 6, 0, 0}), + 8000000); + CHECK(regrow); + const auto regrow_total = audit(**regrow); + r = (*regrow)->advance(1, {290000, 0, {}, {0, 1}}); + CHECK(r && r->grown == 0 && r->decomposed[4] == 2 && r->decomposed[7] == 6); + r = (*regrow)->advance(2, {290000, 0, {}}); + CHECK(r && r->grown == 1 && audit(**regrow) == regrow_total); + CHECK((*regrow)->resources().organisms()[0].balances[4] == 1); + + // Extension data cannot be silently lost through the v1 codec. + c.rules = 1; + CHECK(!EnvironmentalCommunity::create(c, resources(), 8000000)); + auto legacy = make(); + CHECK(!legacy->advance(1, death)); +} +void terminal_codec_validation() { + auto c = config(); + c.rules = 2; + c.decay.fill(1); + auto created = + EnvironmentalCommunity::create(c, resources({}, {5, 5, 5, 5, 5, 5, 5, 5, 5, 5}), 8000000); + CHECK(created); + CHECK((*created)->advance(1, {290000, 0, {}, {1, 1}})); + auto saved = (*created)->snapshot(); + CHECK(saved); + for (std::size_t n = 0; n < saved->size(); ++n) + CHECK(!EnvironmentalCommunity::restore(std::span{*saved}.first(n), identity, 8000000)); + // v2 offsets: config24, progress336, anchor392, count688, first input696, + // terminal flags752/760, report768, consumer transition912, decay920. + for (std::size_t offset : + {std::size_t{8}, std::size_t{24}, std::size_t{384}, std::size_t{680}, std::size_t{688}, + std::size_t{752}, std::size_t{760}, std::size_t{912}, std::size_t{920}}) { + auto b = *saved; + b[offset] = 255; + std::uint64_t h = 14695981039346656037ULL; + for (auto v : std::span{b}.first(b.size() - 8)) + h = (h ^ v) * 1099511628211ULL; + for (unsigned j = 0; j < 8; ++j) + b[b.size() - 8 + j] = static_cast((h >> (8 * j)) & 255U); + CHECK(!EnvironmentalCommunity::restore(b, identity, 8000000)); + } + CHECK((*created)->snapshot() == saved); +} +void decay_continuation() { + for (std::uint64_t sample = 0; sample < 8; ++sample) { + auto c = config(); + c.rules = 2; + std::array producer{}, consumer{}; + for (std::size_t k = 0; k < 10; ++k) { + producer[k] = 100 + sample * 5 + k * 3; + consumer[k] = 140 + sample + k; + c.decay[k] = (k + sample) % 5; + } + auto created = + EnvironmentalCommunity::create(c, resources({}, producer, consumer), 8000000); + CHECK(created); + auto o = std::move(*created); + const auto total = audit(*o); + for (std::uint64_t t = 1; t <= 90; ++t) { + const EnvironmentalInput input{290000, 0, {}, {t == 3 ? 1U : 0U, t == 3 ? 1U : 0U}}; + auto r = o->advance(t, input); + CHECK(r); + CHECK(audit(*o) == total); + for (std::size_t k = 0; k < 10; ++k) { + // Closed-form cumulative quota, independent of runtime per-tick recurrence. + const auto quota = (t > 2 ? t - 2 : 0) * c.decay[k]; + const auto first = quota < producer[k] ? producer[k] - quota : 0; + const auto second_quota = quota > producer[k] ? quota - producer[k] : 0; + const auto second = second_quota < consumer[k] ? consumer[k] - second_quota : 0; + CHECK(o->resources().organisms()[0].balances[k] == first); + CHECK(o->resources().organisms()[1].balances[k] == second); + } + if (t == 17 || t == 65 || t == 90) { + auto bytes = o->snapshot(); + CHECK(bytes); + auto restored = EnvironmentalCommunity::restore(*bytes, identity, 8000000); + CHECK(restored); + CHECK((*restored)->snapshot() == bytes); + CHECK((*restored)->advance(t, input) == r); + CHECK((*restored)->snapshot() == bytes); + o = std::move(*restored); + } + } + } +} } // namespace int main() { try { vectors(); rollback_limits(); codec_replay(); + terminal_decay(); + terminal_codec_validation(); + decay_continuation(); return 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); diff --git a/tests/environmental_qualification.cpp b/tests/environmental_qualification.cpp index c93f864..b73f8ac 100644 --- a/tests/environmental_qualification.cpp +++ b/tests/environmental_qualification.cpp @@ -116,7 +116,7 @@ void refusals() { auto c = config(); switch (which) { case 0: - c.rules = 2; + c.rules = 3; // Rules 2 are the M6.6 terminal/decay extension. break; case 1: c.world = 8;