feat(ecology): own cells and their local environment together
Foundation / checks (ecs) (push) Successful in 2m28s
Foundation / checks (deploy) (push) Successful in 4m59s
Foundation / checks (network) (push) Successful in 20m56s
Foundation / checks (client) (push) Successful in 22m1s
Foundation / checks (tsan) (push) Successful in 45m41s
Foundation / checks (postgres) (push) Successful in 1h13m35s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (checks) (push) Canceled after 1h20m34s

ADR-0172 records the maintainer's M12.5 ownership decision: one owner per
patch of space for cells and their local environment, reserves belonging
to the biological individual, and an open planet boundary whose every
crossing is a recorded import or export.

The portable CellularEnvironment owner (envelope AEVOCEN1) holds an exact
population with tagged water and dissolved compartments, refuses declared
atmosphere, imports infall from finite per-source entitlements (ADR-0136
step B) and radiates retained heat. Each tick's exchange is a validated
swap on the nested owner, undone if the biological tick refuses. Closed
and source-off regions keep their biology byte for byte; raw and cohort
representations agree under infall. No existing format, trace, golden,
default opening or live version changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-19 16:05:17 -04:00
co-authored by Claude Opus 5.5
parent a898a35e1b
commit 4c70257883
17 changed files with 1335 additions and 6 deletions
+13 -2
View File
@@ -94,9 +94,10 @@ add_library(evo_lifecycle STATIC src/server/lifecycle/primitive_lives.cpp
src/server/lifecycle/cellular_batch.cpp src/server/lifecycle/wildlife_controller.cpp
src/server/lifecycle/cellular_play_summary.cpp src/server/lifecycle/cellular_population.cpp
src/server/lifecycle/cellular_population_codec.cpp src/server/lifecycle/cellular_population_policy.cpp
src/server/lifecycle/cellular_schedule.cpp src/server/lifecycle/cellular_population_batch.cpp)
src/server/lifecycle/cellular_schedule.cpp src/server/lifecycle/cellular_population_batch.cpp
src/server/lifecycle/cellular_environment.cpp)
add_library(evo::lifecycle ALIAS evo_lifecycle)
target_link_libraries(evo_lifecycle PUBLIC evo::biology)
target_link_libraries(evo_lifecycle PUBLIC evo::biology evo::world)
evo_owned_target(evo_lifecycle)
add_library(evo_ecology STATIC src/ecology/cohort.cpp src/ecology/collapse.cpp src/ecology/population.cpp src/ecology/materialize.cpp)
@@ -705,6 +706,16 @@ if(BUILD_TESTING)
-P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake")
set_tests_properties(cellular-retained-plan-population cellular-retained-plan-population-restart
PROPERTIES TIMEOUT ${evo_cohort_timeout})
add_executable(evo-cellular-environment-tests tests/cellular_environment_tests.cpp)
target_link_libraries(evo-cellular-environment-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-cellular-environment-tests)
add_test(NAME cellular-environment-contracts COMMAND evo-cellular-environment-tests)
add_test(NAME cellular-environment-restart COMMAND "${CMAKE_COMMAND}"
"-DPOPULATION_TEST=$<TARGET_FILE:evo-cellular-environment-tests>"
"-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/environment-restart"
-P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake")
set_tests_properties(cellular-environment-contracts cellular-environment-restart
PROPERTIES TIMEOUT ${evo_cohort_timeout})
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)
@@ -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-20261019T191902-e356d1d1:1792451942"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261019T195802-5aa0ff3e:1792454282"}
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
ports:
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
+6
View File
@@ -647,6 +647,12 @@ the later multicellular idea are not ratified game rules.
## M12 - Persistent ecology
2026-10-19: [ADR-0172](adr/0172-cellular-environment-ownership.md) accepts one
owner per patch of space for cells and their local environment, individual
reserves and an open planet boundary. The portable joint owner adds finite infall
entitlements and radiative export with exact closure; producers, durable admission
and integration remain open.
2026-10-19 gameplay clarification:
[ADR-0163](adr/0163-structural-inheritance-and-offspring-succession.md) accepts
offspring-only structural expression, permanent birth-time parent/child control
+16
View File
@@ -1,5 +1,21 @@
# Project status and next steps
## Cellular environment ownership (M12.5a-b) - 2026-10-19
The maintainer accepted one owner per patch of space for cells and their local
environment, individual reserves (colony/multicellular sharing later) and an open
planet boundary. [ADR-0172](adr/0172-cellular-environment-ownership.md) records
that contract and adds the portable `CellularEnvironment` owner (envelope
`AEVOCEN1`): tagged water/dissolved compartments, refused atmosphere, finite infall
entitlements (ADR-0136 step B) and radiative heat export, applied with each joint
tick or not at all. Closed and source-off regions keep their biology byte for byte.
Raw and cohort representations agree under infall. Old formats and goldens keep
their meaning; no default/live version changes.
Both full Release suites pass **94/94**; see [Validation](engineering/VALIDATION.md).
Producers (ADR-0136 step C), durable admission (12.5c), worker/census/migration
integration (12.5d) and target-host qualification (12.5e) remain open.
## Portable retained-plan exact populations - 2026-10-19
[ADR-0171](adr/0171-retained-plan-exact-populations.md) adds envelope/batch 3 for
@@ -0,0 +1,124 @@
# ADR-0172: Cellular environment ownership and open-boundary contract
## Status and scope
Accepted 2026-10-19. The maintainer accepted the single-owner direction of the
[ownership resolution](../engineering/M12_ENVIRONMENT_OWNERSHIP_RESOLUTION.md) and
clarified its scope. This ADR is M12.5a: the contract that the portable composite
owner (12.5b) implements. It extends ADR-0136 step B, ADR-0144 and ADR-0157/0165.
No default/live version, durable profile, SQL schema, photosynthesis, atmosphere
or M6 fixture change. ADR-0136 step C remains proposed design input.
## Maintainer clarification
- **One owner per patch of space, at any moment.** It is not one global owner.
A world is many regions, each with exactly one owner of its cells *and* their
local environment. Stock changes owner only through recorded, paired transfers
(ADR-0147–0149 escrow). This carries forward unchanged to the multicellular 3D
world (M13.8/M14): more and larger owners, never two ledgers for one stock.
- **Reserves belong to the biological individual.** A single cell owns its body
and reserve. A colony or multicellular body sharing resources internally is a
later, separately versioned rule (ADR-0135 colonies, M14.2). Nothing here pools
reserves between organisms or forecloses that rule.
- **The planet is an open system.** Resources may enter or leave the region, and
later the planet as a whole. Every crossing is an explicit, versioned process
recorded as a cumulative import or export. Nothing is minted or deleted silently:
`current = opening + imports − exports`, per channel. Exported stock is gone; it
returns only as a new recorded import.
## Decision
`CellularEnvironment` (envelope `AEVOCEN1`, format 1, environment rules 1) takes
exclusive ownership of one exact `CellularPopulation` (raw or cohort; nested owner
7 with rules 8 or 9, or owner 8 with rules 10) and of that region's tagged
environmental compartments. Neither the nested owner nor any copy is separately
spendable while the composite exists. It exposes read-only views only.
### Geometry
One declared axis-aligned habitat inside one environmental voxel: voxel address,
micrometre origin and a box whose width and height equal the cellular area and
whose effective depth is positive (`world::measure_habitat`). Depth defines a
sampling volume for concentration views only; it never creates or scales stock.
Organism count and camera size never determine depth or supply.
### Compartment map, version 1
| Compartment | Owner | Edible | v1 processes |
|---|---|---|---|
| Organic energy, C, N, P, other in deposits, lives, corpses, nursery | nested cellular owner | yes (existing contact feeding) | existing biology; infall import |
| Heat (energy) | nested cellular owner | no | radiative export |
| Water | composite | no | none: conserved, audited, never converted |
| Dissolved inorganic N, P | composite | no | none: conserved, audited, never converted |
| Atmospheric species | unsupported | — | declaring any is refused (`unsupported`), never zero or unlimited |
| Incident light | not stock | — | not represented until a producer process exists |
Cellular `other` means organic other only. `accounting::Inventory` has no water,
dissolved or gas channel, so no generic retag can turn water into food, dissolved
nutrients into edible matter or heat into usable energy. A conversion between
compartments requires a separately versioned process with debit, credit, work,
waste and residual terms. Rules 1 define none.
### Processes, rules 1 (all coefficients are trial values)
1. **Infall import (ADR-0136 step B).** At most four sources, sorted unique
nonzero ids, with disjoint rectangles inside the habitat, a half-open active
tick interval and a finite per-channel **entitlement**. On each advancing tick
`t` in its interval a source fires when a SplitMix64 roll of
`(world, region, source, t)` is divisible by its mean interval (trial 2,400
ticks, two simulated minutes). An event drops `min..max` (trial 12–24) single-
channel bubbles within a 500 µm disc at a seeded centre in the source rectangle,
cycling the channels its per-bubble amount stocks. Each bubble credits
`min(per-bubble amount, remaining entitlement)`. A zero credit, an occupied
address or the 4,096-deposit limit skips that bubble; skips are counted, never
deferred. Credits enter the nested boundary `incoming` and the source's
cumulative `imported`; remaining entitlement is derived, never stored twice.
Exhausted or inactive sources import nothing. Restart, retry and representation
change cannot reset entitlement, because `imported` is persisted.
2. **Radiative heat export.** Each advancing tick exports `min(heat, cap)` pJ of
retained heat (cap per tick is configuration; zero closes the boundary). The
amount enters the nested boundary `outgoing` and the composite's cumulative
export. Heat is never spendable before or after export.
Infall happens only on advancing ticks, so a region that does not tick (offline,
ADR-0128) imports nothing. There is no catch-up credit.
### Tick and atomicity
For advancing tick `t`: derive the exchange from the committed state; apply it to
the nested owner as a validated swap (new habitat, heat and boundary ledger, with
`current = opening + incoming − outgoing` rechecked); then run the unchanged
population tick (shared wildlife controller, controlled intentions, selections).
If the biological tick refuses, the exchange is swapped back and the composite is
byte-for-byte unchanged. Environment progress commits only with the tick. There is
no independently acknowledged environmental or cellular prefix.
### Envelope and versions
The envelope stores identity, completed tick, geometry, compartments, radiation
cap and cumulative export, every source with its cumulative import and event/skip
counters, and the complete nested population envelope, with an FNV-1a64 checksum
and byte-identical re-encoding. A nested owner restored alone must not publish a
joint result. Old cellular formats 6/7/8, rules 8/9/10, population envelopes 1–3,
traces and durable bundles 9–11 keep their exact meaning; none gains fields. The
composite admits only nested owners with a boundary ledger (format 7 or 8).
The nested boundary ledger also carries migration flows (ADR-0144). The composite's
own cumulative import and export distinguish environmental crossings from migration.
## Consequences
The open boundary is auditable: replay re-derives every infall from configuration,
tick and seed, and restore continues from persisted cumulative entitlement. Source-
off, exhausted and open worlds become directly comparable. Producers (photosynthesis)
still require ADR-0136 step C's genome capability, coefficients and a capture
process debiting a declared light entitlement; until then 12.5 is not complete.
Durable publication (12.5c), worker/census/migration integration (12.5d) and target-
host qualification (12.5e) remain separate segments.
## Alternatives
A copied environmental view, reuse of the M6 two-actor fixture, two independently
committed checkpoints and a generic inventory setter remain rejected (see the
resolution). A single global owner was rejected by the maintainer's clarification:
regions scale by count, not by one shared ledger.
+2
View File
@@ -1,5 +1,7 @@
# Architecture decision records
- [ADR-0172: Cellular environment ownership](0172-cellular-environment-ownership.md) - one owner per patch of space for cells and their local environment; reserves stay individual; open planet boundary with recorded imports/exports; portable envelope `AEVOCEN1` with finite infall entitlements and radiative heat export.
- [ADR-0171: Retained-plan exact populations](0171-retained-plan-exact-populations.md) - portable envelope/batch 3 preserve every member's expressed/heritable state, exact conversion/policy replay and projection-2 plan counts; durable admission remains separate.
- [ADR-0170: Explicit DEV worker placement](0170-dev-worker-placement.md) - required control-plane/master exclusion for DEV workloads in full and standalone overlays, with rendered-policy regression checks; no live-placement claim.
+1 -1
View File
@@ -12,7 +12,7 @@ Commit and push each validated scoped segment separately.
| 12.2 | Exact local model selected and paired qualification implemented (12.2d); production cost gate open | ADR-0139, exact canonical equality across 196,608 paired ticks per platform. Regional approximation disabled; no compression claim. Deployment-host capacity and fuller interaction coverage remain open. |
| 12.3 | Exact population profile/trace/store and opt-in host integration implemented (12.3b) | ADR-0142, schema 44; exact publication/recovery, mutation race guards, ambiguous replies and process kills. Executable/network population fault drills and target-host qualification remain open. |
| 12.4 | Owned intervals and durable paired migration/fault qualification implemented in scoped segments through 12.4l | ADR-0143–0149/schema 49; bounded admitted work, source freeze, staged ghost, atomic pair and exact recovery, local TLS and storage faults. Multi-host/orchestrator, linked ecology and integrated stock audits remain open. |
| 12.5 | Blocked on 12.2-12.4 | Finite M6 process fixtures do not qualify coupled persistent cellular/cohort atmosphere/water budgets. |
| 12.5 | Ownership accepted; portable joint owner implemented (12.5a-b) | ADR-0172: one owner per patch, tagged water/dissolved compartments, finite infall entitlements and radiative export with exact raw/cohort, refusal and restart evidence. Producers (ADR-0136 step C), durable profile, worker integration and target-host qualification remain open. |
| 12.6 | Regional queries, replayed history, scoped multi-region queries and consistent database head snapshots implemented (12.6a-d) | ADR-0150–0153; short read-only snapshot capture prevents atomic pairs from straddling declared head sets, with exact immutable replay. Durable world/branch coverage, outside transfer/viability reconciliation, target-host query/index costs and client path remain required. |
| 12.7 | Evidence policy, registered coverage, history domains and verified pending handoff evidence implemented (12.7a-c) | ADR-0154–0156/schema 52 captures namespace/registry/heads/pending handoffs together, with exact capsule/ghost replay and supported restore forks. Cross-domain clone provenance, other viable-store coverage and durable accepted global reconciliation/freshness remain required. |
| 12.8 | Bounded unscripted generation evidence; actual-days gate not qualified | ADR-0162 measures four real wildlife generations with exact raw/cohort recovery, predation and twins. Actual multi-day integrated ecology/restart/clone evidence remains required. |
@@ -4,6 +4,15 @@
implementation boundary; it does not declare a new biological rule, accepted
producer chemistry, working adapter or completed gate.
**Decision (2026-10-19):** the maintainer accepted the single-owner direction with
three clarifications recorded in [ADR-0172](../adr/0172-cellular-environment-ownership.md):
one owner per patch of space at any moment (many regions, paired transfers between
them, unchanged for the later multicellular 3D world); reserves belong to the
biological individual, with colony/multicellular sharing a later versioned rule;
and the planet is an open system whose every crossing is a recorded import or
export. ADR-0172 is the 12.5a contract and implements the portable 12.5b owner
with finite infall entitlements and radiative heat export. Producers remain open.
## Concrete conflict
`CellularLives` exclusively owns its finite habitat, nursery, living bodies and
+4 -2
View File
@@ -66,7 +66,7 @@ or authorize production enablement.
| 12.2 | Exact cellular model and paired matrix; local samples through 256 lives; bounded four-generation rules-9 predation/twin matrix | Deployment-host tail costs including publication; larger wildlife cohorts and fuller contention coverage; useful compression remains unimplemented. |
| 12.3 | Dedicated population profile/trace/store/owning host; exact recovery and private PostgreSQL fault tests | Population-specific executable/network fault drills and target-host publication/capacity qualification. |
| 12.4 | Owned intervals; exact transfer/accounting; durable atomic pair/recovery; independent loopback TLS path loss and owner expiry/replacement/heal; local object sync/read-failure matrix | Multi-host/kernel-network, storage-host and orchestrator drills, linked-boundary contracts and integrated ownership/stock audits at scale. |
| 12.5 | Finite cellular contact feeding/decay and separate M6 producer/consumer resource owner | One jointly owned cellular/environment budget, explicit effective depth and source entitlements, versioned water/atmosphere species mapping and producer coefficients, plus closed/open and nutrient-exhaustion comparisons. |
| 12.5 | ADR-0172 portable joint owner: one budget for cells and local environment, effective depth, tagged water/dissolved compartments, refused atmosphere, finite infall entitlements, radiative export; closed/source-off/open/exhaustion and raw/cohort comparisons | Producer process and coefficients (ADR-0136 step C), durable profile/trace/recovery (12.5c), worker/census/migration integration and escrowed cross-worker sources (12.5d), target-host qualification (12.5e). |
| 12.6 | Retained archive, regional census/lineage queries, replayed history, scoped multi-region queries and consistent database head snapshots (12.6a-d); registered coverage/history domains follow in 12.7a-b | Cross-domain clone provenance, retained historical coverage/other viable stores, target-host query/index qualification and client permission/presentation; no account power or invented precise statistical ancestry. |
| 12.7 | Viability/unknown policy; consistent cuts, registered coverage, history domains/restore forks and verified pending handoff evidence (12.7a-c/schema 52) | Cross-domain clone provenance, other viable-store coverage and durable accepted global evidence records/freshness. Missing/stale/unsupported owners must prevent terminal extinction. |
| 12.8 | Deterministic seed/regime drivers, separate-process exact continuation and bounded unscripted generations | Reproducible integrated worlds running for actual days, real restarts/clone comparisons and retained accounting/diversity/cost audits. Accelerated tests cannot supply elapsed days. |
@@ -82,7 +82,9 @@ and photosynthesis steps B/C do not silently become accepted M12 mechanics.
The [ownership resolution proposal](M12_ENVIRONMENT_OWNERSHIP_RESOLUTION.md)
records the actual public-API conflict, a composite-owner/checkpoint direction,
typed compartment and source requirements, worked balances and delivery segments.
It is a concrete design for review, not an implemented adapter or completed 12.5.
The maintainer accepted it on 2026-10-19; [ADR-0172](../adr/0172-cellular-environment-ownership.md)
records the clarified scope and implements the portable joint owner. It is not a
durable profile, live upgrade, producer ecology or completed 12.5.
The engineering constitution requires stopping expansion at this architectural
boundary and documenting the resolution. That does not prevent the independent
+39
View File
@@ -1,5 +1,44 @@
# Validation report
## 2026-10-19 - Cellular environment joint owner (M12.5a-b)
[ADR-0172](../adr/0172-cellular-environment-ownership.md) records the maintainer's
ownership decision and adds envelope `AEVOCEN1`. The joint owner applies each
tick's infall import and radiative heat export to the nested cellular owner as one
validated swap, then runs the unchanged population tick; a refused tick swaps the
exchange back. The only nested change is a private exchange/savepoint pair; no
existing envelope, trace, golden or rule changes meaning.
Executed locally:
- GCC 14.2 Release full CTest **94/94, 8.83 s** and MSVC 19.44 Release full CTest
**94/94, 15.16 s**, with NDEBUG. After trimming test tick counts only, the two
environment tests pass **2/2** on both (2.48 s GCC, 3.23 s MSVC).
- Clang 19.1 ASan/UBSan cellular subset **28/28, 200.52 s**, then the trimmed
environment tests **2/2, 66.03 s**, with no sanitizer reports.
- clang-tidy 19 (warnings as errors) on the new owner/tests and the changed
cellular owner/population sources; clang-format 19 on every touched file.
- Fresh-process continuation of a two-source, radiating region (400 + 400 ticks):
MSVC and GCC checkpoint and resumed outputs are byte-identical, SHA-256
`1746dd489226d612d46624c36987fba83f711c54dfe3f03f3e0bb0be65ea7379`.
Evidence in the suite: closed and source-off regions keep population bytes
identical to a plain population every tick; a finite entitlement of ten bubbles
per channel is consumed exactly (20 credited, later events counted exhausted and
skipped, nothing more imported); radiated heat (75,000 pJ over 1,500 ticks at a
50 pJ cap) leaves lives, corpses and habitat identical to the closed run; real
wildlife collapsed into an exact cohort matches the individual run through 121
infall events; a refused tick on an import tick leaves the envelope unchanged and
the retried tick imports. Restore refuses corruption, wrong identity, future
format, import above entitlement, a changed nested length, declared atmosphere,
zero depth, a box unequal to the cellular area or outside its voxel, overlapping
or unsorted sources, stockless or out-of-habitat sources and an owner without a
boundary ledger. Every tick audits `current = opening + incoming - outgoing` and
that environmental flows equal the nested ledger.
No producer, durable profile, SQL schema, worker integration, target-host cost,
default opening or live upgrade. No World0 operation.
## 2026-10-19 - Portable retained-plan exact populations
[ADR-0171](../adr/0171-retained-plan-exact-populations.md) adds explicit envelope
@@ -0,0 +1,141 @@
#pragma once
#include "evo/server/lifecycle/cellular_population.hpp"
#include "evo/world/coordinates.hpp"
#include "evo/world/environment_units.hpp"
#include <array>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <span>
#include <vector>
namespace evo::server {
// ADR-0172: one owner of a region's cells and their local environment.
inline constexpr std::uint32_t cellular_environment_format = 1;
inline constexpr std::uint32_t cellular_environment_rules = 1;
inline constexpr std::size_t max_cellular_infall_sources = 4;
// Trial values (ADR-0136 step B): two simulated minutes between events on average,
// 12-24 bubbles per event, dropped within a 1 mm disc.
inline constexpr std::uint64_t cellular_infall_trial_interval_ticks = 2'400;
inline constexpr std::uint32_t cellular_infall_trial_bubbles_min = 12;
inline constexpr std::uint32_t cellular_infall_trial_bubbles_max = 24;
inline constexpr std::uint32_t cellular_infall_clump_radius_um = 500;
inline constexpr std::uint32_t max_cellular_infall_bubbles = 64;
inline constexpr std::size_t cellular_environment_header_bytes = 176;
inline constexpr std::size_t cellular_infall_source_bytes = 208;
inline constexpr std::size_t max_cellular_environment_bytes =
cellular_environment_header_bytes + cellular_infall_source_bytes * max_cellular_infall_sources +
max_cellular_population_bytes + 8;
// One axis-aligned habitat inside one environmental voxel. Its width and height
// equal the cellular area; depth only defines a sampling volume, never stock.
struct CellularEnvironmentGeometry {
world::VoxelAddress voxel{};
world::HabitatBox box{};
};
// Tagged, inedible compartments. No rules-1 process converts them.
struct CellularWaterColumn {
accounting::Femtograms water{}, dissolved_nitrogen{}, dissolved_phosphorus{};
auto operator<=>(const CellularWaterColumn&) const = default;
};
// An audited external import over a declared rectangle and half-open tick interval.
// The entitlement is finite; what remains is entitlement minus imported.
struct CellularInfallSource {
std::uint64_t id{};
std::uint32_t x_um{}, y_um{}, width_um{}, height_um{};
std::uint64_t start_tick{}, end_tick{};
std::uint64_t mean_interval_ticks{cellular_infall_trial_interval_ticks};
std::uint32_t bubbles_min{cellular_infall_trial_bubbles_min};
std::uint32_t bubbles_max{cellular_infall_trial_bubbles_max};
accounting::Inventory per_bubble{}; // Single-channel bubbles cycle stocked channels.
accounting::Inventory entitlement{}; // Cumulative import limit, per channel.
auto operator<=>(const CellularInfallSource&) const = default;
};
struct CellularInfallProgress {
accounting::Inventory imported{};
std::uint64_t events{}, credited_bubbles{}, skipped_bubbles{}, exhausted_events{};
auto operator<=>(const CellularInfallProgress&) const = default;
};
struct CellularEnvironmentConfig {
CellularEnvironmentGeometry geometry{};
CellularWaterColumn water{};
std::vector<CellularInfallSource> sources; // Sorted unique ids, disjoint rectangles.
accounting::Picojoules radiation_cap{}; // Heat exported per tick; zero is closed.
std::uint32_t atmosphere_species{}; // Any declared species is unsupported.
};
struct CellularEnvironmentTickReport {
std::uint64_t tick{};
accounting::Inventory imported{};
accounting::Picojoules exported{};
std::uint64_t events{}, credited_bubbles{}, skipped_bubbles{};
CellularTickExecution biology;
};
enum class CellularEnvironmentError : std::uint8_t {
unsupported,
invalid_geometry,
invalid_source,
identity,
habitat,
biology,
overflow,
conservation,
format,
checksum
};
class CellularEnvironment {
public:
// Consumes the population on success or failure.
[[nodiscard]] static std::expected<std::unique_ptr<CellularEnvironment>,
CellularEnvironmentError>
create(std::unique_ptr<CellularPopulation> population, CellularEnvironmentConfig config);
CellularEnvironment(const CellularEnvironment&) = delete;
CellularEnvironment& operator=(const CellularEnvironment&) = delete;
~CellularEnvironment();
// Read-only views; they confer no separate spending rights.
[[nodiscard]] const CellularPopulation& population() const noexcept;
[[nodiscard]] const CellularLives& state() const noexcept;
[[nodiscard]] const CellularEnvironmentGeometry& geometry() const noexcept;
[[nodiscard]] world::HabitatMeasure measure() const noexcept;
[[nodiscard]] const CellularWaterColumn& water() const noexcept;
[[nodiscard]] std::span<const CellularInfallSource> sources() const noexcept;
[[nodiscard]] std::span<const CellularInfallProgress> infall() const noexcept;
[[nodiscard]] accounting::Picojoules radiation_cap() const noexcept;
[[nodiscard]] accounting::Inventory imported() const noexcept; // All sources, cumulative.
[[nodiscard]] accounting::Picojoules exported() const noexcept;
[[nodiscard]] std::uint64_t tick() const noexcept;
// One joint 50 ms tick: the environmental exchange, then the unchanged population
// tick. Any refusal leaves the whole owner byte-for-byte unchanged.
[[nodiscard]] std::expected<CellularEnvironmentTickReport, CellularEnvironmentError>
advance_tick(std::span<const CellularLifeIntent> controlled,
std::span<const CellularMutationSelection> selections = {});
// Explicit representation changes of the nested population; no tick advances.
[[nodiscard]] std::expected<std::size_t, CellularEnvironmentError>
collapse(std::uint64_t genome);
[[nodiscard]] std::expected<std::size_t, CellularEnvironmentError>
materialize(std::uint64_t genome);
[[nodiscard]] std::vector<std::uint8_t> snapshot() const;
[[nodiscard]] static std::expected<std::unique_ptr<CellularEnvironment>,
CellularEnvironmentError>
restore(std::span<const std::uint8_t> bytes, std::uint64_t world, std::uint64_t region,
std::uint64_t frame, std::uint64_t tick);
private:
struct Exchange;
CellularEnvironment(std::unique_ptr<CellularPopulation> population,
CellularEnvironmentConfig config);
[[nodiscard]] std::expected<Exchange, CellularEnvironmentError>
plan_exchange(std::uint64_t tick) const;
std::unique_ptr<CellularPopulation> population_;
CellularEnvironmentConfig config_;
std::vector<CellularInfallProgress> progress_; // Source order.
accounting::Picojoules exported_{};
};
} // namespace evo::server
@@ -139,6 +139,7 @@ struct CellularOffspringRevision {
return life.offspring_genome == 0 ? life.identity.genome : life.offspring_genome;
}
class CellularMigration;
class CellularEnvironment;
struct CellularLifeIntent {
std::uint64_t life_id{};
biology::CellularStepIntent intent{};
@@ -325,6 +326,19 @@ class CellularLives {
private:
friend class CellularMigration;
friend class CellularEnvironment;
// ADR-0172: the exchanged-out values, so a refused joint tick can swap them back.
struct BoundarySavepoint {
std::unique_ptr<biology::CellularHabitat> habitat; // Null when no deposit changed.
accounting::Inventory heat{}, current_total{};
CellularBoundaryLedger boundary{};
};
// Validated no-tick exchange: imports the new deposits (ids assigned here) and exports
// retained heat, both through the boundary ledger. Refusal changes nothing.
[[nodiscard]] std::expected<BoundarySavepoint, CellularLivesError>
exchange_boundary(std::span<const biology::CellularPatch> deposits,
accounting::Picojoules heat_export);
void restore_boundary(BoundarySavepoint savepoint) noexcept;
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migration_replacement(std::vector<CellularOwnedLife>, const biology::LineageArchive&,
CellularBoundaryLedger) const;
@@ -85,6 +85,7 @@ class CellularPopulation {
private:
friend class CellularMigration;
friend class CellularEnvironment; // ADR-0172: exclusive joint owner of this population.
friend std::expected<std::unique_ptr<CellularPopulation>, CellularPopulationError>
execute_population_batch(const CellularPopulation&, CellularPopulationBatch&, bool);
explicit CellularPopulation(std::unique_ptr<CellularLives> state, CellularTierPolicy policy);
+46
View File
@@ -0,0 +1,46 @@
# Cellular environment envelope 1
Authority: ADR-0172. Little-endian integers, no padding. Size is bounded by
`max_cellular_environment_bytes`. No existing cellular, population, trace or durable
bundle format changes.
| Offset | Bytes | Field |
|---:|---:|---|
| 0 | 8 | Magic `AEVOCEN1` |
| 8 | 4 | Format 1 |
| 12 | 4 | Environment rules 1 |
| 16 | 8 | World |
| 24 | 8 | Region |
| 32 | 8 | Frame |
| 40 | 8 | Completed tick |
| 48 | 24 | Voxel address x, y, z (two's-complement i64) |
| 72 | 48 | Habitat box x, y, z, width, height, depth in micrometres (u64 each) |
| 120 | 24 | Water, dissolved inorganic N, dissolved inorganic P in femtograms |
| 144 | 8 | Radiation cap, pJ per tick |
| 152 | 8 | Cumulative radiated heat, pJ |
| 160 | 4 | Infall source count, at most 4 |
| 164 | 4 | Reserved, zero |
| 168 | 8 | Nested population envelope bytes |
| 176 | 208 each | Infall sources in strictly increasing id order (below) |
| after sources | declared length | Complete canonical population envelope 2 or 3 |
| final | 8 | FNV-1a64 over all preceding bytes |
Each source record: id (8); rectangle x, y, width, height (4 each); start and end
tick (8 each, half-open); mean interval ticks (8); bubbles min and max (4 each);
per-bubble inventory, entitlement and cumulative imported inventory (40 each:
energy then C, N, P, other); events, credited bubbles, skipped bubbles and
exhausted events (8 each).
Restore requires exact length, matching trusted identity and tick, a canonical
nested population whose owner has a boundary ledger (format 7 with rules 8/9, or
format 8 with rules 10), the box inside one voxel with width and height equal to the
cellular area and positive depth, valid disjoint sources, cumulative import within
entitlement, environmental imports within the nested ledger's incoming flow and
radiated heat within its outgoing energy, and byte-identical re-encoding. Atmospheric
species have no field: a configuration declaring any is refused.
Remaining entitlement and every infall event are derived, never stored: replay
re-derives events from world, region, source id and tick. The checksum detects
corruption only; durable publication must bind SHA-256, predecessor, fence and
manifest. No checkpoint profile, SQL schema or durable bundle admits this envelope
yet, and a nested population restored alone must not publish a joint result.
@@ -0,0 +1,460 @@
#include "evo/server/lifecycle/cellular_environment.hpp"
#include "evo/core/random.hpp"
#include <algorithm>
#include <limits>
#include <set>
#include <utility>
namespace evo::server {
namespace {
constexpr std::uint64_t magic = 0x314E45434F564541ULL; // "AEVOCEN1"
constexpr std::uint64_t infall_stream = 0x494E46414C4CULL; // "INFALL"
std::uint64_t checksum(std::span<const std::uint8_t> bytes) {
std::uint64_t hash = 14695981039346656037ULL;
for (const auto byte : bytes)
hash = (hash ^ byte) * 1099511628211ULL;
return hash; // Corruption detection; trusted publication must also bind SHA-256.
}
void put(std::vector<std::uint8_t>& bytes, std::uint64_t value, unsigned width) {
for (unsigned i = 0; i < width; ++i) {
bytes.push_back(static_cast<std::uint8_t>(value & 255U));
value >>= 8U;
}
}
void put(std::vector<std::uint8_t>& bytes, const accounting::Inventory& value) {
put(bytes, value.energy.value, 8);
for (const auto& channel : value.matter)
put(bytes, channel.value, 8);
}
class Reader {
public:
explicit Reader(std::span<const std::uint8_t> bytes) : bytes_(bytes) {}
std::uint64_t get(unsigned width) {
std::uint64_t value = 0;
for (unsigned i = 0; i < width; ++i)
value |= std::uint64_t{bytes_[at_++]} << (8U * i);
return value;
}
accounting::Inventory inventory() {
accounting::Inventory value;
value.energy.value = get(8);
for (auto& channel : value.matter)
channel.value = get(8);
return value;
}
[[nodiscard]] std::size_t at() const noexcept {
return at_;
}
private:
std::span<const std::uint8_t> bytes_;
std::size_t at_{};
};
// Channel 0 is energy; 1..4 are C, N, P and organic other.
std::uint64_t& channel(accounting::Inventory& value, std::size_t index) noexcept {
return index == 0 ? value.energy.value : value.matter[index - 1].value;
}
std::uint64_t channel(const accounting::Inventory& value, std::size_t index) noexcept {
return index == 0 ? value.energy.value : value.matter[index - 1].value;
}
bool add(accounting::Inventory& total, const accounting::Inventory& value) noexcept {
for (std::size_t index = 0; index < 5; ++index) {
if (channel(value, index) >
std::numeric_limits<std::uint64_t>::max() - channel(total, index))
return false;
channel(total, index) += channel(value, index);
}
return true;
}
bool within(const accounting::Inventory& part, const accounting::Inventory& whole) noexcept {
for (std::size_t index = 0; index < 5; ++index)
if (channel(part, index) > channel(whole, index))
return false;
return true;
}
std::uint64_t roll(std::uint64_t world, std::uint64_t region, std::uint64_t source,
std::uint64_t tick) noexcept {
std::uint64_t value = world;
for (const auto salt : {region, source, tick}) {
Random random{value};
value = random.next() ^ salt;
}
Random random{value};
return random.next();
}
bool overlaps(const CellularInfallSource& a, const CellularInfallSource& b) noexcept {
return std::uint64_t{a.x_um} < std::uint64_t{b.x_um} + b.width_um &&
std::uint64_t{b.x_um} < std::uint64_t{a.x_um} + a.width_um &&
std::uint64_t{a.y_um} < std::uint64_t{b.y_um} + b.height_um &&
std::uint64_t{b.y_um} < std::uint64_t{a.y_um} + a.height_um;
}
bool supported(const CellularLives& state) noexcept {
return (state.format_version() == cellular_lives_migration_format &&
(state.rules_version() == cellular_lives_foraging_rules ||
state.rules_version() == cellular_lives_maturation_rules)) ||
(state.format_version() == cellular_lives_inheritance_format &&
state.rules_version() == cellular_lives_inheritance_rules);
}
std::expected<world::HabitatMeasure, CellularEnvironmentError>
validate(const CellularLives& state, const CellularEnvironmentConfig& config) {
if (!supported(state))
return std::unexpected(CellularEnvironmentError::unsupported);
if (config.atmosphere_species != 0)
return std::unexpected(CellularEnvironmentError::unsupported);
const auto& box = config.geometry.box;
const auto measure = world::measure_habitat(box);
if (!measure || box.width.value != state.area().width_um ||
box.height.value != state.area().height_um || box.depth.value == 0)
return std::unexpected(CellularEnvironmentError::invalid_geometry);
if (config.sources.size() > max_cellular_infall_sources)
return std::unexpected(CellularEnvironmentError::invalid_source);
for (std::size_t index = 0; index < config.sources.size(); ++index) {
const auto& source = config.sources[index];
const bool stocked = source.per_bubble != accounting::Inventory{};
if (source.id == 0 || (index != 0 && config.sources[index - 1].id >= source.id) ||
source.width_um == 0 || source.height_um == 0 ||
std::uint64_t{source.x_um} + source.width_um > state.area().width_um ||
std::uint64_t{source.y_um} + source.height_um > state.area().height_um ||
source.start_tick >= source.end_tick || source.mean_interval_ticks == 0 ||
source.bubbles_min == 0 || source.bubbles_min > source.bubbles_max ||
source.bubbles_max > max_cellular_infall_bubbles || !stocked)
return std::unexpected(CellularEnvironmentError::invalid_source);
for (std::size_t other = 0; other < index; ++other)
if (overlaps(config.sources[other], source))
return std::unexpected(CellularEnvironmentError::invalid_source);
}
return *measure;
}
} // namespace
struct CellularEnvironment::Exchange {
std::vector<biology::CellularPatch> deposits;
accounting::Picojoules heat_export{};
std::vector<CellularInfallProgress> progress;
CellularEnvironmentTickReport report;
};
CellularEnvironment::CellularEnvironment(std::unique_ptr<CellularPopulation> population,
CellularEnvironmentConfig config)
: population_(std::move(population)), config_(std::move(config)),
progress_(config_.sources.size()) {}
CellularEnvironment::~CellularEnvironment() = default;
std::expected<std::unique_ptr<CellularEnvironment>, CellularEnvironmentError>
CellularEnvironment::create(std::unique_ptr<CellularPopulation> population,
CellularEnvironmentConfig config) {
if (!population)
return std::unexpected(CellularEnvironmentError::unsupported);
const auto measure = validate(population->state(), config);
if (!measure)
return std::unexpected(measure.error());
return std::unique_ptr<CellularEnvironment>(
new CellularEnvironment(std::move(population), std::move(config)));
}
const CellularPopulation& CellularEnvironment::population() const noexcept {
return *population_;
}
const CellularLives& CellularEnvironment::state() const noexcept {
return population_->state();
}
const CellularEnvironmentGeometry& CellularEnvironment::geometry() const noexcept {
return config_.geometry;
}
world::HabitatMeasure CellularEnvironment::measure() const noexcept {
// Validated at creation and restore; the box never changes.
const auto& box = config_.geometry.box;
return {{box.width.value * box.height.value},
{box.width.value * box.height.value * box.depth.value}};
}
const CellularWaterColumn& CellularEnvironment::water() const noexcept {
return config_.water;
}
std::span<const CellularInfallSource> CellularEnvironment::sources() const noexcept {
return config_.sources;
}
std::span<const CellularInfallProgress> CellularEnvironment::infall() const noexcept {
return progress_;
}
accounting::Picojoules CellularEnvironment::radiation_cap() const noexcept {
return config_.radiation_cap;
}
accounting::Inventory CellularEnvironment::imported() const noexcept {
accounting::Inventory total;
for (const auto& source : progress_)
static_cast<void>(add(total, source.imported)); // Bounded by the nested ledger.
return total;
}
accounting::Picojoules CellularEnvironment::exported() const noexcept {
return exported_;
}
std::uint64_t CellularEnvironment::tick() const noexcept {
return population_->state().tick();
}
std::expected<CellularEnvironment::Exchange, CellularEnvironmentError>
CellularEnvironment::plan_exchange(std::uint64_t tick) const {
const auto& state = population_->state();
const auto& habitat = state.habitat();
const auto area = state.area();
Exchange exchange;
exchange.progress = progress_;
exchange.report.tick = tick;
std::set<biology::CellularPatchAddress> taken;
for (std::size_t index = 0; index < config_.sources.size(); ++index) {
const auto& source = config_.sources[index];
auto& progress = exchange.progress[index];
if (tick < source.start_tick || tick >= source.end_tick)
continue;
const auto event = roll(state.world(), state.region(), source.id, tick);
if (event % source.mean_interval_ticks != 0)
continue;
Random stream{event ^ infall_stream};
const auto count =
source.bubbles_min + static_cast<std::uint32_t>(
stream.next() % (source.bubbles_max - source.bubbles_min + 1));
const auto centre_x =
source.x_um + static_cast<std::uint32_t>(stream.next() % source.width_um);
const auto centre_y =
source.y_um + static_cast<std::uint32_t>(stream.next() % source.height_um);
std::vector<std::size_t> stocked;
for (std::size_t slot = 0; slot < 5; ++slot)
if (channel(source.per_bubble, slot) != 0)
stocked.push_back(slot);
const auto first = static_cast<std::size_t>(stream.next() % stocked.size());
bool remaining = false;
for (const auto slot : stocked)
remaining =
remaining || channel(progress.imported, slot) < channel(source.entitlement, slot);
++progress.events;
++exchange.report.events;
if (!remaining)
++progress.exhausted_events;
for (std::uint32_t bubble = 0; bubble < count; ++bubble) {
const auto slot = stocked[(first + bubble) % stocked.size()];
constexpr auto radius = std::int64_t{cellular_infall_clump_radius_um};
std::int64_t dx = 0, dy = 0;
for (unsigned attempt = 0; attempt < 8; ++attempt) {
const auto x = static_cast<std::int64_t>(stream.next() % (2 * radius + 1)) - radius;
const auto y = static_cast<std::int64_t>(stream.next() % (2 * radius + 1)) - radius;
if (x * x + y * y <= radius * radius) {
dx = x;
dy = y;
break;
}
}
const biology::CellularPatchAddress address{
static_cast<std::uint32_t>(std::clamp<std::int64_t>(
std::int64_t{centre_x} + dx, 0, static_cast<std::int64_t>(area.width_um) - 1)),
static_cast<std::uint32_t>(
std::clamp<std::int64_t>(std::int64_t{centre_y} + dy, 0,
static_cast<std::int64_t>(area.height_um) - 1))};
const auto left = channel(source.entitlement, slot) - channel(progress.imported, slot);
const auto amount = std::min(channel(source.per_bubble, slot), left);
if (amount == 0 || habitat.find(address) || taken.contains(address) ||
habitat.patches().size() + exchange.deposits.size() >=
biology::max_cellular_patches) {
++progress.skipped_bubbles;
++exchange.report.skipped_bubbles;
continue;
}
biology::CellularPatch deposit;
deposit.address = address;
deposit.source = source.id;
deposit.radius_um = biology::cellular_mote_radius_um;
deposit.kind = biology::CellularDepositKind::mote;
channel(deposit.stock, slot) = amount;
if (!add(progress.imported, deposit.stock) ||
!add(exchange.report.imported, deposit.stock))
return std::unexpected(CellularEnvironmentError::overflow);
taken.insert(address);
exchange.deposits.push_back(deposit);
++progress.credited_bubbles;
++exchange.report.credited_bubbles;
}
}
exchange.heat_export.value = std::min(state.heat().energy.value, config_.radiation_cap.value);
if (exchange.heat_export.value > std::numeric_limits<std::uint64_t>::max() - exported_.value)
return std::unexpected(CellularEnvironmentError::overflow);
exchange.report.exported = exchange.heat_export;
return exchange;
}
std::expected<CellularEnvironmentTickReport, CellularEnvironmentError>
CellularEnvironment::advance_tick(std::span<const CellularLifeIntent> controlled,
std::span<const CellularMutationSelection> selections) {
if (tick() == std::numeric_limits<std::uint64_t>::max())
return std::unexpected(CellularEnvironmentError::overflow);
auto exchange = plan_exchange(tick() + 1);
if (!exchange)
return std::unexpected(exchange.error());
auto& lives = *population_->state_;
auto savepoint = lives.exchange_boundary(exchange->deposits, exchange->heat_export);
if (!savepoint)
return std::unexpected(savepoint.error() == CellularLivesError::habitat
? CellularEnvironmentError::habitat
: CellularEnvironmentError::conservation);
auto executed = population_->advance_tick(controlled, selections);
if (!executed) {
lives.restore_boundary(std::move(*savepoint));
return std::unexpected(CellularEnvironmentError::biology);
}
progress_ = std::move(exchange->progress);
exported_.value += exchange->heat_export.value;
exchange->report.biology = std::move(*executed);
return std::move(exchange->report);
}
std::expected<std::size_t, CellularEnvironmentError>
CellularEnvironment::collapse(std::uint64_t genome) {
const auto converted = population_->collapse(genome);
if (!converted)
return std::unexpected(CellularEnvironmentError::biology);
return *converted;
}
std::expected<std::size_t, CellularEnvironmentError>
CellularEnvironment::materialize(std::uint64_t genome) {
const auto converted = population_->materialize(genome);
if (!converted)
return std::unexpected(CellularEnvironmentError::biology);
return *converted;
}
std::vector<std::uint8_t> CellularEnvironment::snapshot() const {
const auto nested = population_->snapshot();
const auto& state = population_->state();
const auto& geometry = config_.geometry;
std::vector<std::uint8_t> bytes;
bytes.reserve(cellular_environment_header_bytes +
cellular_infall_source_bytes * config_.sources.size() + nested.size() + 8);
put(bytes, magic, 8);
put(bytes, cellular_environment_format, 4);
put(bytes, cellular_environment_rules, 4);
for (const auto value :
{state.world(), state.region(), state.frame(), state.tick(),
static_cast<std::uint64_t>(geometry.voxel.x),
static_cast<std::uint64_t>(geometry.voxel.y),
static_cast<std::uint64_t>(geometry.voxel.z), geometry.box.x.value, geometry.box.y.value,
geometry.box.z.value, geometry.box.width.value, geometry.box.height.value,
geometry.box.depth.value, config_.water.water.value,
config_.water.dissolved_nitrogen.value, config_.water.dissolved_phosphorus.value,
config_.radiation_cap.value, exported_.value})
put(bytes, value, 8);
put(bytes, config_.sources.size(), 4);
put(bytes, 0, 4);
put(bytes, nested.size(), 8);
for (std::size_t index = 0; index < config_.sources.size(); ++index) {
const auto& source = config_.sources[index];
const auto& progress = progress_[index];
put(bytes, source.id, 8);
for (const auto value : {source.x_um, source.y_um, source.width_um, source.height_um})
put(bytes, value, 4);
put(bytes, source.start_tick, 8);
put(bytes, source.end_tick, 8);
put(bytes, source.mean_interval_ticks, 8);
put(bytes, source.bubbles_min, 4);
put(bytes, source.bubbles_max, 4);
put(bytes, source.per_bubble);
put(bytes, source.entitlement);
put(bytes, progress.imported);
for (const auto value : {progress.events, progress.credited_bubbles,
progress.skipped_bubbles, progress.exhausted_events})
put(bytes, value, 8);
}
bytes.insert(bytes.end(), nested.begin(), nested.end());
put(bytes, checksum(bytes), 8);
return bytes;
}
std::expected<std::unique_ptr<CellularEnvironment>, CellularEnvironmentError>
CellularEnvironment::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
std::uint64_t region, std::uint64_t frame, std::uint64_t tick) {
if (bytes.size() < cellular_environment_header_bytes + 8 ||
bytes.size() > max_cellular_environment_bytes)
return std::unexpected(CellularEnvironmentError::format);
Reader tail(bytes.last(8));
if (tail.get(8) != checksum(bytes.first(bytes.size() - 8)))
return std::unexpected(CellularEnvironmentError::checksum);
Reader in(bytes);
if (in.get(8) != magic)
return std::unexpected(CellularEnvironmentError::format);
if (in.get(4) != cellular_environment_format || in.get(4) != cellular_environment_rules)
return std::unexpected(CellularEnvironmentError::unsupported);
if (in.get(8) != world || in.get(8) != region || in.get(8) != frame || in.get(8) != tick)
return std::unexpected(CellularEnvironmentError::identity);
CellularEnvironmentConfig config;
config.geometry.voxel = {static_cast<std::int64_t>(in.get(8)),
static_cast<std::int64_t>(in.get(8)),
static_cast<std::int64_t>(in.get(8))};
auto& box = config.geometry.box;
box.x.value = in.get(8);
box.y.value = in.get(8);
box.z.value = in.get(8);
box.width.value = in.get(8);
box.height.value = in.get(8);
box.depth.value = in.get(8);
config.water.water.value = in.get(8);
config.water.dissolved_nitrogen.value = in.get(8);
config.water.dissolved_phosphorus.value = in.get(8);
config.radiation_cap.value = in.get(8);
const accounting::Picojoules exported{in.get(8)};
const auto count = in.get(4);
if (in.get(4) != 0 || count > max_cellular_infall_sources)
return std::unexpected(CellularEnvironmentError::format);
const auto nested_bytes = in.get(8);
if (nested_bytes == 0 || nested_bytes > max_cellular_population_bytes ||
bytes.size() != cellular_environment_header_bytes + count * cellular_infall_source_bytes +
nested_bytes + 8)
return std::unexpected(CellularEnvironmentError::format);
std::vector<CellularInfallProgress> progress;
for (std::uint64_t index = 0; index < count; ++index) {
CellularInfallSource source;
source.id = in.get(8);
source.x_um = static_cast<std::uint32_t>(in.get(4));
source.y_um = static_cast<std::uint32_t>(in.get(4));
source.width_um = static_cast<std::uint32_t>(in.get(4));
source.height_um = static_cast<std::uint32_t>(in.get(4));
source.start_tick = in.get(8);
source.end_tick = in.get(8);
source.mean_interval_ticks = in.get(8);
source.bubbles_min = static_cast<std::uint32_t>(in.get(4));
source.bubbles_max = static_cast<std::uint32_t>(in.get(4));
source.per_bubble = in.inventory();
source.entitlement = in.inventory();
CellularInfallProgress done;
done.imported = in.inventory();
done.events = in.get(8);
done.credited_bubbles = in.get(8);
done.skipped_bubbles = in.get(8);
done.exhausted_events = in.get(8);
if (!within(done.imported, source.entitlement))
return std::unexpected(CellularEnvironmentError::conservation);
config.sources.push_back(source);
progress.push_back(done);
}
auto population = CellularPopulation::restore(
bytes.subspan(in.at(), static_cast<std::size_t>(nested_bytes)), world, region, frame, tick);
if (!population)
return std::unexpected(CellularEnvironmentError::format);
auto candidate = create(std::move(*population), std::move(config));
if (!candidate)
return std::unexpected(candidate.error());
(*candidate)->progress_ = std::move(progress);
(*candidate)->exported_ = exported;
// Environmental flows are part of the nested ledger, never in addition to it.
accounting::Inventory flows;
for (const auto& done : (*candidate)->progress_)
if (!add(flows, done.imported))
return std::unexpected(CellularEnvironmentError::conservation);
const auto& ledger = (*candidate)->state().boundary_ledger();
if (!within(flows, ledger.incoming) || exported.value > ledger.outgoing.energy.value)
return std::unexpected(CellularEnvironmentError::conservation);
if (!std::ranges::equal((*candidate)->snapshot(), bytes))
return std::unexpected(CellularEnvironmentError::format);
return candidate;
}
} // namespace evo::server
+71
View File
@@ -800,6 +800,77 @@ CellularLives::migration_replacement(std::vector<CellularOwnedLife> living,
return replacement;
}
std::expected<CellularLives::BoundarySavepoint, CellularLivesError>
CellularLives::exchange_boundary(std::span<const biology::CellularPatch> deposits,
accounting::Picojoules heat_export) {
if (state_->format_version != cellular_lives_migration_format &&
state_->format_version != cellular_lives_inheritance_format)
return std::unexpected(CellularLivesError::version);
if (heat_export.value > state_->heat.energy.value)
return std::unexpected(CellularLivesError::conservation);
auto boundary = state_->boundary;
auto heat = state_->heat;
heat.energy.value -= heat_export.value;
if (heat_export.value >
std::numeric_limits<std::uint64_t>::max() - boundary.outgoing.energy.value)
return std::unexpected(CellularLivesError::overflow);
boundary.outgoing.energy.value += heat_export.value;
if (deposits.empty()) {
// Heat alone: the total falls by exactly the recorded export, so closure holds.
BoundarySavepoint savepoint{nullptr, state_->heat, state_->current_total, state_->boundary};
state_->heat = heat;
state_->current_total.energy.value -= heat_export.value;
state_->boundary = std::move(boundary);
return savepoint;
}
std::unique_ptr<biology::CellularHabitat> habitat;
{
auto config = state_->habitat->config();
if (config.format != biology::cellular_habitat_deposit_format)
return std::unexpected(CellularLivesError::version);
for (auto deposit : deposits) {
if (config.next_deposit == std::numeric_limits<std::uint32_t>::max() ||
deposit.stock == accounting::Inventory{} ||
!add_inventory(boundary.incoming, deposit.stock))
return std::unexpected(CellularLivesError::overflow);
deposit.id = config.next_deposit++;
const auto at = std::ranges::lower_bound(config.patches, deposit.address, {},
&biology::CellularPatch::address);
if (at != config.patches.end() && at->address == deposit.address)
return std::unexpected(CellularLivesError::habitat);
config.patches.insert(at, deposit);
}
auto created = biology::CellularHabitat::create(std::move(config));
if (!created)
return std::unexpected(CellularLivesError::habitat);
habitat = std::move(*created);
}
const auto rules = state_->rules_version;
const auto total = validate_state(
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
*habitat, state_->lives, state_->corpses, state_->archive, state_->nursery, heat,
state_->opening_total, rules >= cellular_lives_engulf_rules,
rules >= cellular_lives_bud_rules, state_->next_bud_sequence,
rules >= cellular_lives_presence_rules, &boundary,
rules == cellular_lives_inheritance_rules ? &state_->offspring_revisions : nullptr);
if (!total)
return std::unexpected(total.error());
BoundarySavepoint savepoint{std::move(state_->habitat), state_->heat, state_->current_total,
state_->boundary};
state_->habitat = std::move(habitat);
state_->heat = heat;
state_->current_total = *total;
state_->boundary = std::move(boundary);
return savepoint;
}
void CellularLives::restore_boundary(BoundarySavepoint savepoint) noexcept {
if (savepoint.habitat)
state_->habitat = std::move(savepoint.habitat);
state_->heat = savepoint.heat;
state_->current_total = savepoint.current_total;
state_->boundary = std::move(savepoint.boundary);
}
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::migration_upgrade_candidate() const {
if (state_->rules_version != cellular_lives_foraging_rules)
+387
View File
@@ -0,0 +1,387 @@
#include "evo/server/lifecycle/cellular_environment.hpp"
#include "fixtures/cellular_ecology.hpp"
#include <cstring>
#include <fstream>
#include <iterator>
namespace {
using namespace evo;
using namespace evo::server;
using namespace evo::fixture;
using Environment = std::unique_ptr<CellularEnvironment>;
std::vector<CellularLifeIntent> controlled(const CellularLives& state, bool bud = false) {
std::vector<CellularLifeIntent> result;
for (const auto& life : state.lives())
if (life.account != LifeAccount{}) {
CellularLifeIntent input{life.identity.life, {}};
input.intent.bud = bud;
result.push_back(input);
}
return result;
}
// A real rules-9/owner-7 region: four funded founders on finite contact food.
Owner founders(std::uint64_t seed = 7) {
auto state = opening(seed, true);
state = checked(state->migration_upgrade_candidate(), "boundary upgrade");
return checked(state->maturation_upgrade_candidate(), "maturation upgrade");
}
Inventory energy_and_carbon(std::uint64_t energy, std::uint64_t carbon) {
Inventory value{{energy}, {}};
value.matter[0].value = carbon;
return value;
}
CellularInfallSource source(std::uint64_t id, std::uint32_t x, std::uint64_t interval,
Inventory entitlement, std::uint64_t start = 1,
std::uint64_t end = std::numeric_limits<std::uint64_t>::max()) {
CellularInfallSource made;
made.id = id;
made.x_um = x;
made.y_um = 0;
made.width_um = 3'000;
made.height_um = 6'000;
made.start_tick = start;
made.end_tick = end;
made.mean_interval_ticks = interval;
made.per_bubble = energy_and_carbon(400'000, 40'000);
made.entitlement = entitlement;
return made;
}
CellularEnvironmentConfig config(std::vector<CellularInfallSource> sources = {},
std::uint64_t radiation = 0) {
CellularEnvironmentConfig made;
made.geometry.voxel = {3, -2, 5};
made.geometry.box = {{1'000}, {2'000}, {0}, {6'000}, {6'000}, {10}};
made.water = {{5'000'000}, {70'000}, {9'000}};
made.sources = std::move(sources);
made.radiation_cap = {radiation};
return made;
}
Environment environment(Owner state, CellularEnvironmentConfig made) {
auto population =
checked(CellularPopulation::create(std::move(state), {false, 900, 1'600}), "population");
return checked(CellularEnvironment::create(std::move(population), std::move(made)),
"environment");
}
Environment copy(const CellularEnvironment& value) {
return checked(CellularEnvironment::restore(value.snapshot(), value.state().world(),
value.state().region(), value.state().frame(),
value.tick()),
"environment copy");
}
void step(CellularEnvironment& value, bool bud = false) {
checked(value.advance_tick(controlled(value.state(), bud)), "joint tick");
}
// Every channel: current == opening + incoming - outgoing, and the environment's own
// flows are the complete ledger here (no migration).
void audit(const CellularEnvironment& value) {
const auto& state = value.state();
const auto& ledger = state.boundary_ledger();
auto expected = state.opening_total();
expected.energy.value += ledger.incoming.energy.value;
expected.energy.value -= ledger.outgoing.energy.value;
for (std::size_t channel = 0; channel < expected.matter.size(); ++channel)
expected.matter[channel].value +=
ledger.incoming.matter[channel].value - ledger.outgoing.matter[channel].value;
require(state.current_total() == expected, "joint owner broke open-boundary closure");
require(ledger.incoming == value.imported() &&
ledger.outgoing == Inventory{value.exported(), {}},
"environment flows differ from the nested boundary ledger");
for (std::size_t index = 0; index < value.sources().size(); ++index) {
const auto& made = value.sources()[index];
const auto& done = value.infall()[index];
require(done.imported.energy <= made.entitlement.energy &&
done.imported.matter[0] <= made.entitlement.matter[0],
"infall exceeded its entitlement");
}
require(value.water() == CellularWaterColumn{{5'000'000}, {70'000}, {9'000}},
"rules 1 changed tagged water or dissolved nutrients");
}
// Source-off and closed regions keep the original biology exactly; a plain population
// advanced without the composite agrees byte for byte.
void closed_and_source_off() {
auto closed = environment(founders(), config());
const auto next = founders()->tick() + 1;
auto off = environment(
founders(), config({source(1, 0, 1, energy_and_carbon(1 << 30, 1 << 30), next, next + 1)}));
auto plain =
checked(CellularPopulation::create(founders(), {false, 900, 1'600}), "plain population");
// Tick 1 is inside the off source's interval; advance past it first without events.
for (unsigned tick = 0; tick < 1'000; ++tick) {
step(*closed, tick % 100 == 0);
if (tick == 0) {
const auto report = off->advance_tick(controlled(off->state(), true));
require(report && report->events == 1 && report->credited_bubbles > 0,
"every-tick source missed its only active tick");
} else {
step(*off, tick % 100 == 0);
}
checked(plain->advance_tick(controlled(plain->state(), tick % 100 == 0)), "plain tick");
audit(*closed);
audit(*off);
require(closed->population().snapshot() == plain->snapshot(),
"closed joint owner changed biology");
}
require(closed->imported() == Inventory{} && closed->exported().value == 0 &&
closed->state().current_total() == closed->state().opening_total(),
"closed region crossed its boundary");
require(off->infall()[0].events == 1 && off->imported() != Inventory{} &&
off->state().current_total() != off->state().opening_total(),
"source interval did not end after one tick");
}
// Open infall exhausts a finite entitlement exactly, then imports nothing.
void exhaustion() {
const auto entitlement = energy_and_carbon(4'000'000, 400'000); // Ten bubbles each.
auto open = environment(founders(), config({source(1, 0, 40, entitlement)}));
std::uint64_t exhausted_at = 0;
for (unsigned tick = 0; tick < 2'000; ++tick) {
step(*open, tick % 100 == 0);
audit(*open);
if (exhausted_at == 0 && open->imported() == entitlement)
exhausted_at = open->tick();
}
const auto& done = open->infall()[0];
require(exhausted_at != 0 && open->imported() == entitlement && done.exhausted_events > 0 &&
done.credited_bubbles == 20 && done.skipped_bubbles > 0,
"finite infall entitlement was not consumed exactly once");
std::cout << "exhaustion: entitlement consumed at tick " << exhausted_at << ", events "
<< done.events << ", credited " << done.credited_bubbles << ", skipped "
<< done.skipped_bubbles << ", exhausted events " << done.exhausted_events << '\n';
const auto after = open->imported();
for (unsigned tick = 0; tick < 500; ++tick)
step(*open);
require(open->imported() == after, "exhausted source imported more stock");
}
// Radiative export removes retained heat only: biology is unchanged against closed.
void radiation() {
auto closed = environment(founders(), config());
auto radiating = environment(founders(), config({}, 50));
for (unsigned tick = 0; tick < 1'500; ++tick) {
step(*closed, tick % 100 == 0);
step(*radiating, tick % 100 == 0);
audit(*radiating);
const auto& a = closed->state();
const auto& b = radiating->state();
require(std::ranges::equal(a.lives(), b.lives()) &&
std::ranges::equal(a.corpses(), b.corpses()) &&
a.habitat().snapshot() == b.habitat().snapshot() &&
a.heat().energy.value == b.heat().energy.value + radiating->exported().value,
"radiated heat changed biology or was not removed exactly");
}
require(radiating->exported().value > 0, "no heat was radiated");
std::cout << "radiation: exported " << radiating->exported().value << " pJ, retained "
<< radiating->state().heat().energy.value << " of "
<< closed->state().heat().energy.value << " pJ closed\n";
}
// A refused tick on an infall tick changes nothing; restore continues exactly.
void atomic_and_restore() {
// Every tick of the first 25 imports, so the refused tick carries an exchange.
const auto next = founders()->tick() + 1;
auto value = environment(
founders(),
config({source(1, 0, 1, energy_and_carbon(1 << 30, 1 << 30), next, next + 25)}, 7));
for (unsigned tick = 0; tick < 20; ++tick)
step(*value);
const auto before = value->snapshot();
const auto patches = value->state().habitat().patches().size();
require(!value->advance_tick({}).has_value() && value->snapshot() == before &&
value->state().habitat().patches().size() == patches,
"refused joint tick kept a torn exchange");
auto restored = copy(*value);
require(restored->snapshot() == before, "restore changed the joint envelope");
const auto retried = checked(value->advance_tick(controlled(value->state())), "retried tick");
require(retried.credited_bubbles > 0 && retried.imported != Inventory{},
"the refused tick carried no exchange");
step(*restored);
require(value->snapshot() == restored->snapshot(), "retry differed from the restored owner");
for (unsigned tick = 0; tick < 200; ++tick) {
step(*value, tick % 50 == 0);
step(*restored, tick % 50 == 0);
require(value->snapshot() == restored->snapshot(), "restored owner diverged");
}
audit(*restored);
}
// Exact cohorts of real wildlife see the same environment and biology as individuals.
void raw_and_cohort() {
auto raw = environment(
founders(), config({source(1, 0, 60, energy_and_carbon(1ULL << 40, 1ULL << 40))}, 20));
std::uint64_t genome = 0;
for (unsigned tick = 0; tick < 30'000 && genome == 0; ++tick) {
step(*raw, true);
for (const auto& life : raw->state().lives())
if (life.account == LifeAccount{})
genome = life.identity.genome;
}
require(genome != 0, "no real wildlife for cohort comparison");
auto cohort = copy(*raw);
require(checked(cohort->collapse(genome), "collapse wildlife") > 0, "empty cohort");
for (unsigned tick = 0; tick < 1'500; ++tick) {
const auto a = checked(raw->advance_tick(controlled(raw->state(), tick % 40 == 0)), "raw");
const auto b =
checked(cohort->advance_tick(controlled(cohort->state(), tick % 40 == 0)), "cohort");
require(a.imported == b.imported && a.exported == b.exported &&
a.biology.buds == b.biology.buds &&
raw->state().snapshot() == cohort->state().snapshot(),
"cohort and individual representations diverged");
}
audit(*cohort);
require(raw->infall()[0].events > 0, "comparison saw no infall");
std::cout << "raw/cohort: " << cohort->population().members().size() << " tagged of "
<< raw->state().lives().size() << " lives, infall events " << raw->infall()[0].events
<< ", imported energy " << raw->imported().energy.value << " pJ, radiated "
<< raw->exported().value << " pJ at tick " << raw->tick() << '\n';
}
std::vector<std::uint8_t> resealed(std::vector<std::uint8_t> bytes) {
std::uint64_t hash = 14695981039346656037ULL;
for (std::size_t i = 0; i + 8 < bytes.size(); ++i)
hash = (hash ^ bytes[i]) * 1099511628211ULL;
for (std::size_t i = 0; i < 8; ++i)
bytes[bytes.size() - 8 + i] = static_cast<std::uint8_t>(hash >> (8U * i));
return bytes;
}
void refusals() {
auto value = environment(founders(), config({source(1, 0, 1, energy_and_carbon(800'000, 1))}));
for (unsigned tick = 0; tick < 5; ++tick)
step(*value);
const auto bytes = value->snapshot();
const auto world = value->state().world(), region = value->state().region(),
frame = value->state().frame(), tick = value->tick();
auto corrupt = bytes;
corrupt[200] ^= 1U;
require(CellularEnvironment::restore(corrupt, world, region, frame, tick).error() ==
CellularEnvironmentError::checksum,
"corruption accepted");
require(CellularEnvironment::restore(bytes, world, region, frame, tick + 1).error() ==
CellularEnvironmentError::identity,
"wrong tick accepted");
auto version = bytes;
version[8] = 2;
require(CellularEnvironment::restore(resealed(version), world, region, frame, tick).error() ==
CellularEnvironmentError::unsupported,
"future envelope accepted");
// The first source's cumulative energy import (after id, rect, ticks, interval,
// bubble bounds, per-bubble and entitlement) above its entitlement.
auto excess = bytes;
const auto imported = cellular_environment_header_bytes + 8 + 16 + 24 + 8 + 40 + 40;
excess[imported + 7] = 0x7F;
require(CellularEnvironment::restore(resealed(excess), world, region, frame, tick).error() ==
CellularEnvironmentError::conservation,
"import above entitlement accepted");
auto nested = bytes;
nested[cellular_environment_header_bytes - 8] ^= 1U; // Nested length.
require(!CellularEnvironment::restore(resealed(nested), world, region, frame, tick),
"nested length accepted");
const auto refused = [](CellularEnvironmentConfig made, CellularEnvironmentError error,
Owner state = founders()) {
auto population = checked(CellularPopulation::create(std::move(state), {false, 900, 1'600}),
"refusal population");
const auto result = CellularEnvironment::create(std::move(population), std::move(made));
return !result && result.error() == error;
};
auto atmosphere = config();
atmosphere.atmosphere_species = 1;
require(refused(atmosphere, CellularEnvironmentError::unsupported),
"atmosphere treated as zero or unlimited");
auto flat = config();
flat.geometry.box.depth = {0};
require(refused(flat, CellularEnvironmentError::invalid_geometry), "zero depth accepted");
auto camera = config();
camera.geometry.box.width = {5'000};
require(refused(camera, CellularEnvironmentError::invalid_geometry),
"box disagreed with the cellular area");
auto outside = config();
outside.geometry.box.x = {996'000};
require(refused(outside, CellularEnvironmentError::invalid_geometry),
"habitat crossed its voxel");
const auto plenty = energy_and_carbon(1 << 20, 1 << 20);
require(refused(config({source(1, 0, 1, plenty), source(2, 2'000, 1, plenty)}),
CellularEnvironmentError::invalid_source),
"overlapping entitlements accepted");
require(refused(config({source(2, 0, 1, plenty), source(1, 3'000, 1, plenty)}),
CellularEnvironmentError::invalid_source),
"unsorted sources accepted");
auto empty = source(1, 0, 1, plenty);
empty.per_bubble = {};
require(refused(config({empty}), CellularEnvironmentError::invalid_source),
"stockless source accepted");
require(
refused(config({source(1, 4'000, 1, plenty)}), CellularEnvironmentError::invalid_source),
"source outside the habitat accepted");
require(refused(config(), CellularEnvironmentError::unsupported, opening(7, true)),
"owner without a boundary ledger accepted");
}
constexpr std::uint64_t restart_ticks = 400;
Environment restart_fixture() {
auto value =
environment(founders(), config({source(1, 0, 25, energy_and_carbon(1ULL << 40, 1ULL << 40)),
source(4, 3'000, 30, energy_and_carbon(1ULL << 40, 9))},
11));
for (std::uint64_t tick = 0; tick < restart_ticks; ++tick)
step(*value, tick % 50 == 0);
return value;
}
void write(const char* path, const std::vector<std::uint8_t>& bytes) {
std::ofstream out(path, std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(bytes.size()));
require(out.good(), "write failed");
}
std::vector<std::uint8_t> read(const char* path) {
std::ifstream in(path, std::ios::binary);
return {std::istreambuf_iterator<char>(in), {}};
}
void continue_fixture(CellularEnvironment& value) {
for (std::uint64_t tick = 0; tick < restart_ticks; ++tick)
step(value, tick % 50 == 0);
}
} // namespace
int main(int argc, char** argv) {
try {
if (argc == 4 && std::strcmp(argv[1], "--checkpoint") == 0) {
auto value = restart_fixture();
write(argv[2], value->snapshot());
continue_fixture(*value);
audit(*value);
write(argv[3], value->snapshot());
return 0;
}
if (argc == 4 && std::strcmp(argv[1], "--resume") == 0) {
const auto bytes = read(argv[2]);
// Identity is trusted input, never taken from the envelope it checks.
const auto origin = founders();
auto value = checked(CellularEnvironment::restore(bytes, origin->world(),
origin->region(), origin->frame(),
origin->tick() + restart_ticks),
"fresh-process restore");
continue_fixture(*value);
write(argv[3], value->snapshot());
return 0;
}
closed_and_source_off();
exhaustion();
radiation();
atomic_and_restore();
raw_and_cohort();
refusals();
auto value = restart_fixture();
audit(*value);
require(value->infall()[0].events > 0 && value->infall()[1].events > 0 &&
value->exported().value > 0,
"restart fixture crossed no boundary");
std::cout << "cellular environment contracts passed\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}