Add shared feeding community with atomic resource transfers

This commit is contained in:
dingo
2026-09-20 10:28:54 -04:00
parent c86e286c0d
commit b7dd466f57
14 changed files with 534 additions and 8 deletions
+6 -1
View File
@@ -40,7 +40,7 @@ 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 STATIC src/processes/producer.cpp src/processes/feeding.cpp)
add_library(evo::processes ALIAS evo_processes)
target_link_libraries(evo_processes PUBLIC evo::accounting)
evo_owned_target(evo_processes)
@@ -51,6 +51,11 @@ evo_owned_target(evo-sim)
include(CTest)
if(BUILD_TESTING)
add_executable(evo-feeding-tests tests/feeding_tests.cpp)
target_link_libraries(evo-feeding-tests PRIVATE evo::processes)
evo_owned_target(evo-feeding-tests)
add_test(NAME feeding-contracts COMMAND evo-feeding-tests)
set_tests_properties(feeding-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-producer-tests tests/producer_tests.cpp)
target_link_libraries(evo-producer-tests PRIVATE evo::processes)
evo_owned_target(evo-producer-tests)
+4 -1
View File
@@ -45,7 +45,7 @@ this proof. Production indexing awaits actual interaction workloads.
|---|---|---|---|---|---|
| 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 | 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.3 Add consumer intentions and ingestion | processes/feeding.*, ADR-0026 | 2.2 | Shared ledger and atomic tick; capped ordered feeding with heat/waste outputs | Predation, contention, rollback, terminal depletion, replay/conservation | Fixture rules becoming gameplay; spatial validation remains separate |
| 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 |
| 2.6 Long-run ecosystem fixture | apps/evo-sim, tests/ecosystem, metrics | 2.2–2.5 | Producer→consumer→death→nutrients cycle; report over million ticks | Many seeds, nonnegative balances, measured extinction/diversity | Passing invariants despite uninteresting ecology |
@@ -59,6 +59,9 @@ 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.
M2.3 now supplies this bounded shared ownership and ingestion fixture. M2.4 must
retain remaining inventory on death and implement explicit corpse/decomposition
flows, rather than relying on M2.3's zero-inventory depletion trigger.
## M3 — Genome v0.1
+12 -4
View File
@@ -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 25 ADRs.
diagrams, biological contracts, engineering constitution and 26 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.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 |
| 1 | M2.4 death and decomposition contract | Terminal activity with remaining inventory, corpse ownership, bounded decomposition and nutrient return |
| 2 | M2.5–2.6 first headless energy cycle | Funded reproduction and complete producer/consumer/decomposition cycle; 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):
@@ -105,7 +105,15 @@ 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.
Native Release, analysis, ASan and format checks passed, and Gitea run 1413
passed all Linux checks, ECS, TSan and image jobs. M2.3 is the next increment.
passed all Linux checks, ECS, TSan and image jobs.
M2.3 adds a shared feeding community with one producer and up to 16 consumer
capabilities. One ledger owns all process resources, heat and waste. Ordered
intake-capped feeding, producer progression and terminal depletion commit as one
tick; a rejected request leaves the entire community unchanged. Tests cover
predation, resource contention, terminal actors, batch order/replay and conservation.
No spatial/perception validation,
organism biology, persistent checkpoint or deployment is included in this fixture.
Before biology, resolve the relevant heredity and energetic contracts rather
than treating proof particles as organisms. Exact game tick rate, NPC mutation,
+3
View File
@@ -39,6 +39,9 @@ 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.
ADR-0026 extends ledger action allocation to next-watermark IDs within a shared
community. Standalone action IDs still equal ticks; multiple feeding actions in
a community tick no longer conflict with the next producer step.
One owner provides sequential access. Copies are experiment branches only.
## Alternatives Considered
+85
View File
@@ -0,0 +1,85 @@
# ADR-0026: Shared synthetic feeding community
## Status
Adopted for bounded M2.3 process fixtures; not biological classes or live-world
organism rules. Extends ADR-0025's isolated ownership with one community owner.
## Context
Copying producer balances into a consumer ledger would duplicate resources.
Producer progress and feeding must commit against one inventory owner.
## Decision
`FeedingCommunity` privately owns one ProducerProcess and 1–16 configured consumer
capabilities sharing its ledger. A narrow friend boundary permits this owner to
construct the larger ledger and orchestrate transfers; no mutable ledger escapes.
The standalone producer API and four-reservoir fixture remain compatible.
Producer stepping uses the next ledger action watermark rather than assuming one
ledger action per tick. The community clock remains the producer's logical tick.
Reservoirs 1–4 retain source/nutrients/producer/heat. Consumer reservoirs follow;
one final reservoir holds unassimilated matter. Process IDs: producer=1, consumers
=2 onward. These IDs are fixture identities, not entity handles, species or classes.
Opening consumer inventories are explicit experimental budgets; no persistent
world founder or biomass is automatically created.
Each exact-next-tick call accepts at most 16 immutable FeedIntent records, with
nonzero unique host sequences. Sort by sequence; at most one feeding request per
consumer per tick. This prevents splitting an intake limit into multiple requests.
Requests name a distinct active target (producer or another consumer), a nonzero
inventory bundle and an active consumer. Each channel must fit the configured
intake cap and current target balance. No silently reduced bite. First ordered
request gets first access; later overdraft rejects the entire tick.
Run producer capture/growth first if active, then feeding on a private community
copy. Assimilated energy and matter use a fixed configured fraction in thousandths;
floor each channel independently with overflow-safe quotient decomposition. Energy
remainder goes to heat, matter remainder to waste. This split deliberately has no
fractional entitlement carried between bites: integer waste is real inventory.
It cannot create an advantage by splitting, but its small-quantity bias must be
reviewed before biological tuning. An efficiency of 1000 transfers all, 0 transfers
all energy to heat and all matter to waste.
A target whose entire inventory becomes zero due to feeding becomes terminally
inactive. It cannot act, be targeted again or resume capture/growth. This is a
synthetic depletion trigger, not a chosen health/starvation rule. Empty opening
fixtures may be active; only actual feeding causes this transition. Partial injury,
corpses and decomposition remain M2.4. Inactive producer ticks advance the shared
clock without advancing its fractional capture/growth state.
Any invalid command, stale tick, overflow or allocation failure rejects the whole
candidate. Publish inventories, activity flags, producer remainders and sorted
receipts via noexcept moves only. No current operation resurrects a process.
## Alternatives Considered
Separate ledgers need escrow and cross-owner transactions; unjustified locally.
Public mutation access could recycle heat. Partial per-request commits complicate
replay. A generic ECS rewrite or service boundary has no benefit for this fixture.
## Benefits
One conserved source of truth, bounded input, deterministic contention, shared
capture/feeding atomicity and explicit terminal activity.
## Costs
Whole-community copies and small fixed actor/command limits. No spatial gate is
implemented: requests are trusted co-located fixture intentions, not network input.
Body reserve and material are independently requested, not a complete digestion model.
## Risks
This fairness, rounding and depletion policy must not become gameplay by accident.
No lineage, perception, authorization or collision rule is implied. A later corpse
model must preserve inventories when death occurs before complete depletion.
## Consequences
Test order permutations, whole-tick rollback including producer progress, competing
feeders, intake bounds, invalid/self/dead targets, terminal actors, heat/waste,
efficiency endpoints, arithmetic extremes and repeated conservation/replay.
No snapshot, database, renderer or deployment changes. M2.4 must extend this shared
ownership model for terminal death with remaining resources and decomposition.
+1
View File
@@ -18,6 +18,7 @@ Each record has the eight required sections.
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.
0026 adds shared community ownership and bounded synthetic feeding for M2.3.
Every dependency adoption records exact version/commit and integrity hash,
transitive license obligations, maintenance/security review, owner and removal
+4
View File
@@ -61,6 +61,10 @@ 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.
The processes library now includes a shared feeding community (ADR-0026): producer
and consumer reservoirs have one owner, with heat/waste and activity flags committed
atomically. Standalone producer fixtures remain available for focused testing.
## Runtime topology and data flow (target)
```mermaid
+28
View File
@@ -146,3 +146,31 @@ 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.
## Implemented M2.3 shared feeding fixture
[ADR-0026](../adr/0026-shared-feeding-community.md) introduces `FeedingCommunity`,
owning one producer and up to 16 consumer capabilities in a single ledger. The
producer's standalone interface remains unchanged. A narrow private ownership
boundary permits orchestration without exposing arbitrary inventory writes.
Each tick stages producer activity, then at most one feeding request per consumer
in ascending host sequence. Intake limits apply per inventory channel, and a
request must be fully available. Assimilated quantities go to the consumer,
unassimilated energy to heat, and unassimilated matter to a finite waste reservoir.
Every quantity has a counterpart. Floor rounding in feeding goes to real waste/
heat, unlike the producer's carried capture entitlement; see the ADR for scope.
A depleted target becomes inactive only when all its inventory is consumed. It
cannot act, be targeted or restart capture. This is a terminal synthetic trigger,
not a biological death model. Whole-community staging ensures failed feeding
rolls back producer progress, earlier bites, terminal flags and ledger outcomes.
The host submits trusted co-located intentions; spatial reach, authenticated input,
partial injury, corpses, decomposition and actual organism ancestry are absent.
```mermaid
flowchart LR
P[Producer or consumer target] -->|assimilated energy and matter| C[Consumer]
P -->|unassimilated energy| H[Heat]
P -->|unassimilated matter| W[Waste inventory]
```
+18
View File
@@ -232,3 +232,21 @@ passed all four jobs for source `af293b8b50cbb506a49dfff10c6cc92307e16aca`:
Linux checks, ECS regression, separate TSan and runtime image smoke/publication.
The initial push was delayed by a tool approval-review usage limit; retry succeeded
after the maintainer resumed work. No deployment image pin was changed.
## M2.3 shared feeding community (2026-09-20)
Native Release, clang-tidy and MSVC ASan each passed 8/8 CTests; formatting passed.
Commands: `tools/windows-check.ps1 -Preset <release|analysis|asan> -Action check`
and Release `-Action format`. The new suite checks hand-calculated capture/feeding,
producer-to-consumer and consumer-to-consumer predation, heat/waste outputs,
terminal actor rejection, full-tick rollback, competing resource requests,
duplicate sequence/consumer admission, per-channel intake caps, invalid actors,
config/capacity limits and u64 assimilation endpoints. 32 seeds × 200 ticks compare
reordered input batches, receipts, full balances and producer progress, with
independently recomputed energy and elemental totals. Standalone producer and
existing particle golden tests remain unchanged and passing.
No serialized recovery, allocation-failure injection, spatial reach/perception,
physical injury, corpse handling or persistent-world integration was tested or
implemented. These are co-located synthetic process fixtures. Linux CI is pending
the source push; no deployment image pin is changed.
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include "evo/processes/producer.hpp"
namespace evo::processes {
struct ConsumerConfig {
accounting::Inventory opening;
accounting::Inventory intake_limit;
std::uint16_t assimilation_per_thousand;
};
struct FeedIntent {
std::uint64_t sequence;
std::uint32_t consumer;
std::uint32_t target;
accounting::Inventory amount;
};
struct FeedReceipt {
std::uint64_t sequence;
accounting::Inventory assimilated;
bool target_depleted;
auto operator<=>(const FeedReceipt&) const = default;
};
enum class FeedingError : std::uint8_t {
invalid_config,
wrong_tick,
invalid_batch,
invalid_actor,
inactive_actor,
intake_limit,
insufficient_inventory,
accounting_failure
};
inline constexpr std::size_t max_consumers = 16;
class FeedingCommunity {
public:
[[nodiscard]] static std::expected<FeedingCommunity, FeedingError>
create(ProducerConfig producer, accounting::Picojoules source,
std::array<accounting::Femtograms, 4> nutrients,
std::span<const ConsumerConfig> consumers);
[[nodiscard]] std::expected<std::vector<FeedReceipt>, FeedingError>
advance(Tick target, std::span<const FeedIntent> inputs = {});
[[nodiscard]] std::span<const accounting::Inventory> balances() const noexcept {
return producer_.balances();
}
[[nodiscard]] ProducerProgress progress() const noexcept {
return producer_.progress();
}
// Process IDs are one-based. Out-of-range is a query error, not an inactive actor.
[[nodiscard]] std::expected<bool, FeedingError> active(std::uint32_t id) const noexcept;
private:
FeedingCommunity(ProducerProcess producer, std::vector<ConsumerConfig> consumers);
[[nodiscard]] std::expected<FeedReceipt, FeedingError> feed(const FeedIntent& input);
ProducerProcess producer_;
std::vector<ConsumerConfig> consumers_;
std::vector<std::uint8_t> active_;
};
} // namespace evo::processes
+1
View File
@@ -56,6 +56,7 @@ class ProducerProcess {
}
private:
friend class FeedingCommunity;
ProducerProcess(ProducerConfig config, accounting::Ledger ledger);
ProducerConfig config_;
accounting::Ledger ledger_;
+150
View File
@@ -0,0 +1,150 @@
#include "evo/processes/feeding.hpp"
#include <algorithm>
#include <limits>
#include <type_traits>
#include <utility>
namespace evo::processes {
namespace {
bool fits(const accounting::Inventory& amount, const accounting::Inventory& available) noexcept {
if (amount.energy > available.energy) {
return false;
}
for (std::size_t index = 0; index < 4; ++index) {
if (amount.matter[index] > available.matter[index]) {
return false;
}
}
return true;
}
std::uint64_t portion(std::uint64_t quantity, std::uint16_t efficiency) noexcept {
return (quantity / 1000) * efficiency + (quantity % 1000) * efficiency / 1000;
}
accounting::ReservoirId reservoir(std::uint32_t actor) noexcept {
return {actor == 1 ? 3U : actor + 3U};
}
} // namespace
FeedingCommunity::FeedingCommunity(ProducerProcess producer, std::vector<ConsumerConfig> consumers)
: producer_{std::move(producer)}, consumers_{std::move(consumers)},
active_(consumers_.size() + 1, 1) {}
std::expected<FeedingCommunity, FeedingError>
FeedingCommunity::create(ProducerConfig producer, accounting::Picojoules source,
std::array<accounting::Femtograms, 4> nutrients,
std::span<const ConsumerConfig> consumers) {
if (consumers.empty() || consumers.size() > max_consumers ||
std::ranges::any_of(consumers,
[](const auto& c) { return c.assimilation_per_thousand > 1000; })) {
return std::unexpected{FeedingError::invalid_config};
}
auto isolated = ProducerProcess::create(producer, source, nutrients);
if (!isolated) {
return std::unexpected{FeedingError::invalid_config};
}
std::vector<accounting::Inventory> opening{isolated->balances().begin(),
isolated->balances().end()};
for (const auto& consumer : consumers) {
opening.push_back(consumer.opening);
}
opening.emplace_back(); // Waste is owned matter, not destroyed inventory.
auto ledger = accounting::Ledger::create(opening);
if (!ledger) {
return std::unexpected{FeedingError::accounting_failure};
}
isolated->ledger_ = std::move(*ledger);
return FeedingCommunity{std::move(*isolated), {consumers.begin(), consumers.end()}};
}
std::expected<bool, FeedingError> FeedingCommunity::active(std::uint32_t id) const noexcept {
if (id == 0 || id > active_.size()) {
return std::unexpected{FeedingError::invalid_actor};
}
return active_[id - 1] != 0;
}
std::expected<FeedReceipt, FeedingError> FeedingCommunity::feed(const FeedIntent& input) {
if (input.consumer < 2 || input.consumer > active_.size() || input.target == 0 ||
input.target > active_.size() || input.target == input.consumer) {
return std::unexpected{FeedingError::invalid_actor};
}
if (active_[input.consumer - 1] == 0 || active_[input.target - 1] == 0) {
return std::unexpected{FeedingError::inactive_actor};
}
const auto& config = consumers_[input.consumer - 2];
if (input.amount == accounting::Inventory{} || !fits(input.amount, config.intake_limit)) {
return std::unexpected{FeedingError::intake_limit};
}
const auto from = reservoir(input.target);
if (!fits(input.amount, balances()[from.value - 1])) {
return std::unexpected{FeedingError::insufficient_inventory};
}
accounting::Inventory assimilated{}, heat{}, waste{};
assimilated.energy.value = portion(input.amount.energy.value, config.assimilation_per_thousand);
heat.energy.value = input.amount.energy.value - assimilated.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
assimilated.matter[index].value =
portion(input.amount.matter[index].value, config.assimilation_per_thousand);
waste.matter[index].value =
input.amount.matter[index].value - assimilated.matter[index].value;
}
const std::array legs{
accounting::Transfer{from, reservoir(input.consumer), assimilated},
accounting::Transfer{from, {4}, heat},
accounting::Transfer{from, {static_cast<std::uint32_t>(balances().size())}, waste}};
auto& ledger = producer_.ledger_;
if (ledger.last_action() == std::numeric_limits<std::uint64_t>::max() ||
!ledger.transfer(ledger.last_action() + 1, legs)) {
return std::unexpected{FeedingError::accounting_failure};
}
const bool depleted = balances()[from.value - 1] == accounting::Inventory{};
if (depleted) {
active_[input.target - 1] = 0;
}
return FeedReceipt{input.sequence, assimilated, depleted};
}
std::expected<std::vector<FeedReceipt>, FeedingError>
FeedingCommunity::advance(Tick target, std::span<const FeedIntent> inputs) {
if (progress().tick.value == std::numeric_limits<std::uint64_t>::max() ||
target.value != progress().tick.value + 1) {
return std::unexpected{FeedingError::wrong_tick};
}
if (inputs.size() > max_consumers || active_.empty()) {
return std::unexpected{FeedingError::invalid_batch};
}
std::vector<FeedIntent> ordered{inputs.begin(), inputs.end()};
std::ranges::sort(ordered, {}, &FeedIntent::sequence);
std::array<bool, max_consumers + 2> seen{};
std::uint64_t previous{};
for (const auto& input : ordered) {
if (input.sequence == 0 || input.sequence == previous || input.consumer < 2 ||
input.consumer > consumers_.size() + 1 || seen[input.consumer]) {
return std::unexpected{FeedingError::invalid_batch};
}
seen[input.consumer] = true;
previous = input.sequence;
}
auto candidate = *this;
if (candidate.active_[0] != 0) {
if (!candidate.producer_.advance(target)) {
return std::unexpected{FeedingError::accounting_failure};
}
} else {
candidate.producer_.progress_.tick = target;
}
std::vector<FeedReceipt> receipts;
receipts.reserve(ordered.size());
for (const auto& input : ordered) {
const auto result = candidate.feed(input);
if (!result) {
return std::unexpected{result.error()};
}
receipts.push_back(*result);
}
static_assert(std::is_nothrow_move_assignable_v<FeedingCommunity>);
*this = std::move(candidate);
return receipts;
}
} // namespace evo::processes
+5 -2
View File
@@ -50,7 +50,7 @@ std::expected<ProducerReport, ProducerError> ProducerProcess::advance(Tick targe
const auto growth =
quota(config_.growth.units, config_.growth.ticks, progress_.growth_remainder);
const auto balances = ledger_.balances();
if (balances.size() != 4) {
if (balances.size() < 4) {
return std::unexpected{ProducerError::ledger_failure};
}
const auto captured = std::min(capture.whole, balances[0].energy.value);
@@ -73,7 +73,10 @@ std::expected<ProducerReport, ProducerError> ProducerProcess::advance(Tick targe
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 (ledger_.last_action() == std::numeric_limits<std::uint64_t>::max()) {
return std::unexpected{ProducerError::ledger_failure};
}
const auto result = ledger_.transfer(ledger_.last_action() + 1, legs);
if (!result) {
return std::unexpected{ProducerError::ledger_failure};
}
+158
View File
@@ -0,0 +1,158 @@
#include "evo/core/random.hpp"
#include "evo/processes/feeding.hpp"
#include <algorithm>
#include <iostream>
#include <limits>
#include <source_location>
#include <stdexcept>
#include <string>
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("feeding line " + std::to_string(location.line()));
}
}
#define CHECK(expression) check(static_cast<bool>(expression))
Inventory bundle(std::uint64_t value) {
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
}
ProducerConfig producer() {
return {{{10}, 1}, {2, 1}, 1000, {1}, bundle(1).matter};
}
std::vector<Inventory> copy(const FeedingCommunity& community) {
return {community.balances().begin(), community.balances().end()};
}
Inventory sum(const FeedingCommunity& community) {
Inventory total{};
for (const auto& inventory : community.balances()) {
CHECK(inventory.energy.value <=
std::numeric_limits<std::uint64_t>::max() - total.energy.value);
total.energy.value += inventory.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
CHECK(inventory.matter[index].value <=
std::numeric_limits<std::uint64_t>::max() - total.matter[index].value);
total.matter[index].value += inventory.matter[index].value;
}
}
return total;
}
void capture_feeding_and_terminal() {
const std::array configs{ConsumerConfig{{}, bundle(100), 500},
ConsumerConfig{{}, bundle(100), 1000}};
auto community = FeedingCommunity::create(producer(), {100}, bundle(20).matter, configs);
CHECK(community);
const auto total = sum(*community);
// Tick 1 produces 2 material units and retains 8 energy after growth.
const std::array meal{FeedIntent{1, 2, 1, {{8}, bundle(2).matter}}};
const auto result = community->advance(evo::Tick{1}, meal);
CHECK(result && result->size() == 1 && result->front().target_depleted);
CHECK(result->front().assimilated == (Inventory{{4}, bundle(1).matter}));
CHECK(community->balances()[3].energy.value == 6);
CHECK(community->balances().back().matter == bundle(1).matter);
CHECK(community->active(1) && !*community->active(1));
const auto progress = community->progress();
const auto source = community->balances()[0];
CHECK(community->advance(evo::Tick{2}));
CHECK(community->balances()[0] == source);
CHECK(community->progress().capture_remainder == progress.capture_remainder);
const std::array predation{FeedIntent{1, 3, 2, {{4}, bundle(1).matter}}};
CHECK(community->advance(evo::Tick{3}, predation));
CHECK(!*community->active(2));
const auto before = copy(*community);
const std::array dead_action{FeedIntent{1, 2, 3, bundle(1)}};
const auto denied = community->advance(evo::Tick{4}, dead_action);
CHECK(!denied && denied.error() == FeedingError::inactive_actor);
CHECK(copy(*community) == before && community->progress().tick.value == 3);
CHECK(sum(*community) == total);
}
void validation_and_rollback() {
const std::array configs{ConsumerConfig{bundle(10), bundle(10), 1000},
ConsumerConfig{bundle(10), bundle(10), 1000}};
auto community = FeedingCommunity::create(producer(), {100}, bundle(20).matter, configs);
CHECK(community);
const auto before = copy(*community);
const auto progress = community->progress();
const auto reject = [&](std::span<const FeedIntent> inputs) {
CHECK(!community->advance(evo::Tick{1}, inputs));
CHECK(copy(*community) == before && community->progress() == progress);
CHECK(*community->active(1) && *community->active(2) && *community->active(3));
};
std::array inputs{FeedIntent{1, 2, 1, bundle(2)}, FeedIntent{2, 3, 1, bundle(1)}};
reject(inputs); // First takes all producer matter; second cannot also take it.
inputs[1].sequence = 1;
reject(inputs);
inputs[1].sequence = 0;
reject(inputs);
inputs[1] = {2, 2, 1, bundle(1)};
reject(inputs); // Cannot split intake cap.
for (const auto target : {0U, 2U, 999U}) {
const std::array invalid{FeedIntent{1, 2, target, bundle(1)}};
reject(invalid);
}
const std::array excessive{FeedIntent{1, 2, 3, bundle(11)}};
reject(excessive);
const std::array zero{FeedIntent{1, 2, 3, {}}};
reject(zero);
std::vector<FeedIntent> many(max_consumers + 1, FeedIntent{1, 2, 3, bundle(1)});
reject(many);
CHECK(!community->advance(evo::Tick{0}));
CHECK(!community->advance(evo::Tick{2}));
CHECK(!community->active(0));
CHECK(!FeedingCommunity::create(producer(), {}, {}, {}));
auto bad = configs;
bad[0].assimilation_per_thousand = 1001;
CHECK(!FeedingCommunity::create(producer(), {}, {}, bad));
std::vector<ConsumerConfig> too_many(max_consumers + 1, configs[0]);
CHECK(!FeedingCommunity::create(producer(), {}, {}, too_many));
too_many.pop_back();
CHECK(FeedingCommunity::create(producer(), {}, {}, too_many));
}
void ordered_replay() {
for (std::uint64_t seed = 0; seed < 32; ++seed) {
evo::Random random{seed};
const std::array configs{ConsumerConfig{bundle(100), bundle(2), 750},
ConsumerConfig{bundle(100), bundle(2), 500}};
auto a = FeedingCommunity::create(producer(), {10'000}, bundle(1000).matter, configs);
CHECK(a);
auto b = *a;
const auto total = sum(*a);
for (std::uint64_t tick = 1; tick <= 200; ++tick) {
// Capture/growth creates two recipe units, shared by two feeders.
std::array inputs{FeedIntent{1, 2, 1, bundle(1)}, FeedIntent{2, 3, 1, bundle(1)}};
const auto expected = a->advance(evo::Tick{tick}, inputs);
if (random.next() % 2 != 0) {
std::ranges::reverse(inputs);
}
const auto actual = b.advance(evo::Tick{tick}, inputs);
CHECK(expected && actual && *expected == *actual);
CHECK(copy(*a) == copy(b) && a->progress() == b.progress());
CHECK(sum(*a) == total);
}
}
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
for (const auto efficiency : {0U, 1000U}) {
const std::array configs{
ConsumerConfig{bundle(maximum), bundle(maximum), 1000},
ConsumerConfig{{}, bundle(maximum), static_cast<std::uint16_t>(efficiency)}};
auto community = FeedingCommunity::create(producer(), {}, {}, configs);
CHECK(community);
const std::array inputs{FeedIntent{1, 3, 2, bundle(maximum)}};
const auto result = community->advance(evo::Tick{1}, inputs);
CHECK(result && result->front().assimilated == bundle(efficiency == 0 ? 0 : maximum));
CHECK(sum(*community) == bundle(maximum));
}
}
} // namespace
int main() try {
capture_feeding_and_terminal();
validation_and_rollback();
ordered_replay();
std::cout << "PASS shared feeding, rollback, terminality and conservation\n";
return 0;
} catch (...) {
return 1;
}