feat(lifecycle): add opt-in funded cellular maturation
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 2m25s
Foundation / checks (network) (push) Successful in 21m0s
Foundation / checks (client) (push) Successful in 22m13s
Foundation / checks (tsan) (push) Successful in 26m35s
Foundation / checks (postgres) (push) Successful in 1h1m27s
Foundation / checks (checks) (push) Successful in 1h14m29s
Foundation / postgres-tools (push) Successful in 1m19s
Foundation / server-image (push) Successful in 3m46s
Foundation / image (push) Successful in 4m57s

This commit is contained in:
dingo
2026-10-18 21:48:27 -04:00
parent 27ec5729bf
commit a5307c768b
22 changed files with 889 additions and 19 deletions
+10
View File
@@ -685,6 +685,16 @@ endif()
if(BUILD_TESTING)
add_executable(evo-cellular-population-tests tests/cellular_population_tests.cpp)
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)
add_test(NAME cellular-funded-maturation COMMAND evo-cellular-maturation-tests)
set_tests_properties(cellular-funded-maturation PROPERTIES TIMEOUT ${evo_cohort_timeout})
add_test(NAME cellular-maturation-process-restart COMMAND "${CMAKE_COMMAND}"
"-DPOPULATION_TEST=$<TARGET_FILE:evo-cellular-maturation-tests>"
"-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/maturation-restart"
-P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake")
set_tests_properties(cellular-maturation-process-restart PROPERTIES TIMEOUT ${evo_cohort_timeout})
target_link_libraries(evo-cellular-population-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-cellular-population-tests)
add_test(NAME cellular-population-transitions COMMAND evo-cellular-population-tests)
+5 -1
View File
@@ -165,7 +165,11 @@ preserve exact identity/history and regional boundary budgets. Their scoped
durable preparation/staging, atomic paired publication and verified recovery are
implemented; [TLS transport fault checks](docs/engineering/M12_MIGRATION_TRANSPORT_FAULTS.md)
cover independent local path loss and owner replacement. Linked ecology and
deployment qualification remain open. The microscope client is the M11 playtest path.
deployment qualification remain open. Portable opt-in
[rules-9 maturation](docs/adr/0157-funded-cellular-maturation.md) now funds real
juveniles through adulthood and budding in the same raw/cohort kernel; durable
admission and autonomous ecological qualification remain separate gates.
The microscope client is the M11 playtest path.
`evo::simulation` remains
graphics-, network- and database-independent.
+17
View File
@@ -1,5 +1,22 @@
# Project status and next steps
## Portable M12 funded maturation prerequisite - 2026-10-18
[ADR-0157](adr/0157-funded-cellular-maturation.md) adds opt-in rules-9 funded
growth to the exact raw/cohort kernel. A genuine finite-food bud reaches adulthood
and produces its own bud; construction preserves every stock, damage and genome.
The documented trial rate, blocked-expansion refusal, saved-choice funding,
newborn/offline exclusion, conversion and exact replay/process continuation pass.
Rules 8, DEV defaults and durable bundle admission retain their existing meaning.
Native and GCC Release pass **81/81** each. Affected ASan/UBSan, including the final
offline/process guards, clang-tidy and formatting pass; detailed evidence and
fixture limits are in [validation](engineering/VALIDATION.md). Small juveniles'
pool nutrient rounding and sibling placement still constrain ecology. Durable
rules-9 admission/migration/census, automated generations, joint environmental
budgets, target-host costs, actual days and product gates remain open. This is a
portable prerequisite, not completion of M12.
## M12.7c registered census pending handoff evidence - 2026-10-18
Schema 52 captures active biological migration pointers with history domain,
@@ -0,0 +1,65 @@
# ADR-0157: Opt-in funded cellular maturation
## Status
Accepted for the portable M12 ecology prerequisite, 2026-10-18. Extends
ADR-0031/0032/0120/0125/0128/0137/0139/0144. Trial parameters remain revisable;
this does not accept gameplay balance, durable admission or product readiness.
## Decision
Rules 9 explicitly opt an existing rules-8, format-7 owner into maturation.
The detached no-tick upgrade preserves every organism, archive, inventory,
presence, boundary flow and cohort tag. Only the biology rules field changes.
Format 7 already stores growth and all affected inventories. Population envelope
2 and recorded input formats need no new fields. Older readers reject rules 9;
rules 8 and its goldens retain their meaning. No default/DEV or SQL bundle changes.
After old-size movement, maintenance, contact feeding, engulfment/death, selected
mutation, budding and presence changes, surviving active cells can construct at
most **5 realized thousandths per 50,000 microsecond tick** (100 per second).
This is an experimental rate, distinct from the development version's per-plan
bound. A newborn takes no growth step in its birth tick; frozen, lingering and
suspended cells do not grow. A resuming suspended cell starts growth on its next
active tick. Wildlife and controlled cells use the same construction rule.
A juvenile reaching adulthood can first request an admitted bud next tick.
Use the existing channelwise affordable construction transition, additionally
capped by that rate. Pay its gross intake from retained reserve; release body
rounding matter back to reserve and send construction energy to world heat.
Recompute the resulting body from unchanged genome and new growth. Preserve
damage exactly: construction is not repair. There is no new resource source,
reserve grant, automatic mutation or sampled replacement organism. Checked
arithmetic and full owner closure precede publication; failure changes no state.
Expanded squares retain their lower corner and expand toward positive axes.
In ascending stable life-ID order, require the whole proposed extent inside the
region and separated from every other present life, including lingering cells
and newborns. Suspended lives occupy no space. Earlier admitted expansions block
later ones. Refuse the proposed expansion without spending, relocation or trying
a smaller spatial step when blocked. This simple directional/contention bias is
explicit trial behavior, not a claim of physical growth geometry.
Mutation offers remain the original deterministic draw with their recorded
context and displayed budget forecast. Selection validates that exact offer;
rules 9 then prices the selected successor at **current growth**, using retained
reserve. It neither redraws the candidate nor restores an obsolete juvenile body.
The old pure funding API retains recorded-growth behavior; an explicit new API
supports current-growth funding. Insufficient funds retain the offer as before.
Successful growth reports the exact before/after growth and intake/release.
Final tick feedback reports the surviving cell's final reserve under rules 9.
Both representations and recorded unattended intervals execute the same kernel.
## Qualification and limits
Require channel and energy starvation, partial affordability, rounding and damage
checks; real funded founder -> juvenile -> adult -> offspring evidence; newborn
and offline exclusion; obstructed expansion with no spending; saved-choice funding
at changed growth; raw/cohort equivalence, conversion and midpoint restore/replay.
Tests must preserve old goldens and run under NDEBUG, ASan/UBSan and analysis.
Rules-9 durable checkpoint admission, migration, registered census, environmental
coupling and client presentation require their own contract/qualification. Current
durable bundle allowlists continue to reject this rule. No actual-days soak,
deployment, World0 operation, extinction or M12 completion is inferred.
+12
View File
@@ -96,6 +96,18 @@ The maintainer accepted these for the first playable loop (2026-10-09):
Fission, eggs, cohorts, spores, NPC mutation, and how long suspension is retained stay
open. The values marked tunable are playtest hypotheses, not locked rules.
## Portable M12 maturation
The portable M12 ecology prerequisite in
[ADR-0157](../adr/0157-funded-cellular-maturation.md) adds opt-in rules-9 funded
maturation to the cellular owner and exact cohorts. Genuine buds can spend their
own acquired nutrients and energy to reach adulthood, then fund their own buds.
The trial cap is 5 realized thousandths per 50 ms active tick, subject to exact
channel funding and expansion space; damage is retained. Newborn/offline cells
do not advance growth in that tick. Rules 8, DEV defaults and durable admission
remain unchanged. A scripted finite-food family proof is not evidence of
autonomous sustainable ecology, environmental coupling or actual-days operation.
## Implemented M2.5 fixture boundary
[ADR-0028](../adr/0028-funded-reproduction.md) implements funded budding inside
@@ -40,6 +40,10 @@ ordering regression uses a real fully grown local founder reproducing alongside
imported higher-namespace residents. Self-sustaining wildlife generations still
need an explicit versioned maturation contract and ecological qualification.
ADR-0157 subsequently supplies opt-in portable rules-9 maturation with a funded
multi-generation family proof. These transfer contracts and durable bundle 10
remain rules 8; they refuse rules-9 migration until separately qualified.
This is not the durable escrow gate. No prepared candidate may become an active
destination owner before a future fenced transaction commits both heads and
immutable transfer evidence. The source remains the sole owner until that commit;
+12
View File
@@ -99,6 +99,18 @@ not apply it. It is a concrete basis for a separately versioned funded maturatio
contract that also resolves expanded-body collision, tick ordering and offline
freeze. Its existence alone does not admit a new growth rule.
[ADR-0157](../adr/0157-funded-cellular-maturation.md) now implements that **portable
opt-in rules-9** prerequisite, preserving rules 8 and all default/live admission.
The exact construction transfer, bounded rate, spatial refusal, offline exclusion
and saved-choice funding are explicit. A real finite-food founder/bud reaches
funded adulthood and produces another bud, with paid sibling movement; raw/cohort
growth, conversion, recorded replay and separate-process continuation agree.
This is scripted biological evidence, not autonomous multi-generation ecological
qualification. Small juveniles can receive zero phosphorus per tick from a pool
because the existing quarter-yield rounds down; finite nutrient motes/contact and
space still matter. Durable rules-9 publication/migration/census, linked resources,
automatic wildlife robustness, balance and actual-days qualification remain open.
M12.6a's [regional census projection](../../schemas/ecology/regional-cellular-census-v1.md)
independently implements local current-genome and descendant-closure queries.
It keeps suspended stock and retained zero-carrier ancestry, separates exact cohort
+75
View File
@@ -1,5 +1,80 @@
# Validation report
## 2026-10-18 - Portable M12 funded maturation prerequisite
[ADR-0157](../adr/0157-funded-cellular-maturation.md) adds an explicit detached
rules-8/owner-7 -> rules-9 maturation candidate, including exact population tags.
The old owner formats, rules, golden vectors, default/DEV admission, SQL schema
52 and durable bundle allowlists are unchanged. Construction spends exact gross
reserve intake, returns body rounding releases and puts energy into world heat.
The trial cap is 5 realized thousandths per 50 ms active tick. Existing-size
actions finish first; newborn/offline cells do not construct. Fixed-corner
expansion must fit boundaries and all present neighbors, in stable life order.
Saved mutation choices keep their original draw and fund current-size bodies.
Executed locally:
- MSVC default Release full CTest **81/81 passed, 15.33 s**, with NDEBUG.
- GCC 14 Release full portable CTest **81/81 passed, 12.68 s**, with NDEBUG.
- Clang 19 ASan/UBSan affected development, uptake, habitat, step/region, owner,
metabolism, mutation, budding, maturation/process continuation, populations and
checkpoint-admission contracts **13/13 passed, 56.43 s**, without reports.
After adding the final discriminating controlled-subadult offline guard, both
maturation/process contracts passed again **2/2, 28.56 s**, without reports.
- Earlier in this same scope, the unchanged implementation's raw owner, mutation,
maturation, populations, census and migration contracts passed ASan/UBSan
**6/6, 103.80 s**, including the legacy rules-8 regression paths.
- clang-tidy 19 passed on both changed biology sources, all three changed
lifecycle sources and both test files. The final offline fixture passed a
separate analysis recheck. Repository clang-format 19 and `git diff --check`
passed. No old golden or numbered migration was replaced.
The family test starts from a genuinely funded adult founder and its real bud,
never a fabricated adult wildlife record. With finite retained food and paid
sibling movement, that juvenile reaches adulthood and produces another bud at
**tick 27,901**, after **939 reported funded growth steps across the family**.
Every tick checks complete five-channel owner closure and each growth report's
exact reserve spending. Newborns have no growth report in their birth tick;
midpoint canonical restoration preserves continuation. This is accelerated,
scripted biological evidence, not autonomous sustainability or elapsed-day proof.
Raw and cohort execution share the unchanged wildlife controller and produce
identical complete biological bytes for 1,024 growing ticks, including conversion
and repeated restoration. Recorded raw inputs and a full 64-tick population
interval decode/replay identically. A second executable process restores a growing
cohort and produces byte-identical 64-tick continuation. Population upgrade
preserves policy, tags and sequence. Rules-8 juveniles retain their original
growth. Valid rules-8 raw/population manifests accept their original payloads
and reject rules-9 payloads; an unadmitted rules-9 manifest bundle is unsupported.
Geometry fault fixtures only relocate genuine funded juveniles, preserving all
stocks/identity/history. A region boundary and a frozen lingering neighbor each
refuse an otherwise funded extent increase without growth spending or movement.
A separate controlled-subadult offline fixture returns already-owned body matter
to reserve, leaves paid heat intact and grants no resource. Current founders are
born adult, so this artificial fixture tests the guard only, not the family proof.
Its active control demonstrably grows; freeze/linger/suspend preserve body,
growth, reserves and mutation progress. Suspended resume grows only on the next
active tick. Pure budget tests cover rate/zero caps, damage retention, partial
funding, each absent nutrient/energy channel and exact composed-body closure;
saved-offer tests preserve the original choice at changed growth and reject a
changed recorded context.
The qualification exposed an existing ecological constraint: the smallest
juveniles can receive zero pool phosphorus per tick when quarter-yield floors
to zero. Contact with finite nutrient motes, placement and sibling space matter;
no feeding/balance rule was changed to conceal it. The family deliberately moves
a sibling through paid intentions. Automated multi-generation wildlife,
larger-cohort contention/tail cost and comparative ecological regimes remain open.
This gate changes no PostgreSQL adapter, migration or runtime admission, so the
full private database/TLS/storage/backup/DR matrix was not rerun. Durable rules-9
upgrade/publication/recovery, migration, registered census and client presentation
require separate admission/qualification. TSan was not rerun: no shared-memory
concurrency or scheduler ownership changed. Joint environmental budgets, actual
days, deployment-host evidence and product readiness remain open. No deployment,
World0 operation or terminal extinction decision occurred.
## 2026-10-18 - M12.7c registered census pending handoff evidence
[ADR-0156](../adr/0156-census-pending-migration-evidence.md)/schema 52 captures
+4 -1
View File
@@ -55,8 +55,11 @@ struct MetabolicBudget {
metabolic_rules_for(std::uint32_t development_version);
// The single place the genome's description of capability becomes ledger
// quantities. The genome record itself stays free of accounting types.
// max_growth_per_thousand caps this proposal, not a time rate; the caller owns
// its versioned cadence. The default preserves earlier budget results exactly.
[[nodiscard]] std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment);
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment,
std::uint32_t max_growth_per_thousand = 1000);
// An analysis, not a rule (ADR-0098 decision 7): whole seconds until feeding funds the
// budget's reproduction investment, channel by channel and in energy, when the organism
// takes in its full intake limit for `feeding_per_thousand` of the time and pays its
+7
View File
@@ -88,4 +88,11 @@ select_mutation(const Genome& genome, const MutationContext& context, const Muta
fund_mutation(const Genome& genome, const MutationContext& context, const MutationOffer& offered,
std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event,
const accounting::Inventory& reserve);
// ADR-0157: preserve and validate the original draw, but fund its selected genome
// at the organism's current growth. No redraw or reset to the offer's old body.
[[nodiscard]] std::expected<MutationTransition, MutationError>
fund_mutation_at_growth(const Genome& genome, const MutationContext& context,
const MutationOffer& offered, std::uint16_t chosen,
std::uint64_t successor_id, std::uint64_t origin_event,
const accounting::Inventory& reserve, GrowthState current_growth);
} // namespace evo::biology
@@ -43,8 +43,11 @@ inline constexpr std::uint32_t cellular_lives_reproduction_rules = 7;
// carries the new state, so they keep owner format 6.
inline constexpr std::uint32_t cellular_lives_foraging_rules = 8;
// ADR-0144: opt-in boundary accounting and retained nonresident history. Biology
// remains rules 8; every earlier envelope retains its original meaning.
// starts on rules 8; every earlier envelope retains its original meaning.
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;
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
cellular_founder_version(std::uint32_t rules) noexcept {
@@ -158,10 +161,17 @@ struct CellularBudExecution {
CellularBudResult result{};
auto operator<=>(const CellularBudExecution&) const = default;
};
struct CellularGrowthExecution {
std::uint64_t life_id{};
biology::GrowthState before{}, after{};
accounting::Inventory intake{}, release{};
auto operator<=>(const CellularGrowthExecution&) const = default;
};
struct CellularTickExecution {
biology::CellularRegionStepCandidate step;
std::vector<CellularMutationExecution> mutations;
std::vector<CellularBudExecution> buds; // Rules 4, in parent life order.
std::vector<CellularBudExecution> buds; // Rules 4, in parent life order.
std::vector<CellularGrowthExecution> growth; // Rules 9: funded expansions only, life order.
};
struct CellularLifeTickFeedback {
std::uint64_t life_id{}, tick{};
@@ -253,6 +263,9 @@ class CellularLives {
// Explicit detached format-6/rules-8 -> format-7 upgrade. No biology advances.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migration_upgrade_candidate() const;
// 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;
// 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;
@@ -53,6 +53,9 @@ class CellularPopulation {
// Explicit no-tick envelope-1 -> envelope-2 upgrade, retaining all cohort tags.
[[nodiscard]] std::expected<std::unique_ptr<CellularPopulation>, CellularPopulationError>
migration_upgrade_candidate() const;
// ADR-0157: preserve exact membership while upgrading nested biology to rules 9.
[[nodiscard]] std::expected<std::unique_ptr<CellularPopulation>, CellularPopulationError>
maturation_upgrade_candidate() const;
[[nodiscard]] std::vector<std::uint8_t> snapshot() const;
[[nodiscard]] static std::expected<std::unique_ptr<CellularPopulation>, CellularPopulationError>
restore(std::span<const std::uint8_t> bytes, std::uint64_t world, std::uint64_t region,
+21 -4
View File
@@ -1,13 +1,14 @@
# Cellular owner format 7: exact boundary accounting
Authority: ADR-0144. Portable opt-in representation only; no PostgreSQL manifest
bundle or live worker admission is introduced by this segment. Rules stay 8.
Authority: ADR-0144, with opt-in maturation in ADR-0157. Rules 8 retain their
meaning; the additional rules-9 interpretation is portable only. Durable bundle
10 still admits rules 8 exclusively; no live worker opts into maturation.
Formats 1–6 and their canonical bytes remain unchanged. Explicit no-tick upgrade
from rules-8 format 6 preserves biology and opening stock and adds zero flows
and no nonresident references. No downgrade may discard a nonzero ledger.
Little-endian, no native padding. Magic `AEVCLV07`, format 7, rules 8. The first
220 bytes have the format-6 layout except magic/format. The additional fields are:
Little-endian, no native padding. Magic `AEVCLV07`, format 7, rules 8 or 9. The first
220 bytes have the format-6 layout except magic/format/rules. The additional fields are:
| Offset | Bytes | Field |
|---:|---:|---|
@@ -56,3 +57,19 @@ automatic spatial crossings and linked environmental fields are unimplemented.
Durability must bind both candidates to one fenced atomic pair publication. This
format alone supplies no freeze, escrow, receipt, activation or retry guarantee.
## Rules 9: funded maturation
ADR-0157's explicit no-tick upgrade from rules 8 changes only the rules field and
checksum, preserving this entire layout and all stocks/flows/history. The retained
growth, body, reserve and world heat fields encode every maturation effect. At
most 5 realized thousandths per 50 ms active tick are constructed after old-size
actions, budding and presence changes. Newborn/frozen/suspended cells do not grow;
a suspended resume begins growth next tick. Expanded squares retain their corner
and must fit every present neighbor/boundary, in ascending life-ID order. A blocked
expansion spends nothing. Damage and immutable genomes are preserved.
Saved mutation offers retain their original draw/context; rules 9 fund the chosen
successor at current growth. No context/body reset is encoded. Unknown rules fail
closed; rules 9 in owner format 6 are refused. Biological migration and durable
rules-9 admission remain unsupported pending their separate qualification.
+6
View File
@@ -64,6 +64,12 @@ validator and schema 45's SQL trace checker admit only batch 1. A new durable
bundle/upgrade and exact history/recovery contract remain required before any
publication, scheduling or transfer activation can use the new representation.
ADR-0157 also allows portable batch 2 replay against envelope 2/owner 7/rules 9.
Recorded intentions are unchanged; the bound predecessor's explicit rules field
selects maturation. Both raw and cohort replay perform the same funded growth
and preserve exact member tags and stocks. This is not durable rules-9 admission;
the rules-8 bundle allowlist remains unchanged.
M12.4g/schema 46 adds the dedicated bundle-9 to 10 upgrade and full recovery
contract. Bundle 10 admits batch 2 for ordinary intervals and manual conversion;
bundle 9 still refuses it and remains bound to batch 1. Actual SHA-256 and wire
+7
View File
@@ -57,3 +57,10 @@ history 5 in schema 46. An explicit no-tick version upgrade retains membership,
policy and conversion sequence through the immutable version-upgrade journal.
Ordinary publication requires population batch 2; profile transitions preserve
bundle 10. No worker upgrades automatically and no paired migration is published.
ADR-0157 additionally permits **portable** envelope 2 to contain owner 7/rules 9.
The nested owner identifies the changed growth semantics; no membership, policy,
sequence or wire-layout change is needed. An explicit no-tick maturation candidate
preserves all tags and upgrades only the nested rules. Both representations use
the same funded-growth kernel. Envelope 1 remains rules 8. Durable bundle 10
remains rules 8 and does not admit this portable maturation upgrade.
+4 -2
View File
@@ -117,7 +117,8 @@ metabolic_rules_for(std::uint32_t development_version) {
}
std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment) {
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment,
std::uint32_t max_growth_per_thousand) {
const auto phenotype = derive_phenotype(genome, growth, environment);
if (!phenotype) {
return std::unexpected{phenotype.error()};
@@ -164,7 +165,8 @@ metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState envi
// intake fits channel by channel.
budget.construction.after = growth;
const auto proposed = plan->after.realized_per_thousand - growth.realized_per_thousand;
for (std::uint32_t attempt = proposed; attempt > 0; --attempt) {
for (std::uint32_t attempt = std::min(proposed, max_growth_per_thousand); attempt > 0;
--attempt) {
const GrowthState candidate{growth.realized_per_thousand + attempt,
growth.damage_per_thousand};
const auto grown = derive_phenotype(genome, candidate, environment);
+11 -2
View File
@@ -249,13 +249,22 @@ std::expected<MutationTransition, MutationError>
fund_mutation(const Genome& genome, const MutationContext& context, const MutationOffer& offered,
std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event,
const accounting::Inventory& reserve) {
return fund_mutation_at_growth(genome, context, offered, chosen, successor_id, origin_event,
reserve, context.growth);
}
std::expected<MutationTransition, MutationError>
fund_mutation_at_growth(const Genome& genome, const MutationContext& context,
const MutationOffer& offered, std::uint16_t chosen,
std::uint64_t successor_id, std::uint64_t origin_event,
const accounting::Inventory& reserve, GrowthState current_growth) {
const auto successor =
select_mutation(genome, context, offered, chosen, successor_id, origin_event);
if (!successor) {
return std::unexpected{successor.error()};
}
const auto before = metabolic_budget(genome, context.growth, context.environment);
const auto after = metabolic_budget(*successor, context.growth, context.environment);
const auto before = metabolic_budget(genome, current_growth, context.environment);
const auto after = metabolic_budget(*successor, current_growth, context.environment);
const auto rules = rules_for(genome.development_version());
if (!before || !after || !rules) {
return std::unexpected{MutationError::development};
+84 -5
View File
@@ -711,6 +711,17 @@ std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::migration_upgrade_candidate() const {
return migration_replacement(state_->lives, state_->archive, state_->boundary);
}
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::maturation_upgrade_candidate() const {
if (state_->format_version != cellular_lives_migration_format ||
state_->rules_version != cellular_lives_foraging_rules)
return std::unexpected(CellularLivesError::version);
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
if (!candidate)
return std::unexpected(candidate.error());
(*candidate)->state_->rules_version = cellular_lives_maturation_rules;
return candidate;
}
std::span<const CellularLifeTickFeedback> CellularLives::last_tick_feedback() const noexcept {
return last_tick_feedback_;
}
@@ -1091,7 +1102,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
// 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_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 &&
@@ -1564,9 +1576,11 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
continue;
}
const auto offer = found->mutation.offer.value_or(biology::MutationOffer{});
auto transition =
biology::fund_mutation(*parent, offer.context, offer, selection.operator_id,
selection.successor_id, selection.successor_id, found->reserve);
auto transition = biology::fund_mutation_at_growth(
*parent, offer.context, offer, selection.operator_id, selection.successor_id,
selection.successor_id, found->reserve,
state_->rules_version >= cellular_lives_maturation_rules ? found->growth
: offer.context.growth);
if (!transition) {
if (transition.error() == biology::MutationError::insufficient_funding) {
mutation_results.push_back({selection.life_id, selection.successor_id,
@@ -1732,6 +1746,69 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
}
}
}
// ADR-0157: old-size actions finish first. A newborn, frozen life or a life
// 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) {
for (auto& life : next_lives) {
const auto input = std::ranges::lower_bound(ordered, life.identity.life, {},
&CellularLifeIntent::life_id);
const auto previous =
std::ranges::lower_bound(state_->lives, life.identity.life, {},
[](const auto& old) { return old.identity.life; });
if (input == ordered.end() || input->life_id != life.identity.life ||
input->intent.frozen || life.presence != CellularPresence::active ||
previous == state_->lives.end() || previous->identity.life != life.identity.life ||
previous->presence == CellularPresence::suspended ||
life.growth.realized_per_thousand == 1000)
continue;
const auto genome = next_archive.find(life.identity.genome);
if (!genome)
return std::unexpected(CellularLivesError::archive);
const auto budget = biology::metabolic_budget(
*genome, life.growth,
{state_->config.ambient_temperature_millikelvin, life.reserve},
cellular_growth_per_tick);
if (!budget || budget->body != life.body)
return std::unexpected(CellularLivesError::biology);
const auto& move = budget->construction;
if (move.after == life.growth)
continue;
const auto grown = biology::metabolic_budget(
*genome, move.after, {state_->config.ambient_temperature_millikelvin, {}});
if (!grown)
return std::unexpected(CellularLivesError::biology);
const auto extent = grown->phenotype.extent;
bool clear = extent <= state_->config.area.width_um &&
extent <= state_->config.area.height_um &&
life.position.x_um <= state_->config.area.width_um - extent &&
life.position.y_um <= state_->config.area.height_um - extent;
for (const auto& other : next_lives) {
if (!clear || other.identity.life == life.identity.life ||
other.presence == CellularPresence::suspended)
continue;
const auto obstacle =
budget_for(next_archive, other, state_->config.ambient_temperature_millikelvin);
if (!obstacle)
return std::unexpected(obstacle.error());
clear = separated(life.position.x_um, other.position.x_um, extent,
obstacle->phenotype.extent) ||
separated(life.position.y_um, other.position.y_um, extent,
obstacle->phenotype.extent);
}
if (!clear)
continue; // No partial spatial retry, relocation or spending.
if (!subtract_inventory(life.reserve, move.intake) ||
!add_inventory(life.reserve, move.release) ||
!add_inventory(next_heat, accounting::Inventory{move.intake.energy, {}}))
return std::unexpected(CellularLivesError::overflow);
growth_results.push_back(
{life.identity.life, life.growth, move.after, move.intake, move.release});
life.growth = move.after;
life.body = grown->body;
}
}
std::ranges::sort(next_corpses, {}, &CellularOwnedCorpse::organism);
if (proposal->heat_released.value >
std::numeric_limits<std::uint64_t>::max() - next_heat.energy.value)
@@ -1829,6 +1906,8 @@ 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)
entry->reserve = life.reserve; // Includes funded growth/mutation/budding.
entry->resume_blocked =
std::ranges::find(resume_blocked, life.identity.life) != resume_blocked.end();
}
@@ -1836,6 +1915,6 @@ CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> i
state_.swap(next);
last_tick_feedback_ = std::move(feedback);
return CellularTickExecution{std::move(*proposal), std::move(mutation_results),
std::move(bud_results)};
std::move(bud_results), std::move(growth_results)};
}
} // namespace evo::server
+16 -1
View File
@@ -14,7 +14,10 @@ CellularPopulation::CellularPopulation(std::unique_ptr<CellularLives> state,
std::expected<std::unique_ptr<CellularPopulation>, CellularPopulationError>
CellularPopulation::create(std::unique_ptr<CellularLives> state, CellularTierPolicy policy) {
if (!state || state->rules_version() != cellular_lives_foraging_rules ||
if (!state ||
(state->rules_version() != cellular_lives_foraging_rules &&
!(state->rules_version() == cellular_lives_maturation_rules &&
state->format_version() == cellular_lives_migration_format)) ||
(state->format_version() != cellular_lives_presence_format &&
state->format_version() != cellular_lives_migration_format) ||
policy.materialize_radius_um == 0 ||
@@ -53,6 +56,18 @@ CellularPopulation::migration_upgrade_candidate() const {
(*candidate)->conversion_sequence_ = conversion_sequence_;
return candidate;
}
std::expected<std::unique_ptr<CellularPopulation>, CellularPopulationError>
CellularPopulation::maturation_upgrade_candidate() const {
auto biological = state_->maturation_upgrade_candidate();
if (!biological)
return std::unexpected(CellularPopulationError::unsupported);
auto candidate = create(std::move(*biological), policy_);
if (!candidate)
return std::unexpected(candidate.error());
(*candidate)->members_ = members_;
(*candidate)->conversion_sequence_ = conversion_sequence_;
return candidate;
}
std::expected<std::size_t, CellularPopulationError>
CellularPopulation::collapse(std::uint64_t genome) {
auto candidate = members_;
@@ -77,7 +77,8 @@ class Reader {
} // namespace
bool population_interval_safe(const CellularLives& state) noexcept {
return state.rules_version() == cellular_lives_foraging_rules &&
return (state.rules_version() == cellular_lives_foraging_rules ||
state.rules_version() == cellular_lives_maturation_rules) &&
std::ranges::all_of(state.lives(), [](const auto& life) {
return life.account == LifeAccount{} || life.presence == CellularPresence::suspended;
});
+490
View File
@@ -0,0 +1,490 @@
#include "evo/biology/budding.hpp"
#include "evo/server/lifecycle/cellular_population_batch.hpp"
#include "fixtures/cellular_ecology.hpp"
#include <fstream>
#include <iterator>
namespace {
using namespace evo;
using namespace evo::server;
using namespace evo::fixture;
Inventory stocked(std::uint64_t amount = 1'000'000'000'000ULL) {
Inventory result{{amount}, {}};
for (auto& channel : result.matter)
channel.value = amount;
return result;
}
void construction_and_saved_choices() {
const auto genome =
checked(biology::primitive_founder(1, 1, biology::primitive_founder_v3), "growth genome");
const biology::GrowthState start{400, 37};
const biology::EnvironmentState environment{293'150, stocked()};
const auto budget =
checked(biology::metabolic_budget(genome, start, environment, 5), "growth cap");
require(budget.construction.after == biology::GrowthState{405, 37},
"growth cap/damage changed");
require(checked(biology::metabolic_budget(genome, start, environment, 0), "zero cap")
.construction.after == start,
"zero cap grew");
for (std::size_t channel = 0; channel < 5; ++channel) {
auto available = environment;
if (channel == 0)
available.available.energy.value = 0;
else
available.available.matter[channel - 1].value = 0;
require(checked(biology::metabolic_budget(genome, start, available, 5), "starved growth")
.construction.after == start,
"missing nutrient/energy still grew");
}
const auto one = checked(biology::metabolic_budget(genome, start, environment, 1), "one step");
auto limited = environment;
limited.available = one.construction.intake;
require(checked(biology::metabolic_budget(genome, start, limited, 5), "partial funds")
.construction.after == one.construction.after,
"partial funding did not choose largest affordable step");
const auto grown =
checked(biology::metabolic_budget(genome, budget.construction.after, environment),
"derived grown body");
for (std::size_t channel = 0; channel < 4; ++channel)
require(budget.body.matter[channel].value +
budget.construction.intake.matter[channel].value ==
grown.body.matter[channel].value +
budget.construction.release.matter[channel].value,
"construction channel did not close");
const biology::MutationContext context{17, 2, 1, 8, start, environment};
const auto offer = checked(biology::mutation_candidates(genome, context), "saved offer");
const biology::GrowthState current{700, 37};
for (const auto& choice : offer.candidates) {
const auto transition =
checked(biology::fund_mutation_at_growth(genome, context, offer, choice.operator_id, 2,
2, stocked(), current),
"current-size choice");
const auto expected =
checked(biology::metabolic_budget(transition.successor, current, environment),
"current-size body");
require(transition.body == expected.body, "saved choice restored obsolete body");
require(transition.successor == checked(biology::select_mutation(genome, context, offer,
choice.operator_id, 2, 2),
"original draw"),
"growth rerolled choice");
const auto old = checked(
biology::fund_mutation(genome, context, offer, choice.operator_id, 2, 2, stocked()),
"legacy choice");
require(old.body != transition.body, "current-growth fixture is not discriminating");
auto changed = context;
changed.growth = current;
require(!biology::fund_mutation_at_growth(genome, changed, offer, choice.operator_id, 2, 2,
stocked(), current),
"changed offer context accepted");
}
}
std::vector<CellularLifeIntent> idle(const CellularLives& state, bool freeze = false,
std::uint64_t bud = 0) {
std::vector<CellularLifeIntent> result;
for (const auto& life : state.lives()) {
CellularLifeIntent intent{life.identity.life, {}};
intent.intent.frozen = freeze && life.account != LifeAccount{};
intent.intent.bud = life.identity.life == bud && !intent.intent.frozen;
result.push_back(intent);
}
return result;
}
Owner upgraded(Owner state) {
require(!state->maturation_upgrade_candidate(), "format 6 bypassed explicit boundary upgrade");
auto boundary = checked(state->migration_upgrade_candidate(), "boundary upgrade");
const auto before = boundary->snapshot();
auto result = checked(boundary->maturation_upgrade_candidate(), "growth upgrade");
require(boundary->snapshot() == before && result->tick() == boundary->tick() &&
result->current_total() == boundary->current_total() &&
std::ranges::equal(result->lives(), boundary->lives()),
"upgrade changed biology");
require(!result->maturation_upgrade_candidate() && !result->migration_upgrade_candidate(),
"unsupported upgrade admitted");
return result;
}
struct Family {
Owner state;
std::uint64_t child{};
};
Family first_bud(bool maturation) {
auto state = opening(7, true, 1);
if (maturation)
state = upgraded(std::move(state));
for (unsigned tick = 0; tick < 12'000; ++tick) {
const auto executed = checked(
state->advance_tick_with_mutations(idle(*state, false, tick % 100 == 99 ? 100 : 0), {}),
"first funded bud tick");
for (const auto& bud : executed.buds) {
if (bud.result != CellularBudResult::budded)
continue;
const auto child = std::ranges::find(
state->lives(), bud.bud_life, [](const auto& life) { return life.identity.life; });
require(child != state->lives().end() && child->growth.realized_per_thousand < 1000 &&
child->account == LifeAccount{},
"bud is not a genuine juvenile");
require(std::ranges::none_of(
executed.growth,
[&](const auto& growth) { return growth.life_id == bud.bud_life; }),
"newborn grew in birth tick");
return {std::move(state), bud.bud_life};
}
}
throw std::runtime_error("finite feeding never funded the first bud");
}
// Geometry-only codec fixture: retain real funded biology, identities and all
// five stocks. This is a placement fault seam, never an adult/resource shortcut.
Owner relocated(const CellularLives& state, std::uint64_t id, biology::CellularPosition position) {
auto bytes = state.snapshot();
const auto index = static_cast<std::size_t>(
std::ranges::find(state.lives(), id, [](const auto& life) { return life.identity.life; }) -
state.lives().begin());
require(index < state.lives().size() && state.format_version() == 7, "relocation fixture");
const auto put = [&](std::size_t at, std::uint64_t value) {
for (unsigned shift = 0; shift < 8; ++shift)
bytes[at + shift] = static_cast<std::uint8_t>(value >> (shift * 8U));
};
std::uint32_t sites = 0;
for (unsigned shift = 0; shift < 4; ++shift)
sites |= std::uint32_t{bytes[60 + shift]} << (shift * 8U);
const auto row = 308 + sites * 8 + index * 504;
put(row + 72, position.x_um);
put(row + 80, position.y_um);
std::uint64_t hash = 14695981039346656037ULL;
for (const auto byte : std::span{bytes}.first(bytes.size() - 8))
hash = (hash ^ byte) * 1099511628211ULL;
put(bytes.size() - 8, hash);
return checked(
CellularLives::restore(bytes, state.world(), state.region(), state.frame(), state.tick()),
"geometry fixture restore");
}
void frozen_construction() {
auto family = first_bud(false);
auto state = upgraded(std::move(family.state));
const auto founder = state->lives().front();
const auto genome = checked(state->archive().find(founder.identity.genome), "frozen genome");
const biology::GrowthState juvenile{400, 0};
const auto body =
checked(biology::metabolic_budget(genome, juvenile, {293150, {}}), "frozen body").body;
auto bytes = state->snapshot();
const auto put = [&](std::size_t at, std::uint64_t value, unsigned width = 8) {
for (unsigned shift = 0; shift < width; ++shift)
bytes[at + shift] = static_cast<std::uint8_t>(value >> (shift * 8U));
};
// Offline-guard fixture only: a controlled subadult is not produced by the
// current adult-founder flow. Return already-owned body matter to its reserve;
// grant no stock/energy and leave the paid construction heat in the world.
constexpr std::size_t row = 308 + 8; // One site, first life, format 7.
put(row + 64, juvenile.realized_per_thousand, 4);
for (std::size_t channel = 0; channel < 4; ++channel) {
put(row + 96 + channel * 8, body.matter[channel].value);
put(row + 136 + channel * 8, founder.reserve.matter[channel].value +
founder.body.matter[channel].value -
body.matter[channel].value);
}
std::uint64_t hash = 14695981039346656037ULL;
for (const auto byte : std::span{bytes}.first(bytes.size() - 8))
hash = (hash ^ byte) * 1099511628211ULL;
put(bytes.size() - 8, hash);
state = checked(CellularLives::restore(bytes, state->world(), state->region(), state->frame(),
state->tick()),
"controlled subadult guard fixture");
const auto held = state->lives().front();
auto active = restore(*state);
const auto active_tick =
checked(active->advance_tick_with_mutations(idle(*active), {}), "active subadult");
require(std::ranges::any_of(active_tick.growth,
[](const auto& value) { return value.life_id == 100; }),
"offline fixture could not otherwise grow");
for (unsigned tick = 0; tick <= cellular_linger_ticks; ++tick) {
checked(state->advance_tick(idle(*state, true)), "frozen subadult");
const auto& frozen = state->lives().front();
require(frozen.growth == held.growth && frozen.body == held.body &&
frozen.reserve == held.reserve && frozen.mutation == held.mutation,
"frozen subadult advanced biology");
}
require(state->lives().front().presence == CellularPresence::suspended,
"subadult did not suspend");
state = restore(*state);
const auto resumed =
checked(state->advance_tick_with_mutations(idle(*state), {}), "subadult resume");
require(state->lives().front().presence == CellularPresence::active &&
state->lives().front().growth == held.growth &&
std::ranges::none_of(resumed.growth,
[](const auto& value) { return value.life_id == 100; }),
"suspended resume constructed in its first tick");
const auto next =
checked(state->advance_tick_with_mutations(idle(*state), {}), "resumed growth");
require(
std::ranges::any_of(next.growth, [](const auto& value) { return value.life_id == 100; }),
"resumed active life failed to grow");
}
void obstructed_expansion() {
auto family = first_bud(false);
for (unsigned tick = 0; tick < 3000; ++tick)
checked(family.state->advance_tick(idle(*family.state)), "finite juvenile feeding");
auto state = upgraded(std::move(family.state));
state = relocated(*state, family.child, {2000, 2000});
for (unsigned tick = 0; tick < 200; ++tick) {
auto clear = restore(*state);
const auto before = *std::ranges::find(state->lives(), family.child,
[](const auto& life) { return life.identity.life; });
const auto genome =
checked(state->archive().find(before.identity.genome), "geometry genome");
const auto old_extent =
checked(biology::derive_phenotype(genome, before.growth, {293150, {}}), "old geometry")
.extent;
const auto trial =
checked(clear->advance_tick_with_mutations(idle(*clear, true), {}), "clear growth");
const auto grown =
std::ranges::find(trial.growth, family.child, &CellularGrowthExecution::life_id);
if (grown != trial.growth.end() &&
checked(biology::derive_phenotype(genome, grown->after, {293150, {}}),
"expanded geometry")
.extent > old_extent) {
for (const auto position : {biology::CellularPosition{48000 - old_extent, 2000},
biology::CellularPosition{1000 - old_extent, 1000}}) {
auto blocked = relocated(*state, family.child, position);
const auto executed =
checked(blocked->advance_tick_with_mutations(idle(*blocked, true), {}),
"obstructed growth");
const auto after =
std::ranges::find(blocked->lives(), family.child,
[](const auto& life) { return life.identity.life; });
const auto step = std::ranges::find(executed.step.lives, family.child,
&biology::CellularLifeStepResult::life_id);
require(after != blocked->lives().end() && after->growth == before.growth &&
after->body == before.body && after->position == position &&
step != executed.step.lives.end() &&
after->reserve == step->candidate.reserve_after &&
std::ranges::none_of(
executed.growth,
[&](const auto& value) { return value.life_id == family.child; }),
"blocked expansion spent, moved or grew");
require(restore(*blocked)->snapshot() == blocked->snapshot(),
"blocked restore differs");
}
return;
}
state = std::move(clear);
}
throw std::runtime_error("geometry fixture never exercised a funded extent increase");
}
void funded_generations() {
auto family = first_bud(true);
auto& state = family.state;
const auto opening_total = state->opening_total();
bool adult = false;
std::size_t growth_count = 0;
for (unsigned tick = 0; tick < 24'000; ++tick) {
auto intentions = idle(*state, true, tick % 100 == 99 ? family.child : 0);
// Separate the real bud from a possible twin using paid movement.
if (tick < 20)
for (auto& intent : intentions)
if (intent.life_id != family.child && intent.life_id != 100)
intent.intent.movement = {0, 1000};
const auto executed =
checked(state->advance_tick_with_mutations(intentions, {}), "funded family tick");
growth_count += executed.growth.size();
require(state->current_total() == opening_total, "family stock did not close");
for (const auto& growth : executed.growth)
require(growth.after.realized_per_thousand > growth.before.realized_per_thousand &&
growth.after.realized_per_thousand - growth.before.realized_per_thousand <=
5 &&
growth.after.damage_per_thousand == growth.before.damage_per_thousand,
"growth rate or damage changed");
for (const auto& growth : executed.growth) {
const auto step = std::ranges::find(executed.step.lives, growth.life_id,
&biology::CellularLifeStepResult::life_id);
const auto life =
std::ranges::find(state->lives(), growth.life_id,
[](const auto& value) { return value.identity.life; });
require(step != executed.step.lives.end() && life != state->lives().end(),
"growth report identity");
require(life->reserve.energy.value + growth.intake.energy.value ==
step->candidate.reserve_after.energy.value,
"growth energy did not spend reserve");
for (std::size_t channel = 0; channel < 4; ++channel)
require(life->reserve.matter[channel].value + growth.intake.matter[channel].value ==
step->candidate.reserve_after.matter[channel].value +
growth.release.matter[channel].value,
"growth reserve channel did not close");
}
for (const auto& life : state->lives()) {
if (life.identity.life == family.child)
adult |= life.growth.realized_per_thousand == 1000;
if (life.identity.life == 100)
require(life.growth == biology::GrowthState{1000, 0}, "offline founder changed");
}
if (tick % 317 == 0)
state = restore(*state);
for (const auto& bud : executed.buds) {
if (bud.parent_life != family.child || bud.result != CellularBudResult::budded)
continue;
require(adult && growth_count > 0, "offspring reproduced without funded adulthood");
std::cout << "funded juvenile reached adulthood and budded at tick " << state->tick()
<< ", growth steps " << growth_count << '\n';
return;
}
}
throw std::runtime_error("funded juvenile never reproduced");
}
void legacy_and_population_replay() {
auto family = first_bud(false);
auto legacy = restore(*family.state);
const auto initial = std::ranges::find(legacy->lives(), family.child, [](const auto& life) {
return life.identity.life;
})->growth;
for (unsigned tick = 0; tick < 400; ++tick) {
const auto executed = checked(legacy->advance_tick_with_mutations(idle(*legacy, true), {}),
"legacy no growth");
require(executed.growth.empty(), "rules 8 gained growth");
}
require(std::ranges::find(
legacy->lives(), family.child,
[](const auto& life) {
return life.identity.life;
})->growth == initial,
"rules 8 juvenile changed growth");
auto boundary = checked(family.state->migration_upgrade_candidate(), "population boundary");
auto population = checked(CellularPopulation::create(std::move(boundary)), "population create");
const auto genome = population->state().lives().front().identity.genome;
checked(population->collapse(genome), "juvenile collapse");
const auto tags = std::vector<CellularCohortMember>{population->members().begin(),
population->members().end()};
const auto sequence = population->conversion_sequence();
population = checked(population->maturation_upgrade_candidate(), "population growth upgrade");
require(std::ranges::equal(population->members(), tags) &&
population->conversion_sequence() == sequence,
"upgrade lost cohort tags");
auto raw = restore(population->state());
bool grew = false;
for (unsigned tick = 0; tick < 1024; ++tick) {
auto all = checked(wildlife_intents(*raw, raw->tick() + 1), "raw wildlife intentions");
std::vector<CellularLifeIntent> controlled;
for (const auto& life : raw->lives())
if (life.account != LifeAccount{}) {
CellularLifeIntent frozen{life.identity.life, {}};
frozen.intent.frozen = true;
controlled.push_back(frozen);
all.push_back(frozen);
}
std::ranges::sort(all, {}, &CellularLifeIntent::life_id);
auto before = restore(*raw);
const auto executed = checked(raw->advance_tick_with_mutations(all, {}), "raw maturation");
grew |= !executed.growth.empty();
checked(population->advance_tick(controlled), "cohort maturation");
require(raw->snapshot() == population->state().snapshot(), "cohort changed growth biology");
CellularBatch batch;
batch.header = {raw->world(), raw->region(), raw->frame(), {},
{}, before->tick(), raw->tick()};
batch.header.predecessor[0] = 1;
batch.header.predecessor_digest[0] = 2;
batch.ticks.push_back({all, {}, {}});
const auto bytes = checked(encode_cellular_batch(batch), "growth trace encode");
const auto decoded = checked(decode_cellular_batch(bytes), "growth trace decode");
require(
checked(replay_cellular_batch(*before, decoded), "growth trace replay")->snapshot() ==
raw->snapshot(),
"recorded growth replay differs");
if (tick % 127 == 0) {
population =
checked(CellularPopulation::restore(population->snapshot(), raw->world(),
raw->region(), raw->frame(), raw->tick()),
"growing cohort restore");
raw = restore(*raw);
}
if (tick == 256) {
const auto biology = population->state().snapshot();
checked(population->materialize(genome), "growing materialization");
checked(population->collapse(genome), "growing recollapse");
require(population->state().snapshot() == biology, "conversion reset growth");
}
}
require(grew, "raw/cohort comparison never exercised growth");
require(population_interval_safe(*raw), "suspended controlled owner refused rules 9 interval");
CellularBatchHeader header{raw->world(), raw->region(), raw->frame(), {},
{}, raw->tick(), raw->tick() + 64};
header.predecessor[0] = 1;
header.predecessor_digest[0] = 2;
auto inputs = checked(unattended_population_inputs(*raw, header), "growth interval inputs");
auto execution =
checked(prepare_population_batch(*population, std::move(inputs)), "growth interval");
auto batch = checked(decode_population_batch(checked(encode_population_batch(execution.batch),
"population trace encode")),
"population trace decode");
require(checked(replay_population_batch(*population, batch), "population interval replay")
->snapshot() == execution.state->snapshot(),
"population interval growth replay differs");
}
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(), "maturation checkpoint write");
}
void continue_population(CellularPopulation& population) {
bool grew = false;
for (unsigned tick = 0; tick < 64; ++tick) {
std::vector<CellularLifeIntent> controlled;
for (const auto& life : population.state().lives())
if (life.account != LifeAccount{}) {
CellularLifeIntent input{life.identity.life, {}};
input.intent.frozen = true;
controlled.push_back(input);
}
const auto executed = checked(population.advance_tick(controlled), "restart continuation");
grew |= !executed.growth.empty();
}
require(grew, "restart continuation never grew");
}
void checkpoint(const char* path, const char* expected) {
auto family = first_bud(false);
for (unsigned tick = 0; tick < 400; ++tick)
checked(family.state->advance_tick(idle(*family.state, true)), "restart suspension");
auto population = checked(CellularPopulation::create(upgraded(std::move(family.state))),
"restart population");
checked(population->collapse(population->state().lives().front().identity.genome),
"restart cohort");
save(path, population->snapshot());
continue_population(*population);
save(expected, population->snapshot());
}
void resume(const char* path, const char* output) {
std::ifstream file(path, std::ios::binary);
require(file.good(), "restart checkpoint read");
const std::vector<std::uint8_t> bytes{std::istreambuf_iterator<char>{file}, {}};
require(bytes.size() >= cellular_population_header_bytes + 8, "restart checkpoint length");
// Test-only trusted fixture context; production recovery binds a manifest.
std::uint64_t tick = 0;
for (unsigned shift = 0; shift < 8; ++shift)
tick |= std::uint64_t{bytes[56 + shift]} << (shift * 8U);
auto population =
checked(CellularPopulation::restore(bytes, 207, 1, 1, tick), "fresh-process restore");
continue_population(*population);
save(output, population->snapshot());
}
} // namespace
int main(int argc, char** argv) try {
if (argc == 4 && std::string_view{argv[1]} == "--checkpoint") {
checkpoint(argv[2], argv[3]);
return 0;
}
if (argc == 4 && std::string_view{argv[1]} == "--resume") {
resume(argv[2], argv[3]);
return 0;
}
require(argc == 1, "unknown maturation test arguments");
construction_and_saved_choices();
frozen_construction();
obstructed_expansion();
funded_generations();
legacy_and_population_replay();
return 0;
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
+19
View File
@@ -179,6 +179,25 @@ void manifests() {
raw_mislabeled.payload_bytes = future->state().snapshot().size();
require(!restore_cellular_payload(future->state().snapshot(), raw_mislabeled),
"portable owner 7 bypassed raw durable bundle admission");
// ADR-0157: portable maturation must not acquire durable rules-8 authority.
auto maturation = checked(future->maturation_upgrade_candidate(), "portable maturation");
auto rules8_population = next;
rules8_population.cellular_versions = cellular_v10_versions;
rules8_population.payload_bytes = future->snapshot().size();
require(restore_population_payload(future->snapshot(), rules8_population).has_value() &&
!restore_population_payload(maturation->snapshot(), rules8_population),
"rules 9 bypassed durable population admission");
auto rules8_raw = source;
rules8_raw.cellular_versions = cellular_v10_versions;
rules8_raw.payload_bytes = future->state().snapshot().size();
require(restore_cellular_payload(future->state().snapshot(), rules8_raw).has_value() &&
!restore_cellular_payload(maturation->state().snapshot(), rules8_raw),
"rules 9 bypassed durable raw admission");
auto unsupported_rules = rules8_population;
unsupported_rules.cellular_versions.rules = cellular_lives_maturation_rules;
require(!supported(unsupported_rules) && !encode_manifest(unsupported_rules) &&
population_envelope_version(unsupported_rules.cellular_versions) == 0,
"portable rules 9 silently entered a durable bundle");
auto back = checked(population_profile_transition_manifest(
next, filled<32>(11), filled<16>(12), lease, source.build,
state->snapshot().size(), filled<32>(13)),