diff --git a/CMakeLists.txt b/CMakeLists.txt index 67acf7d..a1bd3a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,7 +34,7 @@ target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in target_compile_features(evo_simulation PUBLIC cxx_std_23) evo_owned_target(evo_simulation) -set(evo_world_sources src/world/coordinates.cpp src/world/generation.cpp src/world/chunks.cpp src/world/edits.cpp src/world/codec.cpp src/world/local_files.cpp src/world/environment_units.cpp) +set(evo_world_sources src/world/coordinates.cpp src/world/generation.cpp src/world/chunks.cpp src/world/edits.cpp src/world/codec.cpp src/world/local_files.cpp src/world/environment_units.cpp src/world/fields.cpp) add_library(evo_world STATIC ${evo_world_sources}) add_library(evo::world ALIAS evo_world) target_include_directories(evo_world PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") @@ -72,6 +72,12 @@ evo_owned_target(evo-sim) include(CTest) if(BUILD_TESTING) + add_executable(evo-world-fields-tests tests/world_fields_tests.cpp) + target_link_libraries(evo-world-fields-tests PRIVATE evo::world) + evo_owned_target(evo-world-fields-tests) + add_test(NAME world-fields-contracts COMMAND evo-world-fields-tests) + set_tests_properties(world-fields-contracts PROPERTIES TIMEOUT 60) + add_executable(evo-environment-units-tests tests/environment_units_tests.cpp) target_link_libraries(evo-environment-units-tests PRIVATE evo::world evo::accounting) evo_owned_target(evo-environment-units-tests) diff --git a/README.md b/README.md index 654d85f..58dcad3 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ network service. Dev verification manifests are separate from the simulation. - [Local periodic spatial queries](docs/architecture/SPATIAL_CONTRACT.md) - [Energy/matter model and implemented ledger boundary](docs/biology/ENERGY_MODEL.md) - [Environmental units and habitat coupling](docs/world/ENVIRONMENTAL_UNITS.md) +- [Optional finite environmental fields and snapshot format](docs/world/ENVIRONMENTAL_FIELDS.md) - [Genome model and implemented v1 record](docs/biology/GENOME_MODEL.md) Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e1633ea..e2f291c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -310,6 +310,11 @@ under ADR-0050. Pure checked habitat/ratio/energy-integration helpers and dimens tests are implemented. No environmental stock, field codec, source scheduler or terrain-to-biological-mass converter is implemented by this gate. Next: M6.2. +M6.2 implements [optional finite field storage](world/ENVIRONMENTAL_FIELDS.md), +material capacity defaults, bounded sparse pages, same-field local relocation and +canonical field snapshot v1 under ADR-0051. Rate-driven sources and combined +terrain/biology persistence are not provided by this independent codec. Next: M6.3. + ## M7 - Persistent region server **Goal:** a disposable authoritative headless process can recover a bounded region diff --git a/docs/STATUS.md b/docs/STATUS.md index 6f5a7c0..cba8635 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 50 ADRs. + diagrams, biological contracts, engineering constitution and 51 ADRs. 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.2 optional environmental fields | Finite versioned inventories, sparse field pages and round-trip persistence without regenerated supply | +| 1 | M6.3 read-only environment views | Footprint queries with explicit units, availability, tick and revision validity | | 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 | @@ -618,3 +618,15 @@ accounting and refusal rollback are tested. Windows Release, clang-tidy and ASan suites pass; see VALIDATION.md for exact checks. Existing formats/goldens are unchanged. No fields or biological coupling are implemented yet. Next: M6.2 optional finite environmental fields with versioned persistence and explicit opening inventories. + +## M6.2 optional finite environmental fields (2026-09-27) + +Added a bounded FieldStore with fixed habitat mappings, material water-capacity +defaults, optional scalar channels and uniform baselines with sparse 64-site pages. +Opening inventories are explicit; missing differs from zero. Same-channel local +transfers preserve finite supply and reject stale commands/overspend without change. +Field snapshot v1 preserves mapping, quantities, defaults, presence and watermark; +restore does not regenerate supplies. [Contract and memory evidence](world/ENVIRONMENTAL_FIELDS.md) +and the byte schema document trust, budget and compatibility limits. M5 terrain +formats remain unchanged; combined terrain/biology durability and rate sources are +not implemented. Next: M6.3 read-only derived environment views. diff --git a/docs/adr/0051-optional-environmental-fields.md b/docs/adr/0051-optional-environmental-fields.md new file mode 100644 index 0000000..b2b4e5a --- /dev/null +++ b/docs/adr/0051-optional-environmental-fields.md @@ -0,0 +1,73 @@ +# ADR-0051: Optional finite environmental field pages + +## Status +Accepted for M6.2 bounded in-memory storage and binary-buffer persistence. + +## Context +ADR-0050 defines units and one-voxel habitats. Terrain contains no extractable +nutrients. M6 needs finite stocks without allocating chemistry on every planet voxel. +The M5 codec cannot silently gain environmental state or promise atomic recovery of +independently saved geometry and biology. + +## Decision +Add a separate `FieldStore` to evo::world. Creation fixes 1..4096 lexicographically +ordered habitat sites, one per voxel, each with an explicit local box and substrate +material ID. A nonzero opening ID records host provenance, not authentication. +World/frame, material defaults, mappings, field presence, quantities and command +watermark are serialized together. No site insertion, removal or regeneration API. + +Three material water-capacity defaults (void/rock/regolith) are explicit nonnegative +fixture parameters. They supply no inventory or density. A site's substrate is a +field property, not a live terrain view; M6.4 must reconcile edits when binding stores. +Optional water, dissolved N/P, organic C/N/P/other/energy, incident energy and heat +channels own finite opening quantities. Missing differs from present zero. A field +opening supplies one uniform value or exactly one value per site; every repeated +uniform quantity is counted in global per-element/energy totals, checked against u64. + +Compress each present channel with its first site's value as baseline, and allocate +64-value pages only where another site differs. Pages use stable site order, not +planet allocation. The bounded scalar layout is a scoped choice, not a claim of +optimal compression. Measure uniform and varying memory in tests. + +Implement a same-channel, same-store transfer only: positive amount, distinct valid +sites, fresh nonzero action ID, sufficient balance, capacity and allocation budget. +Stage a replacement channel before atomic publication; success advances the persisted +watermark. Stale action IDs reject, including exact retries (ADR-0024 semantics). +There is no arbitrary setter, deletion, cross-compartment conversion or organism +credit. M6.4 still owns coordinated transactions and idempotent biological outcomes. + +New field snapshot v1 uses canonical explicit little-endian logical values and an +FNV corruption checksum. Restore checks versions/identity/length/checksum and all +creation invariants into a detached store. It accepts no M5 snapshot as field state. +Host byte budgets exclude input/output buffers and allocator overhead; transient +channel replacement and bounded decode workspace are explicitly charged/documented. +Rate-driven sources are not supported: incident energy is only finite stock. Before +adding rates, persist rate identity, denominator, residual and interval watermark in +a new compatible format or explicit migration; never synthesize these on restore. + +## Alternatives Considered +Dense chemistry per voxel violates sparse allocation goals. Derived material supply +would replenish after unloading. Piggybacking fields into M5 without a combined +transaction gives false durability. General adaptive grids and cross-store transfers +are unnecessary for the first storage contract. First-value baselines are simpler +than dictionaries, but an isolated change at site zero can allocate many pages. + +## Benefits +Finite quantities, deterministic round trips, explicit absence and bounded sparse +allocation with no database or new dependency. Geometry formats remain unchanged. + +## Costs +Logical wire arrays favor validation over compression. Fixed site membership caps +the proof; a changing baseline can increase replacement costs. Read access is scalar +by site/channel, not M6.3's tick/revision-tagged environment query. + +## Risks +Host provenance and substrate declarations are trusted inputs. Restoring the same +snapshot twice does not fence process authority. Checksums do not authenticate data. +The snapshot is not automatically published by LocalWorldFiles or part of M5 recovery. + +## Consequences +Document the byte schema and ownership boundary. Test absence/zero, uniform/varying +memory, exhaustion, rollback, global overflow, budgets, canonical continuation, +old/unknown versions and recomputed-checksum malformed inputs. Integrated persistent +region state remains M6.8/M7; no deployment or existing format/golden changes. diff --git a/docs/adr/README.md b/docs/adr/README.md index 0e912b9..0a9c6fc 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -57,3 +57,4 @@ design. No unadopted candidate is a link dependency of the proof. - [ADR-0048: Local publication](0048-local-publication.md) - accepted for M5.7 single-writer snapshot/journal publication and recovery. - [ADR-0049: Bounded world proof](0049-bounded-world-proof.md) - accepted for M5.8 restart regression and cost evidence. - [ADR-0050: Environmental units and coupling](0050-environmental-units-and-coupling.md) - accepted for M6's bounded habitat/accounting contract; no field storage or terrain conversion yet. +- [ADR-0051: Optional environmental fields](0051-optional-environmental-fields.md) - accepted for M6.2 finite sparse pages, local transfers and field snapshot v1. diff --git a/docs/architecture/WORLD_ARCHITECTURE.md b/docs/architecture/WORLD_ARCHITECTURE.md index 71b9a53..2545ad8 100644 --- a/docs/architecture/WORLD_ARCHITECTURE.md +++ b/docs/architecture/WORLD_ARCHITECTURE.md @@ -163,3 +163,13 @@ derived concentrations/moisture, dimensional examples, closed/open accounting, rate residual ownership and rejection of unsupported terrain mass conversions. The implemented helpers are pure computations. Inventory pages, reservations, ownership enforcement, transfer commits and persistence follow in M6.2-6.4. + +## M6.2 optional field storage + +[ADR-0051](../adr/0051-optional-environmental-fields.md) implements a separate +bounded [FieldStore](../world/ENVIRONMENTAL_FIELDS.md). It owns fixed habitat sites, +explicit finite inventories, property-only material defaults and optional uniform/ +sparse scalar pages. Its versioned codec retains all field state and local transfer +watermark, without relying on procedural resource regeneration. M5 LocalWorldFiles +still publishes only terrain state: integrated terrain/fields/biology recovery must +use a later version bundle. No cross-store biological transfer is authorized here. diff --git a/docs/biology/ENERGY_MODEL.md b/docs/biology/ENERGY_MODEL.md index ca2a111..e04a74c 100644 --- a/docs/biology/ENERGY_MODEL.md +++ b/docs/biology/ENERGY_MODEL.md @@ -297,3 +297,9 @@ obligations of M6.2-6.7. Water is conserved `other` in a distinct compartment; this does not authorize converting it into edible material or modeling reactions. Bulk terrain-to-mass conversion remains unsupported pending density/composition and an atomic representation transfer. No existing ledger or biological rules change. + +M6.2 [optional fields](../world/ENVIRONMENTAL_FIELDS.md) now hold explicit water, +dissolved N/P, organic matter/energy, incident-energy and heat inventories. Material +defaults provide capacity, never supply. Local transfers can only relocate the same +channel; water cannot become organic other. Field snapshots preserve depletion. +No rate source, biochemical conversion or transfer to organisms exists yet. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 7fdadbd..65dcbe7 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1683,3 +1683,41 @@ Linux/UBSan and target-cluster checks were not executed locally; existing CI inc the new CTest. There is no new concurrency requiring TSan work. Helpers do not enforce owner identity, interval deduplication or residual persistence; those remain explicit M6.2-6.7 obligations. No deployment or World0 operation occurred. Next: M6.2. + +## M6.2 optional environmental fields - 2026-09-27 + +Added ADR-0051, FieldStore, field snapshot v1 and its byte schema. Optional water, +N/P, organic matter/energy, incident-energy and heat channels have explicit finite +openings. Material defaults specify water capacity only. Uniform baselines with +optional 64-site pages preserve absence versus zero. Same-channel local transfers +stage replacements before commit and persist a strictly increasing command watermark. +There is no resource setter, site regeneration, cross-compartment or organism credit. + +Executed on Windows x64 / MSVC 19.44: + +- `tools/windows-check.ps1 -Preset release -Action check`: 50/50 passed on final code. +- `tools/windows-check.ps1 -Preset analysis -Action check`: clang-tidy 19 and + 50/50 passed on final code. +- `tools/windows-check.ps1 -Preset asan -Action check`: 50/50 passed on final code. +- `tools/windows-check.ps1 -Preset release -Action format`: passed. +- `git diff --check`: passed. + +Initial build diagnostics corrected explicit aggregate initialization and bit widths. +The hostile fixed-underlying-type enum test has a narrowly scoped analyzer suppression +with rationale; actual channel validation remains exercised. + +Tests cover uniform/sparse/varying memory, page seams and release, exhausted sources, +source/capacity/budget/stale-command rollback, absent/present-zero restore, cross-field +conserved-channel overflow, independent dense transfer continuation and all ten fields +at 4096 sites. Maximum logical snapshot is 630880 bytes. A separately constructed +170-byte absent-field fixture checks canonical schema bytes. Every truncation of a +260-byte fixture, invalid/old versions, identity, malformed/resealed mappings and +quantities, oversized snapshots and 256 repaired-checksum mutations are exercised. +Memory observations are in ENVIRONMENTAL_FIELDS.md; accounted bytes are not RSS. + +Existing terrain/simulation formats and goldens are unchanged. Field snapshot v1 +is a buffer codec, not LocalWorldFiles publication or combined terrain/biology +durability. Rate sources and their interval/residual persistence are not enabled. +Linux/UBSan, target-host performance, allocator-failure injection and cluster recovery +were not executed locally. Existing Linux CTest CI includes the new test. No deployment +or World0 operation occurred. Next: M6.3 read-only environment views. diff --git a/docs/world/ENVIRONMENTAL_FIELDS.md b/docs/world/ENVIRONMENTAL_FIELDS.md new file mode 100644 index 0000000..a70eef6 --- /dev/null +++ b/docs/world/ENVIRONMENTAL_FIELDS.md @@ -0,0 +1,88 @@ +# M6.2 optional environmental fields + +[ADR-0051](../adr/0051-optional-environmental-fields.md) scopes `FieldStore`. +Its public API is `include/evo/world/fields.hpp`; it has no I/O, threads or biology. + +## Ownership and creation + +The store owns 1..4096 fixed sites in strict voxel-address order. Site index is a +stable local ID. Sites have valid one-voxel HabitatBoxes and a substrate material +from M5's table v1. Distinct voxels ensure boxes cannot overlap within this store. +The host must prevent ownership overlap with other stores and bind world/frame. +Creating another store is an independent fixture branch, not additional live supply. +Opening ID is nonzero, immutable host provenance; it is not verified externally. + +Water capacity defaults for materials 0/1/2 are supplied explicitly and stored. +Capacity is not water, pore geometry, density or an extraction grant. Water must +not exceed its site's capacity, including transfers and restore. Zero capacity +allows only zero stored water; moisture remains undefined there per M6.1. +Substrate declarations are immutable field metadata. M6.4 must establish a coupled +geometry revision before terrain edits can change habitat capacity or substrate. + +Optional channels: water; dissolved N, P; organic C, N, P, other, chemical energy; +incident energy; heat. Scalar matter uses fg and energy uses pJ. Channel identity +preserves compartments. Water contributes to `other`, dissolved/organic components +to their named elements, and all energy compartments to energy. The sum of each +conserved channel must fit u64 at creation/restore. Organic mass and total biomass +are derived; there is no second biomass inventory. Missing channels return `missing`, +not zero. A present all-zero field stays present through encoding and restore. + +Opening spans contain either one value repeated at all sites or exactly site-count +values. Channels must be supplied in increasing enum order without duplicates. +No default stock is generated from a material, absent page, restore or read. +No sites/fields can be added after creation in v1. + +## Storage, operations and bounds + +Each present channel uses site zero's scalar as baseline. A 64-site page allocates +64 u64 values only if any valid value differs; the last page's padding is zero. +No pages are allocated for a uniform field. Memory accounting is +`sizeof(FieldStore) + site_count*sizeof(FieldSite) + allocated_pages*512`. +An operation reserves an additional 32768-byte scalar scratch allowance and charges +old plus new channel pages during replacement; this is accounted memory, not RSS. +Caller input/output buffers, allocator headers and small stack metadata are excluded. +Restore additionally uses at most 327680 bytes of dense field staging, a second +`site_count*sizeof(FieldSite)` mapping array and at most ten opening-span records, +outside the resident budget. All counts are bounded before those allocations. + +`read(site, channel)` returns the owned scalar in that channel's units; it grants +no consumption permission. M6.3 will add derived footprint/tick/revision views. +`transfer(action, channel, from, to, amount)` moves a positive quantity between +distinct sites within one present field. It checks source, overflow, water capacity, +fresh nonzero command and replacement budget before publishing. Rejection preserves +all quantities and watermark. Same/older commands reject, never execute again. +This storage primitive cannot feed an organism, convert compartments or create heat. +It transfers no terrain volume. M6.4 supplies coordinated biological transactions. + +Empty input, bad material, invalid box, duplicate voxel/channel, mismatched span, +sum overflow and insufficient budgets fail explicitly. Allocation exceptions +propagate to the host; candidates are detached until success. Stores are noncopyable +and nonmovable; scalar reads return values and retain no lifetime-sensitive views. + +## Persistence and compatibility + +[Snapshot schema](../../schemas/world-fields-v1.md) encodes logical quantities +independently of pages. It includes world/frame, nonzero opening identity, material +defaults, mapping, channel presence and transfer watermark. Canonical decode/re-encode +must match exactly. Runtime byte budgets and pointers are not persisted. +No old/unknown version is migrated implicitly; checksums detect accidental corruption +only. Restoring a field snapshot never calls the terrain generator. + +Snapshot buffers are not durable publication. M5 LocalWorldFiles does not save these +fields and must not be advertised as recovering a coupled environment. M6.8/M7 must +publish a version bundle and ownership boundary across terrain, fields and biology. +There are no configured rate sources in v1, so no fractional rate state exists to +restore. Introducing rates requires explicit serialized residual/interval state. + +Tests measure uniform, sparse and fully varying resident footprints, exhaust a +finite source into another site, reject overspending without mutation, restore the +depleted state and continue deterministically. Codec tests cover truncation, checksum, +version, identity, shape, channel order, capacity and total-overflow rejection, and +bounded repaired-checksum mutation smoke. Next: M6.3 environment read views. + +Measured Windows x64/MSVC 19.44 fixture (130 sites): uniform or absent fields use +15768 accounted resident bytes; one varying 64-site page uses 16280; three varying +pages use 17304. A single present channel serializes to 10756 bytes regardless of +resident layout. These are owned-storage observations, not peak RSS or planetary +capacity claims. Test assertions use relative page costs so ABI metadata differences +do not falsely fail another supported platform. diff --git a/docs/world/ENVIRONMENTAL_UNITS.md b/docs/world/ENVIRONMENTAL_UNITS.md index 79f5841..d1c3955 100644 --- a/docs/world/ENVIRONMENTAL_UNITS.md +++ b/docs/world/ENVIRONMENTAL_UNITS.md @@ -131,3 +131,8 @@ M6.2 introduces optional fields, explicit initial inventories and versioned pers M6.3 read views; M6.4 coordinated ownership/transfer validation; M6.5-6.8 integrated processes, source budgets and replay. Density/composition conversion, chemical reactions, global atmosphere/hydrology and cross-region transfer remain unsupported. + +M6.2 now implements [optional fields](ENVIRONMENTAL_FIELDS.md) and independent field +snapshots under ADR-0051. Incident energy is finite stock only; no configured rates +or fractional source state exist in field format v1. Enabling rates will require +explicit versioned residual/interval persistence before any integration can commit. diff --git a/include/evo/world/fields.hpp b/include/evo/world/fields.hpp new file mode 100644 index 0000000..59d1301 --- /dev/null +++ b/include/evo/world/fields.hpp @@ -0,0 +1,105 @@ +#pragma once +#include "evo/world/chunks.hpp" +#include "evo/world/environment_units.hpp" +#include +#include +#include +#include +#include +#include + +namespace evo::world { +enum class Field : std::uint8_t { + water, + nitrogen, + phosphorus, + organic_carbon, + organic_nitrogen, + organic_phosphorus, + organic_other, + organic_energy, + incident_energy, + heat +}; +inline constexpr std::size_t field_count = 10; +struct FieldSite { + VoxelAddress voxel; + HabitatBox box; + MaterialId substrate; +}; +struct FieldDefaults { + std::array water_capacity{}; +}; +struct FieldOpening { + Field field; + // One value repeated at every site, or exactly site_count values; borrowed during create. + std::span values; +}; +enum class FieldError : std::uint8_t { + config, + mapping, + channel, + missing, + site, + capacity, + overflow, + budget, + stale_command, + invalid_transfer, + insufficient, + format, + version, + identity, + checksum +}; +class FieldStore { + public: + static constexpr std::size_t max_sites = 4096; + static constexpr std::size_t scratch_bytes = 32768; + static constexpr std::size_t max_snapshot_bytes = std::size_t{1024} * 1024; + [[nodiscard]] static std::expected, FieldError> + create(WorldIdentity identity, std::uint64_t opening_id, FieldDefaults defaults, + std::span sites, std::span fields, + std::size_t byte_budget); + FieldStore(const FieldStore&) = delete; + FieldStore& operator=(const FieldStore&) = delete; + FieldStore(FieldStore&&) = delete; + FieldStore& operator=(FieldStore&&) = delete; + [[nodiscard]] std::expected read(std::size_t site, + Field field) const noexcept; + [[nodiscard]] std::expected transfer(std::uint64_t command, Field field, + std::size_t from, std::size_t to, + std::uint64_t amount); + [[nodiscard]] WorldBytes snapshot() const; + [[nodiscard]] static std::expected, FieldError> + restore(std::span bytes, WorldIdentity identity, std::size_t byte_budget); + [[nodiscard]] std::size_t accounted_bytes() const noexcept { + return bytes_; + } + [[nodiscard]] std::uint64_t last_command() const noexcept { + return command_; + } + [[nodiscard]] std::span sites() const noexcept { + return {sites_.get(), count_}; + } + + private: + using Page = std::array; + struct Channel { + bool present{}; + std::uint64_t baseline{}; + std::array, max_sites / 64> pages; + [[nodiscard]] std::uint64_t get(std::size_t site) const noexcept; + [[nodiscard]] std::size_t bytes() const noexcept; + }; + FieldStore() = default; + static std::size_t page_bytes(std::span values) noexcept; + static Channel encode(std::span values); + WorldIdentity identity_{}; + std::uint64_t opening_{}, command_{}; + FieldDefaults defaults_{}; + std::size_t count_{}, budget_{}, bytes_{}; + std::unique_ptr sites_; + std::array fields_; +}; +} // namespace evo::world diff --git a/schemas/world-fields-v1.md b/schemas/world-fields-v1.md new file mode 100644 index 0000000..73cf783 --- /dev/null +++ b/schemas/world-fields-v1.md @@ -0,0 +1,35 @@ +# Environmental field snapshot v1 + +All integers explicit little endian; signed coordinates use two's-complement u64 +encoding. No struct padding. Unknown formats/units/material versions reject. + +| Offset | Type | Meaning | +|---:|---|---| +| 0 | 8 bytes | ASCII AEVOFLD1 | +| 8 | u32 | format=1 | +| 12 | u32 | total length including checksum | +| 16,24 | u64 each | nonzero world, frame | +| 32,36 | u32 each | environmental units=1, material table=1 | +| 40,48 | u64 each | nonzero opening provenance, last transfer command (initially 0) | +| 56 | u32 | sites, 1..4096 | +| 60 | u32 | presence bits 0..9 only, enum order in fields.hpp | +| 64 | 3*u64 | water capacities in fg for material 0,1,2 | +| 88 | site_count*74 bytes | sorted site records | +| following | present_count*site_count*u64 | scalar logical arrays, increasing channel order | +| final 8 | u64 | FNV-1a of all preceding bytes; corruption detection only | + +Each site: signed X/Y/Z (24 bytes), box origin X/Y/Z and width/height/depth in um +(48 bytes), material ID u16. Strictly increasing voxel addresses; valid one-voxel +box and material 0..2. No duplicate habitat in a voxel. Field arrays contain finite +per-site quantities, including repeated uniform values; absent differs from zero. +Water capacity and global per-energy/element sums are validated on restore. + +Length must equal `96 + sites*(74 + 8*present)` (maximum 630880), also bounded by +the API's 1 MiB envelope. All structural counts/lengths are checked before staging +allocations. Canonical encoding omits storage layout, byte budget and pointers. +No rates/residuals exist in v1: incident energy is finite stock only. Adding rate +sources requires explicit versioned persistence, not default construction on restore. +M5 world snapshots are a distinct format and cannot stand in for missing fields. + +Codec buffers do not publish durable state. Field/terrain/biology consistency and +recovery bundles remain later gates; LocalWorldFiles handles M5 terrain only. diff --git a/src/world/fields.cpp b/src/world/fields.cpp new file mode 100644 index 0000000..18be2da --- /dev/null +++ b/src/world/fields.cpp @@ -0,0 +1,291 @@ +#include "evo/world/fields.hpp" +#include +#include +#include +#include + +namespace evo::world { +namespace { +constexpr auto ceiling = std::numeric_limits::max(); +constexpr std::array conserved_channel{4, 2, 3, 1, 2, 3, 4, 0, 0, 0}; +std::size_t index(Field field) noexcept { + return static_cast(field); +} +std::uint64_t value_at(std::span values, std::size_t i) noexcept { + return values[values.size() == 1 ? 0 : i]; +} +} // namespace +std::uint64_t FieldStore::Channel::get(std::size_t site) const noexcept { + const auto& page = pages[site / 64]; + return page ? (*page)[site % 64] : baseline; +} +std::size_t FieldStore::Channel::bytes() const noexcept { + std::size_t total{}; + for (const auto& page : pages) + if (page) + total += sizeof(Page); + return total; +} +std::size_t FieldStore::page_bytes(std::span values) noexcept { + std::size_t total{}; + for (std::size_t start = 0; start < values.size(); start += 64) { + const auto end = std::min(start + 64, values.size()); + for (auto i = start; i < end; ++i) { + if (values[i] != values[0]) { + total += sizeof(Page); + break; + } + } + } + return total; +} +FieldStore::Channel FieldStore::encode(std::span values) { + Channel out; + out.present = true; + out.baseline = values[0]; + for (std::size_t start = 0; start < values.size(); start += 64) { + const auto end = std::min(start + 64, values.size()); + bool changed{}; + for (auto i = start; i < end; ++i) + changed |= values[i] != out.baseline; + if (!changed) + continue; + auto page = std::make_unique(); + for (auto i = start; i < end; ++i) + (*page)[i - start] = values[i]; + out.pages[start / 64] = std::move(page); + } + return out; +} +std::expected, FieldError> +FieldStore::create(WorldIdentity identity, std::uint64_t opening_id, FieldDefaults defaults, + std::span sites, std::span fields, + std::size_t byte_budget) { + if (identity.world == 0 || identity.frame == 0 || opening_id == 0 || sites.empty() || + sites.size() > max_sites || fields.size() > field_count) + return std::unexpected{FieldError::config}; + for (std::size_t i = 0; i < sites.size(); ++i) { + const auto& s = sites[i]; + if (!split(s.voxel, base_chunk_edge) || !measure_habitat(s.box) || + s.substrate.value >= defaults.water_capacity.size() || + (i != 0 && !(sites[i - 1].voxel < s.voxel))) + return std::unexpected{FieldError::mapping}; + } + std::size_t bytes = sizeof(FieldStore) + sites.size() * sizeof(FieldSite); + std::array totals{}; + std::size_t prior{}; + bool first = true; + for (const auto& f : fields) { + const auto k = index(f.field); + if (k >= field_count || (!first && k <= prior) || + (f.values.size() != 1 && f.values.size() != sites.size())) + return std::unexpected{FieldError::channel}; + first = false; + prior = k; + bytes += page_bytes(f.values); + for (std::size_t i = 0; i < sites.size(); ++i) { + const auto value = value_at(f.values, i); + if (f.field == Field::water && + value > defaults.water_capacity[sites[i].substrate.value].value) + return std::unexpected{FieldError::capacity}; + auto& total = totals[conserved_channel[k]]; + if (value > ceiling - total) + return std::unexpected{FieldError::overflow}; + total += value; + } + } + if (bytes > byte_budget || scratch_bytes > byte_budget - bytes) + return std::unexpected{FieldError::budget}; + auto out = std::unique_ptr(new FieldStore); + out->identity_ = identity; + out->opening_ = opening_id; + out->defaults_ = defaults; + out->count_ = sites.size(); + out->budget_ = byte_budget; + out->bytes_ = bytes; + out->sites_ = std::make_unique(sites.size()); + std::copy(sites.begin(), sites.end(), out->sites_.get()); + for (const auto& f : fields) + out->fields_[index(f.field)] = encode(f.values); + return out; +} +std::expected FieldStore::read(std::size_t site, + Field field) const noexcept { + if (site >= count_) + return std::unexpected{FieldError::site}; + if (index(field) >= field_count) + return std::unexpected{FieldError::channel}; + if (!fields_[index(field)].present) + return std::unexpected{FieldError::missing}; + return fields_[index(field)].get(site); +} +std::expected FieldStore::transfer(std::uint64_t command, Field field, + std::size_t from, std::size_t to, + std::uint64_t amount) { + if (command == 0 || command <= command_) + return std::unexpected{FieldError::stale_command}; + if (amount == 0 || from == to) + return std::unexpected{FieldError::invalid_transfer}; + const auto source = read(from, field), destination = read(to, field); + if (!source) + return std::unexpected{source.error()}; + if (!destination) + return std::unexpected{destination.error()}; + if (amount > *source) + return std::unexpected{FieldError::insufficient}; + if (amount > ceiling - *destination) + return std::unexpected{FieldError::overflow}; + if (field == Field::water && + *destination + amount > defaults_.water_capacity[sites_[to].substrate.value].value) + return std::unexpected{FieldError::capacity}; + std::array values{}; + auto& channel = fields_[index(field)]; + for (std::size_t i = 0; i < count_; ++i) + values[i] = channel.get(i); + values[from] -= amount; + values[to] += amount; + const auto logical = std::span{values}.first(count_); + const auto needed = page_bytes(logical); + if (needed > budget_ - bytes_ - scratch_bytes) + return std::unexpected{FieldError::budget}; + auto replacement = encode(logical); + bytes_ = bytes_ - channel.bytes() + needed; + channel = std::move(replacement); + command_ = command; + return {}; +} + +namespace { +constexpr std::uint64_t magic = 0x31444c464f564541ULL; // AEVOFLD1 +std::uint64_t checksum(std::span bytes) noexcept { + std::uint64_t h = 14695981039346656037ULL; + for (auto b : bytes) + h = (h ^ b) * 1099511628211ULL; + return h; +} +void put(WorldBytes& out, std::uint64_t value, unsigned width) { + for (unsigned i = 0; i < width; ++i) { + out.push_back(static_cast(value & 255U)); + value >>= 8U; + } +} +struct Reader { + std::span bytes; + std::size_t at{}; + bool ok{true}; + std::uint64_t get(unsigned width) noexcept { + if (!ok || width > bytes.size() - at) { + ok = false; + return 0; + } + std::uint64_t value{}; + for (unsigned i = 0; i < width; ++i) + value |= std::uint64_t{bytes[at++]} << (8U * i); + return value; + } + std::int64_t signed64() noexcept { + const auto n = get(8); + return n <= static_cast(std::numeric_limits::max()) + ? static_cast(n) + : -1 - static_cast(~n); + } +}; +} // namespace +WorldBytes FieldStore::snapshot() const { + std::uint32_t mask{}; + std::size_t present{}; + for (std::size_t k = 0; k < field_count; ++k) + if (fields_[k].present) { + mask |= 1U << k; + ++present; + } + const auto length = 96 + count_ * (74 + 8 * present); + WorldBytes out; + out.reserve(length); + put(out, magic, 8); + put(out, 1, 4); + put(out, length, 4); + put(out, identity_.world, 8); + put(out, identity_.frame, 8); + put(out, environmental_units_version, 4); + put(out, 1, 4); + put(out, opening_, 8); + put(out, command_, 8); + put(out, count_, 4); + put(out, mask, 4); + for (const auto cap : defaults_.water_capacity) + put(out, cap.value, 8); + for (const auto& site : sites()) { + put(out, static_cast(site.voxel.x), 8); + put(out, static_cast(site.voxel.y), 8); + put(out, static_cast(site.voxel.z), 8); + for (const auto value : + {site.box.x, site.box.y, site.box.z, site.box.width, site.box.height, site.box.depth}) + put(out, value.value, 8); + put(out, site.substrate.value, 2); + } + for (const auto& field : fields_) + if (field.present) + for (std::size_t i = 0; i < count_; ++i) + put(out, field.get(i), 8); + put(out, checksum(out), 8); + return out; +} +std::expected, FieldError> +FieldStore::restore(std::span bytes, WorldIdentity identity, + std::size_t byte_budget) { + if (bytes.size() < 96 || bytes.size() > max_snapshot_bytes) + return std::unexpected{FieldError::format}; + Reader r{bytes.first(bytes.size() - 8)}; + if (r.get(8) != magic) + return std::unexpected{FieldError::format}; + if (r.get(4) != 1) + return std::unexpected{FieldError::version}; + if (r.get(4) != bytes.size()) + return std::unexpected{FieldError::format}; + Reader tail{bytes.last(8)}; + if (checksum(r.bytes) != tail.get(8)) + return std::unexpected{FieldError::checksum}; + const WorldIdentity stored{r.get(8), r.get(8)}; + if (identity.world == 0 || identity.frame == 0 || identity != stored) + return std::unexpected{FieldError::identity}; + if (r.get(4) != environmental_units_version || r.get(4) != 1) + return std::unexpected{FieldError::version}; + const auto opening = r.get(8), command = r.get(8), count = r.get(4), mask = r.get(4); + if (count == 0 || count > max_sites || mask >= (1U << field_count)) + return std::unexpected{FieldError::format}; + std::size_t present{}; + for (std::size_t k = 0; k < field_count; ++k) + if ((mask & (std::uint64_t{1} << k)) != 0) + ++present; + if (bytes.size() != 96 + count * (74 + 8 * present)) + return std::unexpected{FieldError::format}; + FieldDefaults defaults; + for (auto& cap : defaults.water_capacity) + cap.value = r.get(8); + std::vector sites(static_cast(count)); + for (auto& site : sites) { + site.voxel = {r.signed64(), r.signed64(), r.signed64()}; + site.box = {{r.get(8)}, {r.get(8)}, {r.get(8)}, {r.get(8)}, {r.get(8)}, {r.get(8)}}; + site.substrate = {static_cast(r.get(2))}; + } + std::array, field_count> data; + std::vector fields; + fields.reserve(present); + for (std::size_t k = 0; k < field_count; ++k) { + if ((mask & (std::uint64_t{1} << k)) == 0) + continue; + data[k].resize(static_cast(count)); + for (auto& v : data[k]) + v = r.get(8); + fields.push_back({static_cast(k), data[k]}); + } + if (!r.ok || r.at != r.bytes.size()) + return std::unexpected{FieldError::format}; + auto out = create(identity, opening, defaults, sites, fields, byte_budget); + if (!out) + return out; + (*out)->command_ = command; + return out; +} +} // namespace evo::world diff --git a/tests/world_fields_tests.cpp b/tests/world_fields_tests.cpp new file mode 100644 index 0000000..0afad60 --- /dev/null +++ b/tests/world_fields_tests.cpp @@ -0,0 +1,305 @@ +#include "evo/world/fields.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::world; +constexpr WorldIdentity identity{7, 9}; +constexpr std::size_t budget = 2'000'000; +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("world fields line " + std::to_string(at.line())); +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) +template bool refused(const std::expected& result, FieldError error) { + return !result && result.error() == error; +} +std::vector sites(std::size_t count) { + std::vector out(count); + for (std::size_t i = 0; i < count; ++i) + out[i] = {{static_cast(i), 0, -1}, {{0}, {0}, {0}, {10}, {20}, {3}}, {1}}; + return out; +} +FieldDefaults defaults() { + return {{evo::accounting::Femtograms{0}, evo::accounting::Femtograms{1000}, + evo::accounting::Femtograms{2000}}}; +} +std::unique_ptr make(std::span mapping, + std::span opening, + std::size_t limit = budget) { + auto out = FieldStore::create(identity, 11, defaults(), mapping, opening, limit); + CHECK(out); + return std::move(*out); +} +void put(WorldBytes& bytes, std::size_t offset, std::uint64_t value, unsigned width) { + for (unsigned i = 0; i < width; ++i) { + bytes.at(offset + i) = static_cast(value & 255U); + value >>= 8U; + } +} +void seal(WorldBytes& bytes) { + put(bytes, 12, bytes.size(), 4); + std::uint64_t h = 14695981039346656037ULL; + for (std::size_t i = 0; i < bytes.size() - 8; ++i) + h = (h ^ bytes[i]) * 1099511628211ULL; + put(bytes, bytes.size() - 8, h, 8); +} +void storage_and_exhaustion() { + const auto mapping = sites(130); + const std::uint64_t zero = 0, seven = 7; + auto absent = make(mapping, {}); + const FieldOpening uniform[]{{Field::water, {&seven, 1}}, {Field::nitrogen, {&zero, 1}}}; + auto compact = make(mapping, uniform); + CHECK(absent->accounted_bytes() == compact->accounted_bytes()); + CHECK(refused(absent->read(0, Field::water), FieldError::missing)); + CHECK(compact->read(129, Field::nitrogen) == 0); + CHECK(compact->read(129, Field::water) == 7); + std::vector values(130, seven); + values.back() = 9; + const FieldOpening sparse_input[]{{Field::water, values}}; + auto sparse = make(mapping, sparse_input); + CHECK(sparse->accounted_bytes() == compact->accounted_bytes() + 512); + for (std::size_t i = 0; i < values.size(); ++i) + CHECK(sparse->read(i, Field::water) == values[i]); + for (std::size_t i = 0; i < values.size(); ++i) + values[i] = i; + auto varied = make(mapping, sparse_input); + CHECK(varied->accounted_bytes() == compact->accounted_bytes() + 1536); + CHECK(varied->snapshot().size() == 96 + 130 * (74 + 8)); + std::printf("field bytes: uniform=%zu sparse=%zu varying=%zu\n", compact->accounted_bytes(), + sparse->accounted_bytes(), varied->accounted_bytes()); + const auto prior = varied->snapshot(); + CHECK(refused(varied->transfer(1, Field::water, 64, 63, 65), FieldError::insufficient)); + CHECK(varied->snapshot() == prior); + CHECK(varied->transfer(1, Field::water, 64, 63, 64)); + CHECK(varied->read(64, Field::water) == 0); + CHECK(varied->read(63, Field::water) == 127); + const auto depleted = varied->snapshot(); + CHECK(refused(varied->transfer(2, Field::water, 64, 63, 1), FieldError::insufficient)); + CHECK(refused(varied->transfer(1, Field::water, 64, 63, 64), FieldError::stale_command)); + CHECK(varied->snapshot() == depleted); + auto restored = FieldStore::restore(depleted, identity, budget); + CHECK(restored && (*restored)->snapshot() == depleted); + CHECK((*restored)->read(64, Field::water) == 0); + CHECK((*restored)->transfer(2, Field::water, 63, 64, 64)); + CHECK(varied->transfer(2, Field::water, 63, 64, 64)); + CHECK((*restored)->snapshot() == varied->snapshot()); + std::uint64_t total{}; + for (std::size_t i = 0; i < 130; ++i) { + CHECK(varied->read(i, Field::water) == i); + total += *varied->read(i, Field::water); + } + CHECK(total == 8385); + CHECK(compact->transfer(1, Field::water, 128, 129, 7)); + CHECK(compact->accounted_bytes() == absent->accounted_bytes() + 512); + CHECK(compact->transfer(2, Field::water, 129, 128, 7)); + CHECK(compact->accounted_bytes() == absent->accounted_bytes()); + const auto tight_budget = compact->accounted_bytes() + FieldStore::scratch_bytes; + auto tight = make(mapping, uniform, tight_budget); + const auto before = tight->snapshot(); + CHECK(refused(tight->transfer(1, Field::water, 0, 1, 1), FieldError::budget)); + CHECK(tight->snapshot() == before); + CHECK(refused(FieldStore::restore(before, identity, tight_budget - 1), FieldError::budget)); + auto absent_copy = FieldStore::restore(absent->snapshot(), identity, budget); + CHECK(absent_copy && refused((*absent_copy)->read(1, Field::water), FieldError::missing)); + auto zero_copy = FieldStore::restore(compact->snapshot(), identity, budget); + CHECK(zero_copy && (*zero_copy)->read(1, Field::nitrogen) == 0); +} +void invalid_openings_and_transfers() { + auto mapping = sites(2); + const std::uint64_t zero = 0, full = 1000, one = 1; + const FieldOpening water[]{{Field::water, {&full, 1}}}; + auto store = make(mapping, water); + const auto before = store->snapshot(); + CHECK(refused(store->transfer(1, Field::water, 0, 1, 1), FieldError::capacity)); + CHECK(refused(store->transfer(1, Field::water, 0, 0, 1), FieldError::invalid_transfer)); + CHECK(refused(store->transfer(1, Field::water, 0, 1, 0), FieldError::invalid_transfer)); + CHECK(refused(store->transfer(0, Field::water, 0, 1, 1), FieldError::stale_command)); + CHECK(refused(store->transfer(1, Field::water, 0, 2, 1), FieldError::site)); + CHECK(refused(store->transfer(1, Field::nitrogen, 0, 1, 1), FieldError::missing)); + // Fixed uint8_t underlying type permits hostile raw enum values; validate at the API. + // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange) + CHECK(refused(store->read(0, static_cast(255)), FieldError::channel)); + CHECK(store->snapshot() == before); + CHECK(refused(FieldStore::create(identity, 0, defaults(), mapping, water, budget), + FieldError::config)); + CHECK(refused(FieldStore::create({}, 11, defaults(), mapping, water, budget), + FieldError::config)); + const FieldOpening duplicate[]{{Field::water, {&zero, 1}}, {Field::water, {&zero, 1}}}; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, duplicate, budget), + FieldError::channel)); + const FieldOpening invalid[]{{Field::water, {}}}; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, invalid, budget), + FieldError::channel)); + mapping[1].voxel = mapping[0].voxel; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, water, budget), + FieldError::mapping)); + mapping = sites(2); + mapping[0].box.depth.value = 0; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, water, budget), + FieldError::mapping)); + mapping = sites(2); + mapping[0].substrate = {3}; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, water, budget), + FieldError::mapping)); + mapping = sites(2); + const FieldOpening repeated_overflow[]{{Field::nitrogen, {&maximum, 1}}}; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, repeated_overflow, budget), + FieldError::overflow)); + const std::uint64_t max_once[]{maximum, 0}; + for (const auto pair : {std::array{Field::nitrogen, Field::organic_nitrogen}, + std::array{Field::phosphorus, Field::organic_phosphorus}, + std::array{Field::organic_energy, Field::heat}}) { + const FieldOpening overflow[]{{pair[0], max_once}, {pair[1], {&one, 1}}}; + CHECK(refused(FieldStore::create(identity, 11, defaults(), mapping, overflow, budget), + FieldError::overflow)); + } + const FieldOpening organic[]{{Field::organic_other, {&one, 1}}}; + auto isolated = make(mapping, organic); + CHECK(refused(isolated->read(0, Field::water), FieldError::missing)); +} +void codec_validation() { + const auto mapping = sites(2); + const std::uint64_t amount = 4; + const FieldOpening input[]{{Field::water, {&amount, 1}}}; + auto store = make(mapping, input); + const auto bytes = store->snapshot(); + CHECK(bytes.size() == 260); + for (std::size_t length = 0; length < bytes.size(); ++length) + CHECK(!FieldStore::restore(std::span{bytes}.first(length), identity, budget)); + CHECK(refused(FieldStore::restore(bytes, {7, 10}, budget), FieldError::identity)); + auto changed = bytes; + changed[200] ^= 1; + CHECK(refused(FieldStore::restore(changed, identity, budget), FieldError::checksum)); + for (const auto offset : {8U, 32U, 36U}) { + for (const auto version : {0U, 2U}) { + changed = bytes; + put(changed, offset, version, 4); + seal(changed); + CHECK(refused(FieldStore::restore(changed, identity, budget), FieldError::version)); + } + } + for (const auto mutation : {std::array{40, 0, 8}, // opening ID + {56, 4097, 4}, + {60, 1024, 4}, // count/mask + {88, 1048576, 8}, + {112, 1000000, 8}, // address/box + {160, 3, 2}, + {236, 1001, 8}}) { // material/water + changed = bytes; + put(changed, static_cast(mutation[0]), mutation[1], + static_cast(mutation[2])); + seal(changed); + CHECK(!FieldStore::restore(changed, identity, budget)); + } + changed = bytes; + std::copy_n(changed.begin() + 88, 24, changed.begin() + 162); + seal(changed); + CHECK(refused(FieldStore::restore(changed, identity, budget), FieldError::mapping)); + changed = bytes; + changed.push_back(0); + seal(changed); + CHECK(!FieldStore::restore(changed, identity, budget)); + // Repaired checksums reach semantic parsing. Accepted inputs must be canonical. + for (std::size_t n = 0; n < 256; ++n) { + changed = bytes; + changed[(n * 37) % (bytes.size() - 8)] ^= static_cast(1U << (n % 8)); + seal(changed); + auto decoded = FieldStore::restore(changed, identity, budget); + if (decoded) + CHECK((*decoded)->snapshot() == changed); + } + // Independent byte construction of an absent-field, single-site fixture. + const auto one = sites(1); + auto empty = make(one, {}); + WorldBytes expected(170, 0); + const std::string magic = "AEVOFLD1"; + std::copy(magic.begin(), magic.end(), expected.begin()); + put(expected, 8, 1, 4); + put(expected, 16, 7, 8); + put(expected, 24, 9, 8); + put(expected, 32, 1, 4); + put(expected, 36, 1, 4); + put(expected, 40, 11, 8); + put(expected, 56, 1, 4); + put(expected, 72, 1000, 8); + put(expected, 80, 2000, 8); + put(expected, 104, maximum, 8); + put(expected, 136, 10, 8); + put(expected, 144, 20, 8); + put(expected, 152, 3, 8); + put(expected, 160, 1, 2); + seal(expected); + CHECK(empty->snapshot() == expected); +} +void all_channels_and_limits() { + const auto mapping = sites(FieldStore::max_sites); + std::array, field_count> values; + std::array openings; + for (std::size_t k = 0; k < field_count; ++k) { + values[k].resize(mapping.size()); + for (std::size_t i = 0; i < mapping.size(); ++i) + values[k][i] = (i + k) % 100; + openings[k] = {static_cast(k), values[k]}; + } + auto store = make(mapping, openings); + const auto encoded = store->snapshot(); + CHECK(encoded.size() == 630880); + auto restored = FieldStore::restore(encoded, identity, budget); + CHECK(restored && (*restored)->snapshot() == encoded); + for (std::size_t k = 0; k < field_count; ++k) + for (std::size_t i = 0; i < mapping.size(); ++i) + CHECK((*restored)->read(i, static_cast(k)) == values[k][i]); + // Independent dense model across page seams and all compartment types. + for (std::uint64_t command = 1; command <= 100; ++command) { + const auto k = static_cast(command % field_count); + const auto from = static_cast((command * 63) % mapping.size()); + const auto to = (from + 1) % mapping.size(); + const auto amount = values[k][from]; + if (amount == 0) + continue; + CHECK((*restored)->transfer(command, static_cast(k), from, to, amount)); + values[k][from] = 0; + values[k][to] += amount; + CHECK((*restored)->read(from, static_cast(k)) == 0); + CHECK((*restored)->read(to, static_cast(k)) == values[k][to]); + } + auto continued = FieldStore::restore((*restored)->snapshot(), identity, budget); + CHECK(continued && (*continued)->last_command() == (*restored)->last_command()); + for (std::size_t k = 0; k < field_count; ++k) + for (std::size_t i = 0; i < mapping.size(); ++i) + CHECK((*continued)->read(i, static_cast(k)) == values[k][i]); + const auto too_many = sites(FieldStore::max_sites + 1); + CHECK(refused(FieldStore::create(identity, 11, defaults(), too_many, {}, budget), + FieldError::config)); + CHECK( + refused(FieldStore::create(identity, 11, defaults(), {}, {}, budget), FieldError::config)); + WorldBytes oversized(FieldStore::max_snapshot_bytes + 1); + CHECK(refused(FieldStore::restore(oversized, identity, budget), FieldError::format)); + // Global overflow below a valid checksum and structurally correct shape. + auto corrupt = encoded; + const auto data_start = std::size_t{88} + mapping.size() * 74; + put(corrupt, data_start + mapping.size() * 8, maximum, 8); // nitrogen[0] + seal(corrupt); + CHECK(refused(FieldStore::restore(corrupt, identity, budget), FieldError::overflow)); +} +} // namespace +int main() try { + storage_and_exhaustion(); + invalid_openings_and_transfers(); + codec_validation(); + all_channels_and_limits(); + return 0; +} catch (const std::exception& e) { + std::fprintf(stderr, "%s\n", e.what()); + return 1; +} catch (...) { + return 1; +}