From af293b8b50cbb506a49dfff10c6cc92307e16aca Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 20 Sep 2026 08:56:46 -0400 Subject: [PATCH] Add finite producer capture and resource-limited growth process --- CMakeLists.txt | 10 ++ docs/ROADMAP.md | 5 +- docs/STATUS.md | 14 +- docs/adr/0025-finite-producer-process.md | 76 +++++++++ docs/adr/README.md | 1 + docs/architecture/SYSTEM_OVERVIEW.md | 3 +- docs/biology/ENERGY_MODEL.md | 29 ++++ docs/engineering/VALIDATION.md | 18 ++ include/evo/processes/producer.hpp | 64 ++++++++ src/processes/producer.cpp | 85 ++++++++++ tests/producer_tests.cpp | 199 +++++++++++++++++++++++ 11 files changed, 499 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0025-finite-producer-process.md create mode 100644 include/evo/processes/producer.hpp create mode 100644 src/processes/producer.cpp create mode 100644 tests/producer_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5f3de3f..98f52c4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,12 +40,22 @@ target_include_directories(evo_accounting PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in target_compile_features(evo_accounting PUBLIC cxx_std_23) evo_owned_target(evo_accounting) +add_library(evo_processes STATIC src/processes/producer.cpp) +add_library(evo::processes ALIAS evo_processes) +target_link_libraries(evo_processes PUBLIC evo::accounting) +evo_owned_target(evo_processes) + add_executable(evo-sim apps/evo-sim/main.cpp) target_link_libraries(evo-sim PRIVATE evo::simulation) evo_owned_target(evo-sim) include(CTest) if(BUILD_TESTING) + add_executable(evo-producer-tests tests/producer_tests.cpp) + target_link_libraries(evo-producer-tests PRIVATE evo::processes) + evo_owned_target(evo-producer-tests) + add_test(NAME producer-contracts COMMAND evo-producer-tests) + set_tests_properties(producer-contracts PROPERTIES TIMEOUT 60) add_executable(evo-ledger-tests tests/ledger_tests.cpp) target_link_libraries(evo-ledger-tests PRIVATE evo::accounting) evo_owned_target(evo-ledger-tests) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 3f9b875..1bc0ce9 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -44,7 +44,7 @@ this proof. Production indexing awaits actual interaction workloads. | ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | |---|---|---|---|---|---| | 2.1 Ratify accounting units and ledger | accounting/ledger.*, ENERGY_MODEL, ADR-0024 | M1, units ADR | Exact local units/ranges, finite inventories and atomic ordered transfers | Unit-type separation, rollback/overflow/replay, million-transaction independent balance checks | Mistaking conservation for valid biology | -| 2.2 Add abiotic source and producer | biology/metabolism, world/resources | 2.1 | Energy enters only through named source; uptake bounded by resources | Closed-box balance plus external source accounting | Arbitrary growth subsidies | +| 2.2 Add abiotic source and producer | processes/producer.*, ADR-0025 | 2.1 | Finite source capture, whole growth recipes, carried rate remainders and atomic owned ledger | Closed-box audit, independent fractional reference, finite-resource and arithmetic limits | Confusing synthetic process with organism biology | | 2.3 Add consumer intentions and ingestion | biology/digestion, simulation/spatial | 2.2, 1.7 | Shared validated action path transfers matter/energy | Predator/prey transfer and dead-action rejection | Consuming twice in same tick | | 2.4 Death and decomposition | biology/lifecycle, ecology | 2.3 | Active capability ends; corpse pool transfers conserved nutrients | Death terminality, decomposition limits, ledger audit | Nutrients double counted | | 2.5 Reproduction and wildlife identity | biology/reproduction, genome identity | 2.4, reproduction contract | Sufficient resources required; child consumes parent budget | Insufficient investment, unique ID and ancestry tests | Free offspring or implicit player ownership | @@ -56,6 +56,9 @@ M2.1's transfer-only ledger is implemented separately from the particle world. M2.2 must define finite source flux, process-specific restrictions, rate residuals and the atomic boundary between biological state and its inventories. Snapshot integration requires its own versioned format; it is not provided by M1's codec. +M2.2 now supplies the isolated synthetic process contract and implementation. +M2.3 must establish interacting process ownership before introducing consumers; +the existing fixture is not itself a complete ecosystem or an organism model. ## M3 — Genome v0.1 diff --git a/docs/STATUS.md b/docs/STATUS.md index ac668c6..86314a6 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 24 ADRs. + diagrams, biological contracts, engineering constitution and 25 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,8 +61,8 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M2.2 finite source and producer process contract | Finite flux, typed rates/residuals, restricted energy conversion and atomic inventory/process state | -| 2 | M2.3–2.6 first headless energy cycle | Producer → consumer → death → decomposition → nutrients; seeded million-tick ecosystem evidence | +| 1 | M2.3 consumer and ingestion contract | Bounded shared process state, validated feeding transfers, waste/heat accounting and terminal activity rules | +| 2 | M2.4–2.6 first headless energy cycle | Death → decomposition → nutrients and funded reproduction; seeded million-tick ecosystem evidence | | 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 | M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md): @@ -97,6 +97,14 @@ Native Release, clang-tidy, ASan and formatting passed; Gitea run 1411 passed al Linux checks, ECS, TSan and image publication. Validation details are recorded in the engineering validation report. +M2.2 implements a synthetic finite-source producer process owning its ledger. +It captures energy, sends conversion losses to heat, and funds whole material +recipes from reserves and finite nutrients. Fractional rates and efficiency +carry exact remainders; tick/remainders and balances commit together. Tests cover +hand-calculated outcomes, 32 seeded reference/replay runs, source and nutrient +exhaustion, invalid tick/config rejection and u64 arithmetic limits. No organism, +genome, database, process snapshot or deployment is implied by this fixture. + Before biology, resolve the relevant heredity and energetic contracts rather than treating proof particles as organisms. Exact game tick rate, NPC mutation, logout treatment, species/extinction rules and multicellular transition remain diff --git a/docs/adr/0025-finite-producer-process.md b/docs/adr/0025-finite-producer-process.md new file mode 100644 index 0000000..85fe249 --- /dev/null +++ b/docs/adr/0025-finite-producer-process.md @@ -0,0 +1,76 @@ +# ADR-0025: Finite synthetic producer process + +## Status + +Adopted for the M2.2 headless process fixture. Not organism biology or live-world +founder creation; genotype/development and player-origin lineage remain later gates. + +## Context + +The ledger conserves inventories but permits arbitrary transfers. Producer rules +must constrain usable energy, finite source capture, growth costs and rounding, +and commit their own state with inventories. No database is needed for this proof. + +## Decision + +Add an independently tested `evo::processes` library with `ProducerProcess` owning +one ledger. Four fixed reservoirs hold source energy, nutrient matter, producer +reserve/structure, and heat. Opening source energy and nutrients are explicit; +producer and heat start empty. Inspection is read-only; no arbitrary transfer API +or mutable ledger escapes. Heat never funds capture or growth. + +Each exact next logical tick performs capture then growth. Capture quota is +integer picojoules per positive integer number of ticks. Consume at most this +quota and available source energy. A fixed efficiency in thousandths splits the +actual capture into producer reserve and heat. Growth quota is integer recipe +units per positive integer number of ticks. Each recipe unit requires a positive +energy cost and a nonzero C/N/P/other matter bundle; growth is the minimum of its +quota and all available energy/material constraints. Matter moves intact from +nutrients to producer structure; growth energy moves from reserve to heat. + +Maintain separate remainder counters for capture rate, growth rate and conversion +efficiency. Quotient/remainder arithmetic avoids wide multiplication and retains +sub-quantum entitlement without floating point. Unfulfilled whole quotas are +discarded; they cannot accumulate while the source or nutrients are exhausted. +Fractional remainders persist. Conversion remainder follows actual captured +energy, never unfunded quota. Remainders are not additional physical inventory. + +Compute the report and next remainders first, submit four ordered ledger legs +as one transaction with action ID equal to target tick, then publish scalar state +without throwing. A failed or duplicate/late/future tick changes nothing. The +first tick is 1. No host clock, variable dt, network, persistence or hidden RNG. +One owner provides sequential access. Copies are experiment branches only. + +## Alternatives Considered + +Public ledger access could recycle heat. Independent process/ledger commits could +lose fractional state or double-fund growth. Floating rates lose exact residuals. +A general dimensional library remains a gate before physical flux/area/time +equations; this fixture only divides already typed inventory quotas by tick +counts and does not choose watts, geometry, photosynthetic chemistry or a game rate. + +## Benefits + +Finite-source producer behavior, explicit heat losses, exact conserved matter, +resource-limited growth and atomic process/accounting state. + +## Costs + +One producer and four reservoirs only; no interactions, maintenance, starvation, +reproduction or persistent state format. Full ledger copying per tick remains +the bounded correctness baseline. Efficiency and recipe parameters are synthetic. + +## Risks + +Conservation alone cannot establish biochemical plausibility. Recipe units are +not cells or organisms. Rate remainder retention is a scoped fixture policy and +must be reviewed for future changing rates or resource replenishment. The finite +source models a prepaid budget, not a star that shuts off when locally depleted. + +## Consequences + +Tests must cover fractional rates/conversion, 0/100% capture, zero rates, source +and element exhaustion, energy-limited growth, u64 extremes, tick rejection, +copy/replay and independently recomputed conservation. A later process snapshot +must contain all inventories, config, tick and remainders together; M1's snapshot +does not serialize any of this. No production migration/version changes now. diff --git a/docs/adr/README.md b/docs/adr/README.md index aa07777..7ab33c8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -17,6 +17,7 @@ Each record has the eight required sections. 0022 adopts the bounded sequential lifecycle-command scheduler for the proof. 0023 defines local periodic neighborhood queries and a measured linear baseline. 0024 adopts finite, typed energy/matter inventory transfers for M2.1. +0025 scopes finite capture, growth recipes and residual accounting for M2.2. Every dependency adoption records exact version/commit and integrity hash, transitive license obligations, maintenance/security review, owner and removal diff --git a/docs/architecture/SYSTEM_OVERVIEW.md b/docs/architecture/SYSTEM_OVERVIEW.md index f71dd17..1daf771 100644 --- a/docs/architecture/SYSTEM_OVERVIEW.md +++ b/docs/architecture/SYSTEM_OVERVIEW.md @@ -48,6 +48,7 @@ the simulation state. Durable account references live in orchestration mapping. | core | Value types, deterministic algorithms, explicit version constants | Global state, threads, I/O | | simulation (`evo_simulation`, alias `evo::simulation`) | State, stable tick ordering, component lifecycle, pure restore validation | Wall clock, transport, database or rendering | | accounting (`evo_accounting`, alias `evo::accounting`) | Typed finite inventories, atomic conserved transfers, in-memory action watermark | Chemistry, minting resources, entity lifecycle or durable storage | +| processes (`evo_processes`, alias `evo::processes`) | Synthetic source/producer rules and atomic process/accounting state | Live organism ancestry, persistence, heat recycling or external I/O | | biology | Genotype → development → phenotype; energetic transfers | Account rewards, player/NPC subclasses | | world | Procedural base identity, spatial/environmental fields | Dense planet allocation, gameplay authority | | persistence | Durable metadata, snapshots, replay batches, migration | Per-tick simulation decisions | @@ -55,7 +56,7 @@ the simulation state. Durable account references live in orchestration mapping. | backend | Identity adapters, account/world metadata, history queries, directory/lease coordination | Every noun deployed as a service | | app / server | Tick pacing, I/O ownership, durable outcome barrier, metrics export | Alternative biological implementation | -Core, simulation, local snapshot codec, accounting and `evo-sim` are source modules +Core, simulation, local snapshot codec, accounting, processes and `evo-sim` are source modules in the proof. Accounting has an independent tested contract; it is not yet wired into particle state. Future rows are boundaries, not empty directories or dummy services. Split a library when a real independently tested contract exists. diff --git a/docs/biology/ENERGY_MODEL.md b/docs/biology/ENERGY_MODEL.md index 9deb304..c35a1e7 100644 --- a/docs/biology/ENERGY_MODEL.md +++ b/docs/biology/ENERGY_MODEL.md @@ -117,3 +117,32 @@ process operations and finite flux budgets. Never treat conservation as biologic validity. There is no import/mint API, organism lifecycle, persisted ledger codec or cross-ledger transaction in M2.1. Persistent integration must checkpoint both inventories and action watermark atomically; M1 snapshots do not include them. + +## Implemented M2.2 synthetic producer + +[ADR-0025](../adr/0025-finite-producer-process.md) defines the independent +`evo::processes::ProducerProcess` fixture. It owns four reservoirs and exposes only +read-only balances and exact-next-tick advancement. Source energy and C/N/P/other +substrates are finite opening inventories. Capture divides actual source uptake +between reserve and heat. Growth moves a configured whole recipe from substrates +to structure and its energy cost from reserve to heat. The API cannot reuse heat. + +```mermaid +flowchart LR + S[Finite source energy] -->|rate-limited capture| R[Producer reserve] + S -->|conversion loss| H[Heat] + N[Finite substrates] -->|funded recipe units| B[Producer structure] + R -->|growth energy cost| H +``` + +Rates are rational inventories/recipe units per integer tick count. Independent +carried remainders preserve capture, growth and efficiency fractions. Unfunded +whole quotas expire; no starvation debt or future burst accumulates. Remainders +and tick advance only after the ledger transaction succeeds. Arithmetic uses +quotient/remainder decomposition, not overflow-prone numerator multiplication. + +This is a synthetic process, not a biological founder or organism. Its parameters +do not select photosynthetic chemistry, area, metabolic efficiency, world time +or the final units library. No producer state is attached to the particle world, +serialized, connected to PostgreSQL or deployed. Later persistent integration +must include config, reservoirs, tick and all three remainders in one checkpoint. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 9f39297..84b7310 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -210,3 +210,21 @@ configuration passed 6/6 CTests. Ledger-suite times were 3.34s GCC Debug, 0.37s Release, 2.46s Clang analysis and 8.78s Clang ASan/UBSan; these are CI test durations, not controlled performance benchmarks. The image smoke/publication job also passed, completing all four jobs. No deployment image pin was changed. + +## M2.2 finite producer process (2026-09-19) + +Native Release, clang-tidy and MSVC ASan passed 7/7 CTests; format-check passed. +Commands: `tools/windows-check.ps1 -Preset -Action check` +and Release `-Action format`. The producer suite compares hand-calculated ticks +and 32 seeds × 1,000 ticks against a small-domain cumulative arithmetic reference, +an independent replay branch and per-tick energy/element conservation audits. +It covers invalid config/ticks with unchanged state, fractional capture/growth, +efficiency endpoints, finite source exhaustion, all four limiting elements, +zero capture, maximum u64 capture with 50% carried conversion, and maximum recipe +and growth-cost multiplication. Particle goldens remain unchanged. + +Allocation-failure injection and tick-counter exhaustion were not exercised; +the latter has an explicit guard but no arbitrary-state restore API. Tests use +in-memory copies, not serialized recovery. No photosynthetic chemistry, metabolic +model, database integration, throughput guarantee or deployment is claimed. +Linux CI is pending this source push. diff --git a/include/evo/processes/producer.hpp b/include/evo/processes/producer.hpp new file mode 100644 index 0000000..8af41c3 --- /dev/null +++ b/include/evo/processes/producer.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "evo/accounting/ledger.hpp" +#include "evo/core/types.hpp" + +namespace evo::processes { +struct CaptureRate { + accounting::Picojoules energy; + std::uint32_t ticks; +}; +struct GrowthRate { + std::uint64_t units; + std::uint32_t ticks; +}; +struct ProducerConfig { + CaptureRate capture; + GrowthRate growth; + std::uint16_t efficiency_per_thousand; + accounting::Picojoules growth_cost; + std::array recipe; +}; +struct ProducerReport { + accounting::Picojoules captured; + accounting::Picojoules retained; + accounting::Picojoules capture_heat; + std::uint64_t grown_units; + std::uint64_t unmet_growth_units; + auto operator<=>(const ProducerReport&) const = default; +}; +struct ProducerProgress { + Tick tick{}; + std::uint32_t capture_remainder{}; + std::uint32_t growth_remainder{}; + std::uint32_t efficiency_remainder{}; + auto operator<=>(const ProducerProgress&) const = default; +}; +enum class ProducerError : std::uint8_t { + invalid_config, + wrong_tick, + tick_exhausted, + ledger_failure +}; + +class ProducerProcess { + public: + [[nodiscard]] static std::expected + create(ProducerConfig config, accounting::Picojoules source, + std::array nutrients); + [[nodiscard]] std::expected advance(Tick target); + // Reservoir order: source, nutrients, producer, heat. Valid until mutation. + [[nodiscard]] std::span balances() const noexcept { + return ledger_.balances(); + } + [[nodiscard]] ProducerProgress progress() const noexcept { + return progress_; + } + + private: + ProducerProcess(ProducerConfig config, accounting::Ledger ledger); + ProducerConfig config_; + accounting::Ledger ledger_; + ProducerProgress progress_{}; +}; +} // namespace evo::processes diff --git a/src/processes/producer.cpp b/src/processes/producer.cpp new file mode 100644 index 0000000..c54c796 --- /dev/null +++ b/src/processes/producer.cpp @@ -0,0 +1,85 @@ +#include "evo/processes/producer.hpp" + +#include +#include +#include + +namespace evo::processes { +namespace { +struct Quota { + std::uint64_t whole; + std::uint32_t remainder; +}; +Quota quota(std::uint64_t numerator, std::uint32_t denominator, std::uint32_t carry) noexcept { + const auto remainder = numerator % denominator + carry; + return {numerator / denominator + remainder / denominator, + static_cast(remainder % denominator)}; +} +} // namespace + +ProducerProcess::ProducerProcess(ProducerConfig config, accounting::Ledger ledger) + : config_{config}, ledger_{std::move(ledger)} {} + +std::expected +ProducerProcess::create(ProducerConfig config, accounting::Picojoules source, + std::array nutrients) { + if (config.capture.ticks == 0 || config.growth.ticks == 0 || + config.efficiency_per_thousand > 1000 || config.growth_cost.value == 0 || + std::ranges::none_of(config.recipe, [](auto mass) { return mass.value != 0; })) { + return std::unexpected{ProducerError::invalid_config}; + } + const std::array opening{accounting::Inventory{source, {}}, + accounting::Inventory{{}, nutrients}, accounting::Inventory{}, + accounting::Inventory{}}; + auto ledger = accounting::Ledger::create(opening); + if (!ledger) { + return std::unexpected{ProducerError::ledger_failure}; + } + return ProducerProcess{config, std::move(*ledger)}; +} + +std::expected ProducerProcess::advance(Tick target) { + if (progress_.tick.value == std::numeric_limits::max()) { + return std::unexpected{ProducerError::tick_exhausted}; + } + if (target.value != progress_.tick.value + 1) { + return std::unexpected{ProducerError::wrong_tick}; + } + const auto capture = + quota(config_.capture.energy.value, config_.capture.ticks, progress_.capture_remainder); + const auto growth = + quota(config_.growth.units, config_.growth.ticks, progress_.growth_remainder); + const auto balances = ledger_.balances(); + if (balances.size() != 4) { + return std::unexpected{ProducerError::ledger_failure}; + } + const auto captured = std::min(capture.whole, balances[0].energy.value); + const auto efficiency = config_.efficiency_per_thousand; + const auto fractional = (captured % 1000) * efficiency + progress_.efficiency_remainder; + const auto retained = (captured / 1000) * efficiency + fractional / 1000; + // Conserved global energy bounds this addition, including new capture. + const auto reserve = balances[2].energy.value + retained; + auto grown = std::min(growth.whole, reserve / config_.growth_cost.value); + for (std::size_t index = 0; index < config_.recipe.size(); ++index) { + if (config_.recipe[index].value != 0) { + grown = std::min(grown, balances[1].matter[index].value / config_.recipe[index].value); + } + } + accounting::Inventory material{}; + for (std::size_t index = 0; index < config_.recipe.size(); ++index) { + material.matter[index].value = grown * config_.recipe[index].value; + } + const std::array legs{accounting::Transfer{{1}, {3}, {{retained}, {}}}, + accounting::Transfer{{1}, {4}, {{captured - retained}, {}}}, + accounting::Transfer{{3}, {4}, {{grown * config_.growth_cost.value}, {}}}, + accounting::Transfer{{2}, {3}, material}}; + const auto result = ledger_.transfer(target.value, legs); + if (!result) { + return std::unexpected{ProducerError::ledger_failure}; + } + progress_ = {target, capture.remainder, growth.remainder, + static_cast(fractional % 1000)}; + return ProducerReport{ + {captured}, {retained}, {captured - retained}, grown, growth.whole - grown}; +} +} // namespace evo::processes diff --git a/tests/producer_tests.cpp b/tests/producer_tests.cpp new file mode 100644 index 0000000..1d1e333 --- /dev/null +++ b/tests/producer_tests.cpp @@ -0,0 +1,199 @@ +#include "evo/core/random.hpp" +#include "evo/processes/producer.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::processes; +using namespace evo::accounting; +void check(bool condition, std::source_location location = std::source_location::current()) { + if (!condition) { + throw std::runtime_error("producer contract line " + std::to_string(location.line())); + } +} +#define CHECK(expression) check(static_cast(expression)) +ProducerConfig config() { + return { + {{5}, 2}, {3, 2}, 600, {1}, {Femtograms{1}, Femtograms{2}, Femtograms{3}, Femtograms{4}}}; +} +std::vector balances(const ProducerProcess& process) { + return {process.balances().begin(), process.balances().end()}; +} +void audit(const ProducerProcess& process, std::uint64_t energy, + const std::array& matter) { + Inventory sum{}; + for (const auto& balance : process.balances()) { + CHECK(balance.energy.value <= energy - sum.energy.value); + sum.energy.value += balance.energy.value; + for (std::size_t index = 0; index < 4; ++index) { + CHECK(balance.matter[index].value <= matter[index].value - sum.matter[index].value); + sum.matter[index].value += balance.matter[index].value; + } + } + CHECK(sum.energy.value == energy && sum.matter == matter); +} +void hand_calculated() { + const std::array matter{Femtograms{10}, Femtograms{20}, Femtograms{30}, Femtograms{40}}; + auto process = ProducerProcess::create(config(), {10}, matter); + CHECK(process); + const std::array expected{ + ProducerReport{{2}, {1}, {1}, 1, 0}, ProducerReport{{3}, {2}, {1}, 2, 0}, + ProducerReport{{2}, {1}, {1}, 1, 0}, ProducerReport{{3}, {2}, {1}, 2, 0}}; + for (std::size_t index = 0; index < expected.size(); ++index) { + const auto result = process->advance(evo::Tick{index + 1}); + CHECK(result && *result == expected[index]); + audit(*process, 10, matter); + } + CHECK(process->balances()[0].energy.value == 0); + CHECK(process->balances()[2].energy.value == 0); + CHECK(process->balances()[2].matter[0].value == 6); + CHECK(process->balances()[3].energy.value == 10); + const auto stopped = process->advance(evo::Tick{5}); + CHECK(stopped && stopped->captured.value == 0 && stopped->grown_units == 0); + CHECK(process->balances()[3].energy.value == 10); // Heat cannot power growth. +} +void limits_and_rejection() { + const std::array matter{Femtograms{10}, Femtograms{20}, Femtograms{30}, Femtograms{40}}; + for (int invalid = 0; invalid < 5; ++invalid) { + auto settings = config(); + if (invalid == 0) { + settings.capture.ticks = 0; + } + if (invalid == 1) { + settings.growth.ticks = 0; + } + if (invalid == 2) { + settings.efficiency_per_thousand = 1001; + } + if (invalid == 3) { + settings.growth_cost = {}; + } + if (invalid == 4) { + settings.recipe = {}; + } + const auto result = ProducerProcess::create(settings, {10}, matter); + CHECK(!result && result.error() == ProducerError::invalid_config); + } + auto process = ProducerProcess::create(config(), {10}, matter); + CHECK(process); + CHECK(process->advance(evo::Tick{1})); + const auto before = balances(*process); + const auto progress = process->progress(); + for (const auto target : {0U, 1U, 3U}) { + const auto result = process->advance(evo::Tick{target}); + CHECK(!result && result.error() == ProducerError::wrong_tick); + CHECK(process->progress() == progress && balances(*process) == before); + } + for (const auto efficiency : {0U, 1000U}) { + auto settings = config(); + settings.efficiency_per_thousand = static_cast(efficiency); + settings.capture = {{std::numeric_limits::max()}, 1}; + settings.growth = {0, 1}; + auto full = + ProducerProcess::create(settings, {std::numeric_limits::max()}, matter); + CHECK(full); + const auto result = full->advance(evo::Tick{1}); + CHECK(result && result->retained.value == + (efficiency == 0 ? 0 : std::numeric_limits::max())); + audit(*full, std::numeric_limits::max(), matter); + } + auto boundary_config = config(); + constexpr auto maximum = std::numeric_limits::max(); + boundary_config.capture = {{maximum}, 2}; + boundary_config.growth = {0, 1}; + boundary_config.efficiency_per_thousand = 500; + auto boundary = ProducerProcess::create(boundary_config, {maximum}, matter); + CHECK(boundary); + const auto first = boundary->advance(evo::Tick{1}); + CHECK(first && first->captured.value == 9223372036854775807ULL); + CHECK(first->retained.value == 4611686018427387903ULL); + const auto second = boundary->advance(evo::Tick{2}); + CHECK(second && second->captured.value == 9223372036854775808ULL); + CHECK(second->retained.value == 4611686018427387904ULL); + audit(*boundary, maximum, matter); + boundary_config.capture = {{maximum}, 1}; + boundary_config.growth = {maximum, 1}; + boundary_config.efficiency_per_thousand = 1000; + boundary_config.growth_cost = {maximum}; + boundary_config.recipe = {Femtograms{maximum}, Femtograms{}, Femtograms{}, Femtograms{}}; + auto massive = ProducerProcess::create(boundary_config, {maximum}, boundary_config.recipe); + CHECK(massive); + const auto grown = massive->advance(evo::Tick{1}); + CHECK(grown && grown->grown_units == 1 && grown->unmet_growth_units == maximum - 1); + audit(*massive, maximum, boundary_config.recipe); + auto dark_config = config(); + dark_config.capture.energy = {}; + auto dark = ProducerProcess::create(dark_config, {10}, matter); + CHECK(dark); + CHECK(dark->advance(evo::Tick{1})->grown_units == 0); + CHECK(dark->balances()[0].energy.value == 10); + for (std::size_t limiting = 0; limiting < 4; ++limiting) { + auto scarce = matter; + scarce[limiting] = {}; + auto limited = ProducerProcess::create(config(), {10}, scarce); + CHECK(limited); + CHECK(limited->advance(evo::Tick{1})->grown_units == 0); + audit(*limited, 10, scarce); + } +} +void fractional_reference_and_replay() { + for (std::uint64_t seed = 0; seed < 32; ++seed) { + evo::Random random{seed}; + auto settings = config(); + settings.capture = {{random.next() % 17}, + static_cast(1 + random.next() % 13)}; + settings.growth = {random.next() % 9, static_cast(1 + random.next() % 7)}; + settings.efficiency_per_thousand = static_cast(random.next() % 1001); + settings.growth_cost.value = 1 + random.next() % 5; + const std::array matter{Femtograms{50}, Femtograms{100}, Femtograms{150}, Femtograms{200}}; + constexpr std::uint64_t initial_energy = 200; + auto process = ProducerProcess::create(settings, {initial_energy}, matter); + CHECK(process); + auto replay = *process; + std::uint64_t total_capture{}, total_retained{}, total_growth{}; + for (std::uint64_t tick = 1; tick <= 1000; ++tick) { + // Small-domain independent reference: cumulative products fit u64. + const auto cumulative_capture = + tick * settings.capture.energy.value / settings.capture.ticks; + const auto actual_capture = std::min(cumulative_capture, initial_energy); + const auto retained = actual_capture * settings.efficiency_per_thousand / 1000; + const auto growth_quota = tick * settings.growth.units / settings.growth.ticks - + (tick - 1) * settings.growth.units / settings.growth.ticks; + const auto grown = std::min({growth_quota, + (retained - total_growth * settings.growth_cost.value) / + settings.growth_cost.value, + 50 - total_growth}); + const auto result = process->advance(evo::Tick{tick}); + const auto repeated = replay.advance(evo::Tick{tick}); + CHECK(result && repeated && *result == *repeated); + CHECK(result->captured.value == actual_capture - total_capture); + CHECK(result->retained.value == retained - total_retained); + CHECK(result->grown_units == grown); + total_capture = actual_capture; + total_retained = retained; + total_growth += grown; + CHECK(process->balances()[2].energy.value == + total_retained - total_growth * settings.growth_cost.value); + CHECK(process->balances()[2].matter[0].value == total_growth); + CHECK(process->progress() == replay.progress()); + CHECK(balances(*process) == balances(replay)); + audit(*process, initial_energy, matter); + } + } +} +} // namespace + +int main() try { + hand_calculated(); + limits_and_rejection(); + fractional_reference_and_replay(); + std::cout << "PASS producer conservation, fractional reference and replay\n"; + return 0; +} catch (...) { + return 1; +}