Add funded reproduction with retained lineage identity

Close the M2.5 fixture cycle. A bounded list of trusted reproduction
intents runs after feeding and before decomposition, so a consumer can
fund offspring from what it ingested and a process terminated in that
tick cannot reproduce. The intent names a withdrawal from the parent
reservoir; a fixed construction fraction endows the child and the
remainder becomes real heat and waste. Nothing is credited from outside
the community, so conserved totals are unchanged by a birth.

Reserved slots are pre-allocated at creation, so a birth never grows the
ledger and a full community rejects rather than funding a smaller child.
Slots never return to the unborn state, so process identities are never
reused, and a parent reference plus origin tick outlive both organisms
and survive decomposition. A child duplicates the configuration of its
parent because no genome exists yet; this is duplication, not heredity.

Default zero capacity leaves the M2.4 reservoir layout and every existing
result unchanged, including golden d61ad5bf0c928c76. Native Release,
clang-tidy analysis, ASan and format checks pass; Linux CI has not run
for this increment yet. This defines no reproductive strategy, fecundity
rule, mutation model, gestation, spatial placement or account ownership.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-21 20:36:49 -04:00
co-authored by Claude Opus 5
parent b01a824975
commit c84a701edf
10 changed files with 619 additions and 43 deletions
+4 -1
View File
@@ -63,7 +63,10 @@ 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.
M2.4 now implements that terminal-inventory and bounded-return contract. M2.5
must settle offspring identity and funding before adding reproductive operations.
now supplies funded budding, bounded pre-allocated slot capacity and retained
parent/origin identity (ADR-0028); offspring are paid for out of parent inventory
and no trait varies between generations. M2.6 must exercise the whole cycle over
seeded long runs; a closed conservation proof is not yet an interesting ecology.
## M3 — Genome v0.1
+19 -5
View File
@@ -1,13 +1,13 @@
# Project status and next steps
Updated 2026-09-19. The repository contains an engineering foundation and a
Updated 2026-09-21. The repository contains an engineering foundation and a
deterministic headless proof. It does not yet contain cellular gameplay or a
persistent simulation server. The founding vision remains unchanged.
## Completed implementation
- Vision, architectural pillars, risks, open-question register, architecture
diagrams, biological contracts, engineering constitution and 27 ADRs.
diagrams, biological contracts, engineering constitution and 28 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.5 funded reproduction contract | Atomic parent/offspring investment, non-reused identity and explicit ancestry without inherited account power |
| 2 | M2.6 headless energy-cycle fixture | Complete capture/feeding/reproduction/decomposition cycle, seeded million-tick ecosystem runs and diagnostics |
| 1 | M2.6 headless energy-cycle fixture | Complete capture/feeding/reproduction/decomposition cycle, seeded million-tick ecosystem runs and diagnostics |
| 2 | M3.1 immutable genome schema and ancestry | Versioned developmental capability data replacing M2.5's duplicated configuration |
| 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):
@@ -125,7 +125,21 @@ decomposition with all earlier phases. Default zero decay preserves earlier
fixture behavior. This is not death-cause biology, microbial chemistry, corpse
scavenging, persistent lineage history or a database-backed world.
Native Release, analysis, ASan and formatting passed, and all four jobs in Gitea
run 1417 passed. M2.5 funded reproduction is the next increment.
run 1417 passed.
M2.5 adds funded budding (ADR-0028). A bounded list of trusted reproduction
intents runs after feeding and before decomposition, so a consumer can fund
offspring from what it ingested and a process terminated in that tick cannot
reproduce. The intent names a withdrawal from the parent; a fixed construction
fraction endows the child and the remainder becomes real heat and waste. Reserved
slots are pre-allocated at creation, so a birth never grows the ledger and a full
community rejects rather than funding a smaller child. Process identities are
never reused and a parent reference plus origin tick outlive both organisms.
A child duplicates its parent's configuration because no genome exists yet; this
is duplication, not heredity. Default zero capacity leaves every M2.4 result and
the particle goldens unchanged. Native Release, analysis, ASan and formatting
passed; Linux CI for this increment has not run yet. This is not a reproductive
strategy, fecundity rule, mutation model or funded founder admission.
Before biology, resolve the relevant heredity and energetic contracts rather
than treating proof particles as organisms. Exact game tick rate, NPC mutation,
+128
View File
@@ -0,0 +1,128 @@
# ADR-0028: Funded reproduction and retained lineage identity
## Status
Adopted for the M2.5 synthetic community fixture. No genome content, mutation,
player account, control grant, spatial placement or gestation model is selected.
Lineage identity here is an opaque parent reference, not the M3.1 genome record.
## Context
M2.1-M2.4 conserve inventory through capture, growth, feeding, terminal events
and bounded decomposition. No operation creates an actor, so every community
decays monotonically and M2.6's long-run ecology fixture cannot observe anything
but extinction. Reproduction is the missing transfer in ENERGY_MODEL's table.
Offspring must be funded. A child credited from nothing would break conservation;
a child credited by the host would make founder admission implicit. ADR-0024's
ledger fixes its reservoir set at construction and exposes no append operation,
so actor creation cannot allocate storage mid-run without reopening that contract.
## Decision
Extend `FeedingCommunity::advance` with a fourth bounded span of immutable
`ReproduceIntent{sequence, parent, investment}` records. Like FeedIntent these are
trusted co-located fixture intentions, not client commands or autonomous decisions.
Admit at most `max_consumers` per tick, require nonzero unique host sequences,
sort by sequence and permit at most one intent per parent per tick.
`ReproductionConfig{capacity, construction_per_thousand, minimum_endowment}` is
fixed at `create`. Capacity reserves that many additional consumer reservoirs
after the configured consumers and before waste. Configured consumers plus
capacity must not exceed `max_consumers`. Capacity defaults to zero, so existing
fixtures keep an identical reservoir layout, waste index, action sequence and
golden results. Reproduction is intent-driven; a tick without intents is a M2.4 tick.
Process state becomes unborn, active or corpse. Reserved slots begin unborn: they
hold an empty reservoir, never act, are never valid feeding targets, are not
corpses and are not decomposed. `active(id)` is false for unborn and corpse alike;
`corpse(id)` and the ancestry queries reject a reserved slot with a distinct
`unborn_actor` error rather than reporting an empty corpse. Reproduction allocates the
lowest-numbered unborn slot. A slot never returns to unborn, so IDs are never
reused and a dead child's identity persists exactly as ADR-0027 requires.
The intent names the withdrawal from the parent reservoir, mirroring feeding's
bite semantics. A fixed `construction_per_thousand` fraction splits it with the
same overflow-safe quotient decomposition: the quotient endows the child, the
energy remainder goes to heat and the matter remainder goes to waste. Construction
overhead is real inventory, not rounding loss. A value of 1000 endows everything;
0 sends the whole investment to heat and waste and therefore always fails the
endowment floor unless that floor is zero. No fractional entitlement is carried
between reproductions.
Reject the whole tick when the parent is not an active consumer, when the
investment is zero or exceeds the parent's balance, when no unborn slot remains,
or when the resulting endowment does not meet `minimum_endowment` on every
channel. Capacity exhaustion is backpressure: it rejects, it never grants a free
or reduced offspring. The producer cannot reproduce in this increment; capture is
its funding path and conflating the two would make an abiotic source a parent.
A child duplicates its parent's consumer configuration verbatim. With no genome,
offspring differ from their parents only in inventory. This is duplication, not
heredity, and M3 replaces it with developmental capabilities.
Record an immutable `parent` and `origin` tick per process. Founders record parent
zero and origin zero. Both survive the death of the child and of the parent, and
remain readable after decomposition empties the reservoir.
Tick phases: terminal facts -> producer activity -> ordered feeding -> reproduction
-> decomposition -> atomic publish. Reproduction after feeding lets a consumer fund
offspring with what it ingested this tick; this is a deliberate fixture choice, not
a biological claim about digestion latency. Terminal facts run first, so a process
terminated this tick cannot reproduce. Intents validate parents against the state
entering the reproduction phase, so a child born this tick cannot itself be a
parent, feed, be fed upon or be decomposed until the next tick.
All phases run on the existing private candidate. Any rejected intent rolls back
reproduction, feeding, producer progress, decomposition and diagnostics together.
Receipts report the sequence, allocated child ID, endowment and overhead, and are
published by noexcept move with the rest of the committed state.
## Alternatives Considered
Appending reservoirs on birth would reopen ADR-0024's fixed opening totals and
shift the waste index mid-run, invalidating inspection spans and existing goldens
for no benefit at fixture scale. Binary fission would force a decision on parent
continuity and control identity that REPRODUCTION_MODEL explicitly leaves open.
Charging overhead on top of the investment needs a second bounds check and can
overflow a parent that could otherwise afford the child. Eggs, cohorts and
broadcast spores require gestation timers and statistical allocation that this
increment has no fixture for. Reusing dead IDs would save slots and destroy
ancestry. Host-credited offspring would break conservation outright.
## Benefits
The energy cycle closes: nutrients fund growth, growth funds feeding, feeding
funds offspring, death and decomposition return matter. Offspring are provably
paid for, capacity is explicit and bounded, ancestry outlives its organisms, and
M2.6 can run a seeded long-run ecosystem that is not a guaranteed decay.
## Costs
A fixed pre-allocated slot budget is not a population model; a community cannot
outgrow its configured capacity and has no aggregation path until M4. Lowest-slot
allocation is deterministic but arbitrary. Whole-community copies per tick remain
the correctness baseline. Ancestry is a parent reference and an origin tick, not
heredity: nothing is inherited, because nothing heritable exists before M3.
## Risks
Do not read this as a reproductive strategy, a fecundity rule or a funded founder
admission for a persistent world. Construction overhead, the endowment floor and
the post-feeding phase position are synthetic parameters that must be reviewed
before any biological tuning, and must not become gameplay by being measured.
No account owns a process; a parent reference grants no control and no wildlife
ownership. Capacity rejection must never be softened into a reduced endowment.
## Consequences
Test hand-calculated endowment and overhead splits, the endowment floor, per
channel insufficiency with abundant energy, capacity exhaustion, unborn slots
rejected as targets and as corpses, terminated and unknown parents, duplicate and
zero sequences, more than one intent per parent per tick, whole-tick rollback
including producer progress and decomposition, order permutation equality across
seeds, absent ID reuse, ancestry surviving both deaths, construction endpoints,
u64 extremes and independently recomputed conservation. Default zero capacity must
leave every M2.4 result unchanged. A later process snapshot must serialize states,
parents, origins and capacity together; M1's codec serializes none of it. No
database, renderer, network or deployment change follows from this record.
+1
View File
@@ -20,6 +20,7 @@ Each record has the eight required sections.
0025 scopes finite capture, growth recipes and residual accounting for M2.2.
0026 adds shared community ownership and bounded synthetic feeding for M2.3.
0027 adds terminal inventory ownership and budgeted nutrient return for M2.4.
0028 adopts funded reproduction, bounded slot capacity and retained lineage IDs.
Every dependency adoption records exact version/commit and integrity hash,
transitive license obligations, maintenance/security review, owner and removal
+34
View File
@@ -202,3 +202,37 @@ flowchart LR
Host terminal events do not define health, starvation, combat, age or player death
causes. Corpse scavenging, live-world lineage history, persistence and reproduction
remain outside this increment. No physical inventory disappears on death.
## Implemented M2.5 funded reproduction
[ADR-0028](../adr/0028-funded-reproduction.md) closes the fixture cycle. A bounded
list of trusted `ReproduceIntent` records runs after feeding and before
decomposition, so a consumer can fund offspring with what it ingested in the same
tick and a process terminated in that tick cannot reproduce at all.
The intent names a withdrawal from the parent reservoir. A fixed construction
fraction in thousandths splits it with the same quotient decomposition feeding
uses: the quotient endows the child, the energy remainder becomes heat and the
matter remainder becomes waste. Construction overhead is owned inventory, not
rounding loss. Nothing is credited from outside the community, so the conserved
totals are identical before and after a birth.
Reserved slots are allocated at creation and hold empty reservoirs until a funded
birth activates the lowest-numbered one. Capacity exhaustion rejects the tick; it
never funds a smaller child. A slot never returns to the unborn state, so process
identities are not reused and a parent reference plus origin tick outlives both
organisms and survives decomposition of the corpse.
```mermaid
flowchart LR
F[Ingested matter and energy] --> R[Parent reservoir]
R -->|endowment| C[Child reservoir]
R -->|construction overhead| H[Heat]
R -->|construction overhead| W[Waste]
C -->|next tick| A[Feeding, death and decomposition]
```
A child duplicates the configuration of its parent because no genome exists yet.
This is duplication, not heredity, and no trait varies between generations.
Reproductive strategy, fecundity, juvenile viability, gestation, spatial placement
and account ownership are not defined here. No inventory is created on birth.
+14
View File
@@ -78,3 +78,17 @@ descendants independent of parent death/logout; arbitrarily long suspension
preserves every timer; same-tick death/reproduction ordering; huge spore requests;
all suspend/resume crash points; changed habitat; unique control grants and
death committed after snapshot. Extinction includes suspended viability.
## Implemented M2.5 fixture boundary
[ADR-0028](../adr/0028-funded-reproduction.md) implements funded budding inside
the synthetic feeding community only. The parent survives and pays an explicit
investment; construction overhead goes to heat and waste; a bounded pre-allocated
slot capacity rejects rather than granting free or reduced offspring. Ancestry is
a parent reference and an origin tick that survive both deaths.
This settles none of the contracts above. Binary fission continuity, eggs, cohorts,
broadcast spores, gestation, strategy selection, mutation candidates, client
intentions, control grants, durable acknowledgment and logout treatment remain
open. The fixture has no accounts, so a parent reference grants no ownership and
no label. Test processes are not wildlife and do not seed a persistent world.
+26
View File
@@ -275,3 +275,29 @@ no deployment change.
[Gitea run 1417](https://git.aeternalisgames.com/dingo/AEvolution/actions/runs/1417)
passed all four jobs for source `e17a9a7279d6bde736261c0c33abe46108e1f622`:
Linux checks, ECS regression, separate TSan and image smoke/publication.
## M2.5 funded reproduction (2026-09-21)
Native Release, analysis and MSVC ASan passed 8/8 CTests; formatting passed.
Commands: `tools/windows-check.ps1 -Preset <release|analysis|asan> -Action check`
and debug `-Action format`. The first format run rejected three wrapped test
declarations; clang-format 19.1.5 rewrote them and Release was rebuilt and rerun.
Tests cover hand-calculated endowment and construction overhead, the endowment
floor, per-channel insufficiency with abundant energy, zero and oversized
investments, reserved slots rejected as feeding targets, corpses and ancestry
subjects, the producer rejected as a parent, terminated and unknown parents,
zero/duplicate sequences, two intents naming one parent, oversized batches,
capacity exhaustion rejecting the whole tick, absent identity reuse after a child
dies and decomposes, ancestry surviving both deaths, and construction endpoints of
0 and 1000 including a paid-for zero-endowment child. 32 seeds × 4 ticks × 2 births
compare reversed intent order against balances, producer progress, birth receipts
and independently recomputed conservation. A u64-maximum investment endows exactly
and conserves. Default zero capacity leaves the M2.4 reservoir layout, feeding,
producer, ledger and particle tests unchanged; golden `d61ad5bf0c928c76` is intact.
Allocation-failure injection, serialized recovery of states/parents/origins and
long-run ecosystem behavior were not exercised. This fixture defines no
reproductive strategy, fecundity, mutation, gestation, spatial placement or account
ownership, and no deployment manifest or image pin changed. Linux validation is
pending its first pushed run; no Gitea result is claimed for this increment yet.
+46 -4
View File
@@ -26,15 +26,36 @@ struct TerminalEvent {
struct DecompositionConfig {
accounting::Inventory per_tick_limit{};
};
// Reserved slots are allocated at creation; a birth never grows the ledger.
struct ReproductionConfig {
std::uint32_t capacity{};
std::uint16_t construction_per_thousand{};
accounting::Inventory minimum_endowment{};
};
struct ReproduceIntent {
std::uint64_t sequence;
std::uint32_t parent;
accounting::Inventory investment;
};
struct ReproduceReceipt {
std::uint64_t sequence;
std::uint32_t child;
accounting::Inventory endowment;
accounting::Inventory overhead;
auto operator<=>(const ReproduceReceipt&) const = default;
};
enum class FeedingError : std::uint8_t {
invalid_config,
wrong_tick,
invalid_batch,
invalid_actor,
inactive_actor,
unborn_actor,
not_corpse,
intake_limit,
insufficient_inventory,
no_capacity,
invalid_endowment,
accounting_failure
};
inline constexpr std::size_t max_consumers = 16;
@@ -44,10 +65,12 @@ class FeedingCommunity {
[[nodiscard]] static std::expected<FeedingCommunity, FeedingError>
create(ProducerConfig producer, accounting::Picojoules source,
std::array<accounting::Femtograms, 4> nutrients,
std::span<const ConsumerConfig> consumers, DecompositionConfig decomposition = {});
std::span<const ConsumerConfig> consumers, DecompositionConfig decomposition = {},
ReproductionConfig reproduction = {});
[[nodiscard]] std::expected<std::vector<FeedReceipt>, FeedingError>
advance(Tick target, std::span<const FeedIntent> inputs = {},
std::span<const TerminalEvent> terminal_events = {});
std::span<const TerminalEvent> terminal_events = {},
std::span<const ReproduceIntent> births = {});
[[nodiscard]] std::span<const accounting::Inventory> balances() const noexcept {
return producer_.balances();
}
@@ -56,21 +79,40 @@ class FeedingCommunity {
}
// 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;
// False for a reserved slot that no reproduction has allocated yet.
[[nodiscard]] std::expected<bool, FeedingError> born(std::uint32_t id) const noexcept;
[[nodiscard]] std::expected<accounting::Inventory, FeedingError>
corpse(std::uint32_t id) const noexcept;
// Ancestry outlives both organisms; zero identifies a documented founder.
[[nodiscard]] std::expected<std::uint32_t, FeedingError>
parent(std::uint32_t id) const noexcept;
[[nodiscard]] std::expected<Tick, FeedingError> origin(std::uint32_t id) const noexcept;
[[nodiscard]] accounting::Inventory last_decomposed() const noexcept {
return last_decomposed_;
}
// Committed births of the last successful tick; invalidated by mutation.
[[nodiscard]] std::span<const ReproduceReceipt> last_births() const noexcept {
return last_births_;
}
private:
enum class State : std::uint8_t { unborn, active, corpse };
FeedingCommunity(ProducerProcess producer, std::vector<ConsumerConfig> consumers,
DecompositionConfig decomposition);
DecompositionConfig decomposition, ReproductionConfig reproduction,
std::uint32_t living);
[[nodiscard]] std::expected<FeedReceipt, FeedingError> feed(const FeedIntent& input);
[[nodiscard]] std::expected<ReproduceReceipt, FeedingError>
reproduce(const ReproduceIntent& input, Tick target);
[[nodiscard]] std::expected<void, FeedingError> decompose();
[[nodiscard]] std::expected<State, FeedingError> state(std::uint32_t id) const noexcept;
ProducerProcess producer_;
std::vector<ConsumerConfig> consumers_;
std::vector<std::uint8_t> active_;
std::vector<State> states_;
std::vector<std::uint32_t> parents_;
std::vector<Tick> origins_;
DecompositionConfig decomposition_;
ReproductionConfig reproduction_;
accounting::Inventory last_decomposed_{};
std::vector<ReproduceReceipt> last_births_;
};
} // namespace evo::processes
+175 -32
View File
@@ -27,16 +27,26 @@ accounting::ReservoirId reservoir(std::uint32_t actor) noexcept {
} // namespace
FeedingCommunity::FeedingCommunity(ProducerProcess producer, std::vector<ConsumerConfig> consumers,
DecompositionConfig decomposition)
DecompositionConfig decomposition,
ReproductionConfig reproduction, std::uint32_t living)
: producer_{std::move(producer)}, consumers_{std::move(consumers)},
active_(consumers_.size() + 1, 1), decomposition_{decomposition} {}
states_(consumers_.size() + 1, State::unborn), parents_(consumers_.size() + 1, 0),
origins_(consumers_.size() + 1, Tick{}), decomposition_{decomposition},
reproduction_{reproduction} {
// Index zero is the producer; reserved slots stay unborn until a funded birth.
for (std::size_t index = 0; index <= living; ++index) {
states_[index] = State::active;
}
}
std::expected<FeedingCommunity, FeedingError>
FeedingCommunity::create(ProducerConfig producer, accounting::Picojoules source,
std::array<accounting::Femtograms, 4> nutrients,
std::span<const ConsumerConfig> consumers,
DecompositionConfig decomposition) {
DecompositionConfig decomposition, ReproductionConfig reproduction) {
if (consumers.empty() || consumers.size() > max_consumers ||
reproduction.capacity > max_consumers - consumers.size() ||
reproduction.construction_per_thousand > 1000 ||
std::ranges::any_of(consumers,
[](const auto& c) { return c.assimilation_per_thousand > 1000; })) {
return std::unexpected{FeedingError::invalid_config};
@@ -50,30 +60,94 @@ FeedingCommunity::create(ProducerConfig producer, accounting::Picojoules source,
for (const auto& consumer : consumers) {
opening.push_back(consumer.opening);
}
// Reserved reservoirs precede waste, so the waste index remains last.
opening.insert(opening.end(), reproduction.capacity, accounting::Inventory{});
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()}, decomposition};
std::vector<ConsumerConfig> slots{consumers.begin(), consumers.end()};
slots.resize(consumers.size() + reproduction.capacity);
return FeedingCommunity{std::move(*isolated), std::move(slots), decomposition, reproduction,
static_cast<std::uint32_t>(consumers.size())};
}
std::expected<FeedingCommunity::State, FeedingError>
FeedingCommunity::state(std::uint32_t id) const noexcept {
if (id == 0 || id > states_.size()) {
return std::unexpected{FeedingError::invalid_actor};
}
return states_[id - 1];
}
std::expected<bool, FeedingError> FeedingCommunity::active(std::uint32_t id) const noexcept {
if (id == 0 || id > active_.size()) {
return std::unexpected{FeedingError::invalid_actor};
const auto current = state(id);
if (!current) {
return std::unexpected{current.error()};
}
return active_[id - 1] != 0;
return *current == State::active;
}
std::expected<bool, FeedingError> FeedingCommunity::born(std::uint32_t id) const noexcept {
const auto current = state(id);
if (!current) {
return std::unexpected{current.error()};
}
return *current != State::unborn;
}
std::expected<std::uint32_t, FeedingError>
FeedingCommunity::parent(std::uint32_t id) const noexcept {
const auto exists = born(id);
if (!exists) {
return std::unexpected{exists.error()};
}
if (!*exists) {
return std::unexpected{FeedingError::unborn_actor};
}
return parents_[id - 1];
}
std::expected<Tick, FeedingError> FeedingCommunity::origin(std::uint32_t id) const noexcept {
const auto exists = born(id);
if (!exists) {
return std::unexpected{exists.error()};
}
if (!*exists) {
return std::unexpected{FeedingError::unborn_actor};
}
return origins_[id - 1];
}
std::expected<accounting::Inventory, FeedingError>
FeedingCommunity::corpse(std::uint32_t id) const noexcept {
const auto current = state(id);
if (!current) {
return std::unexpected{current.error()};
}
if (*current == State::unborn) {
return std::unexpected{FeedingError::unborn_actor};
}
if (*current == State::active) {
return std::unexpected{FeedingError::not_corpse};
}
return balances()[reservoir(id).value - 1];
}
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) {
if (input.consumer < 2 || input.consumer > states_.size() || input.target == 0 ||
input.target > states_.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};
for (const auto actor : {input.consumer, input.target}) {
if (states_[actor - 1] == State::unborn) {
return std::unexpected{FeedingError::unborn_actor};
}
if (states_[actor - 1] != State::active) {
return std::unexpected{FeedingError::inactive_actor};
}
}
const auto& config = consumers_[input.consumer - 2];
if (input.amount == accounting::Inventory{} || !fits(input.amount, config.intake_limit)) {
@@ -103,32 +177,74 @@ std::expected<FeedReceipt, FeedingError> FeedingCommunity::feed(const FeedIntent
}
const bool depleted = balances()[from.value - 1] == accounting::Inventory{};
if (depleted) {
active_[input.target - 1] = 0;
states_[input.target - 1] = State::corpse;
}
return FeedReceipt{input.sequence, assimilated, depleted};
}
std::expected<accounting::Inventory, FeedingError>
FeedingCommunity::corpse(std::uint32_t id) const noexcept {
const auto alive = active(id);
if (!alive) {
return std::unexpected{alive.error()};
std::expected<ReproduceReceipt, FeedingError>
FeedingCommunity::reproduce(const ReproduceIntent& input, Tick target) {
// The producer is funded by capture; treating it as a parent would conflate the two.
if (input.parent < 2 || input.parent > states_.size()) {
return std::unexpected{FeedingError::invalid_actor};
}
if (*alive) {
return std::unexpected{FeedingError::not_corpse};
if (states_[input.parent - 1] == State::unborn) {
return std::unexpected{FeedingError::unborn_actor};
}
return balances()[reservoir(id).value - 1];
if (states_[input.parent - 1] != State::active) {
return std::unexpected{FeedingError::inactive_actor};
}
if (input.investment == accounting::Inventory{}) {
return std::unexpected{FeedingError::invalid_endowment};
}
const auto from = reservoir(input.parent);
if (!fits(input.investment, balances()[from.value - 1])) {
return std::unexpected{FeedingError::insufficient_inventory};
}
const auto slot = std::ranges::find(states_, State::unborn);
if (slot == states_.end()) {
return std::unexpected{FeedingError::no_capacity};
}
const auto child = static_cast<std::uint32_t>(slot - states_.begin()) + 1;
accounting::Inventory endowment{}, heat{}, waste{};
endowment.energy.value =
portion(input.investment.energy.value, reproduction_.construction_per_thousand);
heat.energy.value = input.investment.energy.value - endowment.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
endowment.matter[index].value =
portion(input.investment.matter[index].value, reproduction_.construction_per_thousand);
waste.matter[index].value =
input.investment.matter[index].value - endowment.matter[index].value;
}
if (!fits(reproduction_.minimum_endowment, endowment)) {
return std::unexpected{FeedingError::invalid_endowment};
}
const std::array legs{
accounting::Transfer{from, reservoir(child), endowment},
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};
}
*slot = State::active;
// No genome exists yet, so a child duplicates the configuration of its parent.
consumers_[child - 2] = consumers_[input.parent - 2];
parents_[child - 1] = input.parent;
origins_[child - 1] = target;
return ReproduceReceipt{input.sequence, child, endowment, {heat.energy, waste.matter}};
}
std::expected<void, FeedingError> FeedingCommunity::decompose() {
auto remaining = decomposition_.per_tick_limit;
// Final iteration is waste, after all inactive process reservoirs.
for (std::size_t index = 0; index <= active_.size(); ++index) {
if (index < active_.size() && active_[index] != 0) {
// Final iteration is waste, after all corpse reservoirs. Unborn slots are skipped.
for (std::size_t index = 0; index <= states_.size(); ++index) {
if (index < states_.size() && states_[index] != State::corpse) {
continue;
}
const auto from =
index == active_.size()
index == states_.size()
? accounting::ReservoirId{static_cast<std::uint32_t>(balances().size())}
: reservoir(static_cast<std::uint32_t>(index + 1));
const auto available = balances()[from.value - 1];
@@ -164,13 +280,14 @@ std::expected<void, FeedingError> FeedingCommunity::decompose() {
std::expected<std::vector<FeedReceipt>, FeedingError>
FeedingCommunity::advance(Tick target, std::span<const FeedIntent> inputs,
std::span<const TerminalEvent> terminal_events) {
std::span<const TerminalEvent> terminal_events,
std::span<const ReproduceIntent> births) {
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() ||
terminal_events.size() > active_.size()) {
if (inputs.size() > max_consumers || states_.empty() ||
terminal_events.size() > states_.size() || births.size() > max_consumers) {
return std::unexpected{FeedingError::invalid_batch};
}
std::vector<FeedIntent> ordered{inputs.begin(), inputs.end()};
@@ -185,19 +302,35 @@ FeedingCommunity::advance(Tick target, std::span<const FeedIntent> inputs,
seen[input.consumer] = true;
previous = input.sequence;
}
// Reproduction sequences form a separate space; a consumer may feed and then reproduce.
std::vector<ReproduceIntent> ordered_births{births.begin(), births.end()};
std::ranges::sort(ordered_births, {}, &ReproduceIntent::sequence);
std::array<bool, max_consumers + 2> expecting{};
previous = 0;
for (const auto& birth : ordered_births) {
if (birth.sequence == 0 || birth.sequence == previous || birth.parent < 2 ||
birth.parent > consumers_.size() + 1 || expecting[birth.parent]) {
return std::unexpected{FeedingError::invalid_batch};
}
expecting[birth.parent] = true;
previous = birth.sequence;
}
auto candidate = *this;
std::array<bool, max_consumers + 2> terminated{};
for (const auto event : terminal_events) {
if (event.actor == 0 || event.actor > active_.size() || terminated[event.actor]) {
if (event.actor == 0 || event.actor > states_.size() || terminated[event.actor]) {
return std::unexpected{FeedingError::invalid_batch};
}
if (candidate.active_[event.actor - 1] == 0) {
if (candidate.states_[event.actor - 1] == State::unborn) {
return std::unexpected{FeedingError::unborn_actor};
}
if (candidate.states_[event.actor - 1] != State::active) {
return std::unexpected{FeedingError::inactive_actor};
}
terminated[event.actor] = true;
candidate.active_[event.actor - 1] = 0;
candidate.states_[event.actor - 1] = State::corpse;
}
if (candidate.active_[0] != 0) {
if (candidate.states_[0] == State::active) {
if (!candidate.producer_.advance(target)) {
return std::unexpected{FeedingError::accounting_failure};
}
@@ -213,6 +346,16 @@ FeedingCommunity::advance(Tick target, std::span<const FeedIntent> inputs,
}
receipts.push_back(*result);
}
std::vector<ReproduceReceipt> delivered;
delivered.reserve(ordered_births.size());
for (const auto& birth : ordered_births) {
const auto result = candidate.reproduce(birth, target);
if (!result) {
return std::unexpected{result.error()};
}
delivered.push_back(*result);
}
candidate.last_births_ = std::move(delivered);
if (const auto result = candidate.decompose(); !result) {
return std::unexpected{result.error()};
}
+172 -1
View File
@@ -268,6 +268,174 @@ void ordered_replay() {
CHECK(sum(*community) == bundle(maximum));
}
}
void funded_reproduction() {
const std::array configs{ConsumerConfig{bundle(100), bundle(100), 1000}};
auto community =
FeedingCommunity::create(producer(), {100}, bundle(20).matter, configs, {}, {2, 750, {}});
CHECK(community);
const auto total = sum(*community);
// Four producer reservoirs, one consumer, two reserved slots and waste.
CHECK(community->balances().size() == 8);
CHECK(*community->born(2) && !*community->born(3) && !*community->born(4));
CHECK(!community->corpse(3) && community->corpse(3).error() == FeedingError::unborn_actor);
CHECK(!community->parent(3) && community->parent(3).error() == FeedingError::unborn_actor);
CHECK(!community->origin(4) && community->origin(4).error() == FeedingError::unborn_actor);
CHECK(community->parent(2) && *community->parent(2) == 0);
CHECK(community->origin(2) && community->origin(2)->value == 0);
const std::array early{FeedIntent{1, 2, 3, bundle(1)}};
const auto denied = community->advance(evo::Tick{1}, early);
CHECK(!denied && denied.error() == FeedingError::unborn_actor);
// 750/1000 of eight units endows six; the remainder is real heat and waste.
const std::array birth{ReproduceIntent{1, 2, bundle(8)}};
CHECK(community->advance(evo::Tick{1}, {}, {}, birth));
CHECK(community->last_births().size() == 1);
CHECK(community->last_births()[0] == (ReproduceReceipt{1, 3, bundle(6), bundle(2)}));
CHECK(community->balances()[4] == bundle(92) && community->balances()[5] == bundle(6));
CHECK(community->balances()[3].energy.value == 4); // Growth heat plus construction heat.
CHECK(community->balances().back() == (Inventory{{}, bundle(2).matter}));
CHECK(*community->born(3) && *community->active(3));
CHECK(*community->parent(3) == 2 && community->origin(3)->value == 1);
CHECK(sum(*community) == total);
// The child acts from the next tick using its duplicated parent configuration.
const std::array meal{FeedIntent{1, 3, 2, bundle(1)}};
CHECK(community->advance(evo::Tick{2}, meal));
CHECK(community->balances()[4] == bundle(91) && community->balances()[5] == bundle(7));
CHECK(community->last_births().empty() && sum(*community) == total);
}
void reproduction_limits_and_rollback() {
const std::array configs{ConsumerConfig{bundle(100), bundle(100), 1000}};
auto community = FeedingCommunity::create(producer(), {100}, bundle(20).matter, configs, {},
{1, 1000, bundle(10)});
CHECK(community);
const auto before = copy(*community);
const auto progress = community->progress();
const auto reject = [&](std::span<const ReproduceIntent> births, FeedingError expected) {
const auto result = community->advance(evo::Tick{1}, {}, {}, births);
CHECK(!result && result.error() == expected);
CHECK(copy(*community) == before && community->progress() == progress);
CHECK(community->last_births().empty() && *community->active(2) && !*community->born(3));
};
const std::array small{ReproduceIntent{1, 2, bundle(9)}};
reject(small, FeedingError::invalid_endowment); // Below the configured endowment floor.
const std::array nothing{ReproduceIntent{1, 2, {}}};
reject(nothing, FeedingError::invalid_endowment);
const std::array huge{ReproduceIntent{1, 2, bundle(101)}};
reject(huge, FeedingError::insufficient_inventory);
const std::array reserved{ReproduceIntent{1, 3, bundle(10)}};
reject(reserved, FeedingError::unborn_actor);
for (const auto parent : {0U, 1U, 99U}) {
const std::array invalid{ReproduceIntent{1, parent, bundle(10)}};
reject(invalid, FeedingError::invalid_batch);
}
const std::array unsequenced{ReproduceIntent{0, 2, bundle(10)}};
reject(unsequenced, FeedingError::invalid_batch);
const std::array twice{ReproduceIntent{1, 2, bundle(10)}, ReproduceIntent{2, 2, bundle(10)}};
reject(twice, FeedingError::invalid_batch); // One funded birth per parent per tick.
const std::vector<ReproduceIntent> many(max_consumers + 1, ReproduceIntent{1, 2, bundle(10)});
reject(many, FeedingError::invalid_batch);
// Energy is abundant but one element is not; the whole tick must roll back.
const std::array starved{ConsumerConfig{{{1000}, {Femtograms{1}}}, {}, 0}};
auto scarce = FeedingCommunity::create(producer(), {}, {}, starved, {}, {1, 1000, {}});
CHECK(scarce);
const auto opening = copy(*scarce);
const std::array unfunded{ReproduceIntent{1, 2, {{10}, {Femtograms{2}}}}};
const auto refused = scarce->advance(evo::Tick{1}, {}, {}, unfunded);
CHECK(!refused && refused.error() == FeedingError::insufficient_inventory);
CHECK(copy(*scarce) == opening && !*scarce->born(3));
const std::array affordable{ReproduceIntent{1, 2, {{10}, {Femtograms{1}}}}};
CHECK(scarce->advance(evo::Tick{1}, {}, {}, affordable));
const std::array pair{ConsumerConfig{bundle(100), bundle(100), 1000},
ConsumerConfig{bundle(100), bundle(100), 1000}};
auto limited =
FeedingCommunity::create(producer(), {100}, bundle(20).matter, pair, {}, {1, 1000, {}});
CHECK(limited);
const auto available = copy(*limited);
const std::array both{ReproduceIntent{1, 2, bundle(10)}, ReproduceIntent{2, 3, bundle(10)}};
const auto overflowing = limited->advance(evo::Tick{1}, {}, {}, both);
CHECK(!overflowing && overflowing.error() == FeedingError::no_capacity);
CHECK(copy(*limited) == available); // Capacity rejects; it never funds a smaller child.
const std::array single{ReproduceIntent{1, 2, bundle(10)}};
CHECK(limited->advance(evo::Tick{1}, {}, {}, single));
CHECK(limited->last_births()[0].child == 4);
const std::array queued{ReproduceIntent{1, 3, bundle(10)}};
const auto full = limited->advance(evo::Tick{2}, {}, {}, queued);
CHECK(!full && full.error() == FeedingError::no_capacity);
const std::array death{TerminalEvent{2}};
CHECK(limited->advance(evo::Tick{2}, {}, death));
const auto orphaned = limited->advance(evo::Tick{3}, {}, {}, single);
CHECK(!orphaned && orphaned.error() == FeedingError::inactive_actor);
CHECK(*limited->parent(4) == 2 && limited->origin(4)->value == 1);
CHECK(!*limited->active(2) && *limited->parent(2) == 0); // Ancestry outlives the parent.
}
void lineage_identity_and_permutation() {
const std::array configs{ConsumerConfig{bundle(100), bundle(100), 1000}};
auto community =
FeedingCommunity::create(producer(), {}, {}, configs, {bundle(1000)}, {2, 1000, {}});
CHECK(community);
const auto total = sum(*community);
const std::array first{ReproduceIntent{1, 2, bundle(10)}};
CHECK(community->advance(evo::Tick{1}, {}, {}, first));
CHECK(community->last_births()[0].child == 3);
const std::array kill{TerminalEvent{3}};
CHECK(community->advance(evo::Tick{2}, {}, kill));
CHECK(!*community->active(3) && *community->corpse(3) == Inventory{});
CHECK(*community->parent(3) == 2 && community->origin(3)->value == 1);
const std::array second{ReproduceIntent{1, 2, bundle(10)}};
CHECK(community->advance(evo::Tick{3}, {}, {}, second));
CHECK(community->last_births()[0].child == 4); // A retired identity is never reused.
CHECK(*community->parent(4) == 2 && community->origin(4)->value == 3);
CHECK(*community->parent(3) == 2 && sum(*community) == total);
for (std::uint64_t seed = 0; seed < 32; ++seed) {
evo::Random random{seed};
const std::array parents{ConsumerConfig{bundle(1000), bundle(10), 1000},
ConsumerConfig{bundle(1000), bundle(10), 1000}};
auto a = FeedingCommunity::create(producer(), {10'000}, bundle(1000).matter, parents, {},
{8, 600, {}});
CHECK(a);
auto b = *a;
const auto conserved = sum(*a);
for (std::uint64_t tick = 1; tick <= 4; ++tick) {
std::array births{ReproduceIntent{1, 2, bundle(4)}, ReproduceIntent{2, 3, bundle(4)}};
CHECK(a->advance(evo::Tick{tick}, {}, {}, births));
if (random.next() % 2 != 0) {
std::ranges::reverse(births);
}
CHECK(b.advance(evo::Tick{tick}, {}, {}, births));
CHECK(copy(*a) == copy(b) && a->progress() == b.progress());
CHECK(std::ranges::equal(a->last_births(), b.last_births()));
CHECK(sum(*a) == conserved);
}
const std::array exhausted{ReproduceIntent{1, 2, bundle(4)}};
CHECK(!a->advance(evo::Tick{5}, {}, {}, exhausted));
}
for (const auto construction : {0U, 1000U}) {
const std::array funded{ConsumerConfig{bundle(50), {}, 0}};
auto endpoint = FeedingCommunity::create(producer(), {}, {}, funded, {},
{1, static_cast<std::uint16_t>(construction), {}});
CHECK(endpoint);
const auto conserved = sum(*endpoint);
const std::array birth{ReproduceIntent{1, 2, bundle(50)}};
CHECK(endpoint->advance(evo::Tick{1}, {}, {}, birth));
const auto receipt = endpoint->last_births()[0];
CHECK(receipt.endowment == bundle(construction == 0 ? 0 : 50));
CHECK(receipt.overhead == bundle(construction == 0 ? 50 : 0));
// A zero endowment is an empty living child, not a free one: the parent still paid.
CHECK(*endpoint->active(3) && sum(*endpoint) == conserved);
}
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
const std::array extremes{ConsumerConfig{bundle(maximum), {}, 0}};
auto extreme =
FeedingCommunity::create(producer(), {}, {}, extremes, {}, {1, 1000, bundle(maximum)});
CHECK(extreme);
const std::array birth{ReproduceIntent{1, 2, bundle(maximum)}};
CHECK(extreme->advance(evo::Tick{1}, {}, {}, birth));
CHECK(extreme->last_births()[0].endowment == bundle(maximum));
CHECK(*extreme->parent(3) == 2 && sum(*extreme) == bundle(maximum));
CHECK(!FeedingCommunity::create(producer(), {}, {}, configs, {}, {1, 1001, {}}));
const std::vector<ConsumerConfig> saturated(max_consumers, configs[0]);
CHECK(!FeedingCommunity::create(producer(), {}, {}, saturated, {}, {1, 1000, {}}));
CHECK(FeedingCommunity::create(producer(), {}, {}, saturated, {}, {0, 1000, {}}));
}
} // namespace
int main() try {
capture_feeding_and_terminal();
@@ -276,7 +444,10 @@ int main() try {
corpse_preservation_and_rollback();
decomposition_reference();
nutrient_return_and_waste();
std::cout << "PASS shared feeding, rollback, terminality and conservation\n";
funded_reproduction();
reproduction_limits_and_rollback();
lineage_identity_and_permutation();
std::cout << "PASS shared feeding, reproduction, lineage identity and conservation\n";
return 0;
} catch (...) {
return 1;