diff --git a/apps/evo-server/cellular_bridge.hpp b/apps/evo-server/cellular_bridge.hpp index 099fb4c..d786978 100644 --- a/apps/evo-server/cellular_bridge.hpp +++ b/apps/evo-server/cellular_bridge.hpp @@ -157,6 +157,8 @@ class CellularBridge { result.identity = {state.world(), state.frame()}; result.organism_revision = tick; for (const auto& life : state.lives()) { + if (life.presence == server::CellularPresence::suspended) + continue; // Out of the world (ADR-0128). const auto voxel_x = life.position.x_um / 1'000'000; const auto voxel_y = life.position.y_um / 1'000'000; if (voxel_x > @@ -188,6 +190,8 @@ class CellularBridge { sessions_->replicate(tick, source); sessions_->clear_cellular_perceptions(tick); for (const auto& life : state.lives()) { + if (life.presence == server::CellularPresence::suspended) + continue; const auto perceived = state.perceive(life.identity.life); if (!perceived) continue; diff --git a/apps/evo-server/main.cpp b/apps/evo-server/main.cpp index bed0656..8569ec1 100644 --- a/apps/evo-server/main.cpp +++ b/apps/evo-server/main.cpp @@ -1021,14 +1021,15 @@ int serve_cellular(Options& o) { const auto* state = host.state(); bool player_present = false; + // ADR-0128: a lingering life keeps the region ticking until its linger completes. + bool lingering_present = false; if (status.ready && state) { for (const auto& life : state->lives()) { network::AccountId account; account.bytes = life.account; - if (bridge->sessions().holder(account)) { - player_present = true; - break; - } + player_present = player_present || bridge->sessions().holder(account); + lingering_present = + lingering_present || life.presence == server::CellularPresence::lingering; } } // A queued birth publishes only while its account holds a session here: the @@ -1044,7 +1045,7 @@ int serve_cellular(Options& o) { held_births.push_back(birth); } const bool birth_waiting = !held_births.empty(); - if (status.ready && state && (player_present || birth_waiting)) { + if (status.ready && state && (player_present || birth_waiting || lingering_present)) { const auto now = std::chrono::steady_clock::now(); if (!next_tick) next_tick = now + std::chrono::milliseconds{50}; @@ -1052,8 +1053,23 @@ int serve_cellular(Options& o) { const auto tick = state->tick() + 1; std::vector baseline; baseline.reserve(state->lives().size()); - for (const auto& life : state->lives()) - baseline.push_back({life.identity.life, {}}); + // ADR-0128: an owned life whose account holds no session here is frozen + // (rules 5); the trace records the boundary, and its carried actions are + // refused below. + const bool presence_rules = + state->rules_version() >= server::cellular_lives_presence_rules; + std::vector offline; + for (const auto& life : state->lives()) { + server::CellularLifeIntent intent{life.identity.life, {}}; + network::AccountId account; + account.bytes = life.account; + if (presence_rules && life.account != server::LifeAccount{} && + !bridge->sessions().holder(account)) { + intent.intent.frozen = true; + offline.push_back(life.account); + } + baseline.push_back(intent); + } std::ranges::sort(baseline, {}, &server::CellularLifeIntent::life_id); // ADR-0125: wildlife follow the deterministic controller; its intentions // ride the trace like a player's, and the owner validates them. @@ -1066,6 +1082,16 @@ int serve_cellular(Options& o) { } } auto actions = bridge->carry(tick); + if (!offline.empty()) { + std::vector departed; + std::erase_if(actions, [&](const network::CarriedAction& action) { + if (std::ranges::find(offline, action.account.bytes) == offline.end()) + return false; + departed.push_back(action); + return true; + }); + bridge->dropped(departed, true); + } auto builder = server::CellularSessionBatchBuilder::create(*state, host.committed()->head); if (!builder) { diff --git a/apps/evo-world-clone/main.cpp b/apps/evo-world-clone/main.cpp index b1d3208..f6f7d72 100644 --- a/apps/evo-world-clone/main.cpp +++ b/apps/evo-world-clone/main.cpp @@ -10,14 +10,15 @@ // evo-world-clone check-store --world W --region R --pg-* ... --objects DIR // [--reserve-mib N] // evo-world-clone provision --world W --region R --opening -// development-v1|primitive-v1|cellular-v1|cellular-v2|cellular-v3 +// development-v1|primitive-v1|cellular-v1|cellular-v2|cellular-v3|cellular-v4 // --pg-* ... --objects DIR --build HEX [--commit HEX32] [--retain-build] // primitive-v1 also requires --frame N --source-id N, every --funding-*-* channel, // and one or more ordered --site X,Y values. -// cellular-v1, cellular-v2 and cellular-v3 also require --width-um N --height-um N +// cellular-v1 to cellular-v4 also require --width-um N --height-um N // --ambient-temperature-mk N and one or more ordered --patch X,Y,SOURCE,ENERGY,C,N,P,O values // plus a stable --commit HEX32. cellular-v2 is the same opening on rules 3 (ADR-0124: -// engulfment, detritus); cellular-v3 is it on rules 4 (ADR-0125: budding wildlife). +// engulfment, detritus); cellular-v3 is it on rules 4 (ADR-0125: budding wildlife); +// cellular-v4 on rules 5 (ADR-0128: offline freeze and resume). // primitive-v1 and cellular-v1/v2/v3 accept --life-allocator-start N // (ADR-0123): the world's life-identity allocator is created once at the operator-audited // start N; a later run leaves it untouched and refuses one that is below N. @@ -273,7 +274,7 @@ std::optional parse(int argc, char** argv) { o.reserve_mib = *n; else if (o.command == "provision" && flag == "--opening" && (value == "development-v1" || value == "primitive-v1" || value == "cellular-v1" || - value == "cellular-v2" || value == "cellular-v3")) + value == "cellular-v2" || value == "cellular-v3" || value == "cellular-v4")) o.opening = value; else if (o.command == "provision" && flag == "--frame" && n) o.primitive_frame = n; @@ -347,7 +348,7 @@ std::optional parse(int argc, char** argv) { if (cellular_options) return std::nullopt; } else if (o.opening == "cellular-v1" || o.opening == "cellular-v2" || - o.opening == "cellular-v3") { + o.opening == "cellular-v3" || o.opening == "cellular-v4") { const bool has_stock = std::ranges::any_of(o.cellular_patches, [](const auto& patch) { return patch.stock.energy.value != 0 || std::ranges::any_of(patch.stock.matter, @@ -456,8 +457,8 @@ std::vector probe_bytes() { int provision(const Options& o) { const bool primitive = o.opening == "primitive-v1"; - const bool cellular = - o.opening == "cellular-v1" || o.opening == "cellular-v2" || o.opening == "cellular-v3"; + const bool cellular = o.opening == "cellular-v1" || o.opening == "cellular-v2" || + o.opening == "cellular-v3" || o.opening == "cellular-v4"; const auto primitive_frame = o.primitive_frame.value_or(0); if ((primitive || cellular) && primitive_frame == 0) return 2; @@ -560,7 +561,8 @@ int provision(const Options& o) { auto opening = server::CellularLives::create( *primitive_opening, std::move(*habitat), {{cellular_width_um, cellular_height_um}, 0, cellular_temperature_mk}, - o.opening == "cellular-v3" ? server::CellularLivesProfile::budding + o.opening == "cellular-v4" ? server::CellularLivesProfile::presence + : o.opening == "cellular-v3" ? server::CellularLivesProfile::budding : o.opening == "cellular-v2" ? server::CellularLivesProfile::engulf : server::CellularLivesProfile::offers); if (!opening) { diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index e5d8e19..70e42b3 100644 --- a/deploy/kubernetes/region/dev-session-route/listener.yaml +++ b/deploy/kubernetes/region/dev-session-route/listener.yaml @@ -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-20261014T112750-39502:1791988070"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261014T115045-65696:1791989445"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/docs/adr/0128-cellular-offline-freeze-and-resume.md b/docs/adr/0128-cellular-offline-freeze-and-resume.md new file mode 100644 index 0000000..d001747 --- /dev/null +++ b/docs/adr/0128-cellular-offline-freeze-and-resume.md @@ -0,0 +1,80 @@ +# ADR-0128: Cellular offline freeze, linger and resume + +## Status + +Accepted engineering contract for M11.7 (2026-10-14), implementing ADR-0098 +decisions 4 and 5. Linger time and resume radius are **trial** values for 11.9. + +## Context + +A cellular region simulates while any player is present (M11.3). A player who +disconnects leaves an owned cell that keeps paying maintenance, and can starve or +be eaten, while others keep the region ticking: offline progress, which ADR-0098 +forbids. ADR-0098 decides the boundary: on logout or a detected disconnect the +organism freezes at once, lingers perceivable and vulnerable for a tunable time +(starting at 10 s), then is suspended out of the world; a reconnect during the +linger resumes in place, and a later resume uses the same spot or the nearest +valid one within a small radius, else the life stays suspended. + +## Decision + +### The frozen intention + +- `CellularStepIntent::frozen` (trace intent byte 13, bit 0) says the life does + nothing this tick. It is exclusive with movement, a target, engulfment and a bud. + Only owned lives may be frozen; wildlife never is. +- The server sets it for every owned life whose account holds no established + session, so the trace records the boundary and replay never consults sessions. + Carried actions of such an account are refused before the tick is built. +- The region step leaves a frozen cell exactly unchanged: no maintenance, movement, + intake, growth or heat. It cannot engulf, but it can be engulfed, and it occupies + space for contact and placement. + +### Presence (owner format 6, rules 5) + +Each life has a presence and the tick its freeze began: + +- **Active**: ordinary. A frozen intent makes it **lingering** from that tick. +- **Lingering**: frozen in place, perceivable and vulnerable. An unfrozen intent + (the player is back) makes it active again in place. After 200 ticks (10 s, + trial) of linger it becomes **suspended** at the end of that tick. +- **Suspended**: out of the world. It keeps its inventory (counted in the region's + conserved totals) but takes no part in the step, perception, replication, contact + or placement, and may hold any intent value only as `frozen`. An unfrozen intent + resumes it: at its own position if that is clear of every cell in the world, else + at the first clear spot found by trying the eight fixed directions at one, two and + three of its own extents from that position (trial radius). With none clear it + stays suspended and the tick reports `resume_blocked`. +- Wildlife is always active. A death decided in a tick is committed before a + presence change in that tick; a dead life never resumes. A mutation choice + reserved before the freeze still publishes at its tick (it was decided before the + boundary); the host admits no choice for a life that is not active. + +### Server loop + +- The region also ticks while any owned life is lingering, so a linger always + completes and nobody farms safety by leaving others' region empty. +- Suspended lives are skipped by replication and perception. + +### Versions + +- Owner format 6 adds presence (u8, 7 zero bytes) and the freeze tick (u64) to each + life record; rules 5 are rules 4 plus presence. Openings: `cellular-v4`. +- Version bundle v6 (`{5,6,1,1,1,2,1,2,1}`), normalized like v4 and v5 by schema + v38, which also admits it for format-3 birth traces. The trace format is + unchanged: the flag lives in a byte SQL does not parse. + +## Alternatives + +- **Remove a suspended life from the owner state:** rejected. A separate list + would need a new trace record for resumes and a second recovery path; keeping it + in the life set with a presence costs 24 trace bytes per tick per suspended life + and keeps one closure. +- **Let sessions drive presence directly in the owner:** rejected; replay must not + depend on live sessions. + +## Consequences + +Logging out is neither an escape nor a farm: the cell freezes, can still be eaten +for 10 seconds, then leaves the world without aging. Wildlife keeps living while a +region ticks. A region with only suspended players stops ticking, as before. diff --git a/docs/adr/README.md b/docs/adr/README.md index db6ab3d..bd08bdf 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -28,6 +28,7 @@ - [ADR-0125: Cellular budding and wildlife descendants](0125-cellular-budding-and-wildlife-descendants.md) - M11.5: a bud is v10 action kind 3, paid from the parent's reserve (ADR-0032 investment plus a 30 s provision), placed touching the parent, identified in a region namespace above 2^63, carrying the parent's genome; unowned wildlife driven by a pure deterministic controller whose intentions ride the trace. - [ADR-0126: PostgreSQL parameter bound for cellular traces](0126-postgres-parameter-bound-for-cellular-traces.md) - each query parameter may hold 4 MiB of text (was 4 KiB, ADR-0059), so every admitted cellular trace (64 ticks of 256 lives as hex bytea) reaches the database in one atomic publication. - [ADR-0127: Cellular permadeath and restart](0127-cellular-permadeath-and-restart.md) - M11.6: schema v37 marks a published life ended once (`end_cellular_lives`, recorded by the host after the death and again on recovery); one active life per account replaces one life per account, so a dead player starts a new primitive founder; a dead account's stale action no longer refuses the whole tick. +- [ADR-0128: Cellular offline freeze, linger and resume](0128-cellular-offline-freeze-and-resume.md) - M11.7: a frozen step intent (set for owned lives without a session) freezes biology; owner format 6 / rules 5 track presence: lingering for 200 ticks (10 s, trial) perceivable and vulnerable, then suspended out of the world without aging; an unfrozen intent resumes in place or at the nearest clear spot within three extents; bundle v6, schema v38. - [ADR-0058: Region durability contract](0058-region-durability-contract.md) - accepted M7.1 full checkpoint batches and explicit state closure; storage implementation follows. diff --git a/docs/engineering/M11_7_DELIVERY_PLAN.md b/docs/engineering/M11_7_DELIVERY_PLAN.md new file mode 100644 index 0000000..4f60de0 --- /dev/null +++ b/docs/engineering/M11_7_DELIVERY_PLAN.md @@ -0,0 +1,28 @@ +# M11.7: Freeze offline organisms and resume uniquely + +An offline player's cell freezes at once, lingers perceivable and vulnerable for +a trial 10 s, then leaves the world without aging until the player returns. The +engineering contract is +[ADR-0128](../adr/0128-cellular-offline-freeze-and-resume.md); the game rules are +ADR-0098 decisions 4 and 5. Client presentation is the maintainer's. + +## Segments + +| Segment | Affected modules | Acceptance evidence | +|---|---|---| +| 11.7a: frozen intention and presence | Region step, owner format 6 / rules 5, trace flag, bundle v6, schema v38, `cellular-v4` opening | A frozen cell pays nothing and stays put; linger returns to active; 200 frozen ticks suspend without aging; a suspended cell takes no step; exact restore; a stale lingering presence is refused; resume in place or within three extents; frozen intents only in rules 5, only for owned lives, carrying nothing else | +| 11.7b: server boundary | Server tick build, bridge, host | Owned lives without a session are frozen in the trace; their carried actions are refused; the region ticks while anyone lingers; suspended cells are not replicated or perceived; no mutation choice for a non-active life | + +## Required checks + +- Long offline intervals, repeated disconnects, death at the freeze boundary + (engulfed while lingering), duplicate resume, and wildlife continuing. +- Linux CI PostgreSQL evidence for the v6 bundle and `cellular-v4` provisioning. + +## Progress + +- 2026-10-14: 11.7a and 11.7b implemented. `rules_five_owner_freezes_lingers_suspends_and_resumes` + covers freeze, linger, return, suspension without aging, restore, the stale + presence refusal, a newborn on the suspended cell's spot and the relocated + resume; the trace round-trips the flag and refuses other flag values; rules 4 + refuse a frozen intent; `cellular-v4` provisions on the v6 bundle. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 2b87a34..9915acf 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -7423,3 +7423,25 @@ compares the recovered state. Executed locally: `postgres-check.sh --full` (WSL g++-14 Release, 488 s) passes; g++-14 `-Werror -Wshadow` and clang-tidy-19 on the host, lease store, tests and server main; clang-format 19.1.5. + +## 2026-10-14 — M11.7 offline freeze, linger and resume (CI pending) + +ADR-0128: the frozen step intent (trace intent byte 13, bit 0), owner format 6 / +rules 5 presence (active, lingering for 200 ticks, suspended) with resume in place +or within three extents, bundle v6, schema v38 and the `cellular-v4` opening. The +cellular server freezes owned lives whose account holds no session, refuses their +carried actions, keeps ticking while anyone lingers, and skips suspended cells in +replication and perception; the host refuses mutation choices for non-active lives. + +Executed locally: `postgres-check.sh --full` (WSL g++-14 Release, 492 s) passes with +schema v38; MSVC Debug 69/69, ASan cellular/budding/mutation/lineage 10/10, network +75/75, client-network 89/89; g++-14 +`-Werror -Wshadow` and clang-tidy-19 on the owner, region step, trace codec, host, +persistence, provisioner, tests and server main; clang-format 19.1.5. + +## 2026-10-14 — CI run 374 TSan failure (test-only use after free) + +Run 374 (e71147f) failed `checks (tsan)`: `cellular-lives-owner` read the bud +through a reference into the owner's previous state after the M11.5d controller +check advanced a tick. The test now reads the current life. ASan locally confirms +the fix; no product code was involved. diff --git a/include/evo/biology/cellular_step.hpp b/include/evo/biology/cellular_step.hpp index 570fa50..5b5ef62 100644 --- a/include/evo/biology/cellular_step.hpp +++ b/include/evo/biology/cellular_step.hpp @@ -15,6 +15,9 @@ struct CellularStepIntent { // ADR-0125: fund and place one wildlife bud after the tick's mutations (rules 4 only). // Exclusive with an intake target and with engulfment; the owner decides everything. bool bud{}; + // ADR-0128: the owner is offline; the cell does nothing this tick (no maintenance, + // movement, intake or heat) but can still be engulfed. Exclusive with every other field. + bool frozen{}; auto operator<=>(const CellularStepIntent&) const = default; }; diff --git a/include/evo/persistence/region_checkpoint.hpp b/include/evo/persistence/region_checkpoint.hpp index 523bc20..1a426c1 100644 --- a/include/evo/persistence/region_checkpoint.hpp +++ b/include/evo/persistence/region_checkpoint.hpp @@ -57,9 +57,12 @@ inline constexpr CellularVersionBundle cellular_v3_versions{2, 3, 1, 1, 1, 2, 1, inline constexpr CellularVersionBundle cellular_v4_versions{3, 4, 1, 1, 1, 2, 1, 2, 1}; // ADR-0125: rules 4 (budding wildlife) and owner envelope 5 (bud sequence, parents). inline constexpr CellularVersionBundle cellular_v5_versions{4, 5, 1, 1, 1, 2, 1, 2, 1}; +// ADR-0128: rules 5 (offline freeze and resume) and owner envelope 6 (presence). +inline constexpr CellularVersionBundle cellular_v6_versions{5, 6, 1, 1, 1, 2, 1, 2, 1}; // Bundles with genome revisions: the revision history profile and format-3 traces. [[nodiscard]] constexpr bool cellular_revision_bundle(const CellularVersionBundle& b) noexcept { - return b == cellular_v3_versions || b == cellular_v4_versions || b == cellular_v5_versions; + return b == cellular_v3_versions || b == cellular_v4_versions || b == cellular_v5_versions || + b == cellular_v6_versions; } // Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis. diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index 6175e62..7fc75b1 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -26,7 +26,19 @@ inline constexpr std::uint32_t cellular_lives_engulf_rules = 3; // life; rules 4 add funded budding of unowned wildlife on top of rules 3. inline constexpr std::uint32_t cellular_lives_bud_format = 5; inline constexpr std::uint32_t cellular_lives_bud_rules = 4; -// A bud's life, organism and event identity: 2^63 + region * 2^32 + sequence. A rules-4 +// ADR-0128: format 6 adds each life's presence and freeze tick; rules 5 are rules 4 plus +// the offline freeze, linger, suspension and resume. +inline constexpr std::uint32_t cellular_lives_presence_format = 6; +inline constexpr std::uint32_t cellular_lives_presence_rules = 5; +// Trial values (ADR-0128): ticks a frozen life lingers in the world (10 s at 50 ms), and +// how many of its own extents away a resume may look for a clear spot. +inline constexpr std::uint64_t cellular_linger_ticks = 200; +inline constexpr std::uint32_t cellular_resume_extents = 3; +enum class CellularPresence : std::uint8_t { + active, + lingering, + suspended +}; // A bud's life, organism and event identity: 2^63 + region * 2^32 + sequence. A rules-4 // owner refuses an allocated identity at or above 2^63, so the namespaces never meet. inline constexpr std::uint64_t cellular_bud_namespace = std::uint64_t{1} << 63U; inline constexpr std::uint64_t cellular_bud_max_region = (std::uint64_t{1} << 31U) - 1; @@ -60,6 +72,9 @@ struct CellularOwnedLife { accounting::Inventory reserve{}; CellularMutationProgress mutation{}; std::uint64_t parent_life{}; // Format 5: the budding parent; zero for a founder. + // Format 6 (ADR-0128): presence and the tick its freeze began (zero while active). + CellularPresence presence{CellularPresence::active}; + std::uint64_t frozen_since{}; auto operator<=>(const CellularOwnedLife&) const = default; }; struct CellularOwnedCorpse { @@ -119,12 +134,15 @@ struct CellularLifeTickFeedback { std::uint64_t prey_life{}; std::optional bud; // Rules 4, when this life asked to bud. std::uint64_t bud_life{}; + // Rules 5: presence after the tick, and whether a requested resume found no clear spot. + CellularPresence presence{CellularPresence::active}; + bool resume_blocked{}; auto operator<=>(const CellularLifeTickFeedback&) const = default; }; // Which owner version a new region starts on. Offers: format 2, rules 2 (the M11.3/11.4 // trial, upgraded by the no-tick migrations). Engulf: format 4, rules 3 (ADR-0124). -// Budding: format 5, rules 4 (ADR-0125). -enum class CellularLivesProfile : std::uint8_t { offers, engulf, budding }; +// Budding: format 5, rules 4 (ADR-0125). Presence: format 6, rules 5 (ADR-0128). +enum class CellularLivesProfile : std::uint8_t { offers, engulf, budding, presence }; struct CellularLivesConfig { biology::CellularArea area{}; std::uint64_t tick{}; diff --git a/migrations/0038_cellular_v6_presence_bundle.sql b/migrations/0038_cellular_v6_presence_bundle.sql new file mode 100644 index 0000000..f4deeaf --- /dev/null +++ b/migrations/0038_cellular_v6_presence_bundle.sql @@ -0,0 +1,126 @@ +-- M11.7, ADR-0128: admit the cellular-v6 bundle (rules 5: offline freeze, linger, +-- suspension and resume; owner envelope 6: presence). The frozen flag lives in a trace +-- intent byte SQL does not parse. Earlier bundles and committed rows keep their meaning. + +-- The v6 bundle shares v3's revision history profile and format-3 traces. Normalize it +-- to v3 for the existing parser chain, then report the real bundle. +ALTER FUNCTION evolution.parse_checkpoint_manifest(bytea) + RENAME TO parse_checkpoint_manifest_v37; + +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; + v3_bundle constant bytea := '\x020000000300000001000000010000000100000002000000010000000200000001000000'; + v6_bundle constant bytea := '\x050000000600000001000000010000000100000002000000010000000200000001000000'; +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) = v6_bundle + AND evolution.manifest_uint(m, 228, 4) = 0 + AND evolution.manifest_uint(m, 232, 4) = 4 + AND evolution.manifest_uint(m, 236, 4) = 1 THEN + r := evolution.parse_checkpoint_manifest_v37(overlay(m PLACING v3_bundle FROM 161 FOR 36)); + r.versions := v6_bundle; + RETURN r; + END IF; + RETURN evolution.parse_checkpoint_manifest_v37(m); +END $$; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC; + +-- Birth binding: v3 to v6 publications carry format-3 traces. Otherwise unchanged from +-- schema v36. +CREATE OR REPLACE FUNCTION evolution.cellular_births(p_trace bytea, p_manifest bytea) +RETURNS TABLE(account_id uuid, request_id evolution.u64, generation evolution.u64, + identity evolution.u64, born evolution.u64) +LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + revision boolean; + ticks numeric; + tick_index integer; + trace_format numeric; + tick_header_size integer; + intent_count numeric; + birth_count numeric; + mutation_count numeric; + off integer := 112; + account bytea; + previous_account bytea; + previous_request numeric; +BEGIN + revision := c.versions IN ( + '\x020000000300000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x030000000400000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x040000000500000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x050000000600000001000000010000000100000002000000010000000200000001000000'::bytea); + trace_format := evolution.manifest_uint(p_trace, 8, 4); + tick_header_size := CASE trace_format WHEN 2 THEN 8 WHEN 3 THEN 16 ELSE 0 END; + IF c.profile <> 4 OR c.commit_sequence = 0 OR p_trace IS NULL + OR octet_length(p_trace) <> c.trace_bytes OR sha256(p_trace) <> c.trace_sha256 + OR substring(p_trace FROM 1 FOR 8) <> '\x45564c4342543031' + OR tick_header_size = 0 + OR (revision AND trace_format <> 3) + OR (NOT revision AND trace_format <> 2) + OR evolution.manifest_uint(p_trace, 12, 4) <> 4 + OR evolution.manifest_uint(p_trace, 16, 8) <> c.world_id + OR evolution.manifest_uint(p_trace, 24, 8) <> c.region_id + OR evolution.manifest_uint(p_trace, 32, 8) <> c.frame_id + OR encode(substring(p_trace FROM 41 FOR 16), 'hex')::uuid <> c.predecessor_commit + OR substring(p_trace FROM 57 FOR 32) <> c.predecessor_digest + OR evolution.manifest_uint(p_trace, 88, 8) <> c.begin_tick + OR evolution.manifest_uint(p_trace, 96, 8) <> c.end_tick THEN + RAISE EXCEPTION 'invalid cellular birth trace binding' USING ERRCODE = '22023'; + END IF; + ticks := c.end_tick - c.begin_tick; + IF ticks < 1 OR ticks > 64 OR evolution.manifest_uint(p_trace, 104, 4) <> ticks + OR evolution.manifest_uint(p_trace, 108, 4) <> 0 THEN + RAISE EXCEPTION 'invalid cellular birth trace range' USING ERRCODE = '22023'; + END IF; + FOR tick_index IN 0 .. ticks::integer - 1 LOOP + IF off + tick_header_size > octet_length(p_trace) THEN + RAISE EXCEPTION 'truncated cellular tick header' USING ERRCODE = '22023'; + END IF; + intent_count := evolution.manifest_uint(p_trace, off, 4); + birth_count := evolution.manifest_uint(p_trace, off + 4, 4); + mutation_count := 0; + IF trace_format = 3 THEN + mutation_count := evolution.manifest_uint(p_trace, off + 8, 4); + IF evolution.manifest_uint(p_trace, off + 12, 4) <> 0 THEN + RAISE EXCEPTION 'invalid cellular tick reserved word' USING ERRCODE = '22023'; + END IF; + END IF; + IF intent_count > 256 OR birth_count > 256 OR mutation_count > 256 + OR off + tick_header_size + intent_count * 24 + birth_count * 40 + + mutation_count * 40 > octet_length(p_trace) THEN + RAISE EXCEPTION 'invalid cellular tick counts' USING ERRCODE = '22023'; + END IF; + off := off + tick_header_size + intent_count::integer * 24; + previous_account := ''::bytea; + previous_request := -1; + FOR birth_index IN 0 .. birth_count::integer - 1 LOOP + account := substring(p_trace FROM off + 1 FOR 16); + account_id := encode(account, 'hex')::uuid; + request_id := evolution.manifest_uint(p_trace, off + 16, 8); + generation := evolution.manifest_uint(p_trace, off + 24, 8); + identity := evolution.manifest_uint(p_trace, off + 32, 8); + born := c.begin_tick + tick_index + 1; + IF account_id = '00000000-0000-0000-0000-000000000000' OR request_id = 0 + OR generation = 0 OR identity = 0 + OR (account, request_id) <= (previous_account, previous_request) THEN + RAISE EXCEPTION 'invalid cellular birth record' USING ERRCODE = '22023'; + END IF; + previous_account := account; + previous_request := request_id; + off := off + 40; + RETURN NEXT; + END LOOP; + off := off + mutation_count::integer * 40; + END LOOP; + IF off <> octet_length(p_trace) THEN + RAISE EXCEPTION 'trailing cellular trace bytes' USING ERRCODE = '22023'; + END IF; +END $$; + +INSERT INTO evolution.schema_migrations(version, sha256) VALUES (38, :'migration_sha_38'); diff --git a/migrations/apply.sql b/migrations/apply.sql index 5446607..245fdb1 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -113,6 +113,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v34' || ',35:' || :'migration_sha_35' AS history_v35 \gset SELECT :'history_v35' || ',36:' || :'migration_sha_36' AS history_v36 \gset SELECT :'history_v36' || ',37:' || :'migration_sha_37' AS history_v37 \gset + SELECT :'history_v37' || ',38:' || :'migration_sha_38' AS history_v38 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -128,8 +129,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v34' AS at_v34, :'history' = :'history_v35' AS at_v35, :'history' = :'history_v36' AS at_v36, - :'history' = :'history_v37' AS at_v37 \gset - \if :at_v37 + :'history' = :'history_v37' AS at_v37, + :'history' = :'history_v38' AS at_v38 \gset + \if :at_v38 + \elif :at_v37 \elif :at_v36 \elif :at_v35 \elif :at_v34 @@ -497,7 +500,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 34 AS at_v34, coalesce(max(version), 0) = 35 AS at_v35, coalesce(max(version), 0) = 36 AS at_v36, - coalesce(max(version), 0) = 37 AS at_v37 + coalesce(max(version), 0) = 37 AS at_v37, + coalesce(max(version), 0) = 38 AS at_v38 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -513,6 +517,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v25 \ir 0026_cellular_profile_migration.sql \ir 0027_cellular_v3_migration.sql @@ -526,6 +531,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v26 \ir 0027_cellular_v3_migration.sql \ir 0028_cellular_v3_trace_bounds.sql @@ -538,6 +544,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v27 \ir 0028_cellular_v3_trace_bounds.sql \ir 0029_cellular_mutation_reservations.sql @@ -549,6 +556,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v28 \ir 0029_cellular_mutation_reservations.sql \ir 0030_cellular_birth_publication_binding.sql @@ -559,6 +567,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v29 \ir 0030_cellular_birth_publication_binding.sql \ir 0031_fix_cellular_birth_publication_record.sql @@ -568,6 +577,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v30 \ir 0031_fix_cellular_birth_publication_record.sql \ir 0032_fix_cellular_v3_manifest_normalization.sql @@ -576,6 +586,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v31 \ir 0032_fix_cellular_v3_manifest_normalization.sql \ir 0033_fix_cellular_action_tick_offset.sql @@ -583,29 +594,37 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v32 \ir 0033_fix_cellular_action_tick_offset.sql \ir 0034_cellular_v4_engulf_bundle.sql \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v33 \ir 0034_cellular_v4_engulf_bundle.sql \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v34 \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v35 \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v36 \ir 0037_cellular_life_endings.sql + \ir 0038_cellular_v6_presence_bundle.sql \elif :at_v37 + \ir 0038_cellular_v6_presence_bundle.sql +\elif :at_v38 \else - \echo 'Unknown or changed migration history after v37' + \echo 'Unknown or changed migration history after v38' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; \endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes diff --git a/schemas/cellular-lives-v1.md b/schemas/cellular-lives-v1.md index 3b88c74..e558c4d 100644 --- a/schemas/cellular-lives-v1.md +++ b/schemas/cellular-lives-v1.md @@ -99,3 +99,13 @@ canonical re-encoding. Empty profile-4 genesis has zero living and corpse records, an empty lineage archive, and an explicit finite habitat/nursery opening. Owner provisioning does not add player lives; they require a separate durable birth operation. + +### Format 6 (rules 5, ADR-0128) + +Magic `AEVCLV06`, format 6, rules 5: format 5 plus presence. Each life record is +504 bytes: the format 5 record followed by a u8 presence (0 active, 1 lingering, +2 suspended), seven zero bytes and the u64 tick its freeze began. An active life +has freeze tick 0; a lingering one a freeze tick at most the checkpoint tick and +less than 200 ticks before it; a suspended one a non-zero freeze tick at most the +checkpoint tick. Wildlife is always active. Suspended lives keep their inventory +in the region's conserved totals. diff --git a/src/biology/cellular_region_step.cpp b/src/biology/cellular_region_step.cpp index 5f96b2b..23bc2ea 100644 --- a/src/biology/cellular_region_step.cpp +++ b/src/biology/cellular_region_step.cpp @@ -64,6 +64,10 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, for (const auto& life : lives) { if (life.life_id == 0) return std::unexpected{CellularRegionStepError::invalid_life_id}; + if (life.intent.frozen && + (life.intent.movement != CellularIntent{} || life.intent.intake_target || + life.intent.engulf || life.intent.bud)) + return std::unexpected{CellularRegionStepError::invalid_intent}; if (rules.engulf_and_detritus && (life.membrane_um == 0 || life.source == 0 || (life.intent.engulf && life.intent.intake_target))) return std::unexpected{CellularRegionStepError::invalid_intent}; @@ -92,6 +96,18 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, if (std::ranges::any_of(life->heat.matter, [](const auto& channel) { return channel.value != 0; })) return std::unexpected{CellularRegionStepError::invalid_heat}; + if (life->intent.frozen) { + // ADR-0128: a frozen cell is unchanged and pays nothing; it can still be prey. + CellularStepCandidate frozen{}; + frozen.begin_tick = begin_tick; + frozen.end_tick = begin_tick + 1; + frozen.position = life->position; + frozen.reserve_after = life->reserve; + frozen.heat_after = life->heat; + candidate.lives.push_back({life->life_id, frozen}); + survivors.push_back(life); + continue; + } auto intent = life->intent; const auto target = intent.intake_target; intent.intake_target.reset(); diff --git a/src/persistence/cellular_checkpoint_store.cpp b/src/persistence/cellular_checkpoint_store.cpp index ab62fc8..7f6b6f1 100644 --- a/src/persistence/cellular_checkpoint_store.cpp +++ b/src/persistence/cellular_checkpoint_store.cpp @@ -163,6 +163,11 @@ provision_cellular_region(Postgres& owner, const FilesystemObjectStore& objects, // ADR-0125: a rules-4 region starts on the v5 bundle with genome revisions. manifest->cellular_versions = cellular_v5_versions; manifest->history_profile = cellular_revision_history_profile; + } else if (manifest && opening.format_version() == server::cellular_lives_presence_format && + opening.rules_version() == server::cellular_lives_presence_rules) { + // ADR-0128: a rules-5 region starts on the v6 bundle with genome revisions. + manifest->cellular_versions = cellular_v6_versions; + manifest->history_profile = cellular_revision_history_profile; } else if (manifest && (opening.format_version() != server::cellular_lives_legacy_format || opening.rules_version() != 1)) return std::unexpected{failure(PublicationError::candidate)}; diff --git a/src/persistence/region_checkpoint.cpp b/src/persistence/region_checkpoint.cpp index 05d085f..236f2e7 100644 --- a/src/persistence/region_checkpoint.cpp +++ b/src/persistence/region_checkpoint.cpp @@ -71,7 +71,8 @@ bool structural(const CheckpointManifest& m) noexcept { m.cellular_versions != cellular_v2_versions && m.cellular_versions != cellular_v3_versions && m.cellular_versions != cellular_v4_versions && - m.cellular_versions != cellular_v5_versions) || + m.cellular_versions != cellular_v5_versions && + m.cellular_versions != cellular_v6_versions) || (cellular && m.versions != environmental_v1_versions)) return false; if (primitive && (m.manifest_version != 2 || m.tick_microseconds != 50000 || @@ -165,7 +166,8 @@ bool supported(const CheckpointManifest& m) noexcept { m.cellular_versions == cellular_v2_versions || m.cellular_versions == cellular_v3_versions || m.cellular_versions == cellular_v4_versions || - m.cellular_versions == cellular_v5_versions) && + m.cellular_versions == cellular_v5_versions || + m.cellular_versions == cellular_v6_versions) && m.versions == environmental_v1_versions && m.tick_microseconds == 50000 && m.rng_streams == 0 && m.durability == DurabilityPolicy::single_volume_development; } diff --git a/src/server/cellular_region_host.cpp b/src/server/cellular_region_host.cpp index 11f0088..ad6c491 100644 --- a/src/server/cellular_region_host.cpp +++ b/src/server/cellular_region_host.cpp @@ -469,7 +469,8 @@ CellularRegionHost::select_mutation(const persistence::Uuid& account, std::uint6 const auto life = std::ranges::find(state_->lives(), account, &CellularOwnedLife::account); if (life == state_->lives().end() || life->identity.life != input.life_id || input.event_index == 0 || life->mutation.event_index != input.event_index || - life->mutation.offer_tick != input.offer_tick || input.offer_tick >= tick) + life->mutation.offer_tick != input.offer_tick || input.offer_tick >= tick || + life->presence != CellularPresence::active) // ADR-0128: only an active life chooses. return {invalid, 0, {}}; const auto& offer = life->mutation.offer; if (!offer || !std::ranges::any_of(offer->candidates, [&](const auto& candidate) { diff --git a/src/server/lifecycle/cellular_batch.cpp b/src/server/lifecycle/cellular_batch.cpp index 589ee75..3ec0eeb 100644 --- a/src/server/lifecycle/cellular_batch.cpp +++ b/src/server/lifecycle/cellular_batch.cpp @@ -37,7 +37,9 @@ bool valid_intent(const CellularLifeIntent& life) { return life.life_id != 0 && step.movement.x >= -movement_limit && step.movement.x <= movement_limit && step.movement.y >= -movement_limit && step.movement.y <= movement_limit && !(step.engulf && step.intake_target) && - !(step.bud && (step.intake_target || step.engulf)); + !(step.bud && (step.intake_target || step.engulf)) && + !(step.frozen && (step.movement != biology::CellularIntent{} || step.intake_target || + step.engulf || step.bud)); } bool valid_ticks(std::span ticks) { std::set identities; @@ -142,7 +144,8 @@ void put_intent(std::vector& out, const CellularLifeIntent& life) : life.intent.engulf ? 2 : life.intent.bud ? 3 : 0); - put(out, 0, 3); + out.push_back(life.intent.frozen ? 1 : 0); // Flags (ADR-0128): bit 0 frozen. + put(out, 0, 2); put(out, life.intent.intake_target ? life.intent.intake_target->x_um : 0, 4); put(out, life.intent.intake_target ? life.intent.intake_target->y_um : 0, 4); } @@ -291,7 +294,7 @@ decode_cellular_batch(std::span bytes) { step.lives.reserve(static_cast(count)); for (std::uint64_t i = 0; i < count; ++i) { const auto record = bytes.subspan(offset, cellular_batch_intent_bytes); - if (record[12] > 3 || !all_zero(record.subspan(13, 3))) + if (record[12] > 3 || record[13] > 1 || !all_zero(record.subspan(14, 2))) return std::unexpected{CellularBatchError::format}; CellularLifeIntent life; life.life_id = get(record, 0, 8); @@ -308,6 +311,7 @@ decode_cellular_batch(std::span bytes) { } life.intent.engulf = record[12] == 2; // ADR-0124 target kind. life.intent.bud = record[12] == 3; // ADR-0125. + life.intent.frozen = record[13] == 1; // ADR-0128. if (!valid_intent(life) || (!step.lives.empty() && step.lives.back().life_id >= life.life_id)) return std::unexpected{CellularBatchError::format}; diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index a9a2c65..04e0cba 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -17,6 +17,7 @@ constexpr std::uint64_t cellular_lives_v2_magic = 0x3230564C43564541ULL; // AEVC constexpr std::uint64_t cellular_lives_v3_magic = 0x3330564C43564541ULL; // AEVCLV03 constexpr std::uint64_t cellular_lives_v4_magic = 0x3430564C43564541ULL; // AEVCLV04 constexpr std::uint64_t cellular_lives_v5_magic = 0x3530564C43564541ULL; // AEVCLV05 +constexpr std::uint64_t cellular_lives_v6_magic = 0x3630564C43564541ULL; // AEVCLV06 constexpr std::size_t cellular_lives_header_bytes = 212; constexpr std::size_t cellular_site_bytes = 8; constexpr std::size_t cellular_life_v1_bytes = 168; @@ -29,6 +30,8 @@ constexpr std::size_t cellular_corpse_v4_bytes = cellular_corpse_bytes + 16; constexpr std::size_t cellular_lives_v5_header_bytes = cellular_lives_header_bytes + 8; constexpr std::size_t cellular_life_v5_bytes = cellular_life_v2_bytes + 8; constexpr std::size_t cellular_corpse_v5_bytes = cellular_corpse_v4_bytes + 8; +// Format 6 (ADR-0128): each life adds presence (1), 7 zero bytes and its freeze tick (8). +constexpr std::size_t cellular_life_v6_bytes = cellular_life_v5_bytes + 16; std::uint64_t checksum(std::span bytes) noexcept { std::uint64_t value = 14695981039346656037ULL; @@ -196,7 +199,8 @@ bud_position(const CellularOwnedLife& parent, std::uint32_t parent_extent, std:: static_cast(y)}; bool clear = true; for (std::size_t i = 0; i < lives.size() && clear; ++i) - clear = separated(candidate.x_um, lives[i].position.x_um, bud_extent, extents[i]) || + clear = lives[i].presence == CellularPresence::suspended || + separated(candidate.x_um, lives[i].position.x_um, bud_extent, extents[i]) || separated(candidate.y_um, lives[i].position.y_um, bud_extent, extents[i]); if (clear) return std::optional{candidate}; @@ -204,6 +208,53 @@ bud_position(const CellularOwnedLife& parent, std::uint32_t parent_extent, std:: return std::optional{}; } +// ADR-0128 resume: its own position if clear of every cell in the world, else the first +// clear spot at one, two or three of its extents in the eight fixed directions. +std::expected, CellularLivesError> +resume_position(const CellularOwnedLife& life, std::uint32_t extent, + std::span lives, const biology::LineageArchive& archive, + const CellularLivesConfig& config) { + constexpr std::array, 8> directions{ + {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}}; + if (extent == 0 || extent > config.area.width_um || extent > config.area.height_um) + return std::optional{}; + std::vector> present; + for (const auto& other : lives) { + if (other.presence == CellularPresence::suspended || + other.identity.life == life.identity.life) + continue; + const auto budget = budget_for(archive, other, config.ambient_temperature_millikelvin); + if (!budget) + return std::unexpected{budget.error()}; + present.emplace_back(&other, budget->phenotype.extent); + } + const auto clear = [&](std::int64_t x, std::int64_t y) { + if (x < 0 || y < 0 || static_cast(x) > config.area.width_um - extent || + static_cast(y) > config.area.height_um - extent) + return false; + return std::ranges::all_of(present, [&](const auto& entry) { + const auto& [other, other_extent] = entry; + return separated(static_cast(x), other->position.x_um, extent, + other_extent) || + separated(static_cast(y), other->position.y_um, extent, + other_extent); + }); + }; + const auto x0 = static_cast(life.position.x_um); + const auto y0 = static_cast(life.position.y_um); + if (clear(x0, y0)) + return std::optional{life.position}; + for (std::uint32_t ring = 1; ring <= cellular_resume_extents; ++ring) + for (const auto& [dx, dy] : directions) { + const auto step = static_cast(ring) * extent; + if (clear(x0 + dx * step, y0 + dy * step)) + return std::optional{ + biology::CellularPosition{static_cast(x0 + dx * step), + static_cast(y0 + dy * step)}}; + } + return std::optional{}; +} + std::expected sum_state(accounting::Inventory nursery, accounting::Inventory heat, const biology::CellularHabitat& habitat, std::span lives, @@ -229,7 +280,8 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame, std::span corpses, const biology::LineageArchive& archive, accounting::Inventory nursery, accounting::Inventory heat, accounting::Inventory opening_total, bool detritus_rules = false, - bool bud_rules = false, std::uint64_t next_bud_sequence = 1) { + bool bud_rules = false, std::uint64_t next_bud_sequence = 1, + bool presence_rules = false) { // A bud's identity lies in this region's namespace below the next sequence; anything // else is an allocated identity, below the namespace (ADR-0125). const auto bud_identity = [&](std::uint64_t identity) noexcept { @@ -291,6 +343,17 @@ validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame, const auto& life = lives[i]; // Founders are owned; buds are unowned wildlife (rules 4) and never earn offers. const bool wildlife = life.parent_life != 0; + // ADR-0128: only owned lives leave; a lingering life is within its linger time. + const bool presence_valid = + life.presence == CellularPresence::active + ? life.frozen_since == 0 + : presence_rules && !wildlife && life.frozen_since != 0 && + life.frozen_since <= config.tick && + (life.presence == CellularPresence::suspended || + (life.presence == CellularPresence::lingering && + config.tick - life.frozen_since < cellular_linger_ticks)); + if (!presence_valid) + return std::unexpected{CellularLivesError::invalid_life}; if ((life.account == LifeAccount{}) != wildlife || life.identity.life == 0 || life.identity.organism == 0 || life.identity.genome == 0 || life.identity.event == 0 || life.identity.born.value == 0 || life.identity.born.value > config.tick || @@ -472,7 +535,8 @@ CellularLives::create(const PrimitiveLives& opening, const auto world = nursery_config.world; const auto region = nursery_config.region; const auto frame = nursery_config.frame; - const bool budding = profile == CellularLivesProfile::budding; + const bool presence = profile == CellularLivesProfile::presence; + const bool budding = profile == CellularLivesProfile::budding || presence; const bool engulf = profile == CellularLivesProfile::engulf || budding; if (engulf) archive.upgrade_to_revision_format(); // Rules 3+ regions carry genome revisions. @@ -480,12 +544,14 @@ CellularLives::create(const PrimitiveLives& opening, std::move(habitat), std::move(lives), std::vector{}, archive, nursery, heat, opening_total, *current, - budding ? cellular_lives_bud_format - : engulf ? cellular_lives_engulf_format - : cellular_lives_format, - budding ? cellular_lives_bud_rules - : engulf ? cellular_lives_engulf_rules - : cellular_lives_rules); + presence ? cellular_lives_presence_format + : budding ? cellular_lives_bud_format + : engulf ? cellular_lives_engulf_format + : cellular_lives_format, + presence ? cellular_lives_presence_rules + : budding ? cellular_lives_bud_rules + : engulf ? cellular_lives_engulf_rules + : cellular_lives_rules); return std::unique_ptr{new CellularLives{std::move(state)}}; } @@ -550,11 +616,13 @@ std::vector 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 bool parents = state_->format_version == cellular_lives_bud_format; + const bool parents = state_->format_version >= cellular_lives_bud_format; + const bool presence = state_->format_version >= cellular_lives_presence_format; const auto life_bytes = state_->format_version == cellular_lives_legacy_format ? cellular_life_v1_bytes - : parents ? cellular_life_v5_bytes - : cellular_life_v2_bytes; + : presence ? cellular_life_v6_bytes + : parents ? cellular_life_v5_bytes + : cellular_life_v2_bytes; const bool causes = state_->format_version >= cellular_lives_engulf_format; const auto corpse_bytes = parents ? cellular_corpse_v5_bytes : causes ? cellular_corpse_v4_bytes @@ -579,6 +647,7 @@ std::vector CellularLives::snapshot() const { : state_->format_version == cellular_lives_revision_format ? cellular_lives_v3_magic : state_->format_version == cellular_lives_engulf_format ? cellular_lives_v4_magic : state_->format_version == cellular_lives_bud_format ? cellular_lives_v5_magic + : state_->format_version == cellular_lives_presence_format ? cellular_lives_v6_magic : cellular_lives_v2_magic; out.put(magic); out.put(state_->format_version, 4); @@ -655,6 +724,11 @@ std::vector CellularLives::snapshot() const { } if (parents) out.put(life.parent_life); + if (presence) { + out.put(static_cast(life.presence), 1); + out.zeros(7); + out.put(life.frozen_since); + } } for (const auto& corpse : state_->corpses) { out.put(corpse.life_id); @@ -801,6 +875,8 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c static_cast(site.y_um)}; bool occupied = false; for (const auto& living : state_->lives) { + if (living.presence == CellularPresence::suspended) + continue; // Out of the world (ADR-0128). const auto living_budget = budget_for(state_->archive, living, state_->config.ambient_temperature_millikelvin); if (!living_budget) @@ -852,11 +928,12 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c state_->region, state_->frame); if (!habitat) return std::unexpected{CellularLivesError::habitat}; - const auto current = validate_state( - state_->world, state_->region, state_->frame, state_->config, nursery_config, **habitat, - lives, state_->corpses, archive, nursery, heat, state_->opening_total, - state_->rules_version >= cellular_lives_engulf_rules, - state_->rules_version == cellular_lives_bud_rules, state_->next_bud_sequence); + const auto current = + validate_state(state_->world, state_->region, state_->frame, state_->config, nursery_config, + **habitat, lives, state_->corpses, archive, nursery, heat, + state_->opening_total, state_->rules_version >= cellular_lives_engulf_rules, + state_->rules_version >= cellular_lives_bud_rules, state_->next_bud_sequence, + state_->rules_version >= cellular_lives_presence_rules); if (!current) return std::unexpected{current.error()}; @@ -887,9 +964,13 @@ CellularLives::restore(std::span bytes, std::uint64_t world, const bool offer_version = magic == cellular_lives_v2_magic && format_version == cellular_lives_format && rules_version == cellular_lives_rules; - const bool bud_version = magic == cellular_lives_v5_magic && - format_version == cellular_lives_bud_format && - rules_version == cellular_lives_bud_rules; + const bool presence_version = magic == cellular_lives_v6_magic && + format_version == cellular_lives_presence_format && + rules_version == cellular_lives_presence_rules; + // Formats 5 and 6 carry the bud sequence and parent lives (rules 4 and 5). + const bool bud_version = presence_version || (magic == cellular_lives_v5_magic && + format_version == cellular_lives_bud_format && + rules_version == cellular_lives_bud_rules); // Formats 4 and 5 record death causes and leave detritus (rules 3 and 4). const bool engulf_version = bud_version || (magic == cellular_lives_v4_magic && format_version == cellular_lives_engulf_format && @@ -931,9 +1012,10 @@ CellularLives::restore(std::span bytes, std::uint64_t world, const auto nursery = in.inventory(); const auto heat = in.inventory(); const auto next_bud_sequence = bud_version ? in.get() : std::uint64_t{1}; - const auto life_bytes = legacy ? cellular_life_v1_bytes - : bud_version ? cellular_life_v5_bytes - : cellular_life_v2_bytes; + const auto life_bytes = legacy ? cellular_life_v1_bytes + : presence_version ? cellular_life_v6_bytes + : bud_version ? cellular_life_v5_bytes + : cellular_life_v2_bytes; const auto corpse_bytes = bud_version ? cellular_corpse_v5_bytes : engulf_version ? cellular_corpse_v4_bytes : cellular_corpse_bytes; @@ -1015,6 +1097,14 @@ CellularLives::restore(std::span bytes, std::uint64_t world, } if (bud_version) life.parent_life = in.get(); + if (presence_version) { + const auto presence = in.get(1); + const auto padding = in.get(7); + life.frozen_since = in.get(); + if (presence > static_cast(CellularPresence::suspended) || padding != 0) + return std::unexpected{CellularLivesError::noncanonical}; + life.presence = static_cast(presence); + } lives.push_back(life); } @@ -1096,9 +1186,10 @@ CellularLives::restore(std::span bytes, std::uint64_t world, 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, engulf_version, bud_version, next_bud_sequence); + const auto current = + validate_state(saved_world, saved_region, saved_frame, config, nursery_config, **habitat, + lives, corpses, *archive, nursery, heat, opening_total, engulf_version, + bud_version, next_bud_sequence, presence_version); if (!current) return std::unexpected{current.error()}; @@ -1139,12 +1230,19 @@ CellularLives::advance_tick_with_mutations(std::span i return std::unexpected{CellularLivesError::version}; // Rules 4 keep rules 3 (engulfment, detritus) and add budding (ADR-0125). const bool engulf_rules = state_->rules_version >= cellular_lives_engulf_rules; - const bool bud_rules = state_->rules_version == cellular_lives_bud_rules; - for (const auto& ordered_intent : ordered) { - const auto& intent = ordered_intent.intent; + const bool bud_rules = state_->rules_version >= cellular_lives_bud_rules; + const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules; + for (std::size_t i = 0; i < ordered.size(); ++i) { + const auto& intent = ordered[i].intent; // Below rules 4 a bud is ignored, as engulfment is below rules 3 (ADR-0124/0125). if (intent.bud && (intent.intake_target || intent.engulf)) return std::unexpected{CellularLivesError::invalid_intents}; + // ADR-0128: only an owned life of a rules-5 region freezes, and a frozen intent + // carries nothing else. + if (intent.frozen && (!presence_rules || state_->lives[i].account == LifeAccount{} || + intent.movement != biology::CellularIntent{} || + intent.intake_target || intent.engulf || intent.bud)) + return std::unexpected{CellularLivesError::invalid_intents}; } for (std::size_t i = 0; i < selections.size(); ++i) { const auto& selection = selections[i]; @@ -1179,6 +1277,8 @@ CellularLives::advance_tick_with_mutations(std::span i inputs.reserve(state_->lives.size()); for (std::size_t i = 0; i < state_->lives.size(); ++i) { const auto& life = state_->lives[i]; + if (life.presence == CellularPresence::suspended) + continue; // Out of the world: no step, no contact (ADR-0128). const auto budget = budget_for(state_->archive, life, state_->config.ambient_temperature_millikelvin); if (!budget) @@ -1338,6 +1438,10 @@ CellularLives::advance_tick_with_mutations(std::span i bud_results.push_back({request.life_id, 0, CellularBudResult::life_died}); continue; } + if (parent->presence == CellularPresence::suspended) { + bud_results.push_back({request.life_id, 0, CellularBudResult::not_able}); + continue; // Out of the world (ADR-0128). + } const auto temperature = state_->config.ambient_temperature_millikelvin; const auto genome = next_archive.find(parent->identity.genome); const auto parent_budget = budget_for(next_archive, *parent, temperature); @@ -1390,6 +1494,44 @@ CellularLives::advance_tick_with_mutations(std::span i } std::ranges::sort(next_lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; }); + // Rules 5 presence (ADR-0128), after deaths, mutations and buds: a death in this tick + // is final before any presence change. + std::vector resume_blocked; + if (presence_rules) { + for (auto& life : next_lives) { + const auto request = std::ranges::lower_bound(ordered, life.identity.life, {}, + &CellularLifeIntent::life_id); + if (request == ordered.end() || request->life_id != life.identity.life) + continue; // Born this tick: active. + const bool frozen = request->intent.frozen; + if (life.presence == CellularPresence::active && frozen) { + life.presence = CellularPresence::lingering; + life.frozen_since = proposal->end_tick; + } else if (life.presence == CellularPresence::lingering && !frozen) { + life.presence = CellularPresence::active; + life.frozen_since = 0; + } else if (life.presence == CellularPresence::lingering && + proposal->end_tick - life.frozen_since >= cellular_linger_ticks) { + life.presence = CellularPresence::suspended; + } else if (life.presence == CellularPresence::suspended && !frozen) { + const auto budget = + budget_for(next_archive, life, state_->config.ambient_temperature_millikelvin); + if (!budget) + return std::unexpected{budget.error()}; + const auto spot = resume_position(life, budget->phenotype.extent, next_lives, + next_archive, state_->config); + if (!spot) + return std::unexpected{spot.error()}; + if (*spot) { + life.position = **spot; + life.presence = CellularPresence::active; + life.frozen_since = 0; + } else { + resume_blocked.push_back(life.identity.life); + } + } + } + } std::ranges::sort(next_corpses, {}, &CellularOwnedCorpse::organism); if (proposal->heat_released.value > std::numeric_limits::max() - next_heat.energy.value) @@ -1420,7 +1562,7 @@ CellularLives::advance_tick_with_mutations(std::span i state_->config.ambient_temperature_millikelvin}, state_->nursery_config, **next_habitat, next_lives, next_corpses, next_archive, state_->nursery, next_heat, state_->opening_total, - engulf_rules, bud_rules, next_bud_sequence); + engulf_rules, bud_rules, next_bud_sequence, presence_rules); if (!total) return std::unexpected{total.error()}; @@ -1441,7 +1583,8 @@ CellularLives::advance_tick_with_mutations(std::span i feedback.push_back({result.life_id, proposal->end_tick, result.candidate.reserve_after, result.candidate.maintenance_cost, result.candidate.movement_cost, result.candidate.movement_status, result.candidate.intake_status, - result.engulf, result.prey_id, std::nullopt, 0}); + result.engulf, result.prey_id, std::nullopt, 0, + CellularPresence::active, false}); if (const auto bud = std::ranges::find(bud_results, result.life_id, &CellularBudExecution::parent_life); bud != bud_results.end()) { @@ -1451,6 +1594,32 @@ CellularLives::advance_tick_with_mutations(std::span i if (input == ordered.end() || input->life_id != result.life_id) return std::unexpected{CellularLivesError::invalid_intents}; } + // ADR-0128: each surviving life reports its presence after the tick; a suspended life, + // which took no step, reports its unchanged reserve and any blocked resume. + for (const auto& life : next->lives) { + auto entry = + std::ranges::find(feedback, life.identity.life, &CellularLifeTickFeedback::life_id); + if (entry == feedback.end()) { + feedback.push_back({life.identity.life, + proposal->end_tick, + life.reserve, + {}, + {}, + biology::CellularMovementStatus::not_requested, + biology::CellularIntakeStatus::not_requested, + biology::CellularEngulfStatus::not_requested, + 0, + std::nullopt, + 0, + life.presence, + false}); + entry = std::prev(feedback.end()); + } + entry->presence = life.presence; + entry->resume_blocked = + std::ranges::find(resume_blocked, life.identity.life) != resume_blocked.end(); + } + std::ranges::sort(feedback, {}, &CellularLifeTickFeedback::life_id); state_.swap(next); last_tick_feedback_ = std::move(feedback); return CellularTickExecution{std::move(*proposal), std::move(mutation_results), diff --git a/tests/cellular_lives_tests.cpp b/tests/cellular_lives_tests.cpp index b2493c7..17724c4 100644 --- a/tests/cellular_lives_tests.cpp +++ b/tests/cellular_lives_tests.cpp @@ -668,6 +668,11 @@ void rules_four_owner_buds_wildlife() { feeding_bud.bud = true; CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, feeding_bud}}).error() == CellularLivesError::invalid_intents); + // Freezing is rules 5 (ADR-0128). + evo::biology::CellularStepIntent frozen{}; + frozen.frozen = true; + CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, frozen}}).error() == + CellularLivesError::invalid_intents); const auto parent_genome = owner.lives().front().identity.genome; std::optional budded; @@ -721,8 +726,10 @@ void rules_four_owner_buds_wildlife() { CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, feed}, controlled->front()})); // Wildlife feeds like any cell but never earns a mutation offer. - const auto child_x = child.position.x_um / 1000; - const auto child_y = child.position.y_um / 1000; + // Read the bud from the current state: the tick above replaced the one `child` named. + const auto& wildlife = owner.lives()[1]; + const auto child_x = wildlife.position.x_um / 1000 * 1000; + const auto child_y = wildlife.position.y_um / 1000 * 1000; evo::biology::CellularStepIntent child_feed{}; child_feed.intake_target = evo::biology::CellularPatchAddress{ static_cast(child_x), static_cast(child_y)}; @@ -743,6 +750,108 @@ void rules_four_owner_buds_wildlife() { refresh_checksum(rewound); CHECK(!CellularLives::restore(rewound, 93, 1, 7, owner.tick())); } +// ADR-0128: an offline owned life freezes, lingers 200 ticks, is suspended without aging, +// survives restore, and resumes; a newborn on its spot makes it resume nearby. +void rules_five_owner_freezes_lingers_suspends_and_resumes() { + auto primitive = PrimitiveLives::create({94, 1, 7, 17, founder_price(3), {{0, 0}, {1'500, 0}}}); + CHECK(primitive); + LifeRequest request{}; + request.account.back() = 1; + request.action = 1; + CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}})); + request.account.back() = 2; + CHECK((*primitive)->spawn(request, {2, 102, 202, 302, {1}})); + auto habitat = evo::biology::CellularHabitat::create({94, 1, 7, 3'000, 2'000, {}}); + CHECK(habitat); + auto created = + CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 1, 293'150}, + CellularLivesProfile::presence); + CHECK(created); + auto owner = std::move(*created); + CHECK(owner->format_version() == cellular_lives_presence_format && + owner->rules_version() == cellular_lives_presence_rules); + + evo::biology::CellularStepIntent frozen{}; + frozen.frozen = true; + // The trace keeps the flag (intent byte 13) and refuses it with anything else. + CellularBatch frozen_batch; + frozen_batch.header = {94, 1, 7, {}, {}, owner->tick(), owner->tick() + 1}; + frozen_batch.header.predecessor.fill(1); + frozen_batch.header.predecessor_digest.fill(2); + frozen_batch.ticks.push_back({{{1, frozen}, {2, {}}}, {}, {}}); + const auto frozen_bytes = encode_cellular_batch(frozen_batch); + CHECK(frozen_bytes); + CHECK(decode_cellular_batch(*frozen_bytes) == frozen_batch); + auto flag_two = *frozen_bytes; + flag_two[cellular_batch_header_bytes + cellular_batch_tick_header_bytes + 13] = 2; + CHECK(!decode_cellular_batch(flag_two)); + // A frozen intent carries nothing else. + auto moving = frozen; + moving.movement = {100, 0}; + CHECK(owner->advance_tick(std::array{CellularLifeIntent{1, moving}, CellularLifeIntent{2, {}}}) + .error() == CellularLivesError::invalid_intents); + + const auto before = owner->lives()[0]; + CHECK( + owner->advance_tick(std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}})); + const auto first_frozen = owner->tick(); + CHECK(owner->lives()[0].presence == CellularPresence::lingering && + owner->lives()[0].frozen_since == first_frozen && + owner->lives()[0].reserve == before.reserve && + owner->lives()[0].position == before.position && + owner->lives()[1].reserve.energy.value < before.reserve.energy.value); + // Back within the linger: active again in place. + CHECK(owner->advance_tick(std::array{CellularLifeIntent{1, {}}, CellularLifeIntent{2, {}}})); + CHECK(owner->lives()[0].presence == CellularPresence::active && + owner->lives()[0].frozen_since == 0); + + // Frozen through the whole linger: suspended after 200 ticks, without aging. + CHECK( + owner->advance_tick(std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}})); + const auto parked = owner->lives()[0]; + for (std::uint64_t tick = 1; tick <= cellular_linger_ticks; ++tick) { + CHECK(owner->lives()[0].presence == CellularPresence::lingering); + CHECK(owner->advance_tick( + std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}})); + CHECK(owner->current_total() == owner->opening_total()); + } + CHECK(owner->lives()[0].presence == CellularPresence::suspended && + owner->lives()[0].reserve == parked.reserve && + owner->lives()[0].position == parked.position && + owner->last_tick_feedback()[0].presence == CellularPresence::suspended); + // Suspended lives stay out of the step while frozen. + for (int tick = 0; tick < 5; ++tick) + CHECK(owner->advance_tick( + std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}})); + CHECK(owner->lives()[0].reserve == parked.reserve); + + const auto saved = owner->snapshot(); + auto recovered = CellularLives::restore(saved, 94, 1, 7, owner->tick()); + CHECK(recovered && (*recovered)->snapshot() == saved && + std::ranges::equal((*recovered)->lives(), owner->lives())); + // A lingering presence older than the linger is refused on restore. + auto stale = saved; + const auto presence_at = std::size_t{220} + std::size_t{2} * 8 + 480 + 8; + stale[presence_at] = static_cast(CellularPresence::lingering); + refresh_checksum(stale); + CHECK(!CellularLives::restore(stale, 94, 1, 7, owner->tick())); + + // A newborn takes the suspended cell's spot (placement ignores suspended cells)... + LifeRequest third{}; + third.account.back() = 3; + third.action = 1; + auto born = owner->birth_candidate(third, {50, 50, 50, 50, {owner->tick()}}); + CHECK(born); + owner = std::move(*born); + CHECK(owner->lives().size() == 3 && owner->lives()[2].position == parked.position); + // ...so the resume relocates within three extents, clear of everyone. + CHECK(owner->advance_tick(std::array{CellularLifeIntent{1, {}}, CellularLifeIntent{2, {}}, + CellularLifeIntent{50, {}}})); + const auto& resumed = owner->lives()[0]; + CHECK(resumed.presence == CellularPresence::active && resumed.frozen_since == 0 && + resumed.position != parked.position && !owner->last_tick_feedback()[0].resume_blocked); + CHECK(owner->current_total() == owner->opening_total()); +} } // namespace int main() { @@ -753,6 +862,7 @@ int main() { owner_advances_and_closes_death_atomically(); rules_three_owner_resolves_engulf_and_detritus(); rules_four_owner_buds_wildlife(); + rules_five_owner_freezes_lingers_suspends_and_resumes(); std::puts( "PASS cellular lives: feeding, tick ownership, terminal closure, rules 3, budding"); } catch (const std::exception& error) { diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index 1fdbc71..8fde30a 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -212,7 +212,7 @@ void upgrade_across_migration_and_barrier() { " 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," - "25,26,27,28,29,30,31,32,33,34,35,36,37"); + "25,26,27,28,29,30,31,32,33,34,35,36,37,38"); CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND " "c.confrelid = 'evolution.region_commits'::regclass)::text " "FROM pg_catalog.pg_constraint c WHERE c.conrelid = " diff --git a/tests/region_store_tests.cpp b/tests/region_store_tests.cpp index 0725808..ff1cded 100644 --- a/tests/region_store_tests.cpp +++ b/tests/region_store_tests.cpp @@ -535,6 +535,25 @@ void cellular_v3_provisioning_uses_the_budding_bundle() { manifest->history_profile == cellular_revision_history_profile); } +// ADR-0128: cellular-v4 is the rules-5 presence opening on the v6 bundle. +void cellular_v4_provisioning_uses_the_presence_bundle() { + const ServerRegion r{{9769, 1}, fresh("cellular-v4-provision-9769")}; + const std::string build(64, 'e'); + const std::string commit(32, 'd'); + const std::string patch = "3000,3000,2,1000,1000,1000,1000,1000"; + int code = -1; + const auto first = provision_cellular(r, "9769", "cellular-v4", build, commit, patch, code); + CHECK(code == 0 && has(first, "provisioned world=9769 region=1 sequence=0 tick=0")); + const auto older = provision_cellular(r, "9769", "cellular-v3", build, commit, patch, code); + CHECK(code == 4); + auto db = owner(); + const auto head = load_region_checkpoint(*db, r.key, 5s); + CHECK(head); + const auto manifest = decode_manifest(head->manifest); + CHECK(manifest && manifest->cellular_versions == cellular_v6_versions && + manifest->history_profile == cellular_revision_history_profile); +} + void cellular_provisioning_survives_a_build_promotion() { const ServerRegion r{{9761, 1}, fresh("cellular-provision-9761")}; const auto run = [&](const std::string& build, const std::string& commit, @@ -567,6 +586,7 @@ void run_region_store_tests() { cellular_provisioning_survives_a_build_promotion(); cellular_v2_provisioning_uses_the_engulf_bundle(); cellular_v3_provisioning_uses_the_budding_bundle(); + cellular_v4_provisioning_uses_the_presence_bundle(); full_volumes_publish_nothing(); failing_writes_leave_nothing(); check_store_qualifies_the_stores(); diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index 74a5034..32b2457 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -122,7 +122,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,24,25,26,27,28,29,30,31,32,33,34,35,36,37 +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,26,27,28,29,30,31,32,33,34,35,36,37,38 # 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%% *}" @@ -143,7 +143,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")" = 37: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,26,27,28,29,30,31,32,33,34,35,36,37 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 38: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,26,27,28,29,30,31,32,33,34,35,36,37,38 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. @@ -197,7 +197,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,24,25,26,27,28,29,30,31,32,33,34,35,36,37 +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,26,27,28,29,30,31,32,33,34,35,36,37,38 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 phase permission-audit @@ -250,9 +250,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.claim_account_control bash "$root/tools/migrate-postgres.sh" # Restored configuration passes the audit again. phase checksum-drift # 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=38 WHERE version=37' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=39 WHERE version=38' 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=37 WHERE version=38" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=38 WHERE version=39" 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" diff --git a/tools/migrate-postgres.sh b/tools/migrate-postgres.sh index e14ceea..ba0d258 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -86,6 +86,8 @@ digest_36="$(sha256sum "$root/migrations/0036_cellular_v5_budding_bundle.sql")" digest_36="${digest_36%% *}" digest_37="$(sha256sum "$root/migrations/0037_cellular_life_endings.sql")" digest_37="${digest_37%% *}" +digest_38="$(sha256sum "$root/migrations/0038_cellular_v6_presence_bundle.sql")" +digest_38="${digest_38%% *}" 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" \ @@ -116,5 +118,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_35=$digest_35" \ --set="migration_sha_36=$digest_36" \ --set="migration_sha_37=$digest_37" \ + --set="migration_sha_38=$digest_38" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"