From 48684d30d95c0a9c2261c94422927821e34a819f Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 9 Oct 2026 18:30:58 -0400 Subject: [PATCH] M11.2b: restore funded life state with canonical closure checks --- docs/STATUS.md | 4 +- ...-primitive-lives-and-persistent-control.md | 11 ++ docs/engineering/VALIDATION.md | 14 ++ .../evo/server/lifecycle/primitive_lives.hpp | 12 ++ schemas/primitive-lives-v1.md | 51 +++++ src/server/lifecycle/primitive_lives.cpp | 180 ++++++++++++++++++ tests/primitive_lives_tests.cpp | 65 +++++++ 7 files changed, 336 insertions(+), 1 deletion(-) create mode 100644 schemas/primitive-lives-v1.md diff --git a/docs/STATUS.md b/docs/STATUS.md index 6510050..d7e4181 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -41,7 +41,9 @@ the maintainer chose directional rounding): authorized finite spawn funding and implementation choices for later review. 11.2a adds in-memory funded creation: full-grown primitive founders, equal energy-only reserves, conserved pool/body/heat and exact successful retries. - Durable recovery, world-wide binding and session integration remain. + 11.2b adds a bounded creation-state checkpoint codec with full inventory/archive + closure and exact retry recovery. Durable publication, world-wide binding and + session integration remain. Open from M10 (BACKLOG): - the maintainer's native-client observation, moved to the later 2k drill; diff --git a/docs/adr/0100-primitive-lives-and-persistent-control.md b/docs/adr/0100-primitive-lives-and-persistent-control.md index 7fa999e..9d6b451 100644 --- a/docs/adr/0100-primitive-lives-and-persistent-control.md +++ b/docs/adr/0100-primitive-lives-and-persistent-control.md @@ -179,3 +179,14 @@ world-allocated identities, never the client. This layer checks local collisions world-wide allocation and authorization are enforced in 11.2c/d. Refusals here are in-memory errors, not durable action outcomes. There are no live ticks or death/logout transitions yet, so this subsection is not deployable gameplay. + +## 11.2b: Creation-state checkpoint codec + +The separate [primitive-lives-v1](../../schemas/primitive-lives-v1.md) envelope +retains the explicit opening, sites, founding requests and identities, every +inventory balance and the complete archive. Restore reconstructs a detached +candidate, compares each saved record/balance/history and requires exact canonical +re-encoding. It refuses unknown versions, mismatched region identity, duplicate +life bindings and inconsistent funding. No biological timers exist in this +creation-only version; introducing progression requires a new format first. +Durable publication and session integration remain 11.2c/d. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index fcdacb7..1b97496 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -5500,3 +5500,17 @@ Executed: Environment: the sandboxed Windows Ninja build stalled before compiler execution; the same release preset succeeded outside the sandbox. WSL required escalated access. No reference-worker load qualification or deployment was performed. + +## 2026-10-09 — M11.2b creation-state checkpoint codec + +The primitive-lives-v1 envelope restores exact source, heat, bodies, reserves, +archive, allocation and retry state. Tests cover empty/populated recovery, +identical continuation, every truncated prefix, trailing bytes, oversized input, +unknown versions/quantum, mismatched scope, and resealed corruption of placement, +growth, ownership, funding and archived history. No durable-store claim yet. + +Executed: Linux GCC 14 debug lifecycle test, Clang 19 ASan+UBSan lifecycle test, +Windows MSVC release 62/62 CTest checks, clang-tidy 19 on the two changed source/test +files, repository format-check and `git diff --check`. All passed. The Linux +full-suite results from 11.2a are not claimed as new codec runs. No wire type or +deployed profile changed; no deployment occurred. diff --git a/include/evo/server/lifecycle/primitive_lives.hpp b/include/evo/server/lifecycle/primitive_lives.hpp index cbb360a..3b08554 100644 --- a/include/evo/server/lifecycle/primitive_lives.hpp +++ b/include/evo/server/lifecycle/primitive_lives.hpp @@ -23,6 +23,10 @@ struct SpawnSite { }; inline constexpr std::size_t max_primitive_lives = 256; inline constexpr std::int32_t spawn_coordinate_limit_um = 1'000'000'000; +inline constexpr std::uint32_t primitive_lives_format = 1; +inline constexpr std::size_t max_primitive_lives_bytes = + 200 + 184 * max_primitive_lives + biology::max_archive_bytes; +enum class LifeCodecError : std::uint8_t { format, version, checksum, closure }; struct NurseryConfig { std::uint64_t world{}, region{}, frame{}, source{}; accounting::Inventory funding{}; // Explicit finite opening, never replenished here. @@ -81,6 +85,14 @@ class PrimitiveLives { [[nodiscard]] accounting::Inventory totals() const noexcept; [[nodiscard]] const biology::LineageArchive& archive() const noexcept; + // Complete creation-state envelope (schemas/primitive-lives-v1.md). It has + // no progressing biology yet. Bytes include balances and archive as well as + // their founding requests; restore reconstructs and checks exact closure. + [[nodiscard]] std::vector snapshot() const; + [[nodiscard]] static std::expected, LifeCodecError> + restore(std::span bytes, std::uint64_t world, std::uint64_t region, + std::uint64_t frame); + private: struct State; explicit PrimitiveLives(std::unique_ptr state); diff --git a/schemas/primitive-lives-v1.md b/schemas/primitive-lives-v1.md new file mode 100644 index 0000000..58dd1d8 --- /dev/null +++ b/schemas/primitive-lives-v1.md @@ -0,0 +1,51 @@ +# Primitive lives creation-state envelope v1 + +M11.2b, ADR-0100. Implemented by `server::PrimitiveLives::snapshot/restore`. +This is a bounded creation-state codec, not yet a published PostgreSQL checkpoint +profile. It supports funded births and their successful retries, not biological +stepping, death, mutation or logout timers. Such state requires a new version +before it is introduced; restoring this format never synthesizes progression. + +All integers little endian; no native layouts. Signed coordinates are two's +complement i32 micrometres. Inventory is energy followed by C/N/P/other, five u64. + +| Header offset | Field | +|---|---| +| 0 | Eight ASCII bytes `EVOLIFE1` | +| 8 | u32 format = 1 | +| 12 | u32 founder-life rules = 1 (genome schema 2, development 2) | +| 16, 24, 32, 40 | u64 world, region, frame, source identity | +| 48 | u64 quantum = 50000 microseconds | +| 56 | 40-byte explicit opening funding inventory | +| 96, 100, 104 | u32 site count, retained life count, archive byte length | +| 108 | u32 reserved = 0 | + +After the 112-byte header: + +1. Sites: 8 bytes each, i32 x/y, lexicographic order, nonoverlapping founder squares. +2. Life records in site/allocation order, 96 bytes each (offsets relative to record): + account bytes (0, 16 bytes), action (16, u64), life/organism/genome/event/born tick + (24/32/40/48/56, u64 each), source (64, u64), x/y (72/76, i32), realized growth + and damage (80/84, u32), body/reserve reservoir IDs (88/92, u32). +3. `2 + 2 * site_count` inventory records: pool, heat, then body/reserve for each + site. Unallocated pairs are zero. Saved balances are not replaced by defaults. +4. Complete canonical LineageArchive bytes, naming its contained schema 2 genomes + when nonempty. Empty nursery history remains the archive's canonical empty form. +5. u64 FNV-1a64 of every preceding byte (offset 14695981039346656037, + multiplier 1099511628211, wrapping). This detects corruption, not forgery; + durable publication must additionally protect the payload with SHA-256. + +Sites 1..256, lives 0..sites, archive length bounded by `biology::max_archive_bytes`. +Exact length is `200 + 88 * sites + 96 * lives + archive_bytes`; the upper byte +bound follows from those limits. All counts/lengths are checked before allocation. +Unknown format, rule or quantum is refused. Expected world/region/frame must match. + +Restore reconstructs a detached nursery from its opening and retained births, +checks each resolved life, compares every saved balance and the complete archive, +then requires byte-identical re-encoding. Thus duplicated accounts/identities, +unfunded bodies, altered reserves, growth, heat, source or archive cannot pass +merely by resealing the checksum. No partial result is exposed on failure. + +The host must still establish authority, choose the latest committed cut and +reconcile durable life/action bindings before readiness. A valid older envelope +is not evidence that it is the current world. No session grant is serialized. diff --git a/src/server/lifecycle/primitive_lives.cpp b/src/server/lifecycle/primitive_lives.cpp index ac925a1..39173a3 100644 --- a/src/server/lifecycle/primitive_lives.cpp +++ b/src/server/lifecycle/primitive_lives.cpp @@ -1,6 +1,7 @@ #include "evo/server/lifecycle/primitive_lives.hpp" #include +#include #include #include #include @@ -114,4 +115,183 @@ accounting::Inventory PrimitiveLives::totals() const noexcept { const biology::LineageArchive& PrimitiveLives::archive() const noexcept { return state_->archive; } + +namespace { +constexpr std::uint64_t life_magic = 0x314546494C4F5645ULL; // "EVOLIFE1" +constexpr std::size_t life_header_bytes = 112; +constexpr std::size_t life_record_bytes = 96; +std::uint64_t checksum(std::span bytes) noexcept { + std::uint64_t value = 14695981039346656037ULL; + for (const auto byte : bytes) + value = (value ^ byte) * 1099511628211ULL; + return value; +} +class Writer { + public: + explicit Writer(std::vector& bytes) : bytes_{bytes} {} + void put(std::uint64_t value, unsigned width = 8) { + for (unsigned i = 0; i < width; ++i, value >>= 8U) + bytes_[at_++] = static_cast(value & 255U); + } + void inventory(accounting::Inventory value) { + put(value.energy.value); + for (const auto mass : value.matter) + put(mass.value); + } + void site(SpawnSite value) { + put(std::bit_cast(value.x_um), 4); + put(std::bit_cast(value.y_um), 4); + } + void raw(std::span value) { + for (const auto b : value) + put(b, 1); + } + + private: + std::vector& bytes_; + std::size_t at_{}; +}; +// Only constructed after exact sizes/counts have been checked, except for the +// fixed header, whose minimum length is checked before reading any byte. +class Reader { + public: + explicit Reader(std::span bytes) : bytes_{bytes} {} + std::uint64_t get(unsigned width = 8) { + std::uint64_t value{}; + for (unsigned i = 0; i < width; ++i) + value |= std::uint64_t{bytes_[at_++]} << (8U * i); + return value; + } + accounting::Inventory inventory() { + accounting::Inventory out{}; + out.energy.value = get(); + for (auto& mass : out.matter) + mass.value = get(); + return out; + } + SpawnSite site() { + const auto x = static_cast(get(4)); + const auto y = static_cast(get(4)); + return {std::bit_cast(x), std::bit_cast(y)}; + } + std::span raw(std::size_t size) { + const auto result = bytes_.subspan(at_, size); + at_ += size; + return result; + } + + private: + std::span bytes_; + std::size_t at_{}; +}; +} // namespace + +std::vector PrimitiveLives::snapshot() const { + const auto& c = state_->config; + const auto history = state_->archive.encode(); + std::vector bytes(life_header_bytes + 8 * c.sites.size() + + life_record_bytes * state_->lives.size() + + 40 * balances().size() + history.size() + 8); + Writer out{bytes}; + out.put(life_magic); + out.put(primitive_lives_format, 4); + out.put(biology::founder_life_rules, 4); + out.put(c.world); + out.put(c.region); + out.put(c.frame); + out.put(c.source); + out.put(50'000); // Ratified M10 quantum; no biological stepping in format 1. + out.inventory(c.funding); + out.put(c.sites.size(), 4); + out.put(state_->lives.size(), 4); + out.put(history.size(), 4); + out.put(0, 4); + for (const auto site : c.sites) + out.site(site); + for (const auto& life : state_->lives) { + out.raw(life.request.account); + out.put(life.request.action); + const auto& id = life.identity; + out.put(id.life); + out.put(id.organism); + out.put(id.genome); + out.put(id.event); + out.put(id.born.value); + out.put(life.source); + out.site(life.site); + out.put(life.growth.realized_per_thousand, 4); + out.put(life.growth.damage_per_thousand, 4); + out.put(life.body.value, 4); + out.put(life.reserve.value, 4); + } + for (const auto inventory : balances()) + out.inventory(inventory); + out.raw(history); + out.put(checksum(std::span{bytes}.first(bytes.size() - 8))); + return bytes; +} + +std::expected, LifeCodecError> +PrimitiveLives::restore(std::span bytes, std::uint64_t world, + std::uint64_t region, std::uint64_t frame) { + if (bytes.size() < life_header_bytes + 8 || bytes.size() > max_primitive_lives_bytes) + return std::unexpected{LifeCodecError::format}; + Reader tail{bytes.last(8)}; + if (checksum(bytes.first(bytes.size() - 8)) != tail.get()) + return std::unexpected{LifeCodecError::checksum}; + Reader in{bytes}; + if (in.get() != life_magic) + return std::unexpected{LifeCodecError::format}; + if (in.get(4) != primitive_lives_format || in.get(4) != biology::founder_life_rules) + return std::unexpected{LifeCodecError::version}; + NurseryConfig c; + c.world = in.get(); + c.region = in.get(); + c.frame = in.get(); + c.source = in.get(); + if (c.world != world || c.region != region || c.frame != frame) + return std::unexpected{LifeCodecError::closure}; + if (in.get() != 50'000) + return std::unexpected{LifeCodecError::version}; + c.funding = in.inventory(); + const auto sites = in.get(4), count = in.get(4), archive_bytes = in.get(4); + if (in.get(4) != 0 || sites == 0 || sites > max_primitive_lives || count > sites || + archive_bytes > biology::max_archive_bytes || + bytes.size() != life_header_bytes + 8 * sites + life_record_bytes * count + + 40 * (2 + 2 * sites) + archive_bytes + 8) + return std::unexpected{LifeCodecError::format}; + for (std::uint64_t i = 0; i < sites; ++i) + c.sites.push_back(in.site()); + auto restored = create(std::move(c)); + if (!restored) + return std::unexpected{LifeCodecError::closure}; + for (std::uint64_t i = 0; i < count; ++i) { + PrimitiveLife saved{}; + std::ranges::copy(in.raw(16), saved.request.account.begin()); + saved.request.action = in.get(); + auto& id = saved.identity; + id.life = in.get(); + id.organism = in.get(); + id.genome = in.get(); + id.event = in.get(); + id.born.value = in.get(); + saved.source = in.get(); + saved.site = in.site(); + saved.growth.realized_per_thousand = static_cast(in.get(4)); + saved.growth.damage_per_thousand = static_cast(in.get(4)); + saved.body.value = static_cast(in.get(4)); + saved.reserve.value = static_cast(in.get(4)); + const auto actual = (*restored)->spawn(saved.request, saved.identity); + if (!actual || *actual != saved || (*restored)->lives().size() != i + 1) + return std::unexpected{LifeCodecError::closure}; + } + for (const auto actual : (*restored)->balances()) + if (actual != in.inventory()) + return std::unexpected{LifeCodecError::closure}; + const auto archive = in.raw(static_cast(archive_bytes)); + if (!std::ranges::equal(archive, (*restored)->archive().encode()) || + !std::ranges::equal(bytes, (*restored)->snapshot())) + return std::unexpected{LifeCodecError::closure}; + return std::move(*restored); +} } // namespace evo::server diff --git a/tests/primitive_lives_tests.cpp b/tests/primitive_lives_tests.cpp index 4e3d3ef..7f7184d 100644 --- a/tests/primitive_lives_tests.cpp +++ b/tests/primitive_lives_tests.cpp @@ -185,6 +185,70 @@ void invalid_sites_and_bounds() { CHECK(huge && (*huge)->spawn(request(1), allocation(1))); CHECK(summed((*huge)->balances()) == c.funding); } + +void reseal(std::vector& bytes) { + std::uint64_t value = 14695981039346656037ULL; + for (std::size_t i = 0; i < bytes.size() - 8; ++i) + value = (value ^ bytes[i]) * 1099511628211ULL; + for (std::size_t i = bytes.size() - 8; i < bytes.size(); ++i, value >>= 8U) + bytes[i] = static_cast(value & 255U); +} +void recover_complete_creation_state() { + auto made = PrimitiveLives::create(config()); + CHECK(made); + const auto genesis = (*made)->snapshot(); + auto empty = PrimitiveLives::restore(genesis, 90, 1, 7); + CHECK(empty && (*empty)->snapshot() == genesis && (*empty)->lives().empty()); + const auto first = (*made)->spawn(request(1), allocation(1)); + CHECK(first); + const auto bytes = (*made)->snapshot(); + CHECK(bytes.size() <= max_primitive_lives_bytes); + auto restored = PrimitiveLives::restore(bytes, 90, 1, 7); + CHECK(restored && (*restored)->snapshot() == bytes && cut(**restored) == cut(**made)); + CHECK((*restored)->spawn(request(1), {}) == first); + CHECK((*restored)->snapshot() == bytes); + CHECK((*restored)->spawn(request(2), allocation(2)) == + (*made)->spawn(request(2), allocation(2))); + CHECK((*restored)->snapshot() == (*made)->snapshot()); + CHECK(!PrimitiveLives::restore(bytes, 91, 1, 7)); + CHECK(!PrimitiveLives::restore(bytes, 90, 2, 7)); + CHECK(!PrimitiveLives::restore(bytes, 90, 1, 8)); + // Every truncation is refused without reading past the input under ASan. + for (std::size_t size = 0; size < bytes.size(); ++size) + CHECK(!PrimitiveLives::restore(std::span{bytes}.first(size), 90, 1, 7)); + auto changed = bytes; + changed.push_back(0); + CHECK(!PrimitiveLives::restore(changed, 90, 1, 7)); + // Resealing distinguishes invariant validation from checksum detection. + const auto rejects = [&](std::size_t offset, LifeCodecError error) { + auto altered = bytes; + altered[offset] ^= 1U; + reseal(altered); + const auto result = PrimitiveLives::restore(altered, 90, 1, 7); + CHECK(!result && result.error() == error); + }; + rejects(0, LifeCodecError::format); // Magic. + rejects(8, LifeCodecError::version); // Format. + rejects(12, LifeCodecError::version); // Rules. + rejects(48, LifeCodecError::version); // Quantum. + rejects(108, LifeCodecError::format); // Reserved. + rejects(96, LifeCodecError::format); // Site count/length disagreement. + rejects(100, LifeCodecError::format); // Life count/length disagreement. + rejects(104, LifeCodecError::format); // Archive length. + rejects(128 + 64, LifeCodecError::closure); // Source provenance. + rejects(128 + 72, LifeCodecError::closure); // Resolved placement. + rejects(128 + 80, LifeCodecError::closure); // Growth. + rejects(128 + 84, LifeCodecError::closure); // Damage. + rejects(128 + 88, LifeCodecError::closure); // Body ownership. + rejects(128 + 92, LifeCodecError::closure); // Reserve ownership. + rejects(128 + 96, LifeCodecError::closure); // Funding balance. + rejects(bytes.size() - 20, LifeCodecError::closure); // Archived history. + changed = bytes; + changed[128] ^= 1U; + CHECK(!PrimitiveLives::restore(changed, 90, 1, 7)); // Unsealed corruption. + changed.assign(max_primitive_lives_bytes + 1, 0); + CHECK(!PrimitiveLives::restore(changed, 90, 1, 7)); +} } // namespace int main() try { @@ -192,6 +256,7 @@ int main() try { failures_and_retries_spend_nothing(); every_channel_must_be_funded(); invalid_sites_and_bounds(); + recover_complete_creation_state(); std::puts("PASS primitive lives: funded bodies, equal starts, atomic refusals and retries"); return 0; } catch (const std::exception& e) {