Persist fed mutation offers in cellular v2
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 1m56s
Foundation / checks (postgres) (push) Canceled after 0s
Foundation / checks (tsan) (push) Canceled after 0s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (network) (push) Canceled after 5m28s
Foundation / checks (checks) (push) Canceled after 7m39s
Foundation / checks (client) (push) Canceled after 7m39s

This commit is contained in:
dingo
2026-10-11 04:51:55 -04:00
parent 3548f2eacf
commit d652291126
21 changed files with 772 additions and 75 deletions
@@ -42,7 +42,8 @@ Binary fission, eggs, cohorts and spores stay open.
### 2. Mutation: earned during life, funded
A player's living organism can change its genome during its life:
- Eligibility is earned by surplus that has been fed and retained. The exact trigger
is part of 11.4's contract.
is the versioned, playtestable M11.4 trial in
[ADR-0120](0120-cellular-mutation-eligibility-trial.md), not a final balance rule.
- The player is offered seeded candidates, using the M3.4 generator (ADR-0033): stable
context, no free rerolls, and stale offers rejected.
- A chosen candidate is applied through funded development (ADR-0031/0032). It
+6 -4
View File
@@ -19,10 +19,12 @@ together, and ADR-0107 additionally produces corpses and a heat transfer.
## Decision
- Add a distinct `cellular-lives-v1` checkpoint profile (profile value 4) with
its own canonical envelope and restore path. Profile 3 bytes, cap, versions,
genesis rules and SQL behavior remain unchanged. A region's successor keeps
the exact profile and version bundle of its predecessor.
- Add a distinct cellular checkpoint profile (profile value 4) with its own
canonical envelope and restore path. Profile 3 bytes, cap, versions, genesis
rules and SQL behavior remain unchanged. A region's ordinary successor keeps
the exact profile and version bundle of its predecessor; the only exception
is the explicit no-tick profile-4 migration defined by
[ADR-0119](0119-cellular-profile-version-migration.md).
- The envelope is a complete single-region state closure, not a tick delta. It
binds world, region, frame, the current 50 ms simulation tick and the cellular
rule/version bundle. It contains the finite habitat and its explicit
@@ -0,0 +1,89 @@
# ADR-0119: No-tick migration for cellular profile versions
## Status
Accepted for M11.4b (2026-10-11) under the maintainer's instruction to proceed
with the recommended existing-region migration. This is a storage/versioning
decision; it does not ratify mutation thresholds, cadence or balance.
## Context
ADR-0108 requires ordinary commits to preserve their predecessor's exact profile
and version bundle. The live profile-4 envelope v1 has no durable fields for
mutation eligibility or a stable outstanding offer. Those values cannot be
reconstructed from its reserves, habitat or lineage archive. Adding them to v1
would reinterpret old canonical bytes; ordinary envelope-v2 successors would
violate the existing version-chain contract.
The engineering region already has identities and conserved inventories worth
retaining. Starting a new region would abandon that state and require separate
identity/world provisioning. M11 needs a narrow, auditable transition that
changes only the durable representation while biology is stopped.
## Decision
- Keep checkpoint profile 4 and its history profile. Introduce the exact v2
cellular version bundle `(rules=2, envelope=2, habitat=1, coordinate=1,
genome=1, development=2, founder=1, archive=1, mutation_state=1)`. The ninth
manifest version slot, zero in v1, pins the new mutation-state section. Keep
all profile-4 v1 decoders so retained history and recovery can read the
predecessor bytes.
- Permit one first-class, operator-authorized **profile migration commit** from
a current profile-4 v1 head to v2. It uses the same world, region, frame,
account/life/organism/genome/event identities and a new sequence; its begin
and end ticks are equal to the predecessor tick. It is fenced by the current
region lease and advances no simulation tick.
- The v2 checkpoint is made by fully restoring and validating v1, then copying
the region closure exactly. Habitat and patch provenance, opening totals,
nursery, heat, all life positions/growth/body/reserve/timers, corpses and
lineage archive remain equal. New per-life mutation state starts with zero
earned eligibility, event index zero and no outstanding offer. The migration
creates no birth, death, action, resource transfer, history event or outbox
record.
- Bind the source commit and manifest digest, source payload digest and version
bundle to the target commit, manifest digest, payload digest and version
bundle in an immutable migration record, created atomically with the new
head. The target manifest names the source as its predecessor. Exact retry
returns the committed receipt; reuse with any different source, target,
manifest or payload is a conflict. Unknown database results are resolved by
that same immutable identity. Stale head or lease fails closed.
- Ordinary commits before and after the migration continue to require exact
profile, version bundle, tick quantum and history profile equality. The
normal cellular publisher cannot publish a zero-tick commit or change a
version bundle. Only the dedicated migration publisher may do so, and only
for the supported v1-to-v2 pair.
- Recovery validates the migration record and both immutable manifests/digests,
restores the v1 predecessor and v2 target independently, and compares every
carried biological and accounting field. The replay stream records the
migration as a representation transition with an empty biological trace.
Corrupt, partial or unsupported pairs reject readiness; recovery never
invents eligibility.
## Alternatives
- **Write new fields under profile-4 v1:** rejected because it changes the
meaning of canonical bytes already retained by the region.
- **Start a separate v2 region:** rejected for this increment because it loses
the current region's live identities and state and requires cross-world
cellular identity remapping.
- **Allow ordinary successor commits to change versions:** rejected because
any worker could reinterpret a durable head during routine stepping.
- **Advance one biological tick during conversion:** rejected because it would
mix a representation upgrade with gameplay and could change inventories or
eligibility at deployment time.
## Benefits and costs
The existing region can continue into M11.4 while its old history stays
immutable and auditable. The extra migration API, durable link table, dual
decoder support and crash/retry tests enlarge persistence and recovery code.
Operators must explicitly schedule the one migration before a v2 build can
resume mutation-enabled simulation.
## Consequences
Update the profile-4 C++ manifest validator/builder, v2 checkpoint codec,
PostgreSQL parser and dedicated transactional migration publisher, durable
recovery/replay, schema documentation and tests together. Keep the migration
administrative path disabled for ordinary ticks. Mutation eligibility values
and offer cadence remain M11 trial rules and require separate evidence.
@@ -0,0 +1,80 @@
# ADR-0120: Cellular mutation eligibility trial
## Status
Accepted for the first M11.4 implementation (2026-10-11). The threshold and
candidate count are versioned trial values for early playtesting, not balance
sign-off. Review them with the exploratory check and again in 11.9.
## Context
ADR-0098 requires mutation eligibility to come from fed surplus retained during
a life, with seeded M3 candidates, stable retries and stale-selection refusal.
ADR-0118 defines the exact funded transition. The current cellular tick records
successful patch uptake after charging maintenance and movement, but the life
checkpoint does not retain an earned surplus counter or an offer identity.
Without those fields, opening reserve could be mistaken for feeding and recovery
could create a free reroll.
## Decision
- Credit only energy successfully acquired from a provisioned environmental
food patch by a living cell and retained in that same tick's reserve. Do not
credit its opening reserve, energy merely held, movement, external grants or
energy returned by another owner. One committed tick credits its intake once;
publication retry cannot credit it again. Corpse/predation intake is outside
this M11.4 trial and needs an explicit rule before it can earn credit.
- Start with one mutation event per **60 seconds of the life's current
per-second maintenance cost** in credited energy. Derive the threshold from
the current genome, growth and environment using checked integer arithmetic.
Carry any remainder. If several events are earned while an offer is open,
retain them as earned credit; issue at most one offer at a time. This starting
interval is a tunable, versioned trial value.
- An offer asks the M3 generator for three candidates; it may return fewer when
the genome has fewer eligible operators. An empty result does not consume the
accumulated credit or event index. Its context records the life,
parent genome identity/digest, event index, offer tick, seed/stream, candidate
count, growth and recorded environment. Event indices advance only when an
earned event becomes an offer. The generator order is canonical, never a
ranking. Re-reading or retrying the same offer regenerates identical bytes.
- Identify an offer by `(life_id, event_index, offer_tick)`. A selection names
that identity and is revalidated against the stored parent and context. A
wrong or consumed offer identity, changed genome or changed recorded context
is stale. Advancing ordinary simulation ticks alone does not expire an open
offer; the offer tick is an identity component the client must echo, not a
50 ms decision deadline. A stale or declined offer earns no replacement; a
later offer needs new retained feeding credit.
- Store the fed-energy remainder, event index and complete outstanding offer
context in profile-4 v2. They are life state and restore exactly. The no-tick
v1-to-v2 migration initializes all credit and event indices to zero and has
no outstanding offer. Offer selection and genome publication remain in the
later atomic path; 11.4b does not publish a chosen mutation.
## Alternatives
- **Use total reserve as eligibility:** rejected because an opening founder
balance would earn mutation without feeding.
- **Reroll whenever context changes or a player asks:** rejected because it
rewards movement through contexts or repeated requests with unearned draws.
- **Expire an offer after one simulation tick:** rejected because a 50 ms
decision window would not leave a practical opportunity to read and choose.
- **Rank or filter to only affordable candidates:** rejected because that hides
the actual tradeoffs and would change the seeded candidate set. Funding
failure remains visible and atomic under ADR-0118.
## Benefits and costs
The checkpoint can prove that offers were earned by feeding, retries reproduce
the same offer, and choices remain readable across several live ticks. This adds
per-life durable state, a profile migration and explicit stale-offer handling.
The 60-second threshold may feel too frequent or too slow; the early M11 check
and repeated-life evidence must guide a versioned adjustment.
## Consequences
Implement the accounting in the authoritative cellular owner, store it in the
v2 checkpoint, expose only the owner's offer through the session boundary, and
test exact retry, stale identity/context, credit carry, no opening-reserve
credit, checkpoint restore and `NDEBUG`. The durable mutation selection and its
genome/archive/resource publication remain a later segment. No ranked score,
class tree, NPC mutation or automatic reroll is introduced.
+3
View File
@@ -18,6 +18,9 @@
- [ADR-0115: Owner-filtered cellular perception protocol v8](0115-cellular-owner-perception-v8.md) - carries the existing exact sensor view only to its authenticated owner without changing v1-v7 behavior.
- [ADR-0116: Cellular life-owner routing](0116-cellular-life-owner-routing.md) - reuses authenticated SessionRedirect with an operator-provisioned per-world region route catalog; owner lookup happens before account-control claim.
- [ADR-0117: Owner-only cellular tick diagnostics protocol v9](0117-cellular-owner-tick-diagnostics-v9.md) - adds the live cell's authoritative reserve and latest committed maintenance, movement and intake result to its owner-filtered view; v1-v8 stay frozen and no gameplay rule changes.
- [ADR-0118: Funded cellular mutation transitions](0118-funded-cellular-mutation-transition.md) - accepted M11 trial contract for exact channel-funded genome transitions; eligibility cadence remains open.
- [ADR-0119: No-tick migration for cellular profile versions](0119-cellular-profile-version-migration.md) - permits an explicit leased, auditable profile-4 v1-to-v2 representation transition while ordinary commits retain exact versions.
- [ADR-0120: Cellular mutation eligibility trial](0120-cellular-mutation-eligibility-trial.md) - starts with 60 seconds of retained fed energy per unranked offer requesting up to three candidates; the threshold remains open to playtest review.
- [ADR-0058: Region durability contract](0058-region-durability-contract.md) - accepted M7.1 full checkpoint batches and explicit state closure; storage implementation follows.
+13 -4
View File
@@ -27,7 +27,7 @@ pending; no gameplay balance is treated as final by this plan.
| Segment | Affected modules | Acceptance evidence |
|---|---|---|
| 11.4a: funded transition proposal | Biology mutation/development public API and implementation; mutation tests; ADR-0118 | Deterministic selection revalidation; exact per-channel body/reserve closure; construction energy charge; insufficient-channel refusal with no partial result; `NDEBUG` tests |
| 11.4b: earned eligibility and offer identity | Cellular life state, tick intake accounting, offer context, profile-4 codec/schema | Offers require retained fed surplus; exact retry returns the same offer; changed genome/context/tick refuses stale selection; no free rerolls; checkpoint restore preserves eligibility and action identity |
| 11.4b: earned eligibility and offer identity | Cellular life state, tick intake accounting, offer context, profile-4 v2 codec/schema | One offer per 60 seconds of retained fed energy (trial), requesting up to three unranked candidates; exact retry returns the same offer; mismatched offer identity or changed genome/context refuses stale selection; ordinary ticks do not expire an offer; no free rerolls; restore preserves eligibility and offer identity |
| 11.4c: durable mutation publication | Cellular host/session, SQL migration/action parser, replay, crash tests | One action atomically publishes debit, genome successor, organism revision, archive and result; duplicate retry is exact; uncertain commit and process restart have one outcome |
| 11.4d: player choice and review | Engineering client trial UI, replication, playtest notes | Owner sees unranked candidates and actual tradeoffs; choice/refusal/recovery is readable; playtest verifies the choice follows useful feeding rather than appearing at spawn |
@@ -46,6 +46,15 @@ pending; no gameplay balance is treated as final by this plan.
## Progress
- 11.4a implementation is in progress: `fund_mutation` returns a detached,
channel-conserving transition under ADR-0118. Session offers, eligibility,
durable publication and UI remain open.
- 11.4a implementation is complete locally: `fund_mutation` returns a detached,
channel-conserving transition under ADR-0118. Its full CI run is pending.
- The ADR-0108 profile-version conflict is resolved by
[ADR-0119](../adr/0119-cellular-profile-version-migration.md): an explicit,
leased, no-tick v1-to-v2 representation migration initializes mutation state
empty and preserves the complete existing region closure. [ADR-0120](../adr/0120-cellular-mutation-eligibility-trial.md)
defines the first versioned eligibility/offer trial. Their owner and persistence
implementation is the current 11.4b work after the 11.4a CI gate.
- The current 11.4b slice adds version-2 owner snapshots, fed-energy eligibility,
stable offers and manifest/schema admission. The no-tick migration publisher,
immutable migration record, and migration-aware recovery/replay are still open;
11.4b is not complete until those durable paths and PostgreSQL CI pass.
@@ -46,10 +46,11 @@ inline constexpr VersionBundle environmental_v1_versions{};
inline constexpr VersionBundle primitive_v1_versions{1, 1, 1, 0, 0, 1, 1, 1, 1};
struct CellularVersionBundle {
std::uint32_t rules{1}, envelope{1}, habitat{1}, coordinate{1}, genome{1}, development{2},
founder{1}, archive{1};
founder{1}, archive{1}, mutation_state{};
friend bool operator==(const CellularVersionBundle&, const CellularVersionBundle&) = default;
};
inline constexpr CellularVersionBundle cellular_v1_versions{};
inline constexpr CellularVersionBundle cellular_v2_versions{2, 2, 1, 1, 1, 2, 1, 1, 1};
// Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis.
struct BatchDigests {
@@ -1,6 +1,7 @@
#pragma once
#include "evo/biology/cellular_region_step.hpp"
#include "evo/biology/mutation.hpp"
#include "evo/server/lifecycle/primitive_lives.hpp"
#include <compare>
@@ -8,12 +9,26 @@
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <span>
#include <vector>
namespace evo::server {
inline constexpr std::uint32_t cellular_lives_format = 1;
inline constexpr std::uint32_t cellular_lives_legacy_format = 1;
inline constexpr std::uint32_t cellular_lives_format = 2;
inline constexpr std::uint32_t cellular_lives_rules = 2;
inline constexpr std::size_t max_cellular_lives_bytes = std::size_t{16} * 1024 * 1024;
inline constexpr std::uint64_t cellular_mutation_surplus_seconds = 60;
inline constexpr std::uint16_t cellular_mutation_candidate_count = 3;
inline constexpr std::uint32_t cellular_mutation_stream = 0x4D555431U; // "MUT1"
struct CellularMutationProgress {
std::uint64_t fed_energy_credit_pj{};
std::uint64_t event_index{};
std::uint64_t offer_tick{};
std::optional<biology::MutationOffer> offer;
auto operator<=>(const CellularMutationProgress&) const = default;
};
struct CellularOwnedLife {
LifeAccount account{};
@@ -23,6 +38,7 @@ struct CellularOwnedLife {
biology::CellularPosition position{};
accounting::Inventory body{};
accounting::Inventory reserve{};
CellularMutationProgress mutation{};
auto operator<=>(const CellularOwnedLife&) const = default;
};
struct CellularOwnedCorpse {
@@ -66,6 +82,7 @@ enum class CellularLivesError : std::uint8_t {
invalid_intents,
biology,
region_step,
mutation,
archive,
habitat,
overflow,
@@ -93,6 +110,8 @@ class CellularLives {
[[nodiscard]] std::uint64_t region() const noexcept;
[[nodiscard]] std::uint64_t frame() const noexcept;
[[nodiscard]] std::uint64_t tick() const noexcept;
[[nodiscard]] std::uint32_t format_version() const noexcept;
[[nodiscard]] std::uint32_t rules_version() const noexcept;
[[nodiscard]] std::uint32_t ambient_temperature_millikelvin() const noexcept;
[[nodiscard]] biology::CellularArea area() const noexcept;
[[nodiscard]] std::span<const CellularOwnedLife> lives() const noexcept;
@@ -110,6 +129,12 @@ class CellularLives {
// M11.3 perception radius. Patch provenance and out-of-range stock are never returned.
[[nodiscard]] std::expected<std::vector<biology::CellularPatchPerception>, CellularLivesError>
perceive(std::uint64_t life_id) const;
// Stable unranked offer for the owning life; an absent offer is legitimate.
[[nodiscard]] std::expected<std::optional<biology::MutationOffer>, CellularLivesError>
mutation_offer(std::uint64_t life_id) const;
// Detached no-tick representation upgrade. Only a fully restored v1 owner can migrate.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migrate_to_v2() const;
// Returns a detached post-birth candidate for an allocator-reserved request.
// The caller supplies the durable identity; the owner derives founder biology,
+26
View File
@@ -0,0 +1,26 @@
-- M11.4b, ADR-0119: admit the profile-4 v2 cellular version bundle.
-- Keep the v24 parser immutable and delegate all other manifests unchanged.
ALTER FUNCTION evolution.parse_checkpoint_manifest(bytea)
RENAME TO parse_checkpoint_manifest_v24;
CREATE FUNCTION evolution.parse_checkpoint_manifest(m bytea)
RETURNS evolution.checkpoint_manifest LANGUAGE plpgsql IMMUTABLE
SET search_path = pg_catalog, pg_temp AS $$
DECLARE
r evolution.checkpoint_manifest;
normalized bytea;
v1_bundle constant bytea := '\x010000000100000001000000010000000100000002000000010000000100000000000000';
v2_bundle constant bytea := '\x020000000200000001000000010000000100000002000000010000000100000001000000';
BEGIN
IF m IS NOT NULL AND octet_length(m) = 360
AND evolution.manifest_uint(m, 12, 4) = 4
AND substring(m FROM 161 FOR 36) = v2_bundle THEN
normalized := overlay(m PLACING v1_bundle FROM 161 FOR 36);
r := evolution.parse_checkpoint_manifest_v24(normalized);
r.versions := v2_bundle;
RETURN r;
END IF;
RETURN evolution.parse_checkpoint_manifest_v24(m);
END $$;
REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC;
INSERT INTO evolution.schema_migrations(version, sha256) VALUES (25, :'migration_sha_25');
+15 -1
View File
@@ -98,7 +98,9 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution')
SELECT right(:'history', length(',22:' || :'migration_sha_22')) = ',22:' || :'migration_sha_22' AS at_v22 \gset
SELECT right(:'history', length(',23:' || :'migration_sha_23')) = ',23:' || :'migration_sha_23' AS at_v23 \gset
SELECT right(:'history', length(',24:' || :'migration_sha_24')) = ',24:' || :'migration_sha_24' AS at_v24 \gset
\if :at_v24
SELECT right(:'history', length(',25:' || :'migration_sha_25')) = ',25:' || :'migration_sha_25' AS at_v25 \gset
\if :at_v25
\elif :at_v24
\elif :at_v23
\ir 0024_primitive_life_owner_lookup.sql
\elif :at_v22
@@ -433,6 +435,18 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution')
\ir 0023_cellular_birth_publication.sql
\ir 0024_primitive_life_owner_lookup.sql
\endif
-- The versioned branch above always leaves an admitted schema at v24. Apply
-- additive follow-ups from that exact prefix, including on a fresh bootstrap.
SELECT coalesce(max(version), 0) = 24 AS at_v24,
coalesce(max(version), 0) = 25 AS at_v25
FROM evolution.schema_migrations \gset
\if :at_v24
\ir 0025_cellular_v2_bundle.sql
\elif :at_v25
\else
\echo 'Unknown or changed migration history after v24'
DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$;
\endif
-- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes
-- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC
-- grants or SET-able memberships would bypass the fenced functions. Checks the
+93
View File
@@ -0,0 +1,93 @@
# Cellular lives checkpoint v2
Authority: ADR-0108, ADR-0109, ADR-0110, ADR-0119 and ADR-0120. This is
checkpoint profile 4, envelope version 2. Version 1 remains decodable and
unchanged; ordinary successors retain the exact version bundle. A live v1 head
reaches v2 only through the explicit no-tick migration in ADR-0119.
## Envelope and closure
All integers are little-endian. The v2 envelope keeps the v1 header offsets and
canonical habitat/archive nesting. Its magic is ASCII `AEVCLV02`; format is 2
and cellular rules are 2. The ninth manifest cellular-version slot is
`mutation_state=1`. The other slots are rules 2, envelope 2, habitat 1,
coordinate 1, genome 1, development 2, founder 1 and archive 1. The tick stays
50 ms. The complete payload remains bounded by 16 MiB.
The header and the 8-byte spawn-site records are byte-for-byte the v1 shape,
except for the v2 magic and version words. Living records are 480 bytes. Corpse
records remain 100 bytes. The exact length is `220 + 8*spawn_site_count +
480*living_count + 100*corpse_count + habitat_bytes + archive_bytes + 8`.
The final eight bytes remain the FNV-1a64 accidental-corruption check; the
manifest SHA-256 binds the immutable object.
All conservation, identity, archive, habitat, placement and canonical-restore
rules from v1 continue unchanged. Mutation counters and offer metadata are
non-inventory life state: they do not enter the conserved energy/matter totals.
## Living record
The first 168 bytes are exactly the v1 living record. The v2 mutation block
follows at offset 168:
| Offset | Width | Field | Contract |
|---:|---:|---|---|
| 168 | 8 | fed_energy_credit | Successfully patch-acquired energy retained after the tick; remainder and already-earned surplus, in pJ |
| 176 | 8 | mutation_event_index | Number of offers issued for this life; no wrap |
| 184 | 8 | offer_tick | Tick when the outstanding offer identity was created; zero when no offer is outstanding |
| 192 | 8 | offer_parent_genome | Parent genome identity bound by the offer; zero without an offer |
| 200 | 8 | offer_parent_digest | Parent genome digest bound by the offer; zero without an offer |
| 208 | 8 | context_seed | Recorded M3 seed; zero without an offer |
| 216 | 4 | context_stream | Recorded M3 stream; zero without an offer |
| 220 | 8 | context_event_index | Must equal `mutation_event_index` for an outstanding offer |
| 228 | 2 | candidate_count | 0 without an offer; otherwise 1..3 and equal to the encoded candidate count |
| 230 | 2 | reserved | Zero |
| 232 | 4 | context_growth_realized | Recorded growth at offer creation |
| 236 | 4 | context_growth_damage | Recorded damage at offer creation |
| 240 | 4 | context_temperature | Recorded millikelvin environment |
| 244 | 4 | reserved | Zero |
| 248 | 40 | context_available | Recorded five-channel development environment inventory |
| 288 | 192 | candidates | Eight 24-byte candidate slots; unused slots are all zero |
Each candidate slot stores operator id (`u16`), capability target (`u8`),
effect (`u8`), successor parameter (`u32`), derived maintenance (`u64`) and
derived total mass (`u64`). Used slots are the exact canonical M3 output in
operator-id order. Restore recomputes the candidates from the archived parent
genome and recorded context and requires exact equality; a list cannot be
rewritten independently of its seed. No ranking is encoded.
The context's requested candidate count is three under cellular rules version
2. M3 may return fewer when fewer than three operators apply; an empty result
does not consume fed credit or an event index. Restore recomputes with the
requested count of three and requires exact equality with the encoded 1..3
candidate list.
The offer identity is `(life_id, mutation_event_index, offer_tick)`. A current
simulation tick later than `offer_tick` does not itself invalidate the offer;
the client must echo the recorded offer identity. Selection still checks that
the parent's current genome and the recorded context match. The offer is
rejected if either changed or if the identity was already consumed.
With no outstanding offer, every offer-specific field and candidate slot is
zero. With an offer, the tick, parent genome identity/digest, seed, stream and
event index are nonzero; candidate count equals the recorded context count;
reserved fields and padding are zero. An outstanding offer's event index is
the record's `mutation_event_index`. Event index overflow refuses the complete
candidate tick.
## Mutation credit and migration
Credit increases only by the energy actually acquired from a provisioned food
patch and retained in that committed tick's reserve. Opening reserve and energy
from other owners do not count. One committed tick contributes once, regardless
of action retry. One event is earned per 60 seconds of the life's current
per-second maintenance energy, with exact checked integer arithmetic and a
carried remainder. At most one offer is outstanding; further earned credit is
retained until the next offer can be created. This cadence is a versioned trial
value under ADR-0120.
The explicit v1-to-v2 migration copies the complete v1 region closure, changes
no tick, inventory, life/genome/archive/habitat/corpse identity or transfer, and
sets `fed_energy_credit=0`, `mutation_event_index=0`, `offer_tick=0` and all
offer fields to zero for every living life. It creates no action, birth, death,
history event or outbox row. See ADR-0119 for the manifest/database/replay link.
+17 -10
View File
@@ -2,9 +2,11 @@
M11.2 adds the portable [primitive creation profile 3](primitive-checkpoint-v1.md)
using manifest v2. M11.3 adds profile 4, the
[cellular lives profile](cellular-lives-v1.md), with its own version bundle,
payload bound and restore validator. These formats do not change profiles 1–3.
PostgreSQL admission and atomic publication are separate migration requirements.
[cellular lives profile v1](cellular-lives-v1.md), with its own version bundle,
payload bound and restore validator. M11.4 adds the compatible cellular-v2
[checkpoint](cellular-lives-v2.md) and its explicit no-tick version migration
(ADR-0119). These formats do not change profiles 1–3. PostgreSQL admission and
atomic publication are separate migration requirements.
## Canonical manifest encoding v1/v2 (ADR-0061, ADR-0063)
@@ -45,13 +47,18 @@ A structurally invalid record is malformed (SQL 22023). A record that parses but
has an unsupported version, profile, RNG, history or durability declaration is
unsupported (EVL06). Values above 255 are never truncated onto a supported enum.
Profile 4 pins cellular rules/envelope/habitat/coordinate/genome/development/
founder/archive as eight u32s, with the ninth version word zero. Its tick
quantum is 50,000 μs; its v2 trace retains the standard 96 + 304·tick encoding,
and its decision block is transactionally bound like other progressing profiles.
Profile 4 clone genesis is unsupported until cellular identity remapping is
specified. Migration 18 accepts and classifies this profile, but a database
trigger currently rejects every progressing profile-4 commit until the dedicated
cellular publisher atomically records its tick evidence. Profile 3 retains its
founder/archive in the first eight u32 version slots. Version bundle 1 is
`(1,1,1,1,1,2,1,1,0)` and uses [cellular-lives-v1](cellular-lives-v1.md).
Version bundle 2 is `(2,2,1,1,1,2,1,1,1)` and uses
[cellular-lives-v2](cellular-lives-v2.md); the ninth slot pins mutation state.
The tick quantum remains 50,000 μs. Both bundles use the bounded profile-4 trace
and bind their decision blocks transactionally. A region's ordinary successor
keeps its exact version bundle. Only the explicit leased migration commit in
ADR-0119 may transition v1 to v2 at an unchanged tick, with an immutable source
and target link; generic cellular publication cannot change versions or publish
a zero-tick commit. Profile-4 clone genesis remains unsupported until cellular
identity remapping is specified. Migration 18 admits profile 4, and the
dedicated cellular publisher binds tick evidence. Profile 3 retains its
creation-only trace and zero-decision rules.
Profile 2 payloads are schemas/environmental-lineage-v1.md containers. A region
never changes profile, history, RNG or durability declarations; schema v4
@@ -89,6 +89,12 @@ provision_cellular_region(Postgres& owner, const FilesystemObjectStore& objects,
auto manifest =
genesis_manifest(key, frame, commit, biology::cellular_motion_tick_microseconds, build,
payload.size(), *digest, CheckpointProfile::cellular_lives_v1);
if (manifest && opening.format_version() == server::cellular_lives_format &&
opening.rules_version() == server::cellular_lives_rules)
manifest->cellular_versions = cellular_v2_versions;
else if (manifest && (opening.format_version() != server::cellular_lives_legacy_format ||
opening.rules_version() != 1))
return std::unexpected{failure(PublicationError::candidate)};
auto encoded = manifest ? encode_manifest(*manifest)
: std::expected<std::vector<std::uint8_t>, CheckpointError>{
std::unexpected{CheckpointError::format}};
@@ -183,6 +189,8 @@ publish_cellular_batch(Postgres& db, const FilesystemObjectStore& objects, const
batch.header.predecessor_digest != *predecessor_digest ||
batch.header.begin_tick != previous->end_tick || candidate.world() != previous->key.world ||
candidate.region() != previous->key.region || candidate.frame() != previous->frame ||
candidate.format_version() != previous->cellular_versions.envelope ||
candidate.rules_version() != previous->cellular_versions.rules ||
candidate.tick() != batch.header.end_tick)
return std::unexpected{failure(PublicationError::candidate)};
+14 -14
View File
@@ -62,6 +62,8 @@ bool structural(const CheckpointManifest& m) noexcept {
const bool primitive = m.profile == CheckpointProfile::primitive_lives_v1;
const bool cellular = m.profile == CheckpointProfile::cellular_lives_v1;
if ((!cellular && m.cellular_versions != cellular_v1_versions) ||
(cellular && m.cellular_versions != cellular_v1_versions &&
m.cellular_versions != cellular_v2_versions) ||
(cellular && m.versions != environmental_v1_versions))
return false;
if (primitive && (m.manifest_version != 2 || m.tick_microseconds != 50000 ||
@@ -134,7 +136,8 @@ bool supported(const CheckpointManifest& m) noexcept {
m.rng_streams == 0 && m.durability == DurabilityPolicy::single_volume_development;
if (m.profile == CheckpointProfile::cellular_lives_v1)
return m.manifest_version == 2 && m.history_profile == cellular_history_profile &&
m.cellular_versions == cellular_v1_versions &&
(m.cellular_versions == cellular_v1_versions ||
m.cellular_versions == cellular_v2_versions) &&
m.versions == environmental_v1_versions && m.tick_microseconds == 50000 &&
m.rng_streams == 0 && m.durability == DurabilityPolicy::single_volume_development;
const bool profile =
@@ -169,15 +172,11 @@ encode_manifest(const CheckpointManifest& m) {
w.u(m.tick_microseconds, 8);
const auto versions =
m.profile == CheckpointProfile::cellular_lives_v1
? std::array{m.cellular_versions.rules,
m.cellular_versions.envelope,
m.cellular_versions.habitat,
m.cellular_versions.coordinate,
m.cellular_versions.genome,
m.cellular_versions.development,
m.cellular_versions.founder,
m.cellular_versions.archive,
0U}
? std::array{m.cellular_versions.rules, m.cellular_versions.envelope,
m.cellular_versions.habitat, m.cellular_versions.coordinate,
m.cellular_versions.genome, m.cellular_versions.development,
m.cellular_versions.founder, m.cellular_versions.archive,
m.cellular_versions.mutation_state}
: std::array{m.versions.rules, m.versions.envelope, m.versions.resources,
m.versions.fields, m.versions.terrain, m.versions.coordinate,
m.versions.generator, m.versions.material, m.versions.interval_adapter};
@@ -230,10 +229,8 @@ decode_manifest(std::span<const std::uint8_t> bytes) {
for (auto& v : versions)
v = static_cast<std::uint32_t>(r.u(4));
if (m.profile == CheckpointProfile::cellular_lives_v1) {
m.cellular_versions = {versions[0], versions[1], versions[2], versions[3],
versions[4], versions[5], versions[6], versions[7]};
if (versions[8] != 0)
return std::unexpected{CheckpointError::format};
m.cellular_versions = {versions[0], versions[1], versions[2], versions[3], versions[4],
versions[5], versions[6], versions[7], versions[8]};
} else {
m.versions = {versions[0], versions[1], versions[2], versions[3], versions[4],
versions[5], versions[6], versions[7], versions[8]};
@@ -435,6 +432,9 @@ restore_cellular_payload(std::span<const std::uint8_t> payload, const Checkpoint
return std::unexpected{restored.error() == server::CellularLivesError::version
? CheckpointError::unsupported
: CheckpointError::payload};
if ((*restored)->format_version() != m.cellular_versions.envelope ||
(*restored)->rules_version() != m.cellular_versions.rules)
return std::unexpected{CheckpointError::unsupported};
if (m.sequence == 0 && (!(*restored)->lives().empty() || !(*restored)->corpses().empty()))
return std::unexpected{CheckpointError::payload};
return std::move(*restored);
+230 -29
View File
@@ -10,11 +10,12 @@
namespace evo::server {
namespace {
constexpr std::uint64_t cellular_lives_magic = 0x3130564C43564541ULL; // AEVCLV01
constexpr std::uint32_t cellular_lives_rules = 1;
constexpr std::uint64_t cellular_lives_v1_magic = 0x3130564C43564541ULL; // AEVCLV01
constexpr std::uint64_t cellular_lives_v2_magic = 0x3230564C43564541ULL; // AEVCLV02
constexpr std::size_t cellular_lives_header_bytes = 212;
constexpr std::size_t cellular_site_bytes = 8;
constexpr std::size_t cellular_life_bytes = 168;
constexpr std::size_t cellular_life_v1_bytes = 168;
constexpr std::size_t cellular_life_v2_bytes = 480;
constexpr std::size_t cellular_corpse_bytes = 100;
std::uint64_t checksum(std::span<const std::uint8_t> bytes) noexcept {
@@ -24,6 +25,17 @@ std::uint64_t checksum(std::span<const std::uint8_t> bytes) noexcept {
return value;
}
std::uint64_t mutation_seed(std::uint64_t world, std::uint64_t region, std::uint64_t life,
std::uint64_t event) noexcept {
auto value = 14695981039346656037ULL;
for (const auto part : {world, region, life, event}) {
for (unsigned index = 0; index < 8; ++index) {
value = (value ^ static_cast<std::uint8_t>(part >> (index * 8U))) * 1099511628211ULL;
}
}
return value == 0 ? 1 : value;
}
class Writer {
public:
explicit Writer(std::vector<std::uint8_t>& bytes) : bytes_{bytes} {}
@@ -46,6 +58,9 @@ class Writer {
void raw(std::span<const std::uint8_t> value) {
bytes_.insert(bytes_.end(), value.begin(), value.end());
}
void zeros(std::size_t count) {
bytes_.insert(bytes_.end(), count, 0);
}
private:
std::vector<std::uint8_t>& bytes_;
@@ -263,6 +278,7 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
struct CellularLives::State {
std::uint64_t world{}, region{}, frame{};
std::uint32_t format_version{cellular_lives_format}, rules_version{cellular_lives_rules};
CellularLivesConfig config{};
NurseryConfig nursery_config{};
std::unique_ptr<biology::CellularHabitat> habitat;
@@ -279,11 +295,13 @@ struct CellularLives::State {
std::unique_ptr<biology::CellularHabitat> map, std::vector<CellularOwnedLife> living,
std::vector<CellularOwnedCorpse> dead, const biology::LineageArchive& history,
accounting::Inventory source, accounting::Inventory accumulated_heat,
accounting::Inventory initial, accounting::Inventory current)
: world{world_id}, region{region_id}, frame{frame_id}, config{cfg},
nursery_config{std::move(nursery_definition)}, habitat{std::move(map)},
lives{std::move(living)}, corpses{std::move(dead)}, archive{history}, nursery{source},
heat{accumulated_heat}, opening_total{initial}, current_total{current} {}
accounting::Inventory initial, accounting::Inventory current,
std::uint32_t format = cellular_lives_format, std::uint32_t rules = cellular_lives_rules)
: world{world_id}, region{region_id}, frame{frame_id}, format_version{format},
rules_version{rules}, config{cfg}, nursery_config{std::move(nursery_definition)},
habitat{std::move(map)}, lives{std::move(living)}, corpses{std::move(dead)},
archive{history}, nursery{source}, heat{accumulated_heat}, opening_total{initial},
current_total{current} {}
};
CellularLives::CellularLives(std::unique_ptr<State> state) : state_{std::move(state)} {}
@@ -378,6 +396,12 @@ std::uint64_t CellularLives::frame() const noexcept {
std::uint64_t CellularLives::tick() const noexcept {
return state_->config.tick;
}
std::uint32_t CellularLives::format_version() const noexcept {
return state_->format_version;
}
std::uint32_t CellularLives::rules_version() const noexcept {
return state_->rules_version;
}
std::uint32_t CellularLives::ambient_temperature_millikelvin() const noexcept {
return state_->config.ambient_temperature_millikelvin;
}
@@ -418,10 +442,12 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
const auto site_count = state_->nursery_config.sites.size();
const auto life_count = state_->lives.size();
const auto corpse_count = state_->corpses.size();
const auto life_bytes = state_->format_version == cellular_lives_legacy_format
? cellular_life_v1_bytes
: cellular_life_v2_bytes;
const auto total_bytes = cellular_lives_header_bytes + cellular_site_bytes * site_count +
cellular_life_bytes * life_count +
cellular_corpse_bytes * corpse_count + habitat.size() +
archive.size() + 8;
life_bytes * life_count + cellular_corpse_bytes * corpse_count +
habitat.size() + archive.size() + 8;
if (total_bytes > max_cellular_lives_bytes ||
habitat.size() > biology::max_cellular_habitat_bytes ||
archive.size() > biology::max_archive_bytes || site_count > max_primitive_lives ||
@@ -432,9 +458,10 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
std::vector<std::uint8_t> bytes;
bytes.reserve(total_bytes);
Writer out{bytes};
out.put(cellular_lives_magic);
out.put(cellular_lives_format, 4);
out.put(cellular_lives_rules, 4);
out.put(state_->format_version == cellular_lives_legacy_format ? cellular_lives_v1_magic
: cellular_lives_v2_magic);
out.put(state_->format_version, 4);
out.put(state_->rules_version, 4);
out.put(state_->world);
out.put(state_->region);
out.put(state_->frame);
@@ -468,6 +495,41 @@ std::vector<std::uint8_t> CellularLives::snapshot() const {
out.put(life.position.y_um);
out.inventory(life.body);
out.inventory(life.reserve);
if (state_->format_version >= cellular_lives_format) {
const auto& mutation = life.mutation;
out.put(mutation.fed_energy_credit_pj);
out.put(mutation.event_index);
out.put(mutation.offer_tick);
out.put(mutation.offer ? mutation.offer->parent : 0);
out.put(mutation.offer ? mutation.offer->parent_digest : 0);
out.put(mutation.offer ? mutation.offer->context.seed : 0);
out.put(mutation.offer ? mutation.offer->context.stream : 0, 4);
out.put(mutation.offer ? mutation.offer->context.event_index : 0);
out.put(mutation.offer ? mutation.offer->context.candidate_count : 0, 2);
out.put(0, 2);
out.put(mutation.offer ? mutation.offer->context.growth.realized_per_thousand : 0, 4);
out.put(mutation.offer ? mutation.offer->context.growth.damage_per_thousand : 0, 4);
out.put(mutation.offer ? mutation.offer->context.environment.temperature_millikelvin
: 0,
4);
out.put(0, 4);
out.inventory(mutation.offer ? mutation.offer->context.environment.available
: accounting::Inventory{});
const auto count = mutation.offer ? mutation.offer->candidates.size() : 0;
for (std::size_t index = 0; index < biology::max_candidates; ++index) {
if (index < count) {
const auto& candidate = mutation.offer->candidates[index];
out.put(candidate.operator_id, 2);
out.put(static_cast<std::uint8_t>(candidate.target), 1);
out.put(static_cast<std::uint8_t>(candidate.effect), 1);
out.put(candidate.parameter, 4);
out.put(candidate.maintenance);
out.put(candidate.total_mass);
} else {
out.zeros(24);
}
}
}
}
for (const auto& corpse : state_->corpses) {
out.put(corpse.life_id);
@@ -505,6 +567,34 @@ CellularLives::perceive(std::uint64_t life_id) const {
return std::move(*view);
}
std::expected<std::optional<biology::MutationOffer>, CellularLivesError>
CellularLives::mutation_offer(std::uint64_t life_id) const {
const auto life = std::ranges::find(state_->lives, life_id,
[](const auto& owned) { return owned.identity.life; });
if (life == state_->lives.end())
return std::unexpected{CellularLivesError::invalid_life};
return life->mutation.offer;
}
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::migrate_to_v2() const {
if (state_->format_version != cellular_lives_legacy_format || state_->rules_version != 1)
return std::unexpected{CellularLivesError::version};
auto lives = state_->lives;
for (auto& life : lives)
life.mutation = {};
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
state_->region, state_->frame);
if (!habitat)
return std::unexpected{CellularLivesError::habitat};
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
std::move(*habitat), std::move(lives), state_->corpses, state_->archive, state_->nursery,
state_->heat, state_->opening_total, state_->current_total, cellular_lives_format,
cellular_lives_rules)}};
return candidate;
}
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) const {
if (request.action == 0 ||
@@ -613,7 +703,7 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
state_->world, state_->region, state_->frame, state_->config, std::move(nursery_config),
std::move(*habitat), std::move(lives), state_->corpses, archive, nursery, heat,
state_->opening_total, *current)}};
state_->opening_total, *current, state_->format_version, state_->rules_version)}};
candidate->last_tick_feedback_ = last_tick_feedback_;
return candidate;
}
@@ -628,9 +718,15 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
return std::unexpected{CellularLivesError::checksum};
Reader in{bytes};
if (in.get() != cellular_lives_magic)
return std::unexpected{CellularLivesError::format};
if (in.get(4) != cellular_lives_format || in.get(4) != cellular_lives_rules)
const auto magic = in.get();
const auto format_version = static_cast<std::uint32_t>(in.get(4));
const auto rules_version = static_cast<std::uint32_t>(in.get(4));
const bool legacy = magic == cellular_lives_v1_magic &&
format_version == cellular_lives_legacy_format && rules_version == 1;
const bool current_version = magic == cellular_lives_v2_magic &&
format_version == cellular_lives_format &&
rules_version == cellular_lives_rules;
if (!legacy && !current_version)
return std::unexpected{CellularLivesError::version};
const auto saved_world = in.get();
const auto saved_region = in.get();
@@ -661,10 +757,10 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
const auto opening_total = in.inventory();
const auto nursery = in.inventory();
const auto heat = in.inventory();
const auto life_bytes = legacy ? cellular_life_v1_bytes : cellular_life_v2_bytes;
const auto expected_size = cellular_lives_header_bytes + cellular_site_bytes * site_count +
cellular_life_bytes * life_count +
cellular_corpse_bytes * corpse_count + habitat_size + archive_size +
8;
life_bytes * life_count + cellular_corpse_bytes * corpse_count +
habitat_size + archive_size + 8;
if (source == 0 || expected_size != bytes.size())
return std::unexpected{CellularLivesError::format};
@@ -689,6 +785,54 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
life.position = {in.get(), in.get()};
life.body = in.inventory();
life.reserve = in.inventory();
if (current_version) {
auto& mutation = life.mutation;
mutation.fed_energy_credit_pj = in.get();
mutation.event_index = in.get();
mutation.offer_tick = in.get();
biology::MutationOffer offer{};
offer.parent = in.get();
offer.parent_digest = in.get();
offer.context.seed = in.get();
offer.context.stream = static_cast<std::uint32_t>(in.get(4));
offer.context.event_index = in.get();
const auto offered_count = static_cast<std::uint16_t>(in.get(2));
if (offered_count != 0)
offer.context.candidate_count = cellular_mutation_candidate_count;
const auto reserved16 = in.get(2);
offer.context.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
offer.context.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
offer.context.environment.temperature_millikelvin =
static_cast<std::uint32_t>(in.get(4));
const auto reserved32 = in.get(4);
offer.context.environment.available = in.inventory();
for (std::size_t slot = 0; slot < biology::max_candidates; ++slot) {
biology::MutationCandidate candidate{};
candidate.operator_id = static_cast<std::uint16_t>(in.get(2));
candidate.target = static_cast<biology::Capability>(in.get(1));
candidate.effect = static_cast<biology::MutationEffect>(in.get(1));
candidate.parameter = static_cast<std::uint32_t>(in.get(4));
candidate.maintenance = in.get();
candidate.total_mass = in.get();
if (slot < offered_count)
offer.candidates.push_back(candidate);
else if (candidate != biology::MutationCandidate{})
return std::unexpected{CellularLivesError::noncanonical};
}
const bool has_offer = mutation.offer_tick != 0;
if (reserved16 != 0 || reserved32 != 0 ||
(has_offer &&
(offer.parent == 0 || offer.parent_digest == 0 || offer.context.seed == 0 ||
offer.context.stream == 0 || offer.context.event_index != mutation.event_index ||
offered_count == 0 || offered_count > cellular_mutation_candidate_count ||
offer.candidates.size() != offered_count)) ||
(!has_offer && (offer.parent != 0 || offer.parent_digest != 0 ||
offer.context != biology::MutationContext{})))
return std::unexpected{CellularLivesError::noncanonical};
if (has_offer) {
mutation.offer = std::move(offer);
}
}
lives.push_back(life);
}
@@ -729,6 +873,19 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
return std::unexpected{CellularLivesError::noncanonical};
return std::unexpected{CellularLivesError::archive};
}
if (current_version) {
for (const auto& life : lives) {
if (!life.mutation.offer)
continue;
const auto genome = archive->find(life.identity.genome);
if (!genome)
return std::unexpected{CellularLivesError::archive};
const auto generated =
biology::mutation_candidates(*genome, life.mutation.offer->context);
if (!generated || *generated != *life.mutation.offer)
return std::unexpected{CellularLivesError::noncanonical};
}
}
const auto current =
validate_state(saved_world, saved_region, saved_frame, config, nursery_config, **habitat,
lives, corpses, *archive, nursery, heat, opening_total);
@@ -738,7 +895,7 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
auto restored = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
saved_world, saved_region, saved_frame, config, std::move(nursery_config),
std::move(*habitat), std::move(lives), std::move(corpses), *archive, nursery, heat,
opening_total, *current)}};
opening_total, *current, format_version, rules_version)}};
if (!std::ranges::equal(bytes, restored->snapshot()))
return std::unexpected{CellularLivesError::noncanonical};
return restored;
@@ -793,6 +950,50 @@ CellularLives::advance_tick(std::span<const CellularLifeIntent> intents) {
found->reserve = result.candidate.reserve_after;
if (!add_inventory(next_heat, result.candidate.heat_after))
return std::unexpected{CellularLivesError::overflow};
if (state_->format_version >= cellular_lives_format && result.candidate.intake) {
const auto acquired = result.candidate.intake->transfer.acquired.energy.value;
if (acquired >
std::numeric_limits<std::uint64_t>::max() - found->mutation.fed_energy_credit_pj)
return std::unexpected{CellularLivesError::overflow};
found->mutation.fed_energy_credit_pj += acquired;
if (!found->mutation.offer) {
const auto budget = budget_for(next_archive, *found,
state_->config.ambient_temperature_millikelvin);
if (!budget ||
budget->maintenance.value > std::numeric_limits<std::uint64_t>::max() /
cellular_mutation_surplus_seconds)
return std::unexpected{CellularLivesError::mutation};
const auto threshold =
budget->maintenance.value * cellular_mutation_surplus_seconds;
if (threshold == 0)
return std::unexpected{CellularLivesError::mutation};
if (found->mutation.fed_energy_credit_pj >= threshold) {
if (found->mutation.event_index == std::numeric_limits<std::uint64_t>::max())
return std::unexpected{CellularLivesError::overflow};
const auto genome = next_archive.find(found->identity.genome);
if (!genome)
return std::unexpected{CellularLivesError::archive};
const auto next_event = found->mutation.event_index + 1;
biology::MutationContext context{
mutation_seed(state_->world, state_->region, result.life_id, next_event),
cellular_mutation_stream,
next_event,
cellular_mutation_candidate_count,
found->growth,
{state_->config.ambient_temperature_millikelvin,
result.candidate.intake->transfer.patch_after}};
const auto offer = biology::mutation_candidates(*genome, context);
if (offer) {
found->mutation.fed_energy_credit_pj -= threshold;
found->mutation.event_index = next_event;
found->mutation.offer_tick = proposal->end_tick;
found->mutation.offer = *offer;
} else if (offer.error() != biology::MutationError::no_candidates) {
return std::unexpected{CellularLivesError::mutation};
}
}
}
}
}
for (const auto& dead : proposal->starved) {
const auto found = std::ranges::lower_bound(
@@ -834,13 +1035,13 @@ CellularLives::advance_tick(std::span<const CellularLifeIntent> intents) {
if (!total)
return std::unexpected{total.error()};
auto next =
std::make_unique<State>(state_->world, state_->region, state_->frame,
CellularLivesConfig{state_->config.area, proposal->end_tick,
state_->config.ambient_temperature_millikelvin},
state_->nursery_config, std::move(*next_habitat),
std::move(next_lives), std::move(next_corpses), next_archive,
state_->nursery, next_heat, state_->opening_total, *total);
auto next = std::make_unique<State>(
state_->world, state_->region, state_->frame,
CellularLivesConfig{state_->config.area, proposal->end_tick,
state_->config.ambient_temperature_millikelvin},
state_->nursery_config, std::move(*next_habitat), std::move(next_lives),
std::move(next_corpses), next_archive, state_->nursery, next_heat, state_->opening_total,
*total, state_->format_version, state_->rules_version);
std::vector<CellularLifeTickFeedback> feedback;
feedback.reserve(proposal->lives.size());
for (const auto& result : proposal->lives) {
+126
View File
@@ -5,6 +5,7 @@
#include <array>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <source_location>
#include <span>
#include <stdexcept>
@@ -152,6 +153,126 @@ void reserved_birth_is_funded_and_detached() {
CellularLivesError::no_placement);
}
void cellular_profile_migration_is_explicit_and_no_tick() {
auto primitive = PrimitiveLives::create({91, 1, 1, 17, founder_price(1), {{0, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 5;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
auto habitat = evo::biology::CellularHabitat::create({91, 1, 1, 1'000, 1'000, {}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 1, 293'150});
CHECK(created && (*created)->lives().size() == 1);
auto current = std::move(*created);
auto legacy_bytes = current->snapshot();
legacy_bytes.erase(legacy_bytes.begin() + 220 + 168, legacy_bytes.begin() + 220 + 480);
constexpr std::uint64_t legacy_magic = 0x3130564C43564541ULL;
for (unsigned index = 0; index < 8; ++index)
legacy_bytes[index] = static_cast<std::uint8_t>(legacy_magic >> (index * 8U));
legacy_bytes[8] = 1;
legacy_bytes[9] = legacy_bytes[10] = legacy_bytes[11] = 0;
legacy_bytes[12] = 1;
legacy_bytes[13] = legacy_bytes[14] = legacy_bytes[15] = 0;
refresh_checksum(legacy_bytes);
const auto legacy = CellularLives::restore(legacy_bytes, current->world(), current->region(),
current->frame(), current->tick());
CHECK(legacy && (*legacy)->format_version() == cellular_lives_legacy_format &&
(*legacy)->rules_version() == 1 && (*legacy)->snapshot() == legacy_bytes &&
(*legacy)->lives().size() == 1);
const auto legacy_life_id = (*legacy)->lives()[0].identity.life;
const std::array legacy_idle{CellularLifeIntent{legacy_life_id, {}}};
CHECK((*legacy)->advance_tick(legacy_idle) &&
(*legacy)->format_version() == cellular_lives_legacy_format &&
(*legacy)->rules_version() == 1 && (*legacy)->tick() == 2);
const auto before = (*legacy)->snapshot();
const auto biological_state = (*legacy)->lives()[0];
const auto migrated = (*legacy)->migrate_to_v2();
CHECK(migrated && (*migrated)->format_version() == cellular_lives_format &&
(*migrated)->rules_version() == cellular_lives_rules &&
(*migrated)->tick() == (*legacy)->tick() &&
(*migrated)->current_total() == (*legacy)->current_total() &&
(*migrated)->lives().size() == 1 &&
(*migrated)->lives()[0].account == biological_state.account &&
(*migrated)->lives()[0].identity == biological_state.identity &&
(*migrated)->lives()[0].source == biological_state.source &&
(*migrated)->lives()[0].growth == biological_state.growth &&
(*migrated)->lives()[0].position == biological_state.position &&
(*migrated)->lives()[0].body == biological_state.body &&
(*migrated)->lives()[0].reserve == biological_state.reserve &&
(*migrated)->lives()[0].mutation == CellularMutationProgress{} &&
(*legacy)->snapshot() == before && (*migrated)->snapshot() != before);
const auto restored =
CellularLives::restore((*migrated)->snapshot(), current->world(), current->region(),
current->frame(), (*migrated)->tick());
CHECK(restored && (*restored)->snapshot() == (*migrated)->snapshot());
const auto migrated_life_id = (*migrated)->lives()[0].identity.life;
const std::array migrated_idle{CellularLifeIntent{migrated_life_id, {}}};
CHECK((*migrated)->advance_tick(migrated_idle) &&
(*migrated)->format_version() == cellular_lives_format &&
(*migrated)->rules_version() == cellular_lives_rules && (*migrated)->tick() == 3);
}
void retained_feeding_earns_a_persistent_mutation_offer() {
auto primitive = PrimitiveLives::create({93, 1, 1, 17, founder_price(1), {{0, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 3;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
Inventory patch_stock{{1'000'000'000'000ULL},
{{{1'000'000'000'000ULL},
{1'000'000'000'000ULL},
{1'000'000'000'000ULL},
{1'000'000'000'000ULL}}}};
auto habitat = evo::biology::CellularHabitat::create(
{93, 1, 1, 1'000, 1'000, {{{0, 0}, 29, patch_stock}}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 1, 293'150});
CHECK(created && (*created)->lives().size() == 1 &&
(*created)->lives()[0].mutation.fed_energy_credit_pj == 0);
auto& owner = **created;
const auto life_id = owner.lives()[0].identity.life;
CHECK(owner.mutation_offer(life_id) && !*owner.mutation_offer(life_id));
const auto founder = owner.archive().find(owner.lives()[0].identity.genome);
CHECK(founder);
const auto founder_budget = evo::biology::metabolic_budget(
*founder, owner.lives()[0].growth, {owner.ambient_temperature_millikelvin(), {}});
CHECK(founder_budget &&
founder_budget->maintenance.value <=
std::numeric_limits<std::uint64_t>::max() / cellular_mutation_surplus_seconds);
const auto threshold = founder_budget->maintenance.value * cellular_mutation_surplus_seconds;
std::uint64_t total_acquired{};
bool offered = false;
for (std::size_t step = 0; step < 10'000 && !offered; ++step) {
const std::array intent{CellularLifeIntent{life_id, {{0, 0}, {{0, 0}}}}};
const auto advanced = owner.advance_tick(intent);
CHECK(advanced && advanced->lives.size() == 1 && advanced->lives[0].candidate.intake);
const auto& intake = advanced->lives[0].candidate.intake.value();
total_acquired += intake.transfer.acquired.energy.value;
const auto offer = owner.mutation_offer(life_id);
CHECK(offer);
offered = offer->has_value();
}
CHECK(offered);
const auto earned = owner.mutation_offer(life_id);
CHECK(earned && *earned && (*earned)->candidates.size() <= cellular_mutation_candidate_count &&
!(*earned)->candidates.empty() && owner.lives()[0].mutation.event_index == 1 &&
owner.lives()[0].mutation.offer_tick == owner.tick() &&
total_acquired == threshold + owner.lives()[0].mutation.fed_energy_credit_pj);
const auto saved = owner.snapshot();
const auto recovered = CellularLives::restore(saved, 93, 1, 1, owner.tick());
CHECK(recovered && (*recovered)->snapshot() == saved);
const auto replayed_offer = (*recovered)->mutation_offer(life_id);
CHECK(replayed_offer && replayed_offer == earned);
const std::array idle{CellularLifeIntent{life_id, {}}};
CHECK(owner.advance_tick(idle));
const auto after_tick = owner.mutation_offer(life_id);
CHECK(after_tick && after_tick == earned);
}
void owner_advances_and_closes_death_atomically() {
auto primitive = PrimitiveLives::create({90, 1, 7, 17, founder_price(2), {{0, 0}, {20, 0}}});
CHECK(primitive);
@@ -197,6 +318,9 @@ void owner_advances_and_closes_death_atomically() {
CHECK(fed && owner.tick() == 2 && owner.lives().size() == 2);
CHECK(fed->lives.size() == 2 &&
fed->lives[0].candidate.intake_status == evo::biology::CellularIntakeStatus::acquired);
CHECK(owner.format_version() == cellular_lives_format &&
owner.lives()[0].mutation.fed_energy_credit_pj > 0 &&
owner.mutation_offer(first_life_id) && !*owner.mutation_offer(first_life_id));
CHECK(owner.last_tick_feedback().size() == 2 &&
owner.last_tick_feedback()[0].tick == owner.tick() &&
owner.last_tick_feedback()[0].life_id == owner.lives()[0].identity.life &&
@@ -315,6 +439,8 @@ void owner_advances_and_closes_death_atomically() {
int main() {
try {
reserved_birth_is_funded_and_detached();
cellular_profile_migration_is_explicit_and_no_tick();
retained_feeding_earns_a_persistent_mutation_offer();
owner_advances_and_closes_death_atomically();
std::puts("PASS cellular lives: feeding, tick ownership and terminal closure");
} catch (const std::exception& error) {
+4 -2
View File
@@ -172,6 +172,7 @@ void run_cellular_publication_tests() {
CHECK(provisioned && provisioned->head.sequence == 0 && provisioned->head.end_tick == 0);
auto empty_manifest = decode_manifest(provisioned->manifest);
CHECK(empty_manifest && empty_manifest->profile == CheckpointProfile::cellular_lives_v1 &&
empty_manifest->cellular_versions == cellular_v2_versions &&
empty_manifest->payload_bytes == (*empty_opening)->snapshot().size());
auto genesis_payload =
(*empty_objects)->get({empty_manifest->payload_sha256, empty_manifest->payload_bytes});
@@ -208,9 +209,10 @@ void run_cellular_publication_tests() {
const auto payload = (*opening)->snapshot();
const auto payload_digest = sha256(payload);
CHECK(payload_digest);
const auto genesis = genesis_manifest(key, 1, filled<16>(0x21), 50'000, build, payload.size(),
*payload_digest, CheckpointProfile::cellular_lives_v1);
auto genesis = genesis_manifest(key, 1, filled<16>(0x21), 50'000, build, payload.size(),
*payload_digest, CheckpointProfile::cellular_lives_v1);
CHECK(genesis);
genesis->cellular_versions = cellular_v2_versions;
const auto genesis_bytes = encode_manifest(*genesis);
CHECK(genesis_bytes);
auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes);
+7 -2
View File
@@ -418,20 +418,25 @@ void cellular_profile() {
const auto payload = (*owner)->snapshot();
auto manifest = genesis_manifest(key, 9, filled<16>(0x02), 50000, build, payload.size(),
filled<32>(0xA2), CheckpointProfile::cellular_lives_v1);
CHECK(manifest);
manifest->cellular_versions = cellular_v2_versions;
CHECK(manifest && supported(*manifest) &&
manifest->history_profile == cellular_history_profile &&
manifest->cellular_versions == cellular_v1_versions &&
manifest->cellular_versions == cellular_v2_versions &&
max_payload_bytes(CheckpointProfile::cellular_lives_v1) == max_cellular_lives_bytes);
const auto encoded = encode_manifest(*manifest);
CHECK(encoded && decode_manifest(*encoded) == *manifest);
const auto restored = restore_cellular_payload(payload, *manifest);
CHECK(restored && (*restored)->snapshot() == payload);
auto mismatched_bundle = *manifest;
mismatched_bundle.cellular_versions = cellular_v1_versions;
CHECK(!restore_cellular_payload(payload, mismatched_bundle));
CHECK(!restore_primitive_payload(payload, *manifest));
const auto successor =
successor_manifest(*manifest, filled<32>(0xA5), filled<16>(0x04), lease(), 1, build,
payload.size(), filled<32>(0xA6), batch_for(1, 1));
CHECK(successor && supported(*successor) &&
successor->cellular_versions == cellular_v1_versions);
successor->cellular_versions == cellular_v2_versions);
auto short_cellular_trace = *successor;
short_cellular_trace.batch.trace_bytes =
cellular_batch_header_bytes + cellular_batch_tick_header_bytes - 1;
+3 -1
View File
@@ -190,6 +190,7 @@ void upgrade_across_migration_and_barrier() {
" -v migration_sha_22=$(s 0022_cellular_birth_trace_bound.sql)"
" -v migration_sha_23=$(s 0023_cellular_birth_publication.sql)"
" -v migration_sha_24=$(s 0024_primitive_life_owner_lookup.sql)"
" -v migration_sha_25=$(s 0025_cellular_v2_bundle.sql)"
" -v runtime_role=evo_runtime_test -f migrations/apply.sql"
" > /dev/null 2>&1") != 0);
CHECK(history(*owner_db) == "1,2,3,4,5,6,7");
@@ -205,7 +206,8 @@ void upgrade_across_migration_and_barrier() {
CHECK(shell("PGDATABASE=" + database +
" EVO_PG_RUNTIME_ROLE=evo_runtime_test bash \"$EVO_SOURCE_ROOT/"
"tools/migrate-postgres.sh\" > /dev/null") == 0);
CHECK(history(*owner_db) == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24");
CHECK(history(*owner_db) ==
"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25");
CHECK(scalar(*owner_db,
"SELECT (to_regprocedure('evolution.primitive_life_owner("
"evolution.u64,evolution.u64,uuid,evolution.u64,uuid)') IS NOT NULL)::text") ==
+5 -5
View File
@@ -69,7 +69,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha"
-f "$root/migrations/0001_region_bootstrap.sql" > /dev/null
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1
PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh"
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
# v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2.
v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")"
v2_sha="${v2_sha%% *}"
@@ -90,7 +90,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \
-c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \
-c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null
PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh"
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 23:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 25:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1
# Review P1: a v4 database holding a published (possibly terminal) checkpoint has
# no durable decisions for it. The v5 upgrade must refuse before changing anything.
@@ -144,7 +144,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \
-c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \
-c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null
PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh"
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1
test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick
# Inherited privileges bypass fencing, so every migrate run audits effective rights.
@@ -190,9 +190,9 @@ expect_audit_failure 'GRANT SELECT ON evolution.account_controls TO evo_runtime_
expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM evo_runtime_test' 'GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64, uuid, evolution.u64, evolution.u64, integer) TO evo_runtime_test'
bash "$root/tools/migrate-postgres.sh" # Restored configuration passes the audit again.
# Unknown future versions and checksum drift must not be repaired silently.
psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=24 WHERE version=23'
psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=26 WHERE version=25'
if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=23 WHERE version=24"
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=25 WHERE version=26"
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14"
if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi
psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13"
+3
View File
@@ -60,6 +60,8 @@ digest_23="$(sha256sum "$root/migrations/0023_cellular_birth_publication.sql")"
digest_23="${digest_23%% *}"
digest_24="$(sha256sum "$root/migrations/0024_primitive_life_owner_lookup.sql")"
digest_24="${digest_24%% *}"
digest_25="$(sha256sum "$root/migrations/0025_cellular_v2_bundle.sql")"
digest_25="${digest_25%% *}"
psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \
--set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \
--set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \
@@ -77,5 +79,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \
--set="migration_sha_22=$digest_22" \
--set="migration_sha_23=$digest_23" \
--set="migration_sha_24=$digest_24" \
--set="migration_sha_25=$digest_25" \
--set="runtime_role=$runtime_role" \
--file="$root/migrations/apply.sql"