feat(lifecycle): retain inherited offspring plans separately from bodies
Foundation / checks (ecs) (push) Successful in 2m26s
Foundation / checks (deploy) (push) Successful in 4m6s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (client) (push) Canceled after 9m29s
Foundation / checks (tsan) (push) Canceled after 7m4s
Foundation / checks (network) (push) Canceled after 9m28s
Foundation / checks (postgres) (push) Canceled after 9m28s
Foundation / checks (checks) (push) Canceled after 9m34s

This commit is contained in:
dingo
2026-10-19 13:55:29 -04:00
parent 5d8aa4d2e3
commit 2c3a3c65a6
16 changed files with 887 additions and 71 deletions
+10
View File
@@ -695,6 +695,16 @@ endif()
if(BUILD_TESTING)
add_executable(evo-cellular-population-tests tests/cellular_population_tests.cpp)
add_executable(evo-cellular-inheritance-tests tests/cellular_inheritance_tests.cpp)
target_link_libraries(evo-cellular-inheritance-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-cellular-inheritance-tests)
add_test(NAME cellular-inherited-plans COMMAND evo-cellular-inheritance-tests)
set_tests_properties(cellular-inherited-plans PROPERTIES TIMEOUT ${evo_cohort_timeout})
add_test(NAME cellular-inheritance-process-restart COMMAND "${CMAKE_COMMAND}"
"-DPOPULATION_TEST=$<TARGET_FILE:evo-cellular-inheritance-tests>"
"-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/inheritance-restart"
-P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake")
set_tests_properties(cellular-inheritance-process-restart PROPERTIES TIMEOUT ${evo_cohort_timeout})
add_executable(evo-cellular-maturation-tests tests/cellular_maturation_tests.cpp)
target_link_libraries(evo-cellular-maturation-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-cellular-maturation-tests)
+8
View File
@@ -203,6 +203,14 @@ runs the declared 80,000-tick development/hold-out matrix with raw/cohort equali
whole-genome conversions, restores and resource controls. This is bounded ecology
evidence, not actual-days or product acceptance.
The opt-in [retained offspring-plan owner](docs/adr/0165-retained-cellular-offspring-plans.md)
keeps parent anatomy separate from earned inherited changes and repeatedly funds
offspring from the saved plan. Build `evo-cellular-inheritance-tests`; CTest
`cellular-inherited-plans` and `cellular-inheritance-process-restart` cover its
portable contract. [Format 8](schemas/cellular-lives-v8.md) is not admitted to
existing durable bundles or live entry. Control succession and behavior/UI
integration remain pending.
M5.1 local voxel/address API and scope: [local voxel contract](docs/world/LOCAL_VOXEL_CONTRACT.md).
M5.8 process restart proof and measured costs: [world proof](docs/engineering/WORLD_PROOF.md).
@@ -12,7 +12,7 @@ spec:
env:
- {name: REGION_SESSION, value: "dev"}
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261019T170913-a5535407:1792444153"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261019T173417-a98f9f06:1792445657"}
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
ports:
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
+15
View File
@@ -1,5 +1,20 @@
# Project status and next steps
## Portable retained offspring plans - 2026-10-19
[ADR-0165](adr/0165-retained-cellular-offspring-plans.md) implements an opt-in
stored-plan owner, format 8/rules 10. Earned selections edit the inherited plan;
the parent's expressed body and biological charges stay unchanged. Repeated
funded births use that plan, later selections preserve earlier siblings, and
reloads/death history retain the distinction. Older saves retain their meaning.
MSVC/GCC full Release suites pass **85/85**; exact separate-process inherited
continuations agree across compilers. [Validation](engineering/VALIDATION.md)
records analysis/sanitizer evidence and scope. Current durable bundles, census,
population, migration and old batch replay refuse the new owner. Durable plan
integration, the in-life expression catalog, birth-time control succession,
retained NPC behavior and choice UI remain open. M12 remains in progress.
## Distinct-genome offspring funding - 2026-10-19
[ADR-0164](adr/0164-distinct-genome-offspring-funding.md) implements the first
@@ -0,0 +1,83 @@
# ADR-0165: Retained cellular offspring plans
## Status and scope
Accepted for the portable stored-plan segment of ADR-0163/0164, 2026-10-19.
No default/DEV upgrade, SQL admission, player succession or NPC behavior policy.
This is an explicit offspring-plan editing mode, not a final classification of
which future mutation operators may also be expressed during an existing life.
## Decision
Add cellular owner format 8/rules 10 through a detached no-tick upgrade from
format 7/rules 9. Preserve all biology, inventories, identities, offers, boundary
flows and archive history. Initialize each living/corpse offspring plan to its
currently expressed genome. Older formats retain zero in the new in-memory
fields and omit them from their unchanged canonical bytes.
`identity.genome` and archive `current_genome` keep their expressed-body meaning.
The separate `offspring_genome` names the inherited developmental plan. Every
newborn starts with both references naming the actual inherited plan. Existing
body derivation, maintenance, movement, feeding, growth, damage, predation and
spatial exclusion always use the expressed genome. Corpses retain the last
offspring plan as history, with no reproductive viability granted to dead tissue.
In this opt-in editing mode, the existing earned mutation choice edits the
offspring plan. Draw from the current plan using the existing recorded context
and eligibility credit. Revalidate selections exactly; admit the successor genome
without adding an expressed-genome revision or constructing parent tissue.
Consume the offer once. Record `(life,previous_plan,successor_plan,tick)` in an
append-only log, bounded by the existing genome archive capacity. Operator zero
still declines. NPCs still earn no mutation offers. No extra mutation fee is
invented: physical construction is funded when an actual offspring is made.
The live-expression path for nonstructural traits requires a later operator
catalog/transaction contract; this mode supplies only offspring-plan selections.
Use ADR-0164 mixed-genome funding for buds and their exact twin eligibility.
Retain existing phase order: surviving-parent plan selection precedes budding;
newborns do not grow or bud in their birth tick. Thus a selected plan can affect
that tick's offspring while the parent's expressed body remains unchanged. The
child's birth archive record names its actual inherited genome. Later selections
affect later offspring only. Wildlife reproduction uses the actual plan cost.
## State and restore invariants
Format 8 extends the format-7 header by a u32 plan-history count and zero u32
reserved field (316 bytes total). Each living/corpse row appends one u64 plan
reference (512/132 bytes). After habitat, archive and nonresident IDs, append
32-byte history rows in increasing `(tick,life)` order, then the existing FNV
trailer. Preserve the 16 MiB owner bound and existing archive limits. The magic is
`AEVCLV08`; only rules 10 uses this format. No native-layout serialization.
Validate counts/size before allocation, all plan references, compatible schema/
development versions, and each complete per-life chain from its expressed genome.
History successors have one genome parent matching the recorded previous plan
and their recorded origin matches the selected successor identity. Require unique
successors, live-at-selection timing, retained actor identity, and final references
matching the log. Selections must follow any legacy expressed-body revision used
as their initial plan. Regenerate outstanding offers from the retained current plan.
Missing, conflicting, forged, over-bound or noncanonical state refuses atomically.
## Alternatives, benefits, costs and risks
Overwriting the parent's expressed genome would rebuild it and misprice its body.
Treating an unexpressed plan as an archive living carrier invents an organism.
Keeping only a final reference loses which parent selected earlier sibling plans.
The distinct reference/log preserves body and ancestry meanings at bounded cost.
A plan without expressed carriers may still be reproductively available in a
living parent. Existing census, migration, population and persistence allowlists
must refuse this new owner until they have complete plan/viability semantics and
versioned replay; absence of expressed carriers cannot prove its extinction.
No old snapshot or golden is rewritten. This portable checkpoint is not durable
publication authority, and no existing SQL bundle admits it.
## Qualification
Require real earned plan selections, unchanged parent anatomy/biological charges,
different funded sibling plans, later choices leaving earlier children unchanged,
exact save/restore and separate-process continuation, death/history retention,
offline exclusion, all-channel closure, unsupported old paths and forged codecs.
Run Release/NDEBUG, analysis, formatting and relevant ASan/UBSan checks. Retained
plans do not implement the birth-time control choice, persistent NPC behavior,
new limb/plant traits, UI, environmental producers or M12 completion.
+2
View File
@@ -1,5 +1,7 @@
# Architecture decision records
- [ADR-0165: Retained cellular offspring plans](0165-retained-cellular-offspring-plans.md) - portable owner format 8/rules 10 keeps expressed bodies separate from earned inherited plans, repeated births and selection history; durable/control/UI integration pending.
- [ADR-0164: Distinct-genome offspring funding](0164-distinct-genome-offspring-funding.md) - pure funded reproduction separates the expressed parent's investment from the inherited child's anatomy and provision; old same-genome behavior retained, owner/control integration pending.
- [ADR-0163: Structural inheritance and one-way offspring succession](0163-structural-inheritance-and-offspring-succession.md) - maintainer-accepted target gameplay: offspring structural traits, irreversible birth-time control choice and NPC-parent behavior/reproductive continuity; implementation pending.
+23 -7
View File
@@ -16,10 +16,10 @@ are living is a different event. Each organism keeps its own identity, inventory
development, ancestry and terminal death. Only the currently controlled organism
freezes on logout; independent parents and siblings continue living normally.
Implementation remains pending. Separate expressed/heritable state and bounded
NPC behavior, versioned mutation timing and a durable birth/control choice must
be implemented before this behavior is offered. Choice timing and pause policy
remain explicit implementation decisions. The M11 decisions and diagram below
Portable expressed/heritable state is now implemented below. Bounded NPC
behavior and a durable birth/control choice must be implemented before this
behavior is offered. Choice timing and pause policy remain explicit implementation
decisions. The M11 decisions and diagram below
describe the old baseline, not a prohibition on the accepted target behavior.
## Implemented portable offspring funding
@@ -34,9 +34,25 @@ refuse. Two share-funded children cannot manufacture the parent's invested matte
Tests cover changed anatomy and demand, sterile children, exact cost/shortages,
twins and retained archive identities. Existing same-genome helpers delegate to
this operation with identical parent/child inputs. This is a pure proposal;
stored heritable state, mutation expression timing, succession, NPC behavior and
birth UI remain unimplemented. Current live rules still produce exact-copy buds.
this operation with identical parent/child inputs. Current live rules still
produce exact-copy buds.
## Implemented portable retained plans
[ADR-0165](../adr/0165-retained-cellular-offspring-plans.md) adds opt-in owner
format 8/rules 10. Expressed genome IDs keep describing existing tissue. Earned
mutation choices in this mode edit a separate offspring plan, without rebuilding
the parent or charging for unconstructed tissue. Physical construction is funded
at birth. Subsequent offspring use that plan until another selection changes it;
earlier children keep their original form. Save/reload retains plan selections
and dead-parent history, and logout freezes the controlled parent's biology.
This scoped mode edits inherited plans only. The future operator catalog still
needs to distinguish traits that can also change during an existing life. Existing
durable bundles, census, population, migration and batch replay refuse the new
owner until their plan semantics are qualified. The birth-time control choice,
persistent NPC behavior and UI remain unimplemented; default/DEV rules do not
opt into this owner.
## Historical M11 baseline and open strategies
+9 -5
View File
@@ -7,15 +7,19 @@ Completed scoped commits do not mean their entire roadmap gates have passed.
The maintainer's 2026-10-19 [gameplay clarification](../adr/0163-structural-inheritance-and-offspring-succession.md)
accepts offspring structural expression, a one-way birth-time control choice and
NPC-parent behavior/reproductive continuity. Current mutation, controller, birth,
control and census state do not implement that target. These require coordinated
versioned biology, authority, recovery and UI work; earlier exact-copy generation
NPC-parent behavior/reproductive continuity. Portable retained plans implement
part of that target; durable mutation/birth, behavior, control and census still
require coordinated versioned biology, authority, recovery and UI work. Earlier
exact-copy generation
evidence does not close that gap or establish the intended generational gameplay.
[ADR-0164](../adr/0164-distinct-genome-offspring-funding.md) now implements the
pure biological funding step with distinct parent/offspring genomes and exact
closure. Existing same-genome behavior remains. Persistent heritable plans,
expression timing, authority handoff and NPC/UI integration are still required.
closure. [ADR-0165](../adr/0165-retained-cellular-offspring-plans.md) adds portable
retained plans and earned selections, unchanged expressed parents and repeated
funded births. Existing same-genome behavior remains. Durable plan/trace/bundle,
population/migration/census admission, the in-life expression catalog, authority
handoff and NPC/UI integration are still required.
## Persistence boundary resolved by 12.3b
+59
View File
@@ -1,5 +1,64 @@
# Validation report
## 2026-10-19 - Portable retained cellular offspring plans
[ADR-0165](../adr/0165-retained-cellular-offspring-plans.md) adds opt-in owner
format 8/rules 10, an explicit no-tick upgrade, separate expressed/inherited
genomes and append-only plan selections. Earned selections change inherited
plans without rebuilding/charging parent tissue; actual births fund the child's
plan. Existing raw/population/durable versions keep their meaning. Old raw batch
replay now explicitly refuses this new unsupported owner.
Executed locally:
- MSVC 19.44 Release full CTest **85/85 passed, 21.91 s**, with NDEBUG.
- GCC 14.2 Release full CTest **85/85 passed, 16.83 s**, with NDEBUG.
- Clang 19.1 Debug inheritance contract and actual separate-process restart
**2/2 passed, 11.74 s**, built with clang-tidy 19 enabled. All changed C++
implementations and the new test compiled under that analysis configuration.
Repository clang-format 19 and diff whitespace checks pass.
- Clang 19.1 ASan/UBSan budding, inherited funding, retained plans, inheritance
process restart and funded maturation **5/5 passed, 70.52 s**, without reports.
After strengthening valid-trace refusal, the two inheritance tests passed again
under ASan/UBSan, **2/2, 40.26 s**; production C++ was unchanged.
- Optional GCC cellular session adapter rebuilt; `cellular-session-batch`
**1/1 passed, 0.14 s**. No private PostgreSQL integration rerun: schema,
SQL admission and durable bundles are unchanged and do not admit this owner.
Tests exercise actual earned structural offers, declines, stale/reused selection
refusal without state changes, unchanged parent body/reserve/heat versus an
unselected control, no fictitious archive carriers, repeated funded siblings,
later plans preserving earlier children, exact reload, suspended-parent exclusion,
ordinary ecological death and retained corpse plans. A legacy expressed mutation
survives upgrade, and a forged selection predating that expression refuses.
Checksummed hostile references, actor/history timing, counts, reserved fields,
version mismatch and checksum damage refuse; unsupported population/census/
migration/replay paths also refuse. The replay test uses a valid encoded/decoded
old trace and requires the version refusal specifically. Inventory closes in
every channel.
The restart fixture writes a selected plan and actual offspring, continues 64
ticks with the controlled parent frozen and offspring metabolism active, and
compares against a separate process restoring that cut. MSVC and GCC final bytes
also have identical SHA-256
`1e2c254df2d38b6cca1444c272a05563eec934e4381653240280958eee107837`.
The initial restart assertion incorrectly required juvenile growth even though
maximal funded birth can already be fully grown. It was corrected to require
real offspring metabolism and plan retention; all checks above ran afterward.
No golden or biological rule was changed to satisfy it.
This is portable checkpoint evidence, not durable publication, live deployment,
controller behavior continuity, control succession or UI qualification. No
target-host/TSan/actual-days evidence or M12 completion is claimed. The fixtures
use finite food and scripted intentions to isolate owner semantics; they do not
replace the separate unscripted ecology matrix. The in-life trait expression
catalog and broader plan viability semantics remain open integration work.
The DEV window in this push expires **2026-10-19 21:34:17 UTC**. Rendered policy
passes: 75 objects in 74 files, 138 rendered objects in 17 overlays, zero failures.
The unchanged policy self-test matrix was not repeated. No deployment or World0
operation occurred; unrelated untracked files were preserved.
## 2026-10-19 - Distinct-genome offspring funding
[ADR-0164](../adr/0164-distinct-genome-offspring-funding.md) adds a complete pure
@@ -98,6 +98,7 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes);
// Replays from an immutable predecessor snapshot. The caller must first bind the
// header identity, predecessor commit/digest and tick range to trusted manifests.
// Every tick must cover its living set; the caller compares the returned snapshot.
// Owner format 8/rules 10 requires separately qualified trace admission and is refused.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch);
// The same replay, also reporting every mutation selection's final result in trace order
@@ -47,6 +47,9 @@ inline constexpr std::uint32_t cellular_lives_foraging_rules = 8;
inline constexpr std::uint32_t cellular_lives_migration_format = 7;
// ADR-0157: opt-in funded maturation, using the unchanged format-7 fields.
inline constexpr std::uint32_t cellular_lives_maturation_rules = 9;
// ADR-0165: explicit offspring-plan editing mode; expressed bodies retain their genomes.
inline constexpr std::uint32_t cellular_lives_inheritance_format = 8;
inline constexpr std::uint32_t cellular_lives_inheritance_rules = 10;
inline constexpr std::uint32_t cellular_growth_per_tick = 5; // Per 50 ms; trial rate.
// The founder a region of these rules creates.
[[nodiscard]] constexpr biology::FounderVersion
@@ -94,7 +97,7 @@ struct CellularMutationProgress {
struct CellularOwnedLife {
LifeAccount account{};
LifeAllocation identity{};
LifeAllocation identity{}; // genome always identifies the expressed body.
std::uint64_t source{};
biology::GrowthState growth{};
biology::CellularPosition position{};
@@ -105,6 +108,7 @@ struct CellularOwnedLife {
// Format 6 (ADR-0128): presence and the tick its freeze began (zero while active).
CellularPresence presence{CellularPresence::active};
std::uint64_t frozen_since{};
std::uint64_t offspring_genome{}; // Format 8; older formats retain zero.
auto operator<=>(const CellularOwnedLife&) const = default;
};
struct CellularOwnedCorpse {
@@ -117,8 +121,9 @@ struct CellularOwnedCorpse {
std::uint32_t extent_um{};
accounting::Inventory inventory{}; // Empty under rules 3: it became detritus.
biology::CellularDeathCause cause{biology::CellularDeathCause::unrecorded};
std::uint64_t predator_life{}; // Engulfed only.
std::uint64_t parent_life{}; // Format 5: kept after death.
std::uint64_t predator_life{}; // Engulfed only.
std::uint64_t parent_life{}; // Format 5: kept after death.
std::uint64_t offspring_genome{}; // Format 8: retained plan, not living stock.
auto operator<=>(const CellularOwnedCorpse&) const = default;
};
struct CellularBoundaryLedger {
@@ -126,6 +131,13 @@ struct CellularBoundaryLedger {
std::vector<std::uint64_t> nonresident_organisms; // Retained history, never activity.
bool operator==(const CellularBoundaryLedger&) const = default;
};
struct CellularOffspringRevision {
std::uint64_t life{}, previous{}, successor{}, tick{};
auto operator<=>(const CellularOffspringRevision&) const = default;
};
[[nodiscard]] constexpr std::uint64_t cellular_offspring_genome(const CellularOwnedLife& life) {
return life.offspring_genome == 0 ? life.identity.genome : life.offspring_genome;
}
class CellularMigration;
struct CellularLifeIntent {
std::uint64_t life_id{};
@@ -142,7 +154,8 @@ enum class CellularMutationResult : std::uint8_t {
applied,
life_died,
insufficient_funding,
declined
declined,
offspring_plan_applied // Rules 10: inherited plan changed, expressed body did not.
};
struct CellularMutationExecution {
std::uint64_t life_id{}, successor_id{};
@@ -266,6 +279,10 @@ class CellularLives {
// ADR-0157: detached no-tick rules-8/format-7 -> rules-9 candidate. No grant.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
maturation_upgrade_candidate() const;
// ADR-0165: explicit no-tick format-7/rules-9 -> format-8/rules-10 upgrade.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
inheritance_upgrade_candidate() const;
[[nodiscard]] std::span<const CellularOffspringRevision> offspring_revisions() const noexcept;
// Latest successful in-memory step report; omitted from snapshots and empty after restore.
[[nodiscard]] std::span<const CellularLifeTickFeedback> last_tick_feedback() const noexcept;
[[nodiscard]] std::vector<std::uint8_t> snapshot() const;
@@ -301,6 +318,7 @@ class CellularLives {
advance_tick(std::span<const CellularLifeIntent> intents);
// Mutation selections are validated against the predecessor offer, then applied
// after the normal life step and before births on the same advancing tick.
// Rules 10 edit only the retained offspring plan; parent tissue is unchanged.
[[nodiscard]] std::expected<CellularTickExecution, CellularLivesError>
advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
std::span<const CellularMutationSelection> selections);
+51
View File
@@ -0,0 +1,51 @@
# Cellular owner format 8: retained offspring plans
Authority: [ADR-0165](../docs/adr/0165-retained-cellular-offspring-plans.md).
Portable opt-in format 8/rules 10 only. No existing durable bundle, population
envelope, batch trace, migration or census adapter admits this version. Earlier
canonical formats and their meanings are unchanged.
Little-endian, no native padding. Magic `AEVCLV08`. The first 308 bytes retain
[format 7](cellular-lives-v7.md), except magic/format/rules. Extensions:
| Offset | Bytes | Field |
|---:|---:|---|
| 308 | 4 | Offspring-plan revision count, at most 4096 |
| 312 | 4 | Reserved zero |
| 316 | 8 each | Sorted spawn sites |
| after sites | 512 each | Existing 504-byte living record, then u64 offspring genome |
| after lives | 132 each | Existing 124-byte corpse record, then u64 offspring genome |
| after corpses | declared lengths | Complete canonical habitat and lineage archive |
| after archive | 8 each | Sorted unique nonresident organism IDs |
| after nonresidents | 32 each | Offspring-plan revisions |
| final | 8 | FNV-1a64 of all preceding bytes |
Each plan revision contains four u64s: life ID, previous genome ID, successor
genome ID and selection tick. Records increase by `(tick, life)`, strictly within
each tick. Successor IDs are unique. The exact length is
`316 + 8*sites + 512*lives + 132*corpses + habitat_bytes + archive_bytes +
8*nonresidents + 32*plan_revisions + 8`, at most 16 MiB. Check counts, lengths,
reserved fields and checksum before nested allocation/restore. The checksum
detects corruption; it supplies no publication authority.
Living identity genome and archive current genome describe expressed anatomy.
Every local living/corpse plan reference is nonzero and resolves in the archive.
Initialize its chain from the expressed genome. Each selection must name that
life's preceding plan and a direct single-parent successor whose origin event is
its own ID, with matching genome schema/development versions. Selections follow
birth and any legacy expressed revision, precede death and cannot be in the
future. Only existing controlled founders select plans in this version. A
successor cannot have an earlier recorded local birth. Final references must
match complete retained chains. Outstanding offers regenerate from the current
plan and their original context. All existing identity, presence, tissue,
inventory, boundary-flow and archive invariants still apply, followed by exact
canonical re-encoding.
The detached no-tick format-7/rules-9 upgrade preserves all old state and gives
each local living/corpse record its current expressed genome as its initial
offspring plan. No prior selections are invented. Newborns express the plan
actually funded at birth and initialize their own plan to that genome. Corpses
retain plans as history, without reproductive viability. Unexpressed plans own
no stock and are not archive living carriers; a living parent can nevertheless
retain one for future reproduction. Terminal extinction needs broader viability
semantics before census/persistence integration.
+3
View File
@@ -407,6 +407,9 @@ std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
std::vector<CellularMutationOutcome>& mutation_outcomes) {
mutation_outcomes.clear();
// ADR-0165: this trace has no admitted offspring-plan outcome contract.
if (base.format_version() >= cellular_lives_inheritance_format)
return std::unexpected{CellularBatchError::version};
const auto& h = batch.header;
if (!valid_header(h, batch.ticks.size()) || !valid_ticks(batch.ticks))
return std::unexpected{CellularBatchError::format};
+250 -53
View File
@@ -6,7 +6,9 @@
#include <array>
#include <bit>
#include <limits>
#include <map>
#include <ranges>
#include <set>
#include <stdexcept>
#include <utility>
@@ -19,6 +21,7 @@ constexpr std::uint64_t cellular_lives_v4_magic = 0x3430564C43564541ULL; // AEVC
constexpr std::uint64_t cellular_lives_v5_magic = 0x3530564C43564541ULL; // AEVCLV05
constexpr std::uint64_t cellular_lives_v6_magic = 0x3630564C43564541ULL; // AEVCLV06
constexpr std::uint64_t cellular_lives_v7_magic = 0x3730564C43564541ULL; // AEVCLV07
constexpr std::uint64_t cellular_lives_v8_magic = 0x3830564C43564541ULL; // AEVCLV08
constexpr std::size_t cellular_lives_header_bytes = 212;
constexpr std::size_t cellular_site_bytes = 8;
constexpr std::size_t cellular_life_v1_bytes = 168;
@@ -35,6 +38,8 @@ constexpr std::size_t cellular_corpse_v5_bytes = cellular_corpse_v4_bytes + 8;
constexpr std::size_t cellular_life_v6_bytes = cellular_life_v5_bytes + 16;
// Format 7: two boundary-flow inventories and nonresident count/reserved.
constexpr std::size_t cellular_lives_v7_header_bytes = cellular_lives_v5_header_bytes + 88;
constexpr std::size_t cellular_lives_v8_header_bytes = cellular_lives_v7_header_bytes + 8;
constexpr std::size_t cellular_offspring_revision_bytes = 32;
std::uint64_t checksum(std::span<const std::uint8_t> bytes) noexcept {
std::uint64_t value = 14695981039346656037ULL;
@@ -276,6 +281,84 @@ sum_state(accounting::Inventory nursery, accounting::Inventory heat,
return total;
}
bool validate_plans(std::span<const CellularOwnedLife> lives,
std::span<const CellularOwnedCorpse> corpses,
const biology::LineageArchive& archive,
std::span<const CellularOffspringRevision> history, std::uint64_t tick) {
if (history.size() > biology::max_archived_genomes)
return false;
struct Plan {
std::uint64_t life, expressed, current, final, editable_after, died;
bool selectable;
};
std::vector<Plan> plans;
std::map<std::uint64_t, std::uint64_t> earliest_birth;
std::map<std::uint64_t, std::uint64_t> last_expression;
for (const auto& revision : archive.revisions())
last_expression[revision.organism] =
std::max(last_expression[revision.organism], revision.at.value);
const auto observe = [&](std::uint64_t genome, std::uint64_t born) {
const auto [position, inserted] = earliest_birth.emplace(genome, born);
if (!inserted)
position->second = std::min(position->second, born);
};
plans.reserve(lives.size() + corpses.size());
for (const auto& life : lives) {
plans.push_back(
{life.identity.life, life.identity.genome, life.identity.genome, life.offspring_genome,
std::max(life.identity.born.value, last_expression[life.identity.organism]), 0,
life.account != LifeAccount{}});
observe(life.identity.genome, life.identity.born.value);
}
for (const auto& corpse : corpses) {
const auto record = archive.organism(corpse.organism);
const auto expressed = archive.current_genome(corpse.organism);
if (!record || !expressed)
return false;
plans.push_back({corpse.life_id, *expressed, *expressed, corpse.offspring_genome,
std::max(record->born.value, last_expression[corpse.organism]),
corpse.died_tick, corpse.parent_life == 0});
observe(record->genome, record->born.value);
observe(*expressed, record->born.value);
}
std::ranges::sort(plans, {}, &Plan::life);
std::set<std::uint64_t> successors;
for (std::size_t index = 0; index < history.size(); ++index) {
const auto& revision = history[index];
if (revision.tick == 0 || revision.tick > tick || revision.successor == revision.previous ||
(index != 0 && (history[index - 1].tick > revision.tick ||
(history[index - 1].tick == revision.tick &&
history[index - 1].life >= revision.life))) ||
!successors.insert(revision.successor).second)
return false;
const auto actor = std::ranges::lower_bound(plans, revision.life, {}, &Plan::life);
const auto parent = archive.find(revision.previous);
const auto child = archive.find(revision.successor);
if (actor == plans.end() || actor->life != revision.life || !actor->selectable ||
actor->current != revision.previous || revision.tick <= actor->editable_after ||
(actor->died != 0 && revision.tick >= actor->died) || !parent || !child ||
child->parents().size() != 1 || child->parents().front() != revision.previous ||
child->origin_event() != revision.successor ||
child->schema_version() != parent->schema_version() ||
child->development_version() != parent->development_version())
return false;
actor->current = revision.successor;
// A plan selected here cannot have been expressed at an earlier birth.
const auto born = earliest_birth.find(revision.successor);
if (born != earliest_birth.end() && born->second < revision.tick)
return false;
}
for (const auto& plan : plans) {
const auto expressed = archive.find(plan.expressed);
const auto inherited = archive.find(plan.final);
if (plan.final == 0 || plan.current != plan.final || !expressed || !inherited ||
expressed->schema_version() != inherited->schema_version() ||
expressed->development_version() != inherited->development_version())
return false;
}
return true;
}
std::expected<accounting::Inventory, CellularLivesError>
validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
const CellularLivesConfig& config, const NurseryConfig& nursery_config,
@@ -284,7 +367,8 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
accounting::Inventory nursery, accounting::Inventory heat,
accounting::Inventory opening_total, bool detritus_rules = false,
bool bud_rules = false, std::uint64_t next_bud_sequence = 1,
bool presence_rules = false, const CellularBoundaryLedger* boundary = nullptr) {
bool presence_rules = false, const CellularBoundaryLedger* boundary = nullptr,
const std::vector<CellularOffspringRevision>* plans = nullptr) {
// A bud's identity lies in this region's namespace below the next sequence; anything
// else is an allocated identity, below the namespace (ADR-0125).
const auto bud_identity = [&](std::uint64_t identity) noexcept {
@@ -350,6 +434,8 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
(boundary ? boundary->nonresident_organisms.size() : 0));
for (std::size_t i = 0; i < lives.size(); ++i) {
const auto& life = lives[i];
if (!plans && life.offspring_genome != 0)
return std::unexpected{CellularLivesError::version};
// Founders are owned; buds are unowned wildlife (rules 4) and never earn offers.
const bool wildlife = life.parent_life != 0;
// ADR-0128: only owned lives leave; a lingering life is within its linger time.
@@ -415,6 +501,8 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
for (std::size_t i = 0; i < corpses.size(); ++i) {
const auto& corpse = corpses[i];
if (!plans && corpse.offspring_genome != 0)
return std::unexpected{CellularLivesError::version};
if (corpse.life_id == 0 || corpse.organism == 0 || corpse.source == 0 ||
corpse.died_tick == 0 || corpse.died_tick > config.tick || corpse.extent_um == 0 ||
(i != 0 && corpses[i - 1].organism >= corpse.organism) ||
@@ -451,6 +539,8 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
if (std::ranges::adjacent_find(life_ids) != life_ids.end())
return std::unexpected{CellularLivesError::duplicate_life};
if (plans && !validate_plans(lives, corpses, archive, *plans, config.tick))
return std::unexpected{CellularLivesError::invalid_life};
const auto current = sum_state(nursery, heat, habitat, lives, corpses);
if (!current)
return std::unexpected{current.error()};
@@ -494,6 +584,7 @@ struct CellularLives::State {
accounting::Inventory current_total{};
std::uint64_t next_bud_sequence{1}; // Format 5: the next bud identity's sequence.
CellularBoundaryLedger boundary{};
std::vector<CellularOffspringRevision> offspring_revisions;
State(std::uint64_t world_id, std::uint64_t region_id, std::uint64_t frame_id,
CellularLivesConfig cfg, NurseryConfig nursery_definition,
@@ -730,6 +821,31 @@ std::span<const CellularLifeTickFeedback> CellularLives::last_tick_feedback() co
return last_tick_feedback_;
}
std::span<const CellularOffspringRevision> CellularLives::offspring_revisions() const noexcept {
return state_->offspring_revisions;
}
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::inheritance_upgrade_candidate() const {
if (state_->format_version != cellular_lives_migration_format ||
state_->rules_version != cellular_lives_maturation_rules)
return std::unexpected{CellularLivesError::version};
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
if (!candidate)
return std::unexpected(candidate.error());
auto& next = *(*candidate)->state_;
next.format_version = cellular_lives_inheritance_format;
next.rules_version = cellular_lives_inheritance_rules;
for (auto& life : next.lives)
life.offspring_genome = life.identity.genome;
for (auto& corpse : next.corpses) {
const auto genome = next.archive.current_genome(corpse.organism);
if (!genome)
return std::unexpected{CellularLivesError::archive};
corpse.offspring_genome = *genome;
}
return restore((*candidate)->snapshot(), world(), region(), frame(), tick());
}
std::vector<std::uint8_t> CellularLives::snapshot() const {
const auto habitat = state_->habitat->snapshot();
const auto archive = state_->archive.encode();
@@ -738,29 +854,36 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
const auto corpse_count = state_->corpses.size();
const bool parents = state_->format_version >= cellular_lives_bud_format;
const bool presence = state_->format_version >= cellular_lives_presence_format;
const auto life_bytes = state_->format_version == cellular_lives_legacy_format
const bool inheritance = state_->format_version == cellular_lives_inheritance_format;
const auto life_bytes = inheritance ? cellular_life_v6_bytes + 8
: state_->format_version == cellular_lives_legacy_format
? cellular_life_v1_bytes
: presence ? cellular_life_v6_bytes
: parents ? cellular_life_v5_bytes
: cellular_life_v2_bytes;
const bool causes = state_->format_version >= cellular_lives_engulf_format;
const auto corpse_bytes = parents ? cellular_corpse_v5_bytes
: causes ? cellular_corpse_v4_bytes
: cellular_corpse_bytes;
const bool migration = state_->format_version == cellular_lives_migration_format;
const auto header_bytes = migration ? cellular_lives_v7_header_bytes
: parents ? cellular_lives_v5_header_bytes
: cellular_lives_header_bytes;
const auto corpse_bytes = inheritance ? cellular_corpse_v5_bytes + 8
: parents ? cellular_corpse_v5_bytes
: causes ? cellular_corpse_v4_bytes
: cellular_corpse_bytes;
const bool migration = state_->format_version >= cellular_lives_migration_format;
const auto header_bytes = inheritance ? cellular_lives_v8_header_bytes
: migration ? cellular_lives_v7_header_bytes
: parents ? cellular_lives_v5_header_bytes
: cellular_lives_header_bytes;
const auto external_count = migration ? state_->boundary.nonresident_organisms.size() : 0;
const auto total_bytes = header_bytes + cellular_site_bytes * site_count +
life_bytes * life_count + corpse_bytes * corpse_count +
habitat.size() + archive.size() + external_count * 8 + 8;
const auto total_bytes =
header_bytes + cellular_site_bytes * site_count + life_bytes * life_count +
corpse_bytes * corpse_count + habitat.size() + archive.size() + external_count * 8 +
state_->offspring_revisions.size() * cellular_offspring_revision_bytes + 8;
if (total_bytes > max_cellular_lives_bytes ||
habitat.size() > biology::max_cellular_habitat_bytes ||
archive.size() > biology::max_archive_bytes || site_count > max_primitive_lives ||
life_count > biology::max_cellular_tick_lives ||
corpse_count > biology::max_archived_organisms ||
external_count > biology::max_archived_organisms)
external_count > biology::max_archived_organisms ||
state_->offspring_revisions.size() > biology::max_archived_genomes ||
(!inheritance && !state_->offspring_revisions.empty()))
throw std::length_error{"cellular lives checkpoint exceeds its format bounds"};
std::vector<std::uint8_t> bytes;
@@ -772,6 +895,7 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
: state_->format_version == cellular_lives_engulf_format ? cellular_lives_v4_magic
: state_->format_version == cellular_lives_bud_format ? cellular_lives_v5_magic
: state_->format_version == cellular_lives_presence_format ? cellular_lives_v6_magic
: inheritance ? cellular_lives_v8_magic
: migration ? cellular_lives_v7_magic
: cellular_lives_v2_magic;
out.put(magic);
@@ -802,6 +926,10 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
out.put(external_count, 4);
out.put(0, 4);
}
if (inheritance) {
out.put(state_->offspring_revisions.size(), 4);
out.put(0, 4);
}
for (const auto site : state_->nursery_config.sites)
out.site(site);
for (const auto& life : state_->lives) {
@@ -860,6 +988,8 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
out.zeros(7);
out.put(life.frozen_since);
}
if (inheritance)
out.put(life.offspring_genome);
}
for (const auto& corpse : state_->corpses) {
out.put(corpse.life_id);
@@ -879,12 +1009,21 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
}
if (parents)
out.put(corpse.parent_life);
if (inheritance)
out.put(corpse.offspring_genome);
}
out.raw(habitat);
out.raw(archive);
if (migration)
for (const auto id : state_->boundary.nonresident_organisms)
out.put(id);
if (inheritance)
for (const auto& revision : state_->offspring_revisions) {
out.put(revision.life);
out.put(revision.previous);
out.put(revision.successor);
out.put(revision.tick);
}
if (bytes.size() + 8 != total_bytes)
throw std::logic_error{"cellular lives checkpoint size calculation mismatch"};
out.put(checksum(bytes));
@@ -1057,6 +1196,8 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c
auto lives = state_->lives;
lives.push_back({request.account, allocation, state_->nursery_config.source, endowed->growth,
*position, endowed->body, endowed->reserve});
if (state_->format_version == cellular_lives_inheritance_format)
lives.back().offspring_genome = allocation.genome;
std::ranges::sort(lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; });
auto nursery_config = state_->nursery_config;
@@ -1071,7 +1212,9 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c
state_->rules_version >= cellular_lives_engulf_rules,
state_->rules_version >= cellular_lives_bud_rules, state_->next_bud_sequence,
state_->rules_version >= cellular_lives_presence_rules,
state_->format_version == cellular_lives_migration_format ? &state_->boundary : nullptr);
state_->format_version >= cellular_lives_migration_format ? &state_->boundary : nullptr,
state_->format_version == cellular_lives_inheritance_format ? &state_->offspring_revisions
: nullptr);
if (!current)
return std::unexpected{current.error()};
@@ -1082,6 +1225,7 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c
state_->boundary)}};
candidate->last_tick_feedback_ = last_tick_feedback_;
candidate->state_->next_bud_sequence = state_->next_bud_sequence;
candidate->state_->offspring_revisions = state_->offspring_revisions;
return candidate;
}
@@ -1104,10 +1248,14 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
format_version == cellular_lives_format &&
rules_version == cellular_lives_rules;
// Format 6 carries rules 5, 6 (founder 2) or 7 (founder 3, ADR-0137); no new state.
const bool migration_version = magic == cellular_lives_v7_magic &&
format_version == cellular_lives_migration_format &&
(rules_version == cellular_lives_foraging_rules ||
rules_version == cellular_lives_maturation_rules);
const bool inheritance_version = magic == cellular_lives_v8_magic &&
format_version == cellular_lives_inheritance_format &&
rules_version == cellular_lives_inheritance_rules;
const bool migration_version =
inheritance_version ||
(magic == cellular_lives_v7_magic && format_version == cellular_lives_migration_format &&
(rules_version == cellular_lives_foraging_rules ||
rules_version == cellular_lives_maturation_rules));
const bool presence_version =
migration_version ||
(magic == cellular_lives_v6_magic && format_version == cellular_lives_presence_format &&
@@ -1132,6 +1280,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
return std::unexpected{CellularLivesError::version};
if (migration_version && bytes.size() < cellular_lives_v7_header_bytes + 8)
return std::unexpected(CellularLivesError::format);
if (inheritance_version && bytes.size() < cellular_lives_v8_header_bytes + 8)
return std::unexpected(CellularLivesError::format);
const auto saved_world = in.get();
const auto saved_region = in.get();
const auto saved_frame = in.get();
@@ -1171,19 +1321,29 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
if (in.get(4) != 0 || nonresident_count > biology::max_archived_organisms)
return std::unexpected(CellularLivesError::format);
}
const auto life_bytes = legacy ? cellular_life_v1_bytes
: presence_version ? cellular_life_v6_bytes
: bud_version ? cellular_life_v5_bytes
: cellular_life_v2_bytes;
const auto corpse_bytes = bud_version ? cellular_corpse_v5_bytes
: engulf_version ? cellular_corpse_v4_bytes
: cellular_corpse_bytes;
const auto expected_size = (migration_version ? cellular_lives_v7_header_bytes
: bud_version ? cellular_lives_v5_header_bytes
: cellular_lives_header_bytes) +
std::uint64_t plan_count = 0;
if (inheritance_version) {
plan_count = in.get(4);
if (in.get(4) != 0 || plan_count > biology::max_archived_genomes)
return std::unexpected{CellularLivesError::format};
}
const auto life_bytes = inheritance_version ? cellular_life_v6_bytes + 8
: legacy ? cellular_life_v1_bytes
: presence_version ? cellular_life_v6_bytes
: bud_version ? cellular_life_v5_bytes
: cellular_life_v2_bytes;
const auto corpse_bytes = inheritance_version ? cellular_corpse_v5_bytes + 8
: bud_version ? cellular_corpse_v5_bytes
: engulf_version ? cellular_corpse_v4_bytes
: cellular_corpse_bytes;
const auto expected_size = (inheritance_version ? cellular_lives_v8_header_bytes
: migration_version ? cellular_lives_v7_header_bytes
: bud_version ? cellular_lives_v5_header_bytes
: cellular_lives_header_bytes) +
cellular_site_bytes * site_count + life_bytes * life_count +
corpse_bytes * corpse_count + habitat_size + archive_size +
nonresident_count * 8 + 8;
nonresident_count * 8 +
plan_count * cellular_offspring_revision_bytes + 8;
if (source == 0 || next_bud_sequence == 0 || expected_size != bytes.size())
return std::unexpected{CellularLivesError::format};
@@ -1266,6 +1426,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
return std::unexpected{CellularLivesError::noncanonical};
life.presence = static_cast<CellularPresence>(presence);
}
if (inheritance_version)
life.offspring_genome = in.get();
lives.push_back(life);
}
@@ -1298,6 +1460,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
}
if (bud_version)
corpse.parent_life = in.get();
if (inheritance_version)
corpse.offspring_genome = in.get();
corpses.push_back(corpse);
}
const auto habitat_payload = in.raw(static_cast<std::size_t>(habitat_size));
@@ -1331,6 +1495,10 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
for (std::uint64_t index = 0; index < nonresident_count; ++index)
boundary.nonresident_organisms.push_back(in.get());
}
std::vector<CellularOffspringRevision> plan_history;
plan_history.reserve(static_cast<std::size_t>(plan_count));
for (std::uint64_t index = 0; index < plan_count; ++index)
plan_history.push_back({in.get(), in.get(), in.get(), in.get()});
if (archive->format_version() != (revision_version ? biology::lineage_archive_revision_format
: biology::lineage_archive_format))
return std::unexpected{CellularLivesError::version};
@@ -1338,12 +1506,13 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
for (const auto& life : lives) {
if (!life.mutation.offer)
continue;
const auto genome = archive->find(life.identity.genome);
const auto genome = archive->find(cellular_offspring_genome(life));
if (!genome)
return std::unexpected{CellularLivesError::archive};
const auto& offer = *life.mutation.offer;
if (life.mutation.event_index == 0 || life.mutation.offer_tick == 0 ||
life.mutation.offer_tick > saved_tick || offer.parent != life.identity.genome ||
life.mutation.offer_tick > saved_tick ||
offer.parent != cellular_offspring_genome(life) ||
offer.context.seed != mutation_seed(saved_world, saved_region, life.identity.life,
life.mutation.event_index) ||
offer.context.stream != cellular_mutation_stream ||
@@ -1359,7 +1528,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
const auto current = validate_state(
saved_world, saved_region, saved_frame, config, nursery_config, **habitat, lives, corpses,
*archive, nursery, heat, opening_total, engulf_version, bud_version, next_bud_sequence,
presence_version, migration_version ? &boundary : nullptr);
presence_version, migration_version ? &boundary : nullptr,
inheritance_version ? &plan_history : nullptr);
if (!current)
return std::unexpected{current.error()};
@@ -1368,6 +1538,7 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
std::move(*habitat), std::move(lives), std::move(corpses), *archive, nursery, heat,
opening_total, *current, format_version, rules_version, std::move(boundary))}};
restored->state_->next_bud_sequence = next_bud_sequence;
restored->state_->offspring_revisions = std::move(plan_history);
if (!std::ranges::equal(bytes, restored->snapshot()))
return std::unexpected{CellularLivesError::noncanonical};
return restored;
@@ -1403,6 +1574,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
const bool contact_rules = state_->rules_version >= cellular_lives_foraging_rules;
const bool bud_rules = state_->rules_version >= cellular_lives_bud_rules;
const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules;
const bool inheritance_rules = state_->rules_version == cellular_lives_inheritance_rules;
for (std::size_t i = 0; i < ordered.size(); ++i) {
const auto& intent = ordered[i].intent;
// Below rules 4 a bud is ignored, as engulfment is below rules 3 (ADR-0124/0125).
@@ -1431,7 +1603,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
if (!life->mutation.offer.has_value())
return std::unexpected{CellularLivesError::mutation};
const auto offer = life->mutation.offer.value_or(biology::MutationOffer{});
if (offer.parent != life->identity.genome ||
if (offer.parent != cellular_offspring_genome(*life) ||
offer.context.event_index != selection.event_index ||
(selection.operator_id != 0 && !std::ranges::any_of(offer.candidates,
[&](const auto& candidate) {
@@ -1481,6 +1653,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
auto next_lives = state_->lives;
auto next_corpses = state_->corpses;
auto next_archive = state_->archive;
auto next_offspring_revisions = state_->offspring_revisions;
auto next_heat = state_->heat;
auto habitat_config = state_->habitat->config();
for (const auto& result : proposal->lives) {
@@ -1514,7 +1687,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
if (found->mutation.fed_energy_credit_pj >= threshold) {
if (found->mutation.event_index == std::numeric_limits<std::uint64_t>::max())
return std::unexpected{CellularLivesError::overflow};
const auto genome = next_archive.find(found->identity.genome);
const auto genome = next_archive.find(cellular_offspring_genome(*found));
if (!genome)
return std::unexpected{CellularLivesError::archive};
const auto next_event = found->mutation.event_index + 1;
@@ -1549,11 +1722,11 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
budget_for(next_archive, *found, state_->config.ambient_temperature_millikelvin);
if (!corpse_budget)
return std::unexpected{corpse_budget.error()};
next_corpses.push_back({found->identity.life, found->identity.organism, found->source,
proposal->end_tick, dead.position, found->growth,
corpse_budget->phenotype.extent, dead.inventory,
engulf_rules ? dead.cause : biology::CellularDeathCause::unrecorded,
engulf_rules ? dead.predator_id : 0, found->parent_life});
next_corpses.push_back(
{found->identity.life, found->identity.organism, found->source, proposal->end_tick,
dead.position, found->growth, corpse_budget->phenotype.extent, dead.inventory,
engulf_rules ? dead.cause : biology::CellularDeathCause::unrecorded,
engulf_rules ? dead.predator_id : 0, found->parent_life, found->offspring_genome});
next_lives.erase(found);
}
std::vector<CellularMutationExecution> mutation_results;
@@ -1567,7 +1740,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
{selection.life_id, selection.successor_id, CellularMutationResult::life_died});
continue;
}
const auto parent = next_archive.find(found->identity.genome);
const auto parent = next_archive.find(cellular_offspring_genome(*found));
if (!parent || !found->mutation.offer.has_value())
return std::unexpected{CellularLivesError::mutation};
if (selection.operator_id == 0) {
@@ -1580,6 +1753,24 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
continue;
}
const auto offer = found->mutation.offer.value_or(biology::MutationOffer{});
if (inheritance_rules) {
const auto selected =
biology::select_mutation(*parent, offer.context, offer, selection.operator_id,
selection.successor_id, selection.successor_id);
if (!selected)
return std::unexpected{CellularLivesError::mutation};
if (next_offspring_revisions.size() >= biology::max_archived_genomes ||
!next_archive.admit(*selected))
return std::unexpected{CellularLivesError::archive};
next_offspring_revisions.push_back({selection.life_id, found->offspring_genome,
selection.successor_id, proposal->end_tick});
found->offspring_genome = selection.successor_id;
found->mutation.offer.reset();
found->mutation.offer_tick = 0;
mutation_results.push_back({selection.life_id, selection.successor_id,
CellularMutationResult::offspring_plan_applied});
continue;
}
auto transition = biology::fund_mutation_at_growth(
*parent, offer.context, offer, selection.operator_id, selection.successor_id,
selection.successor_id, found->reserve,
@@ -1633,15 +1824,17 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
if (state_->rules_version < cellular_lives_reproduction_rules)
return false;
const auto parent_genome = next_archive.find(parent->identity.genome);
if (!parent_genome)
const auto offspring_genome = next_archive.find(cellular_offspring_genome(*parent));
if (!parent_genome || !offspring_genome)
return false;
const auto skill = parent_genome->parameter(biology::Capability::reproduction);
// Twins split one whole bud: the parent must afford that whole bud first.
return skill &&
cellular_twin_bud(state_->world, state_->region, request.life_id,
proposal->end_tick, *skill) &&
biology::fund_bud(*parent_genome, parent->growth, parent->reserve,
state_->config.ambient_temperature_millikelvin)
biology::fund_offspring(*parent_genome, *offspring_genome, parent->growth,
parent->reserve,
state_->config.ambient_temperature_millikelvin)
.has_value();
}();
for (int copy = 0; copy < (twins ? 2 : 1); ++copy) {
@@ -1652,12 +1845,13 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
[](const CellularOwnedLife& value) { return value.identity.life; });
const bool twin = copy == 1;
const auto temperature = state_->config.ambient_temperature_millikelvin;
const auto genome = next_archive.find(parent->identity.genome);
const auto genome = next_archive.find(cellular_offspring_genome(*parent));
const auto expressed = next_archive.find(parent->identity.genome);
const auto parent_budget = budget_for(next_archive, *parent, temperature);
if (!genome || !parent_budget)
if (!genome || !expressed || !parent_budget)
return std::unexpected{CellularLivesError::archive};
const auto transition = biology::fund_bud(*genome, parent->growth, parent->reserve,
temperature, twins ? 2U : 1U);
const auto transition = biology::fund_offspring(
*expressed, *genome, parent->growth, parent->reserve, temperature, twins ? 2U : 1U);
if (!transition) {
if (transition.error() == biology::BuddingError::development)
return std::unexpected{CellularLivesError::biology};
@@ -1687,18 +1881,19 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
break;
}
if (!add_inventory(next_heat, accounting::Inventory{transition->heat, {}}) ||
!next_archive.record_birth(identity, parent->identity.genome, {proposal->end_tick}))
!next_archive.record_birth(identity, genome->id(), {proposal->end_tick}))
return std::unexpected{CellularLivesError::archive};
parent->reserve = transition->parent_reserve;
CellularOwnedLife bud{};
bud.identity = {
identity, identity, parent->identity.genome, identity, {proposal->end_tick}};
bud.identity = {identity, identity, genome->id(), identity, {proposal->end_tick}};
bud.source = parent->source;
bud.growth = transition->growth;
bud.position = **position;
bud.body = transition->body;
bud.reserve = transition->reserve;
bud.parent_life = parent->identity.life;
if (inheritance_rules)
bud.offspring_genome = genome->id();
// Foreign residents can have a higher origin-region namespace. Keep
// the sequence sorted even before the next parent's lookup/twin.
const auto slot = std::ranges::lower_bound(
@@ -1754,7 +1949,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
// resuming from suspension did not take an active step and cannot grow here.
// Expansion holds the existing lower corner fixed; earlier IDs claim space first.
std::vector<CellularGrowthExecution> growth_results;
if (state_->rules_version == cellular_lives_maturation_rules) {
if (state_->rules_version >= cellular_lives_maturation_rules) {
for (auto& life : next_lives) {
const auto input = std::ranges::lower_bound(ordered, life.identity.life, {},
&CellularLifeIntent::life_id);
@@ -1856,7 +2051,8 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
state_->nursery_config, **next_habitat, next_lives, next_corpses, next_archive,
state_->nursery, next_heat, state_->opening_total, engulf_rules, bud_rules,
next_bud_sequence, presence_rules,
state_->format_version == cellular_lives_migration_format ? &state_->boundary : nullptr);
state_->format_version >= cellular_lives_migration_format ? &state_->boundary : nullptr,
inheritance_rules ? &next_offspring_revisions : nullptr);
if (!total)
return std::unexpected{total.error()};
@@ -1868,6 +2064,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
std::move(next_corpses), next_archive, state_->nursery, next_heat, state_->opening_total,
*total, state_->format_version, state_->rules_version, state_->boundary);
next->next_bud_sequence = next_bud_sequence;
next->offspring_revisions = std::move(next_offspring_revisions);
std::vector<CellularLifeTickFeedback> feedback;
feedback.reserve(proposal->lives.size());
for (const auto& result : proposal->lives) {
@@ -1910,7 +2107,7 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
entry = std::prev(feedback.end());
}
entry->presence = life.presence;
if (state_->rules_version == cellular_lives_maturation_rules)
if (state_->rules_version >= cellular_lives_maturation_rules)
entry->reserve = life.reserve; // Includes funded growth/mutation/budding.
entry->resume_blocked =
std::ranges::find(resume_blocked, life.identity.life) != resume_blocked.end();
+4 -1
View File
@@ -109,8 +109,11 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) {
if (!budget)
return std::unexpected{CellularLivesError::biology};
biology::CellularStepIntent intent{};
const auto offspring = state.archive().find(cellular_offspring_genome(life));
if (!offspring)
return std::unexpected{CellularLivesError::archive};
if ((tick + life.identity.life) % wildlife_bud_interval_ticks == 0 &&
biology::fund_bud(*genome, life.growth, life.reserve, temperature)) {
biology::fund_offspring(*genome, *offspring, life.growth, life.reserve, temperature)) {
intent.bud = true;
intents.push_back({life.identity.life, intent});
continue;
+346
View File
@@ -0,0 +1,346 @@
#include "evo/server/lifecycle/cellular_census.hpp"
#include "evo/server/lifecycle/cellular_migration.hpp"
#include "fixtures/cellular_ecology.hpp"
#include <fstream>
#include <iterator>
namespace {
using namespace evo;
using namespace evo::server;
using namespace evo::fixture;
std::vector<CellularLifeIntent> idle(const CellularLives& state, bool frozen = false,
bool bud = false, bool moving = false) {
std::vector<CellularLifeIntent> result;
for (const auto& life : state.lives()) {
CellularLifeIntent input{life.identity.life, {}};
if (life.account != LifeAccount{}) {
input.intent.frozen = frozen;
input.intent.bud = bud && !frozen;
if (moving && !frozen)
input.intent.movement = {1000, 0};
}
result.push_back(input);
}
return result;
}
const CellularOwnedLife& parent(const CellularLives& state) {
const auto life =
std::ranges::find(state.lives(), 100, [](const auto& cell) { return cell.identity.life; });
require(life != state.lives().end(), "inheritance parent missing");
return *life;
}
void closed(const CellularLives& state) {
require(state.current_total() == state.opening_total(), "inheritance stock did not close");
}
Owner initial() {
auto old = opening(7, true, 1);
require(!old->inheritance_upgrade_candidate(), "inheritance skipped prior versions");
old = checked(old->migration_upgrade_candidate(), "boundary upgrade");
require(!old->inheritance_upgrade_candidate(), "inheritance skipped maturation");
old = checked(old->maturation_upgrade_candidate(), "maturation upgrade");
const auto original = old->snapshot();
auto state = checked(old->inheritance_upgrade_candidate(), "inheritance upgrade");
require(old->snapshot() == original && state->tick() == old->tick() &&
state->archive().encode() == old->archive().encode() &&
state->current_total() == old->current_total() &&
parent(*state).identity == parent(*old).identity &&
parent(*state).body == parent(*old).body &&
parent(*state).reserve == parent(*old).reserve &&
parent(*state).offspring_genome == parent(*old).identity.genome &&
state->offspring_revisions().empty(),
"upgrade changed biology");
require(state->format_version() == 8 && state->rules_version() == 10 &&
!state->inheritance_upgrade_candidate(),
"inheritance version boundary");
require(restore(*state)->snapshot() == state->snapshot(), "initial inheritance restore");
return state;
}
void choose_structure(Owner& state, std::uint64_t successor) {
for (unsigned tick = 0; tick < 60'000; ++tick) {
const auto before = parent(*state);
if (before.mutation.offer) {
const auto offer = *before.mutation.offer;
const auto found = std::ranges::find_if(offer.candidates, [](const auto& candidate) {
return candidate.target == biology::Capability::membrane ||
candidate.target == biology::Capability::target_size;
});
const bool selected = found != offer.candidates.end();
const CellularMutationSelection selection{
100, before.mutation.event_index, before.mutation.offer_tick, successor,
selected ? found->operator_id : std::uint16_t{0}};
// Stale and reused identities cannot spend a tick or consume the offer.
const auto bytes = state->snapshot();
auto stale = selection;
++stale.event_index;
require(!state->advance_tick_with_mutations(idle(*state), std::span{&stale, 1}) &&
state->snapshot() == bytes,
"stale plan selection changed state");
stale = selection;
stale.successor_id = before.identity.genome;
require(!state->advance_tick_with_mutations(idle(*state), std::span{&stale, 1}) &&
state->snapshot() == bytes,
"reused plan identity changed state");
auto control = restore(*state);
checked(control->advance_tick_with_mutations(idle(*control), {}), "unselected control");
const auto result =
checked(state->advance_tick_with_mutations(idle(*state), std::span{&selection, 1}),
"plan selection tick");
require(result.mutations.size() == 1 &&
result.mutations.front().result ==
(selected ? CellularMutationResult::offspring_plan_applied
: CellularMutationResult::declined),
"plan selection outcome");
const auto& cell = parent(*state);
const auto& reference = parent(*control);
require(cell.identity == reference.identity && cell.body == reference.body &&
cell.reserve == reference.reserve && cell.growth == reference.growth &&
cell.position == reference.position && state->heat() == control->heat() &&
state->nursery() == control->nursery() &&
state->habitat().snapshot() == control->habitat().snapshot(),
"offspring selection rebuilt or charged the parent's body");
if (selected) {
const auto& revision = state->offspring_revisions().back();
require(cell.offspring_genome == successor && revision.life == 100 &&
revision.previous == before.offspring_genome &&
revision.successor == successor && revision.tick == state->tick() &&
checked(state->archive().current_genome(100), "expressed archive") ==
before.identity.genome &&
checked(state->archive().living_carriers(successor),
"unborn carriers") == 0,
"offspring plan mistaken for an expressed organism");
require(restore(*state)->snapshot() == state->snapshot(), "selected plan restore");
closed(*state);
return;
}
} else
checked(state->advance_tick_with_mutations(idle(*state), {}), "earned offer tick");
closed(*state);
}
throw std::runtime_error("finite feeding never earned a structural offspring choice");
}
std::uint64_t bud(Owner& state) {
for (unsigned tick = 0; tick < 30'000; ++tick) {
const auto plan = parent(*state).offspring_genome;
const auto result =
checked(state->advance_tick_with_mutations(idle(*state, false, true), {}),
"inherited bud tick");
closed(*state);
for (const auto& outcome : result.buds) {
if (outcome.parent_life != 100 || outcome.result != CellularBudResult::budded)
continue;
const auto child =
std::ranges::find(state->lives(), outcome.bud_life,
[](const auto& life) { return life.identity.life; });
require(child != state->lives().end() && child->identity.genome == plan &&
child->offspring_genome == plan && child->parent_life == 100 &&
child->account == LifeAccount{} &&
std::ranges::none_of(result.growth,
[&](const auto& growth) {
return growth.life_id == child->identity.life;
}),
"newborn plan/body identity or phase");
const auto genome = checked(state->archive().find(plan), "inherited genome");
require(checked(biology::metabolic_budget(genome, child->growth, {293150, {}}),
"inherited body")
.body == child->body,
"child body uses parent genome");
return child->identity.life;
}
}
throw std::runtime_error("finite parent never funded inherited offspring");
}
Owner family() {
auto state = initial();
choose_structure(state, 1'000'000);
bud(state);
return state;
}
void continuation(CellularLives& state) {
bool maintained = false;
const auto plan = parent(state).offspring_genome;
const auto history = state.offspring_revisions().size();
for (unsigned tick = 0; tick < 64; ++tick) {
checked(state.advance_tick_with_mutations(idle(state, true), {}), "inherited continuation");
for (const auto& feedback : state.last_tick_feedback())
if (feedback.life_id != 100)
maintained |= feedback.maintenance_cost.value > 0;
require(parent(state).offspring_genome == plan &&
state.offspring_revisions().size() == history,
"continuation lost retained plan");
closed(state);
}
// Maximal funded birth can already be fully grown; maintenance must still run.
require(maintained, "inherited continuation skipped offspring metabolism");
}
void put(std::vector<std::uint8_t>& bytes, std::size_t at, std::uint64_t value,
unsigned width = 8) {
for (unsigned offset = 0; offset < width; ++offset)
bytes.at(at + offset) = static_cast<std::uint8_t>(value >> (offset * 8U));
}
void reseal(std::vector<std::uint8_t>& bytes) {
std::uint64_t value = 14695981039346656037ULL;
for (const auto byte : std::span{bytes}.first(bytes.size() - 8))
value = (value ^ byte) * 1099511628211ULL;
put(bytes, bytes.size() - 8, value);
}
void codecs_and_siblings() {
auto state = family();
const auto first_child = std::ranges::find_if(
state->lives(), [](const auto& life) { return life.parent_life == 100; });
require(first_child != state->lives().end(), "missing first child");
const auto old_child = first_child->identity;
const auto bytes = state->snapshot();
const auto history = bytes.size() - 8 - state->offspring_revisions().size() * 32;
// One founding site, owner-8 header, then life rows. All corruptions carry a
// valid outer checksum; restore must establish biological/history semantics.
const auto corrupt = [&](std::size_t at, std::uint64_t value, unsigned width = 8) {
auto altered = bytes;
put(altered, at, value, width);
reseal(altered);
require(!CellularLives::restore(altered, state->world(), state->region(), state->frame(),
state->tick()),
"forged inherited checkpoint accepted");
};
corrupt(316 + 8 + 504, 0);
corrupt(316 + 8 + 504, 100);
corrupt(316 + 8 + 504, 999'999);
corrupt(history, old_child.life);
corrupt(history + 8, 999'999);
corrupt(history + 16, 100);
corrupt(history + 24, state->tick() + 1);
corrupt(308, 0xFFFF'FFFFULL, 4);
corrupt(312, 1, 4);
corrupt(12, 9, 4);
auto flipped = bytes;
flipped.at(316) ^= 1;
require(!CellularLives::restore(flipped, state->world(), state->region(), state->frame(),
state->tick()),
"checksum damage accepted");
require(!CellularPopulation::create(restore(*state)) && !CellularCensus::observe(*state) &&
!CellularMigration::prepare(*state, *state, 100),
"unsupported old adapter admitted plans");
CellularBatch old_trace;
old_trace.header = {state->world(), state->region(), state->frame(), {}, {},
state->tick(), state->tick() + 1};
old_trace.header.predecessor.fill(1);
old_trace.header.predecessor_digest.fill(2);
old_trace.ticks.push_back({idle(*state), {}, {}});
const auto encoded = checked(encode_cellular_batch(old_trace), "encode valid old trace");
const auto decoded = checked(decode_cellular_batch(encoded), "decode valid old trace");
const auto replayed = replay_cellular_batch(*state, decoded);
if (replayed)
throw std::runtime_error("old replay admitted inherited owner");
require(replayed.error() == CellularBatchError::version,
"old replay refused for a reason other than version admission");
choose_structure(state, 1'000'001);
require(state->offspring_revisions().size() == 2 && parent(*state).identity.genome == 100,
"later plan lost earlier history or changed parent");
require(checked(state->archive().organism(old_child.organism), "older child archive").genome ==
old_child.genome,
"later plan rewrote earlier child's birth");
state = restore(*state);
bud(state);
state = restore(*state);
bud(state);
require(parent(*state).offspring_genome == 1'000'001 &&
state->offspring_revisions().size() == 2,
"sibling birth reset selected plan");
const auto frozen = parent(*state);
for (unsigned tick = 0; tick < 250; ++tick)
checked(state->advance_tick_with_mutations(idle(*state, true), {}), "frozen inheritance");
const auto after = parent(*state);
require(after.presence == CellularPresence::suspended && after.body == frozen.body &&
after.reserve == frozen.reserve && after.growth == frozen.growth &&
after.mutation == frozen.mutation &&
after.offspring_genome == frozen.offspring_genome,
"offline parent progressed its plan or biology");
require(restore(*state)->snapshot() == state->snapshot(), "suspended plan restore");
}
void legacy_expression_upgrade() {
auto state = opening(7, true, 1);
state = checked(state->migration_upgrade_candidate(), "legacy boundary upgrade");
state = checked(state->maturation_upgrade_candidate(), "legacy maturation upgrade");
bool expressed = false;
for (unsigned tick = 0; tick < 60'000 && !expressed; ++tick) {
const auto before = parent(*state);
if (!before.mutation.offer) {
checked(state->advance_tick_with_mutations(idle(*state), {}), "legacy earned offer");
continue;
}
const CellularMutationSelection selection{
100, before.mutation.event_index, before.mutation.offer_tick, 900'000,
before.mutation.offer->candidates.front().operator_id};
const auto result =
checked(state->advance_tick_with_mutations(idle(*state), std::span{&selection, 1}),
"legacy expression");
expressed = result.mutations.front().result == CellularMutationResult::applied;
}
require(expressed && parent(*state).identity.genome == 900'000,
"legacy mutation was not expressed");
const auto at = state->archive().revisions().back().at.value;
const auto archive = state->archive().encode();
state = checked(state->inheritance_upgrade_candidate(), "expressed parent upgrade");
require(state->archive().encode() == archive && parent(*state).offspring_genome == 900'000,
"upgrade lost expressed revision");
choose_structure(state, 1'000'000);
auto forged = state->snapshot();
put(forged, forged.size() - 8 - 32 + 24, at);
reseal(forged);
require(!CellularLives::restore(forged, state->world(), state->region(), state->frame(),
state->tick()),
"plan selected before its expressed baseline existed");
}
void death_history() {
auto state = family();
for (unsigned tick = 0; tick < 100'000; ++tick) {
checked(state->advance_tick_with_mutations(idle(*state, false, false, true), {}),
"parent ecological death");
closed(*state);
const auto corpse = std::ranges::find(state->corpses(), 100, &CellularOwnedCorpse::life_id);
if (corpse != state->corpses().end()) {
require(corpse->offspring_genome == 1'000'000 &&
state->offspring_revisions().size() == 1,
"death discarded selected plan history");
require(restore(*state)->snapshot() == state->snapshot(), "dead-plan history restore");
return;
}
}
throw std::runtime_error("finite parent did not die after leaving food");
}
void save(const char* path, std::span<const std::uint8_t> bytes) {
std::ofstream file(path, std::ios::binary | std::ios::trunc);
file.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(bytes.size()));
require(file.good(), "inheritance checkpoint write");
}
} // namespace
int main(int argc, char** argv) try {
if (argc == 4 && std::string_view{argv[1]} == "--checkpoint") {
auto state = family();
save(argv[2], state->snapshot());
continuation(*state);
save(argv[3], state->snapshot());
return 0;
}
if (argc == 4 && std::string_view{argv[1]} == "--resume") {
std::ifstream file(argv[2], std::ios::binary);
const std::vector<std::uint8_t> bytes{std::istreambuf_iterator<char>{file}, {}};
require(bytes.size() >= 324, "inheritance checkpoint length");
std::uint64_t tick = 0;
for (unsigned offset = 0; offset < 8; ++offset)
tick |= std::uint64_t{bytes[40 + offset]} << (offset * 8U);
auto state = checked(CellularLives::restore(bytes, 207, 1, 1, tick), "new-process plans");
continuation(*state);
save(argv[3], state->snapshot());
return 0;
}
require(argc == 1, "unknown inheritance arguments");
codecs_and_siblings();
legacy_expression_upgrade();
death_history();
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}