diff --git a/apps/evo-client/cellular_controls.hpp b/apps/evo-client/cellular_controls.hpp index 141c484..36be1fa 100644 --- a/apps/evo-client/cellular_controls.hpp +++ b/apps/evo-client/cellular_controls.hpp @@ -40,6 +40,20 @@ steer_cellular(const CellularControls& controls, client::Intention intention, static_cast(own->voxel.y) * 1'000'000 + static_cast(own->y.value); const double extent = static_cast(own->phenotype.extent); bool target_has_energy = false; + // ADR-0136 (v11): deposits feed on contact, so no target; slow near any that + // holds something (within 1 mm of its disc). + for (const auto& d : perception->deposits) { + if (std::ranges::all_of(d.amount_codes, [](auto code) { return code == 0; })) + continue; + const double cx = static_cast(d.x_um), cy = static_cast(d.y_um); + const double gx = std::max({x - cx, cx - x - extent, 0.0}); + const double gy = std::max({y - cy, cy - y - extent, 0.0}); + if (controls.slow_near_food && + std::hypot(gx, gy) <= 1000.0 + static_cast(d.radius_um) && + own->phenotype.movement_speed > 0) + scale = + std::min(scale, 500.0 / static_cast(own->phenotype.movement_speed)); + } for (const auto& p : perception->patches) { if (p.energy_pj == 0 && std::ranges::all_of(p.matter_fg, [](auto v) { return v == 0; })) diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index a13c85a..aad47b0 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -469,6 +470,20 @@ int main(int argc, char** argv) try { int drawn_organisms = -1; evo::client_app::CellularScene scene; // Rebuilt each frame in cellular play. evo::client_app::CellHeadings headings; // Where each drawn cell last moved. + // ADR-0136: deposits seen in the last view (to notice a bubble that ran out) and the + // pops still fading, in world coordinates with their start time. + struct SeenDeposit { + double x_mm{}, y_mm{}; + std::uint32_t radius_um{}; + int channel{}; + }; + struct LivePop { + SeenDeposit at; + std::chrono::steady_clock::time_point start; + }; + std::map seen_deposits; + std::uint64_t seen_deposit_tick{}; + std::vector live_pops; bool scene_active = false; evo::client_app::PanelActions actions; (*app)->set_overlay([&] { @@ -726,6 +741,8 @@ int main(int argc, char** argv) try { // 2026-10-16 microscope view: in cellular play, patches and cells are a scene the // panels draw as granules and living cells; elsewhere organisms stay rectangles. scene.patches.clear(); + scene.deposits.clear(); + scene.pops.clear(); scene.cells.clear(); scene_active = false; const auto* cellular_remote = host.session(); @@ -755,6 +772,66 @@ int main(int argc, char** argv) try { p.seed = (static_cast(patch.x_um) << 32U) ^ patch.y_um; scene.patches.push_back(p); } + // ADR-0136 (v11): pools and bubbles, centred; a vanished bubble pops. + if (const auto* perception = cellular_remote->cellular_perception()) { + const auto now_pop = std::chrono::steady_clock::now(); + std::map current; + for (const auto& d : perception->deposits) { + std::array stock{}; + for (std::size_t c = 0; c < stock.size(); ++c) + stock.at(c) = evo::network::deposit_amount_value(d.amount_codes.at(c)); + int channel = 0; + for (std::size_t c = 1; c < stock.size(); ++c) + if (stock.at(c) > stock.at(static_cast(channel))) + channel = static_cast(c); + const SeenDeposit seen{static_cast(d.x_um) / 1000, + static_cast(d.y_um) / 1000, d.radius_um, + channel}; + current[d.id] = seen; + const auto centre = camera->world_to_screen({seen.x_mm, seen.y_mm}); + const auto edge = camera->world_to_screen( + {seen.x_mm + static_cast(d.radius_um) / 1000, seen.y_mm}); + if (!centre || !edge) + continue; + evo::client_app::SceneDeposit drawn; + drawn.x = static_cast(centre->x); + drawn.y = static_cast(centre->y); + drawn.radius = static_cast(std::abs(edge->x - centre->x)); + drawn.stock = stock; + drawn.pool = d.shape == evo::network::CellularDepositShape::pool; + drawn.drained = d.drained; + drawn.stale = !fresh; + drawn.seed = d.id; + scene.deposits.push_back(drawn); + } + // A bubble absent from a newer view while its old spot is still in + // sight ran out (or left the sensor's edge, which a pop also suits). + if (perception->tick != seen_deposit_tick) { + for (const auto& [id, old] : seen_deposits) + if (!current.contains(id) && live_pops.size() < 256) + live_pops.push_back({old, now_pop}); + seen_deposits = std::move(current); + seen_deposit_tick = perception->tick; + } + constexpr auto pop_life = std::chrono::milliseconds{350}; + std::erase_if(live_pops, [&](const LivePop& pop) { + return now_pop - pop.start > pop_life; + }); + for (const auto& pop : live_pops) { + const auto centre = camera->world_to_screen({pop.at.x_mm, pop.at.y_mm}); + const auto edge = camera->world_to_screen( + {pop.at.x_mm + static_cast(pop.at.radius_um) / 1000, + pop.at.y_mm}); + if (!centre || !edge) + continue; + const auto age = std::chrono::duration(now_pop - pop.start).count() / + std::chrono::duration(pop_life).count(); + scene.pops.push_back({static_cast(centre->x), + static_cast(centre->y), + static_cast(std::abs(edge->x - centre->x)), + age, pop.at.channel}); + } + } const auto own = cellular_remote->cellular_play().life(); if (orgs) for (const auto& cell : orgs->cells()) { diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index 8abd595..1ed5891 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -773,6 +773,79 @@ void draw_patch(ImDrawList& list, const ScenePatch& p) { } } } +// The channel a deposit mostly holds (by its share of the largest amount): its colour. +std::size_t dominant_channel(const std::array& stock) { + std::size_t best = 0; + for (std::size_t c = 1; c < stock.size(); ++c) + if (stock.at(c) > stock.at(best)) + best = c; + return best; +} +// ADR-0136: a bubble is a translucent circle in its nutrient's colour, sized by what it +// holds (never below its contact disc), and pulsing while something drains it. +void draw_bubble(ImDrawList& list, const SceneDeposit& d, float time) { + const auto channel = dominant_channel(d.stock); + const auto total = static_cast(std::max(1, d.stock.at(channel))); + const float scale = + std::clamp(0.7F + 0.12F * static_cast(std::log10(total)), 0.8F, 2.2F); + float r = std::max(d.radius * scale * 0.5F, 2.5F); + if (d.drained) + r *= + 1.0F + 0.25F * (0.5F + 0.5F * std::sin(time * 18.0F + static_cast(d.seed % 7U))); + auto color = nutrient_colors.at(channel); + const auto alpha = static_cast(d.stale ? 90 : (d.drained ? 255 : 200)); + color = (color & 0x00FFFFFFU) | (alpha << IM_COL32_A_SHIFT); + list.AddCircleFilled({d.x, d.y}, r, (color & 0x00FFFFFFU) | ((alpha / 3) << IM_COL32_A_SHIFT)); + list.AddCircle({d.x, d.y}, r, color, 0, std::max(1.0F, r * 0.18F)); + list.AddCircleFilled({d.x - r * 0.35F, d.y - r * 0.35F}, std::max(0.8F, r * 0.22F), + IM_COL32(255, 255, 255, d.stale ? 40 : 110)); +} +// A pool is a puddle: a seeded, wobbling outline around its contact disc, granules inside +// in its nutrients' colours, fewer as it drains. +void draw_pool(ImDrawList& list, const SceneDeposit& d, float time) { + const float r = std::max(d.radius, 8.0F); + constexpr int points = 28; + for (int i = 0; i < points; ++i) { + const float a = 6.2832F * static_cast(i) / points; + const auto key = d.seed * 7919U + static_cast(i); + const float wobble = 0.82F + 0.3F * unit_of(key) + 0.04F * std::sin(time * 0.7F + a * 3); + list.PathLineTo({d.x + std::cos(a) * r * wobble, d.y + std::sin(a) * r * wobble}); + } + list.PathFillConvex(IM_COL32(52, 40, 58, d.stale ? 50 : 110)); + for (int i = 0; i < points; ++i) { + const float a = 6.2832F * static_cast(i) / points; + const auto key = d.seed * 7919U + static_cast(i); + const float wobble = 0.82F + 0.3F * unit_of(key) + 0.04F * std::sin(time * 0.7F + a * 3); + list.PathLineTo({d.x + std::cos(a) * r * wobble, d.y + std::sin(a) * r * wobble}); + } + list.PathStroke(IM_COL32(120, 96, 130, d.drained ? 220 : 140), ImDrawFlags_Closed, 1.5F); + const float grain = std::clamp(r * 0.05F, 1.5F, 5.0F); + for (std::size_t channel = 0; channel < d.stock.size(); ++channel) { + const auto amount = d.stock.at(channel); + if (amount == 0) + continue; + const auto count = std::clamp( + static_cast(2.0 + 3.0 * std::log10(static_cast(amount) / 1.0e5)), 1, 40); + for (int i = 0; i < count; ++i) { + const auto key = d.seed * 131U + channel * 977U + static_cast(i); + const float a = unit_of(key) * 6.2832F, dist = std::sqrt(unit_of(key + 3U)) * r * 0.75F; + auto color = nutrient_colors.at(channel); + if (d.stale) + color = (color & 0x00FFFFFFU) | (110U << IM_COL32_A_SHIFT); + list.AddCircleFilled({d.x + std::cos(a) * dist, d.y + std::sin(a) * dist}, + grain * (0.7F + 0.6F * unit_of(key + 5U)), color); + } + } +} +void draw_pop(ImDrawList& list, const ScenePop& p) { + const float t = std::clamp(p.age, 0.0F, 1.0F); + const auto alpha = static_cast(220.0F * (1.0F - t)); + const auto color = + (nutrient_colors.at(static_cast(std::clamp(p.channel, 0, 4))) & 0x00FFFFFFU) | + (alpha << IM_COL32_A_SHIFT); + list.AddCircle({p.x, p.y}, std::max(p.radius, 3.0F) * (0.6F + 1.6F * t), color, 0, + 1.5F * (1.0F - t) + 0.5F); +} // The eyepiece: everything outside a rounded viewport is masked (a thick rounded stroke // covers the corners) and a vignette darkens toward the rim. Zooming out of the cellular // plane will later shrink this frame. @@ -823,6 +896,14 @@ void draw_scene(const PanelView& v) { const auto time = static_cast(ImGui::GetTime()); for (const auto& patch : v.cellular_scene->patches) draw_patch(list, patch); + for (const auto& deposit : v.cellular_scene->deposits) + if (deposit.pool) + draw_pool(list, deposit, time); + for (const auto& deposit : v.cellular_scene->deposits) + if (!deposit.pool) + draw_bubble(list, deposit, time); + for (const auto& pop : v.cellular_scene->pops) + draw_pop(list, pop); for (const auto& cell : v.cellular_scene->cells) draw_cell(list, cell, time); draw_eyepiece(list, ImGui::GetIO().DisplaySize); @@ -1081,7 +1162,23 @@ void hud_notes(const PanelView& v, FormBuffers& form, PanelActions& a, bool comp ImGui::BeginDisabled(!active); if (v.cellular_feed_target && ImGui::Button("Stop feeding", {-1, 0})) a.stop_feeding = true; - if (const auto* p = v.cellular_perception) { + if (const auto* seen = v.cellular_perception; seen && !seen->deposits.empty()) { + // ADR-0136: pools and bubbles feed on contact; a summary, not a target list. + std::size_t pools = 0; + std::array totals{}; + for (const auto& d : seen->deposits) { + pools += d.shape == network::CellularDepositShape::pool ? 1 : 0; + for (std::size_t c = 0; c < totals.size(); ++c) + totals.at(c) += network::deposit_amount_value(d.amount_codes.at(c)); + } + ImGui::Text("%zu bubbles, %zu pools in range", seen->deposits.size() - pools, pools); + ImGui::TextColored(nutrient(0), "%s", energy_text(totals[0]).c_str()); + for (std::size_t c = 1; c < totals.size(); ++c) { + ImGui::SameLine(); + ImGui::TextColored(nutrient(c), "%s", mass_text(totals.at(c)).c_str()); + } + disabled_wrapped("Swim through bubbles to collect them; pools feed slowly."); + } else if (const auto* p = v.cellular_perception) { if (p->patches.empty()) disabled_wrapped("No food is visible within sensor range."); for (const auto& patch : p->patches) { diff --git a/apps/evo-client/panels.hpp b/apps/evo-client/panels.hpp index 6a1cca2..7387f4b 100644 --- a/apps/evo-client/panels.hpp +++ b/apps/evo-client/panels.hpp @@ -42,8 +42,22 @@ struct ScenePatch { bool target{}, stale{}; std::uint64_t seed{}; }; +// ADR-0136 (v11): a pool (a puddle) or a bubble, centred, with its contact radius in pixels. +struct SceneDeposit { + float x{}, y{}, radius{}; + std::array stock{}; // Approximate (v11 amount codes), same channels. + bool pool{}, drained{}, stale{}; + std::uint64_t seed{}; +}; +// A bubble that just ran out: an expanding, fading ring for a moment. +struct ScenePop { + float x{}, y{}, radius{}, age{}; // Age 0..1 over the pop's life. + int channel{}; +}; struct CellularScene { std::vector patches; + std::vector deposits; + std::vector pops; std::vector cells; }; // Notice layout (logical pixels); the window name is the prefix plus the notice id. diff --git a/apps/evo-client/remote_session.hpp b/apps/evo-client/remote_session.hpp index d59495c..ee8e272 100644 --- a/apps/evo-client/remote_session.hpp +++ b/apps/evo-client/remote_session.hpp @@ -499,7 +499,7 @@ class RemoteSession { return false; client::RegionSessionClientConfig config; if (cellular_trial_) - config.protocol_version = network::session_protocol_v10; + config.protocol_version = network::session_protocol_v11; // ADR-0136 deposits. const auto route = routes_.find(target_region_); config.transport = route != routes_.end() ? route->second : transport_; if (ticket_) { // A handoff: the ticket replaces a grant, once. diff --git a/apps/evo-server/cellular_bridge.hpp b/apps/evo-server/cellular_bridge.hpp index da00434..75833e9 100644 --- a/apps/evo-server/cellular_bridge.hpp +++ b/apps/evo-server/cellular_bridge.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include namespace evo::server_app { @@ -259,7 +260,59 @@ class CellularBridge { } view.diagnostics = diagnostics; view.patches.reserve(perceived->size()); + // ADR-0136 (rules 8): pools and bubbles go out as v11 deposits, the nearest 512 to + // the cell, by ascending id; `drained` marks a stock that fell since last tick. + std::vector> near; + const auto centre_x = static_cast(life.position.x_um); + const auto centre_y = static_cast(life.position.y_um); for (const auto& patch : *perceived) { + if (patch.kind == biology::CellularDepositKind::patch) + continue; + network::CellularPerceivedDeposit deposit; + deposit.id = patch.id; + deposit.x_um = patch.address.x_um; + deposit.y_um = patch.address.y_um; + deposit.radius_um = + static_cast(std::min(patch.radius_um, 65'535)); + deposit.shape = patch.kind == biology::CellularDepositKind::pool + ? network::CellularDepositShape::pool + : network::CellularDepositShape::bubble; + deposit.amount_codes[0] = + network::deposit_amount_code(patch.available.energy.value); + for (std::size_t c = 0; c < patch.available.matter.size(); ++c) + deposit.amount_codes.at(c + 1) = + network::deposit_amount_code(patch.available.matter[c].value); + const auto before = deposit_stock_.find(patch.id); + deposit.drained = before != deposit_stock_.end() && + (patch.available.energy.value < before->second.energy.value || + std::ranges::any_of( + std::array{0, 1, 2, 3}, + [&](int c) { + const auto i = static_cast(c); + return patch.available.matter.at(i).value < + before->second.matter.at(i).value; + })); + seen_stock_[patch.id] = patch.available; + const auto dx = std::int64_t{patch.address.x_um} - centre_x; + const auto dy = std::int64_t{patch.address.y_um} - centre_y; + near.emplace_back(static_cast(dx * dx + dy * dy), deposit); + } + if (near.size() > network::max_cellular_perceived_deposits) { + std::ranges::nth_element( + near, + near.begin() + + static_cast(network::max_cellular_perceived_deposits), + [](const auto& a, const auto& b) { + return std::pair{a.first, a.second.id} < std::pair{b.first, b.second.id}; + }); + near.resize(network::max_cellular_perceived_deposits); + } + for (const auto& [distance, deposit] : near) + view.deposits.push_back(deposit); + std::ranges::sort(view.deposits, {}, &network::CellularPerceivedDeposit::id); + for (const auto& patch : *perceived) { + if (patch.kind != biology::CellularDepositKind::patch) + continue; network::CellularPerceivedPatch visible; visible.x_um = patch.address.x_um; visible.y_um = patch.address.y_um; @@ -276,6 +329,9 @@ class CellularBridge { &server::CellularOwnedLife::account) == state.lives().end(); }); announce_endings(state); + // What each deposit held when last seen, for next tick's `drained` flags. + deposit_stock_ = std::move(seen_stock_); + seen_stock_.clear(); replicated_tick_ = tick; } // ADR-0129: an owned life seen at the last replication and now a corpse is announced to @@ -404,6 +460,8 @@ class CellularBridge { }; std::vector offers_; // Last offer view sent to each owner. std::map> bud_costs_; // By genome. + // ADR-0136: deposit stocks seen at the last replicated tick, and this tick's. + std::map deposit_stock_, seen_stock_; std::vector> owned_; // At last replication. bool shutdown_{}; }; diff --git a/apps/evo-world-clone/main.cpp b/apps/evo-world-clone/main.cpp index a98f1b3..8155b33 100644 --- a/apps/evo-world-clone/main.cpp +++ b/apps/evo-world-clone/main.cpp @@ -10,7 +10,7 @@ // 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 to cellular-v6 +// development-v1|primitive-v1|cellular-v1 to cellular-v7 // --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. @@ -21,6 +21,10 @@ // cellular-v4 on rules 5 (ADR-0128: offline freeze and resume). // cellular-v5 on rules 6 (2026-10-15 balance: finer mutations, cheaper construction). // cellular-v6 on rules 7 (ADR-0137: percentage mutations, skilled budding, twins). +// cellular-v7 on rules 8 (ADR-0136 step A: pools and bubbles fed by contact) takes no +// --patch: one or more --pool X,Y,RADIUS,SOURCE,ENERGY,C,N,P,O (centres, any micrometre) +// and/or --motes COUNT,SOURCE,ENERGY,C,N,P,O (bubbles per channel amount, scattered +// from the --commit bytes, so a genesis is reproducible). // 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. @@ -111,6 +115,8 @@ struct Options { std::vector primitive_sites; std::optional cellular_width_um, cellular_height_um, cellular_temperature_mk; std::vector cellular_patches; + std::vector cellular_pools; // cellular-v7 + std::optional cellular_motes; // cellular-v7 std::optional life_allocator_start; std::optional build; bool retain_build{}; @@ -167,6 +173,55 @@ std::optional cellular_patch(std::string_view text) { result.stock.matter[i].value = fields[4 + i]; return result; } +// Comma-separated unsigned fields, exactly N of them. +template +std::optional> fields_of(std::string_view text) { + std::array fields{}; + for (std::size_t i = 0; i < N; ++i) { + const auto comma = text.find(','); + const auto field = i + 1 == N ? text : text.substr(0, comma); + if (field.empty() || (i + 1 != N && comma == std::string_view::npos)) + return std::nullopt; + const auto [end, error] = + std::from_chars(field.data(), field.data() + field.size(), fields.at(i)); + if (error != std::errc{} || end != field.data() + field.size()) + return std::nullopt; + if (i + 1 != N) + text.remove_prefix(comma + 1); + else if (comma != std::string_view::npos) + return std::nullopt; + } + return fields; +} +// --pool X,Y,RADIUS,SOURCE,ENERGY,C,N,P,O +std::optional cellular_pool(std::string_view text) { + const auto f = fields_of<9>(text); + if (!f || (*f)[0] > std::numeric_limits::max() || + (*f)[1] > std::numeric_limits::max() || + (*f)[2] > biology::max_cellular_deposit_radius_um) + return std::nullopt; + biology::CellularPatch pool{}; + pool.address = {static_cast((*f)[0]), static_cast((*f)[1])}; + pool.radius_um = static_cast((*f)[2]); + pool.source = (*f)[3]; + pool.stock.energy.value = (*f)[4]; + for (std::size_t i = 0; i < pool.stock.matter.size(); ++i) + pool.stock.matter.at(i).value = (*f)[5 + i]; + return pool; +} +// --motes COUNT,SOURCE,ENERGY,C,N,P,O +std::optional cellular_motes(std::string_view text) { + const auto f = fields_of<7>(text); + if (!f || (*f)[0] > biology::max_cellular_patches) + return std::nullopt; + biology::CellularMoteField field{}; + field.count = static_cast((*f)[0]); + field.source = (*f)[1]; + field.amount.energy.value = (*f)[2]; + for (std::size_t i = 0; i < field.amount.matter.size(); ++i) + field.amount.matter.at(i).value = (*f)[3 + i]; + return field; +} template std::optional> hex(std::string_view text) { if (text.size() != N * 2) return std::nullopt; @@ -278,7 +333,7 @@ std::optional parse(int argc, char** argv) { else if (o.command == "provision" && flag == "--opening" && (value == "development-v1" || value == "primitive-v1" || value == "cellular-v1" || value == "cellular-v2" || value == "cellular-v3" || value == "cellular-v4" || - value == "cellular-v5" || value == "cellular-v6")) + value == "cellular-v5" || value == "cellular-v6" || value == "cellular-v7")) o.opening = value; else if (o.command == "provision" && flag == "--frame" && n) o.primitive_frame = n; @@ -313,6 +368,16 @@ std::optional parse(int argc, char** argv) { if (!parsed || o.cellular_patches.size() == biology::max_cellular_patches) return std::nullopt; o.cellular_patches.push_back(*parsed); + } else if (o.command == "provision" && flag == "--pool") { + const auto parsed = cellular_pool(value); + if (!parsed || o.cellular_pools.size() == biology::max_cellular_patches) + return std::nullopt; + o.cellular_pools.push_back(*parsed); + } else if (o.command == "provision" && flag == "--motes") { + const auto parsed = cellular_motes(value); + if (!parsed || o.cellular_motes) + return std::nullopt; + o.cellular_motes = parsed; } else if (o.command == "provision" && flag == "--life-allocator-start" && n && *n > 0 && *n < std::numeric_limits::max()) o.life_allocator_start = n; @@ -343,7 +408,8 @@ std::optional parse(int argc, char** argv) { std::ranges::any_of(o.primitive_funding, [](const auto& v) { return v.has_value(); }) || !o.primitive_sites.empty(); const bool cellular_options = o.cellular_width_um || o.cellular_height_um || - o.cellular_temperature_mk || !o.cellular_patches.empty(); + o.cellular_temperature_mk || !o.cellular_patches.empty() || + !o.cellular_pools.empty() || o.cellular_motes; if (o.opening == "primitive-v1") { if (!o.primitive_frame || *o.primitive_frame == 0 || !o.primitive_source || *o.primitive_source == 0 || o.primitive_sites.empty() || @@ -352,9 +418,22 @@ std::optional parse(int argc, char** argv) { return std::nullopt; if (cellular_options) return std::nullopt; + } else if (o.opening == "cellular-v7") { + // Pools and bubbles only: square patches belong to the earlier openings. + if (!o.primitive_frame || *o.primitive_frame == 0 || !o.primitive_source || + *o.primitive_source == 0 || o.primitive_sites.empty() || + !std::ranges::all_of(o.primitive_funding, + [](const auto& v) { return v.has_value(); }) || + !o.cellular_width_um || !o.cellular_height_um || !o.cellular_temperature_mk || + !o.cellular_patches.empty() || + (o.cellular_pools.empty() && (!o.cellular_motes || o.cellular_motes->count == 0)) || + !o.commit) + return std::nullopt; } else if (o.opening == "cellular-v1" || o.opening == "cellular-v2" || o.opening == "cellular-v3" || o.opening == "cellular-v4" || o.opening == "cellular-v5" || o.opening == "cellular-v6") { + if (!o.cellular_pools.empty() || o.cellular_motes) + return std::nullopt; 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, @@ -465,7 +544,8 @@ 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" || o.opening == "cellular-v4" || - o.opening == "cellular-v5" || o.opening == "cellular-v6"; + o.opening == "cellular-v5" || o.opening == "cellular-v6" || + o.opening == "cellular-v7"; const auto primitive_frame = o.primitive_frame.value_or(0); if ((primitive || cellular) && primitive_frame == 0) return 2; @@ -560,6 +640,20 @@ int provision(const Options& o) { habitat_config.width_um = cellular_width_um; habitat_config.height_um = cellular_height_um; habitat_config.patches = o.cellular_patches; + if (o.opening == "cellular-v7") { + // ADR-0136 step A: pools and bubbles scattered from the genesis commit's bytes. + auto field = o.cellular_motes.value_or(biology::CellularMoteField{0, 1, {}, 0}); + const auto commit = o.commit.value_or(persistence::Uuid{}); + for (std::size_t i = 0; i < 8; ++i) + field.seed = (field.seed << 8U) | commit.at(i); + auto scattered = biology::scatter_deposits(habitat_config, o.cellular_pools, field); + if (!scattered) { + std::printf("cellular habitat refused %u\n", + static_cast(scattered.error())); + return 4; + } + habitat_config = std::move(*scattered); + } auto habitat = biology::CellularHabitat::create(std::move(habitat_config)); if (!habitat) { std::printf("cellular habitat refused %u\n", static_cast(habitat.error())); @@ -568,7 +662,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-v6" ? server::CellularLivesProfile::reproduction + o.opening == "cellular-v7" ? server::CellularLivesProfile::foraging + : o.opening == "cellular-v6" ? server::CellularLivesProfile::reproduction : o.opening == "cellular-v5" ? server::CellularLivesProfile::balance : o.opening == "cellular-v4" ? server::CellularLivesProfile::presence : o.opening == "cellular-v3" ? server::CellularLivesProfile::budding diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index eb24025..e33dd6c 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-20261017T034348-76758:1792219428"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261017T043821-32821:1792222701"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/docs/adr/0136-open-energy-and-scattered-nutrients.md b/docs/adr/0136-open-energy-and-scattered-nutrients.md index 9c3959a..600abd4 100644 --- a/docs/adr/0136-open-energy-and-scattered-nutrients.md +++ b/docs/adr/0136-open-energy-and-scattered-nutrients.md @@ -2,11 +2,29 @@ ## Status -Proposed (2026-10-16) by the maintainer after the region 6 playtest. Design for a new -cellular rules version, delivered in three steps (below), each built and playtested on -its own. It is independent of ADR-0135's rules 7–9; rules numbers are assigned when -each step is built. Every number marked **tunable** is a trial value. Nothing here is -implemented yet. +Proposed (2026-10-16) by the maintainer after the region 6 playtest. Design for new +cellular rules versions, delivered in three steps (below), each built and playtested on +its own. Every number marked **tunable** is a trial value. + +**Step A is implemented (2026-10-17)** as rules 8 on habitat format 2: bundle v9, +schema v43, session v11, the `cellular-v7` opening, served as DEV region 8. Where step A +differs from the plan below: + +- **Boundary account:** not added yet. Step A creates nothing, so totals still equal the + opening; the account arrives with infall (step B). +- **Perception:** amounts travel as 16-bit log codes, 26 bytes per deposit. The view + carries the 512 nearest deposits. +- **Bubble size:** a bubble's contact radius is a fixed 30 µm; clients size its drawing + by its amount. +- **Bubble colour:** each bubble holds one channel, cycling through the channels the + opening stocks. +- **Placement:** three in ten bubbles fall in loose clumps. Positions come from the + genesis commit. +- **Pools:** the opening lists them explicitly with `--pool`. +- **Empty deposits:** removed from the habitat. +- **Intake targets:** ignored by the step, and the v11 client sends none. + +Steps B (infall) and C (photosynthesis) are not implemented. ## Context diff --git a/include/evo/biology/cellular_habitat.hpp b/include/evo/biology/cellular_habitat.hpp index 502edef..9806a3f 100644 --- a/include/evo/biology/cellular_habitat.hpp +++ b/include/evo/biology/cellular_habitat.hpp @@ -18,25 +18,41 @@ inline constexpr std::uint32_t cellular_patch_pitch_um = 1'000; inline constexpr std::uint32_t cellular_trial_perception_radius_um = 5'000; inline constexpr std::size_t max_cellular_patches = 4'096; inline constexpr std::uint32_t cellular_habitat_format = 1; +// ADR-0136 step A: format 2 holds deposits (pools and bubbles) at free micrometre centres, +// each with a stable id, a radius and a kind, and the next id to give a new deposit. +inline constexpr std::uint32_t cellular_habitat_deposit_format = 2; inline constexpr std::size_t cellular_habitat_header_bytes = 72; inline constexpr std::size_t cellular_patch_record_bytes = 56; +inline constexpr std::size_t cellular_deposit_record_bytes = 64; inline constexpr std::size_t max_cellular_habitat_bytes = - cellular_habitat_header_bytes + cellular_patch_record_bytes * max_cellular_patches + 8; + cellular_habitat_header_bytes + cellular_deposit_record_bytes * max_cellular_patches + 8; +// A bubble's contact radius (tunable); pools carry their own. +inline constexpr std::uint32_t cellular_mote_radius_um = 30; +inline constexpr std::uint32_t max_cellular_deposit_radius_um = 5'000; +// A pool yields at most this share (per thousand) of a cell's intake rate per tick. +inline constexpr std::uint64_t cellular_pool_yield_per_thousand = 250; +enum class CellularDepositKind : std::uint8_t { patch, pool, mote }; struct CellularPatchAddress { std::uint32_t x_um{}, y_um{}; auto operator<=>(const CellularPatchAddress&) const = default; }; +// Format 1: a 1 mm square patch at a pitch-aligned corner. Format 2: a deposit centred at +// `address`, a disc of `radius_um`; `id` is stable and only labels it for clients. struct CellularPatch { CellularPatchAddress address; std::uint64_t source{}; // Explicit region-opening provenance. accounting::Inventory stock{}; + std::uint32_t id{}, radius_um{}; + CellularDepositKind kind{}; auto operator<=>(const CellularPatch&) const = default; }; struct CellularHabitatConfig { std::uint64_t world{}, region{}, frame{}; std::uint32_t width_um{}, height_um{}; std::vector patches; // Strictly ordered by (x_um, y_um). + std::uint32_t format{cellular_habitat_format}; + std::uint32_t next_deposit{}; // Format 2: above every deposit id. auto operator<=>(const CellularHabitatConfig&) const = default; }; struct CellularPatchUptakeProposal { @@ -48,8 +64,13 @@ struct CellularPatchUptakeProposal { struct CellularPatchPerception { CellularPatchAddress address; accounting::Inventory available; + std::uint32_t id{}, radius_um{}; // Format 2 deposits; zero for format 1 patches. + CellularDepositKind kind{}; auto operator<=>(const CellularPatchPerception&) const = default; }; +// Whether a cell's square footprint touches a patch (format 1 square) or a deposit's disc. +[[nodiscard]] bool cellular_patch_contact(CellularPosition position, std::uint32_t extent_um, + const CellularPatch& patch) noexcept; enum class CellularHabitatError : std::uint8_t { invalid_config, invalid_patch, @@ -65,6 +86,21 @@ enum class CellularHabitatError : std::uint8_t { identity }; +// ADR-0136 step A opening: bubbles scattered over the whole area. Each holds `amount` on +// one channel (cycling through the channels `amount` stocks), three in ten of them in +// loose clumps; positions follow `seed` only, so a genesis is reproducible. +struct CellularMoteField { + std::uint32_t count{}; + std::uint64_t source{}; + accounting::Inventory amount{}; // Per bubble, per channel. + std::uint64_t seed{}; +}; +// A format-2 habitat of the given pools (centre, radius, source and stock; their ids and kind +// are assigned) and the scattered bubbles, sorted by address with ids 1..n. +[[nodiscard]] std::expected +scatter_deposits(CellularHabitatConfig base, std::span pools, + const CellularMoteField& field); + // Region-local finite food stock for the cellular trial. Empty/unlisted patches // contain no stock. This is a read/proposal owner; the caller commits its patch // and organism candidate together through the durable cellular state owner. diff --git a/include/evo/biology/cellular_region_step.hpp b/include/evo/biology/cellular_region_step.hpp index 507fa61..302a93d 100644 --- a/include/evo/biology/cellular_region_step.hpp +++ b/include/evo/biology/cellular_region_step.hpp @@ -21,6 +21,10 @@ struct CellularRegionRules { // Rules 2 (false) is the original trial: engulf intents are ignored and starvation // corpses keep their inventory. bool engulf_and_detritus{}; + // ADR-0136 step A (format 2 habitats): every cell drains the deposits it touches, up to + // its intake rate, with no intake target; pools yield at most a quarter of that rate. + // A dead life's detritus becomes one bubble per non-empty channel. + bool contact_feeding{}; auto operator<=>(const CellularRegionRules&) const = default; }; diff --git a/include/evo/network/session_protocol.hpp b/include/evo/network/session_protocol.hpp index 752164b..cba1231 100644 --- a/include/evo/network/session_protocol.hpp +++ b/include/evo/network/session_protocol.hpp @@ -35,7 +35,15 @@ inline constexpr std::uint16_t session_protocol_v9 = 9; // v10 adds a reliable owner choice for a previously earned cellular mutation offer. // Its durable effect is committed on the next cellular tick. inline constexpr std::uint16_t session_protocol_v10 = 10; +// v11 (ADR-0136 step A) is v10 with the owner's view of pools and bubbles (deposits) +// instead of square patches; every other message is v10's. +inline constexpr std::uint16_t session_protocol_v11 = 11; +// v10 and v11 share every cellular message but the perception's food list. +[[nodiscard]] constexpr bool cellular_v10_family(std::uint16_t version) noexcept { + return version == session_protocol_v10 || version == session_protocol_v11; +} inline constexpr std::size_t max_cellular_perceived_patches = 256; +inline constexpr std::size_t max_cellular_perceived_deposits = 512; inline constexpr std::size_t session_address_bytes = 64; // Endpoint or server name field. inline constexpr std::size_t session_datagram_bytes = 1200; // Whole message, ADR-0089. inline constexpr std::size_t session_header_bytes = 8; @@ -238,6 +246,37 @@ struct CellularPerceivedPatch { std::array matter_fg{}; friend bool operator==(const CellularPerceivedPatch&, const CellularPerceivedPatch&) = default; }; +// v11 (ADR-0136): one pool or bubble in range. Amounts travel as 16-bit log codes (about +// 0.2 % precision: enough to size, colour and fade them); the HUD's exact numbers stay in +// the diagnostics. `drained` is set when some cell took from it on this tick. +enum class CellularDepositShape : std::uint8_t { pool = 1, bubble = 2 }; +struct CellularPerceivedDeposit { + std::uint32_t id{}, x_um{}, y_um{}; // Centre. + std::uint16_t radius_um{}; + CellularDepositShape shape{CellularDepositShape::bubble}; + bool drained{}; + std::array amount_codes{}; // Energy, then C, N, P, other. + friend bool operator==(const CellularPerceivedDeposit&, + const CellularPerceivedDeposit&) = default; +}; +// 0 for 0; otherwise 1 + 512 * floor(log2 v) + the next 9 bits of v. +[[nodiscard]] constexpr std::uint16_t deposit_amount_code(std::uint64_t value) noexcept { + if (value == 0) + return 0; + unsigned bit = 63; + while ((value >> bit) == 0) + --bit; + const auto fraction = bit >= 9 ? (value >> (bit - 9)) & 511U : (value << (9 - bit)) & 511U; + return static_cast(1 + 512 * bit + fraction); +} +// The smallest amount with that code. +[[nodiscard]] constexpr std::uint64_t deposit_amount_value(std::uint16_t code) noexcept { + if (code == 0) + return 0; + const unsigned bit = (code - 1U) / 512U; + const std::uint64_t mantissa = 512U + (code - 1U) % 512U; + return bit >= 9 ? mantissa << (bit - 9) : mantissa >> (9 - bit); +} enum class CellularMovementResult : std::uint8_t { not_reported, no_movement, @@ -294,6 +333,8 @@ struct CellularPerception { // Present only on v9 for an active life. The values are authoritative observations, // not client claims or additional simulation state. std::optional diagnostics; + // v11 only (then `patches` is empty): pools and bubbles in range, by ascending id. + std::vector deposits{}; friend bool operator==(const CellularPerception&, const CellularPerception&) = default; }; struct IntentionReceipt { diff --git a/include/evo/persistence/region_checkpoint.hpp b/include/evo/persistence/region_checkpoint.hpp index bf69ab9..4103d31 100644 --- a/include/evo/persistence/region_checkpoint.hpp +++ b/include/evo/persistence/region_checkpoint.hpp @@ -63,10 +63,13 @@ inline constexpr CellularVersionBundle cellular_v6_versions{5, 6, 1, 1, 1, 2, 1, inline constexpr CellularVersionBundle cellular_v7_versions{6, 6, 1, 1, 1, 3, 2, 2, 1}; // ADR-0137: rules 7 on owner envelope 6, with development 4 and founder 3. inline constexpr CellularVersionBundle cellular_v8_versions{7, 6, 1, 1, 1, 4, 3, 2, 1}; +// ADR-0136 step A: rules 8 on owner envelope 6 with habitat 2 (pools and bubbles). +inline constexpr CellularVersionBundle cellular_v9_versions{8, 6, 2, 1, 1, 4, 3, 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 || - b == cellular_v6_versions || b == cellular_v7_versions || b == cellular_v8_versions; + b == cellular_v6_versions || b == cellular_v7_versions || b == cellular_v8_versions || + b == cellular_v9_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 ed01c34..5419581 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -38,6 +38,10 @@ inline constexpr std::uint32_t cellular_lives_balance_rules = 6; // steps; development 4: reproduction cheapens buds), twin buds, and wildlife that engulfs. // No new state, so they keep owner format 6. inline constexpr std::uint32_t cellular_lives_reproduction_rules = 7; +// ADR-0136 step A: rules 8 are rules 7 on a format-2 habitat of pools and bubbles, fed by +// contact; detritus becomes bubbles and emptied deposits disappear. The habitat envelope +// carries the new state, so they keep owner format 6. +inline constexpr std::uint32_t cellular_lives_foraging_rules = 8; // The founder a region of these rules creates. [[nodiscard]] constexpr biology::FounderVersion cellular_founder_version(std::uint32_t rules) noexcept { @@ -174,7 +178,8 @@ enum class CellularLivesProfile : std::uint8_t { budding, presence, balance, - reproduction + reproduction, + foraging }; struct CellularLivesConfig { biology::CellularArea area{}; diff --git a/migrations/0043_cellular_v9_foraging_bundle.sql b/migrations/0043_cellular_v9_foraging_bundle.sql new file mode 100644 index 0000000..111ba89 --- /dev/null +++ b/migrations/0043_cellular_v9_foraging_bundle.sql @@ -0,0 +1,129 @@ +-- ADR-0136 step A: admit the cellular-v9 bundle (rules 8 on owner envelope 6 with habitat +-- 2: pools and bubbles fed by contact). Traces keep format 3 and intents keep their layout +-- (an intake target is ignored), so earlier bundles and committed rows keep their meaning. + +-- The v9 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_v42; + +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'; + v9_bundle constant bytea := '\x080000000600000002000000010000000100000004000000030000000200000001000000'; +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) = v9_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_v42(overlay(m PLACING v3_bundle FROM 161 FOR 36)); + r.versions := v9_bundle; + RETURN r; + END IF; + RETURN evolution.parse_checkpoint_manifest_v42(m); +END $$; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC; + +-- Birth binding: v3 to v9 publications carry format-3 traces. Otherwise unchanged from +-- schema v42. +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, + '\x060000000600000001000000010000000100000003000000020000000200000001000000'::bytea, + '\x070000000600000001000000010000000100000004000000030000000200000001000000'::bytea, + '\x080000000600000002000000010000000100000004000000030000000200000001000000'::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 (43, :'migration_sha_43'); diff --git a/migrations/apply.sql b/migrations/apply.sql index 8fe2f5a..9a616d3 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -118,6 +118,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v39' || ',40:' || :'migration_sha_40' AS history_v40 \gset SELECT :'history_v40' || ',41:' || :'migration_sha_41' AS history_v41 \gset SELECT :'history_v41' || ',42:' || :'migration_sha_42' AS history_v42 \gset + SELECT :'history_v42' || ',43:' || :'migration_sha_43' AS history_v43 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -138,8 +139,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v39' AS at_v39, :'history' = :'history_v40' AS at_v40, :'history' = :'history_v41' AS at_v41, - :'history' = :'history_v42' AS at_v42 \gset - \if :at_v42 + :'history' = :'history_v42' AS at_v42, + :'history' = :'history_v43' AS at_v43 \gset + \if :at_v43 + \elif :at_v42 \elif :at_v41 \elif :at_v40 \elif :at_v39 @@ -517,7 +520,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 39 AS at_v39, coalesce(max(version), 0) = 40 AS at_v40, coalesce(max(version), 0) = 41 AS at_v41, - coalesce(max(version), 0) = 42 AS at_v42 + coalesce(max(version), 0) = 42 AS at_v42, + coalesce(max(version), 0) = 43 AS at_v43 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -538,6 +542,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v25 \ir 0026_cellular_profile_migration.sql \ir 0027_cellular_v3_migration.sql @@ -556,6 +561,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v26 \ir 0027_cellular_v3_migration.sql \ir 0028_cellular_v3_trace_bounds.sql @@ -573,6 +579,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v27 \ir 0028_cellular_v3_trace_bounds.sql \ir 0029_cellular_mutation_reservations.sql @@ -589,6 +596,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v28 \ir 0029_cellular_mutation_reservations.sql \ir 0030_cellular_birth_publication_binding.sql @@ -604,6 +612,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v29 \ir 0030_cellular_birth_publication_binding.sql \ir 0031_fix_cellular_birth_publication_record.sql @@ -618,6 +627,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v30 \ir 0031_fix_cellular_birth_publication_record.sql \ir 0032_fix_cellular_v3_manifest_normalization.sql @@ -631,6 +641,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v31 \ir 0032_fix_cellular_v3_manifest_normalization.sql \ir 0033_fix_cellular_action_tick_offset.sql @@ -643,6 +654,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v32 \ir 0033_fix_cellular_action_tick_offset.sql \ir 0034_cellular_v4_engulf_bundle.sql @@ -654,6 +666,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v33 \ir 0034_cellular_v4_engulf_bundle.sql \ir 0035_cellular_mutation_publication.sql @@ -664,6 +677,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v34 \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql @@ -673,6 +687,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v35 \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql @@ -681,6 +696,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v36 \ir 0037_cellular_life_endings.sql \ir 0038_cellular_v6_presence_bundle.sql @@ -688,29 +704,37 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v37 \ir 0038_cellular_v6_presence_bundle.sql \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v38 \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v39 \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v40 \ir 0041_cellular_v7_balance_bundle.sql \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v41 \ir 0042_cellular_v8_reproduction_bundle.sql + \ir 0043_cellular_v9_foraging_bundle.sql \elif :at_v42 + \ir 0043_cellular_v9_foraging_bundle.sql +\elif :at_v43 \else - \echo 'Unknown or changed migration history after v42' + \echo 'Unknown or changed migration history after v43' 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-habitat-v1.md b/schemas/cellular-habitat-v1.md index e5f73aa..88aad72 100644 --- a/schemas/cellular-habitat-v1.md +++ b/schemas/cellular-habitat-v1.md @@ -54,3 +54,33 @@ length, checksum, magic, versions, count cap and exact length. It then validates identity, dimensions, patch pitch, zero reserved fields, patch alignment, source ids, strict ordering and per-channel totals. Restore rebuilds through the same creation validator and accepts only bytes identical to a canonical re-encoding. + +## Format 2: deposits (ADR-0136 step A) + +Format 2 keeps the same 72-byte header with three differences: +- **Format field:** it reads 2. +- **Pitch field:** it is 0, since deposits are not aligned. +- **First reserved u64:** it holds `next_deposit`, which is above every deposit id. + +Records are 64 bytes and keep the format-1 ordering: ascending `(x_um, y_um)`, with +addresses unique. Exact length is `80 + 64 * count`. + +| Offset | Width | Field | Contract | +|---:|---:|---|---| +| 0 | 4 | x_um | Deposit centre, in bounds; any micrometre | +| 4 | 4 | y_um | Deposit centre, in bounds; any micrometre | +| 8 | 4 | id | Nonzero, unique, below `next_deposit`; stable for its life | +| 12 | 2 | radius_um | 1 to 5,000: the contact disc | +| 14 | 1 | kind | 1 pool, 2 bubble | +| 15 | 1 | reserved | Zero | +| 16 | 8 | source | Nonzero provenance identity | +| 24 | 40 | stock | Energy, then carbon, nitrogen, phosphorus, other | + +A cell touches a deposit when its square footprint comes within `radius_um` of the +centre. Under rules 8 that contact is feeding: +- **Feeding order:** by ascending address, up to the cell's intake rate per tick. +- **Pools:** a pool gives at most a quarter of that rate. +- **Corpses:** a dead cell's detritus becomes one bubble per non-empty channel, with + new ids from `next_deposit`. +- **Empty deposits:** removed. + diff --git a/schemas/cellular-lives-v1.md b/schemas/cellular-lives-v1.md index 1995ef9..0b32658 100644 --- a/schemas/cellular-lives-v1.md +++ b/schemas/cellular-lives-v1.md @@ -123,3 +123,9 @@ Rules 7 keep the same layout again. New lives are founder 3 (genome schema 4, development version 4). A bud action can make twins, and wildlife can engulf, but neither adds any state. Restore accepts format 6 with rules 5, 6 or 7, on the v8 bundle for rules 7. + +### Format 6, rules 8 (ADR-0136 step A) + +Rules 8 also keep the layout. Their embedded habitat is format 2 (pools and bubbles), +and restore refuses rules 8 with a format-1 habitat, and any earlier rules with a +format-2 one. Rules 8 use the v9 bundle (habitat 2). diff --git a/src/biology/cellular_habitat.cpp b/src/biology/cellular_habitat.cpp index 2bf00d8..eedb8c7 100644 --- a/src/biology/cellular_habitat.cpp +++ b/src/biology/cellular_habitat.cpp @@ -25,6 +25,21 @@ bool add(accounting::Inventory value, accounting::Inventory& total) noexcept { return true; } +// Squared distance from a centre to the nearest point of a square footprint. +std::uint64_t square_gap_squared(CellularPosition position, std::uint32_t extent_um, + CellularPatchAddress centre) noexcept { + const auto axis = [](std::uint64_t start, std::uint32_t extent, std::uint64_t point) { + if (point < start) + return start - point; + if (point > start + extent) + return point - (start + extent); + return std::uint64_t{}; + }; + const auto dx = axis(position.x_um, extent_um, centre.x_um); + const auto dy = axis(position.y_um, extent_um, centre.y_um); + return dx * dx + dy * dy; +} + std::uint64_t checksum(std::span bytes) noexcept { std::uint64_t value = 14695981039346656037ULL; for (const auto byte : bytes) @@ -81,17 +96,33 @@ CellularHabitat::create(CellularHabitatConfig config) { config.height_um > cellular_motion_axis_limit_um || config.width_um % cellular_patch_pitch_um != 0 || config.height_um % cellular_patch_pitch_um != 0 || - config.patches.size() > max_cellular_patches) + config.patches.size() > max_cellular_patches || + (config.format != cellular_habitat_format && + config.format != cellular_habitat_deposit_format) || + (config.format == cellular_habitat_format && config.next_deposit != 0)) return std::unexpected{CellularHabitatError::invalid_config}; + const bool deposits = config.format == cellular_habitat_deposit_format; accounting::Inventory totals{}; + std::vector ids; + ids.reserve(deposits ? config.patches.size() : 0); for (std::size_t index = 0; index < config.patches.size(); ++index) { const auto& patch = config.patches[index]; if (patch.source == 0 || patch.address.x_um >= config.width_um || - patch.address.y_um >= config.height_um || - patch.address.x_um % cellular_patch_pitch_um != 0 || - patch.address.y_um % cellular_patch_pitch_um != 0) + patch.address.y_um >= config.height_um) return std::unexpected{CellularHabitatError::invalid_patch}; + if (!deposits && (patch.address.x_um % cellular_patch_pitch_um != 0 || + patch.address.y_um % cellular_patch_pitch_um != 0 || patch.id != 0 || + patch.radius_um != 0 || patch.kind != CellularDepositKind::patch)) + return std::unexpected{CellularHabitatError::invalid_patch}; + // Format 2: an id below next_deposit, a radius and a kind (ADR-0136). + if (deposits && + (patch.id == 0 || patch.id >= config.next_deposit || patch.radius_um == 0 || + patch.radius_um > max_cellular_deposit_radius_um || + (patch.kind != CellularDepositKind::pool && patch.kind != CellularDepositKind::mote))) + return std::unexpected{CellularHabitatError::invalid_patch}; + if (deposits) + ids.push_back(patch.id); if (index != 0 && !(config.patches[index - 1].address < patch.address)) return std::unexpected{config.patches[index - 1].address == patch.address ? CellularHabitatError::duplicate_patch @@ -99,6 +130,9 @@ CellularHabitat::create(CellularHabitatConfig config) { if (!add(patch.stock, totals)) return std::unexpected{CellularHabitatError::overflow}; } + std::ranges::sort(ids); + if (std::ranges::adjacent_find(ids) != ids.end()) + return std::unexpected{CellularHabitatError::duplicate_patch}; return std::unique_ptr{new CellularHabitat{std::move(config), totals}}; } @@ -131,6 +165,16 @@ CellularHabitat::perceive(CellularPosition position, std::uint32_t extent_um) co return std::unexpected{CellularHabitatError::outside_area}; std::vector visible; + if (config_.format == cellular_habitat_deposit_format) { + // A deposit is visible when the gap from the footprint to its disc is within range. + for (const auto& patch : config_.patches) { + const auto reach = std::uint64_t{cellular_trial_perception_radius_um} + patch.radius_um; + if (square_gap_squared(position, extent_um, patch.address) <= reach * reach) + visible.push_back( + {patch.address, patch.stock, patch.id, patch.radius_um, patch.kind}); + } + return visible; + } for (const auto& patch : config_.patches) { const auto axis_gap = [](std::uint64_t body_start, std::uint32_t body_extent, std::uint32_t patch_start) { @@ -179,8 +223,7 @@ CellularHabitat::propose_uptake_from_stock(CellularPatchAddress address, Cellula const auto index = find(address); if (!index) return std::unexpected{CellularHabitatError::missing_patch}; - if (!cellular_footprints_contact(position, extent_um, {address.x_um, address.y_um}, - cellular_patch_pitch_um)) + if (!cellular_patch_contact(position, extent_um, config_.patches[*index])) return std::unexpected{CellularHabitatError::not_in_contact}; const auto uptake = propose_cellular_uptake(patch_stock, reserve, budget); if (!uptake) @@ -194,20 +237,27 @@ std::vector CellularHabitat::snapshot() const { cellular_patch_record_bytes * config_.patches.size() + 8); Writer out{bytes}; out.put(habitat_magic); - out.put(cellular_habitat_format, 4); + const bool deposits = config_.format == cellular_habitat_deposit_format; + out.put(config_.format, 4); out.put(habitat_rules, 4); out.put(config_.world); out.put(config_.region); out.put(config_.frame); out.put(config_.width_um, 4); out.put(config_.height_um, 4); - out.put(cellular_patch_pitch_um, 4); + out.put(deposits ? 0 : cellular_patch_pitch_um, 4); out.put(config_.patches.size(), 4); - out.put(0); // Reserved. - out.put(0); // Reserved. + out.put(config_.next_deposit); // Reserved (zero) in format 1. + out.put(0); // Reserved. for (const auto& patch : config_.patches) { out.put(patch.address.x_um, 4); out.put(patch.address.y_um, 4); + if (deposits) { + out.put(patch.id, 4); + out.put(patch.radius_um, 2); + out.put(static_cast(patch.kind), 1); + out.put(0, 1); + } out.put(patch.source); out.inventory(patch.stock); } @@ -227,9 +277,13 @@ CellularHabitat::restore(std::span bytes, std::uint64_t worl Reader in{bytes}; if (in.get() != habitat_magic) return std::unexpected{CellularHabitatError::format}; - if (in.get(4) != cellular_habitat_format || in.get(4) != habitat_rules) + const auto format = in.get(4); + if ((format != cellular_habitat_format && format != cellular_habitat_deposit_format) || + in.get(4) != habitat_rules) return std::unexpected{CellularHabitatError::version}; + const bool deposits = format == cellular_habitat_deposit_format; CellularHabitatConfig config; + config.format = static_cast(format); config.world = in.get(); config.region = in.get(); config.frame = in.get(); @@ -237,17 +291,29 @@ CellularHabitat::restore(std::span bytes, std::uint64_t worl return std::unexpected{CellularHabitatError::identity}; config.width_um = static_cast(in.get(4)); config.height_um = static_cast(in.get(4)); - if (in.get(4) != cellular_patch_pitch_um) + if (in.get(4) != (deposits ? 0U : cellular_patch_pitch_um)) return std::unexpected{CellularHabitatError::version}; const auto count = in.get(4); - if (in.get() != 0 || in.get() != 0 || count > max_cellular_patches || - bytes.size() != cellular_habitat_header_bytes + cellular_patch_record_bytes * count + 8) + const auto next_deposit = in.get(); + const auto record = deposits ? cellular_deposit_record_bytes : cellular_patch_record_bytes; + if (in.get() != 0 || count > max_cellular_patches || + next_deposit > std::numeric_limits::max() || + bytes.size() != cellular_habitat_header_bytes + record * count + 8) return std::unexpected{CellularHabitatError::format}; + config.next_deposit = static_cast(next_deposit); config.patches.reserve(static_cast(count)); for (std::uint64_t index = 0; index < count; ++index) { CellularPatch patch{}; patch.address.x_um = static_cast(in.get(4)); patch.address.y_um = static_cast(in.get(4)); + if (deposits) { + patch.id = static_cast(in.get(4)); + patch.radius_um = static_cast(in.get(2)); + const auto kind = in.get(1); + if (kind > static_cast(CellularDepositKind::mote) || in.get(1) != 0) + return std::unexpected{CellularHabitatError::format}; + patch.kind = static_cast(kind); + } patch.source = in.get(); patch.stock = in.inventory(); config.patches.push_back(patch); @@ -261,4 +327,95 @@ CellularHabitat::restore(std::span bytes, std::uint64_t worl return std::unexpected{CellularHabitatError::format}; return std::move(*restored); } +std::expected +scatter_deposits(CellularHabitatConfig base, std::span pools, + const CellularMoteField& field) { + if (base.width_um == 0 || base.height_um == 0 || field.source == 0 || + pools.size() + field.count > max_cellular_patches) + return std::unexpected{CellularHabitatError::invalid_config}; + std::vector channels; // 0 energy, 1-4 matter + if (field.amount.energy.value != 0) + channels.push_back(0); + for (std::size_t c = 0; c < field.amount.matter.size(); ++c) + if (field.amount.matter[c].value != 0) + channels.push_back(c + 1); + if (field.count != 0 && channels.empty()) + return std::unexpected{CellularHabitatError::invalid_config}; + // splitmix64: a fixed, portable stream. + std::uint64_t state = field.seed; + const auto next = [&state] { + state += 0x9E3779B97F4A7C15ULL; + auto z = state; + z = (z ^ (z >> 30U)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27U)) * 0x94D049BB133111EBULL; + return z ^ (z >> 31U); + }; + const auto below = [&](std::uint64_t bound) { return bound == 0 ? 0 : next() % bound; }; + std::vector deposits; + deposits.reserve(pools.size() + field.count); + for (auto pool : pools) { + pool.kind = CellularDepositKind::pool; + deposits.push_back(pool); + } + const auto clumps = std::max(1, field.count / 40); + std::vector centres; + centres.reserve(clumps); + for (std::uint32_t i = 0; i < clumps; ++i) + centres.push_back({static_cast(below(base.width_um)), + static_cast(below(base.height_um))}); + constexpr std::int64_t spread = 600; // Clump half-width (tunable). + for (std::uint32_t i = 0; i < field.count; ++i) { + std::int64_t x{}, y{}; + if (below(10) < 3) { + const auto& centre = centres[below(centres.size())]; + // Two summed uniforms: denser towards the clump centre. + x = std::int64_t{centre.x_um} + static_cast(below(spread + 1)) + + static_cast(below(spread + 1)) - spread; + y = std::int64_t{centre.y_um} + static_cast(below(spread + 1)) + + static_cast(below(spread + 1)) - spread; + x = std::clamp(x, 0, std::int64_t{base.width_um} - 1); + y = std::clamp(y, 0, std::int64_t{base.height_um} - 1); + } else { + x = static_cast(below(base.width_um)); + y = static_cast(below(base.height_um)); + } + CellularPatch mote{}; + mote.address = {static_cast(x), static_cast(y)}; + mote.source = field.source; + mote.radius_um = cellular_mote_radius_um; + mote.kind = CellularDepositKind::mote; + const auto channel = channels[i % channels.size()]; + if (channel == 0) + mote.stock.energy = field.amount.energy; + else + mote.stock.matter[channel - 1] = field.amount.matter[channel - 1]; + deposits.push_back(mote); + } + // Unique addresses: a repeat moves east (wrapping) until free. + std::ranges::sort(deposits, {}, &CellularPatch::address); + for (std::size_t i = 1; i < deposits.size(); ++i) + while (std::ranges::any_of( + deposits.begin(), deposits.begin() + static_cast(i), + [&](const CellularPatch& other) { return other.address == deposits[i].address; })) + deposits[i].address.x_um = + deposits[i].address.x_um + 1 < base.width_um ? deposits[i].address.x_um + 1 : 0; + std::ranges::sort(deposits, {}, &CellularPatch::address); + std::uint32_t id = 1; + for (auto& deposit : deposits) + deposit.id = id++; + base.format = cellular_habitat_deposit_format; + base.next_deposit = id; + base.patches = std::move(deposits); + return base; +} + +bool cellular_patch_contact(CellularPosition position, std::uint32_t extent_um, + const CellularPatch& patch) noexcept { + if (patch.kind == CellularDepositKind::patch) + return cellular_footprints_contact( + position, extent_um, {patch.address.x_um, patch.address.y_um}, cellular_patch_pitch_um); + const auto radius = std::uint64_t{patch.radius_um}; + return extent_um != 0 && + square_gap_squared(position, extent_um, patch.address) <= radius * radius; +} } // namespace evo::biology diff --git a/src/biology/cellular_region_step.cpp b/src/biology/cellular_region_step.cpp index 4164b28..b28371e 100644 --- a/src/biology/cellular_region_step.cpp +++ b/src/biology/cellular_region_step.cpp @@ -3,7 +3,9 @@ #include "evo/accounting/rates.hpp" #include +#include #include +#include #include namespace evo::biology { @@ -47,7 +49,12 @@ struct Deposit { std::uint64_t life_id{}, source{}; CellularPosition position; accounting::Inventory inventory; + std::uint32_t extent_um{}; }; +// One channel of an inventory: 0 energy, 1-4 matter. +std::uint64_t& channel_of(accounting::Inventory& value, std::size_t channel) noexcept { + return channel == 0 ? value.energy.value : value.matter[channel - 1].value; +} } // namespace std::expected @@ -109,7 +116,8 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, continue; } auto intent = life->intent; - const auto target = intent.intake_target; + // Contact feeding needs no target; one sent anyway is ignored (ADR-0136). + const auto target = rules.contact_feeding ? std::nullopt : intent.intake_target; intent.intake_target.reset(); intent.engulf = false; const auto step = @@ -129,7 +137,8 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, return std::unexpected{CellularRegionStepError::overflow}; candidate.heat_released.value += life->heat.energy.value; if (rules.engulf_and_detritus) { - deposits.push_back({life->life_id, life->source, life->position, corpse.inventory}); + deposits.push_back({life->life_id, life->source, life->position, corpse.inventory, + life->extent_um}); corpse.inventory = {}; } candidate.starved.push_back(corpse); @@ -160,6 +169,53 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, } } } + if (rules.contact_feeding) { + // ADR-0136: drain every touched deposit (ascending address) up to the per-tick + // intake limit; a pool gives at most a quarter of that limit. + std::array limit{}; + for (std::size_t channel = 0; channel < limit.size(); ++channel) { + const auto per_second = channel == 0 + ? life->budget.intake_limit.energy.value + : life->budget.intake_limit.matter[channel - 1].value; + const auto per_tick = accounting::per_tick( + per_second, cellular_motion_tick_microseconds, accounting::Rounding::down); + if (!per_tick) + return std::unexpected{CellularRegionStepError::overflow}; + limit.at(channel) = *per_tick; + } + accounting::Inventory acquired{}; + std::optional first; + for (std::size_t index = 0; index < patch_stock.size(); ++index) { + const auto& deposit = habitat.patches()[index]; + if (!cellular_patch_contact(result.position, life->extent_um, deposit)) + continue; + bool took = false; + for (std::size_t channel = 0; channel < limit.size(); ++channel) { + auto& stock = channel_of(patch_stock[index], channel); + auto& gained = channel_of(acquired, channel); + auto& reserve = channel_of(result.reserve_after, channel); + auto allowance = limit.at(channel) - gained; + if (deposit.kind == CellularDepositKind::pool) + allowance = std::min( + allowance, limit.at(channel) * cellular_pool_yield_per_thousand / 1000); + const auto take = std::min({stock, allowance, u64_max - reserve}); + if (take == 0) + continue; + stock -= take; + gained += take; + reserve += take; + took = true; + } + if (took && !first) + first = index; + } + if (first) { + result.intake_status = CellularIntakeStatus::acquired; + result.intake = CellularPatchUptakeProposal{ + habitat.patches()[*first].address, + {patch_stock[*first], result.reserve_after, acquired}}; + } + } CellularLifeStepResult life_result{life->life_id, result}; if (life->intent.engulf) life_result.engulf = rules.engulf_and_detritus ? CellularEngulfStatus::no_eligible_prey @@ -238,7 +294,8 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, detritus.energy.value -= taken_in.energy.value; for (std::size_t channel = 0; channel < detritus.matter.size(); ++channel) detritus.matter[channel].value -= taken_in.matter[channel].value; - deposits.push_back({prey->life_id, prey->source, prey_step.position, detritus}); + deposits.push_back( + {prey->life_id, prey->source, prey_step.position, detritus, prey->extent_um}); CellularCorpseCandidate corpse{prey->life_id, prey_step.position, {}}; corpse.cause = CellularDeathCause::engulfed; corpse.predator_id = hunter->life_id; @@ -258,8 +315,54 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, std::ranges::sort(candidate.starved, {}, &CellularCorpseCandidate::life_id); // Detritus: each dead life's inventory goes to the patch at its cell, a new patch at - // an empty cell, or the nearest patch once the habitat is full. + // an empty cell, or the nearest patch once the habitat is full. Under contact + // feeding (ADR-0136) it breaks into one bubble per non-empty channel instead. std::ranges::sort(deposits, {}, &Deposit::life_id); + if (rules.contact_feeding) { + const auto taken_address = [&](CellularPatchAddress address) { + if (habitat.find(address)) + return true; + const auto made = std::ranges::lower_bound(candidate.new_patches, address, {}, + &CellularPatch::address); + return made != candidate.new_patches.end() && made->address == address; + }; + std::vector overflow; + for (const auto& deposit : deposits) { + const auto centre_x = deposit.position.x_um + deposit.extent_um / 2; + const auto centre_y = deposit.position.y_um + deposit.extent_um / 2; + for (std::size_t channel = 0; channel < 5; ++channel) { + auto inventory = deposit.inventory; + const auto amount = channel_of(inventory, channel); + if (amount == 0) + continue; + accounting::Inventory single{}; + channel_of(single, channel) = amount; + if (habitat.patches().size() + candidate.new_patches.size() >= + max_cellular_patches) { + overflow.push_back({deposit.life_id, deposit.source, deposit.position, + single, deposit.extent_um}); + continue; + } + // A small ring around the corpse's centre; nudged east past any taken spot. + const std::int64_t offset = (static_cast(channel) - 2) * + std::int64_t{cellular_mote_radius_um}; + auto x = static_cast(centre_x) + offset; + x = std::clamp(x, 0, + static_cast(area.width_um) - 1); + CellularPatchAddress address{static_cast(x), + static_cast(std::min( + centre_y, area.height_um - 1))}; + while (taken_address(address)) + address.x_um = address.x_um + 1 < area.width_um ? address.x_um + 1 : 0; + const auto at = std::ranges::lower_bound(candidate.new_patches, address, {}, + &CellularPatch::address); + candidate.new_patches.insert(at, CellularPatch{address, deposit.source, single, + 0, cellular_mote_radius_um, + CellularDepositKind::mote}); + } + } + deposits = std::move(overflow); // A full habitat: the nearest deposit takes it. + } for (const auto& deposit : deposits) { const auto address = cell_of(deposit.position); if (const auto index = habitat.find(address)) { diff --git a/src/client/session/region_session.cpp b/src/client/session/region_session.cpp index 110903f..70a73dc 100644 --- a/src/client/session/region_session.cpp +++ b/src/client/session/region_session.cpp @@ -189,7 +189,7 @@ RegionSessionClient::connect(RegionSessionClientConfig config, Clock::time_point config.protocol_version != network::session_protocol_v7 && config.protocol_version != network::session_protocol_v8 && config.protocol_version != network::session_protocol_v9 && - config.protocol_version != network::session_protocol_v10) + !network::cellular_v10_family(config.protocol_version)) return std::unexpected(network::quic::EndpointError::configuration); auto endpoint = network::quic::Endpoint::connect(config.transport); if (!endpoint) @@ -297,7 +297,7 @@ bool RegionSessionClient::send_cellular_action( return (m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || - m.protocol_version == network::session_protocol_v10) && + network::cellular_v10_family(m.protocol_version)) && m.state == RegionSessionState::established && m.welcome && action_id != 0 && tick != 0 && m.send(network::CellularAction{m.welcome->session, m.welcome->epoch, action_id, tick, move_x, move_y, intake_target.has_value(), @@ -311,7 +311,7 @@ bool RegionSessionClient::send_cellular_mutation(std::uint64_t action_id, std::u std::uint64_t offer_tick, std::uint16_t operator_id) { auto& m = *impl_; - return m.protocol_version == network::session_protocol_v10 && + return network::cellular_v10_family(m.protocol_version) && m.state == RegionSessionState::established && m.welcome && action_id != 0 && offer_tick != 0 && tick > offer_tick && m.send(network::CellularMutationAction{m.welcome->session, m.welcome->epoch, action_id, @@ -325,7 +325,7 @@ bool RegionSessionClient::query_action(std::uint64_t action_id) { m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || - m.protocol_version == network::session_protocol_v10) && + network::cellular_v10_family(m.protocol_version)) && m.state == RegionSessionState::established && m.send(network::ActionQuery{action_id}); } @@ -334,7 +334,7 @@ bool RegionSessionClient::request_primitive_life(std::uint64_t request_id) { return (m.protocol_version == network::session_protocol_v5 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || - m.protocol_version == network::session_protocol_v10) && + network::cellular_v10_family(m.protocol_version)) && m.state == RegionSessionState::established && m.welcome && request_id != 0 && m.send(network::PrimitiveLifeRequest{m.welcome->session, m.welcome->epoch, request_id}); } @@ -344,7 +344,7 @@ bool RegionSessionClient::query_primitive_life(std::uint64_t request_id) { return (m.protocol_version == network::session_protocol_v5 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || - m.protocol_version == network::session_protocol_v10) && + network::cellular_v10_family(m.protocol_version)) && m.state == RegionSessionState::established && request_id != 0 && m.send(network::PrimitiveLifeQuery{request_id}); } @@ -383,7 +383,7 @@ bool RegionSessionClient::set_interest(const network::SessionInterest& interest) m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || - m.protocol_version == network::session_protocol_v10) && + network::cellular_v10_family(m.protocol_version)) && m.state == RegionSessionState::established && m.send(interest); } diff --git a/src/network/protocol/session_protocol.cpp b/src/network/protocol/session_protocol.cpp index 5887bfa..4ce1ad0 100644 --- a/src/network/protocol/session_protocol.cpp +++ b/src/network/protocol/session_protocol.cpp @@ -28,6 +28,8 @@ constexpr std::size_t cellular_bud_cost_bytes = std::size_t{5} * 8; constexpr std::size_t cellular_perception_v10_prefix_bytes = cellular_perception_v9_prefix_bytes + cellular_bud_cost_bytes; constexpr std::size_t cellular_perceived_patch_bytes = 8 + 8 + (4 * 8); +// v11: id, centre, radius, shape, drained flag and five 16-bit amount codes. +constexpr std::size_t cellular_perceived_deposit_bytes = 4 + 4 + 4 + 2 + 1 + 1 + (5 * 2); constexpr std::size_t intention_receipt_bytes = 8 + 1 + 8; constexpr std::size_t simulated_bytes = std::size_t{3} * 8; constexpr std::size_t action_bytes = (std::size_t{3} * 8) + 2 + 8; @@ -171,7 +173,7 @@ std::vector encode_session(const SessionMessage& message, std::uin if (version != session_protocol_version && version != session_protocol_v5 && version != session_protocol_v6 && version != session_protocol_v7 && version != session_protocol_v8 && version != session_protocol_v9 && - version != session_protocol_v10) + !cellular_v10_family(version)) return {}; if (version == session_protocol_version && (std::holds_alternative(message) || @@ -182,27 +184,27 @@ std::vector encode_session(const SessionMessage& message, std::uin if (version != session_protocol_v6 && std::holds_alternative(message)) return {}; if (version != session_protocol_v7 && version != session_protocol_v8 && - version != session_protocol_v9 && version != session_protocol_v10 && + version != session_protocol_v9 && !cellular_v10_family(version) && std::holds_alternative(message)) return {}; if (version != session_protocol_v7 && version != session_protocol_v8 && - version != session_protocol_v9 && version != session_protocol_v10 && + version != session_protocol_v9 && !cellular_v10_family(version) && std::holds_alternative(message) && std::get(message).result == ActionResult::committed) return {}; - if (version != session_protocol_v10 && std::holds_alternative(message)) + if (!cellular_v10_family(version) && std::holds_alternative(message)) return {}; if (const auto* offer = std::get_if(&message); - offer && (version != session_protocol_v10 || !valid_offer(*offer))) + offer && (!cellular_v10_family(version) || !valid_offer(*offer))) return {}; if (const auto* ended = std::get_if(&message); - ended && (version != session_protocol_v10 || ended->tick == 0 || - ended->life_identity == 0 || ended->cause > CellularDeathReason::engulfed)) + ended && (!cellular_v10_family(version) || ended->tick == 0 || ended->life_identity == 0 || + ended->cause > CellularDeathReason::engulfed)) return {}; // v9 has no room for engulf and bud effects or the bud cost; only v10 reports them // (ADR-0129). if (const auto* perception = std::get_if(&message); - perception && version != session_protocol_v10 && perception->diagnostics && + perception && !cellular_v10_family(version) && perception->diagnostics && (perception->diagnostics->engulf != CellularEngulfResult::not_reported || perception->diagnostics->bud != CellularBudOutcome::not_reported || perception->diagnostics->bud_cost_energy_pj != 0 || @@ -211,17 +213,35 @@ std::vector encode_session(const SessionMessage& message, std::uin return {}; if (const auto* action = std::get_if(&message); action && (action->engulf || action->bud) && - (version != session_protocol_v10 || action->has_intake_target || action->intake_x_um || + (!cellular_v10_family(version) || action->has_intake_target || action->intake_x_um || action->intake_y_um || (action->engulf && action->bud))) return {}; if (version != session_protocol_v8 && version != session_protocol_v9 && - version != session_protocol_v10 && std::holds_alternative(message)) + !cellular_v10_family(version) && std::holds_alternative(message)) return {}; if (const auto* perception = std::get_if(&message)) { + // v11 (ADR-0136) lists deposits by ascending id, never patches; earlier versions the + // reverse. + if (version == session_protocol_v11 + ? !perception->patches.empty() || + perception->deposits.size() > max_cellular_perceived_deposits || + (!perception->life_identity && !perception->deposits.empty()) || + std::ranges::adjacent_find(perception->deposits, + [](const auto& a, const auto& b) { + return a.id >= b.id; + }) != perception->deposits.end() || + std::ranges::any_of(perception->deposits, + [](const auto& d) { + return d.id == 0 || + (d.shape != CellularDepositShape::pool && + d.shape != CellularDepositShape::bubble); + }) + : !perception->deposits.empty()) + return {}; if (!perception->tick || perception->patches.size() > max_cellular_perceived_patches || (!perception->life_identity && !perception->patches.empty()) || (version == session_protocol_v8 && perception->diagnostics) || - ((version == session_protocol_v9 || version == session_protocol_v10) && + ((version == session_protocol_v9 || cellular_v10_family(version)) && perception->life_identity && !perception->diagnostics) || (perception->life_identity == 0 && perception->diagnostics) || (perception->diagnostics && !valid_diagnostics(*perception->diagnostics)) || @@ -344,15 +364,16 @@ std::vector encode_session(const SessionMessage& message, std::uin std::vector operator()(const CellularPerception& m) const { auto out = header(SessionMessageType::cellular_perception, - (version == session_protocol_v10 ? cellular_perception_v10_prefix_bytes + (cellular_v10_family(version) ? cellular_perception_v10_prefix_bytes : version == session_protocol_v9 ? cellular_perception_v9_prefix_bytes : cellular_perception_prefix_bytes) + - m.patches.size() * cellular_perceived_patch_bytes, + m.patches.size() * cellular_perceived_patch_bytes + + m.deposits.size() * cellular_perceived_deposit_bytes, version); put(out, m.tick, 8); put(out, m.life_identity, 8); - put(out, m.patches.size(), 2); - if (version == session_protocol_v9 || version == session_protocol_v10) { + put(out, version == session_protocol_v11 ? m.deposits.size() : m.patches.size(), 2); + if (version == session_protocol_v9 || cellular_v10_family(version)) { const auto& d = m.diagnostics; put(out, d ? d->reserve_energy_pj : 0, 8); for (const auto value : d ? d->reserve_matter_fg : std::array{}) @@ -364,7 +385,7 @@ std::vector encode_session(const SessionMessage& message, std::uin out.push_back(d ? static_cast(d->intake) : static_cast(CellularIntakeResult::not_reported)); out.push_back(d && d->has_tick_effects ? 1 : 0); - if (version == session_protocol_v10) { + if (cellular_v10_family(version)) { out.push_back(d ? static_cast(d->engulf) : 0); out.push_back(d ? static_cast(d->bud) : 0); put(out, 0, 3); @@ -383,6 +404,16 @@ std::vector encode_session(const SessionMessage& message, std::uin for (const auto matter : patch.matter_fg) put(out, matter, 8); } + for (const auto& deposit : m.deposits) { + put(out, deposit.id, 4); + put(out, deposit.x_um, 4); + put(out, deposit.y_um, 4); + put(out, deposit.radius_um, 2); + out.push_back(static_cast(deposit.shape)); + out.push_back(deposit.drained ? 1 : 0); + for (const auto code : deposit.amount_codes) + put(out, code, 2); + } return out; } std::vector operator()(const IntentionReceipt& m) const { @@ -518,7 +549,7 @@ std::expected decode_session(std::span decode_session(std::span(SessionMessageType::cellular_action): { if (wire_version != session_protocol_v7 && wire_version != session_protocol_v8 && - wire_version != session_protocol_v9 && wire_version != session_protocol_v10) + wire_version != session_protocol_v9 && !cellular_v10_family(wire_version)) return std::unexpected(SessionCodecError::unsupported_version); if (!expect(cellular_action_bytes)) return std::unexpected(SessionCodecError::wrong_length); @@ -614,7 +645,7 @@ std::expected decode_session(std::span(static_cast(get(payload, 32, 2))); m.move_y = static_cast(static_cast(get(payload, 34, 2))); // Target kind: 0 none, 1 patch intake, 2 engulf and 3 bud (v10 only, ADR-0124/0125). - if (payload[36] > (wire_version == session_protocol_v10 ? 3 : 1) || payload[37] != 0 || + if (payload[36] > (cellular_v10_family(wire_version) ? 3 : 1) || payload[37] != 0 || payload[38] != 0 || payload[39] != 0) return std::unexpected(SessionCodecError::invalid_value); m.has_intake_target = payload[36] == 1; @@ -628,7 +659,7 @@ std::expected decode_session(std::span(SessionMessageType::cellular_mutation_action): { - if (wire_version != session_protocol_v10) + if (!cellular_v10_family(wire_version)) return std::unexpected(SessionCodecError::unsupported_version); if (!expect(cellular_mutation_action_bytes)) return std::unexpected(SessionCodecError::wrong_length); @@ -649,7 +680,7 @@ std::expected decode_session(std::span(SessionMessageType::cellular_life_ended): { - if (wire_version != session_protocol_v10) + if (!cellular_v10_family(wire_version)) return std::unexpected(SessionCodecError::unsupported_version); if (!expect(cellular_life_ended_bytes)) return std::unexpected(SessionCodecError::wrong_length); @@ -665,7 +696,7 @@ std::expected decode_session(std::span(SessionMessageType::cellular_mutation_offer): { - if (wire_version != session_protocol_v10) + if (!cellular_v10_family(wire_version)) return std::unexpected(SessionCodecError::unsupported_version); if (payload.size() < cellular_offer_prefix_bytes) return std::unexpected(SessionCodecError::wrong_length); @@ -702,7 +733,7 @@ std::expected decode_session(std::span(SessionMessageType::cellular_perception): { if (wire_version != session_protocol_v8 && wire_version != session_protocol_v9 && - wire_version != session_protocol_v10) + !cellular_v10_family(wire_version)) return std::unexpected(SessionCodecError::unsupported_version); if (payload.size() < cellular_perception_prefix_bytes) return std::unexpected(SessionCodecError::wrong_length); @@ -713,20 +744,23 @@ std::expected decode_session(std::span max_cellular_perceived_patches || - payload.size() != prefix + count * cellular_perceived_patch_bytes) + const bool deposits = wire_version == session_protocol_v11; + const auto entry = + deposits ? cellular_perceived_deposit_bytes : cellular_perceived_patch_bytes; + if (count > (deposits ? max_cellular_perceived_deposits : max_cellular_perceived_patches) || + payload.size() != prefix + count * entry) return std::unexpected(SessionCodecError::wrong_length); CellularPerception m; m.tick = get(payload, 0, 8); m.life_identity = get(payload, 8, 8); if (!m.tick || (!m.life_identity && count)) return std::unexpected(SessionCodecError::invalid_value); - if (wire_version == session_protocol_v9 || wire_version == session_protocol_v10) { + if (wire_version == session_protocol_v9 || cellular_v10_family(wire_version)) { CellularLifeDiagnostics d; d.reserve_energy_pj = get(payload, 18, 8); for (std::size_t channel = 0; channel < d.reserve_matter_fg.size(); ++channel) @@ -737,13 +771,13 @@ std::expected decode_session(std::span(CellularMovementResult::insufficient_energy) || payload[75] > static_cast(CellularIntakeResult::out_of_contact) || payload[76] > 1 || - std::ranges::any_of(payload.subspan(wire_version == session_protocol_v10 ? 79 : 77, - wire_version == session_protocol_v10 ? 3 : 5), + std::ranges::any_of(payload.subspan(cellular_v10_family(wire_version) ? 79 : 77, + cellular_v10_family(wire_version) ? 3 : 5), [](std::uint8_t value) { return value != 0; }) || payload[77] > static_cast(CellularEngulfResult::membrane_too_thick) || payload[78] > static_cast(CellularBudOutcome::no_placement)) return std::unexpected(SessionCodecError::invalid_value); - if (wire_version == session_protocol_v10) { + if (cellular_v10_family(wire_version)) { d.engulf = static_cast(payload[77]); d.bud = static_cast(payload[78]); if (!without_bud_cost) { @@ -769,13 +803,37 @@ std::expected decode_session(std::span(get(payload, offset, 4)); + d.x_um = static_cast(get(payload, offset + 4, 4)); + d.y_um = static_cast(get(payload, offset + 8, 4)); + d.radius_um = static_cast(get(payload, offset + 12, 2)); + const auto shape = payload[offset + 14]; + const auto drained = payload[offset + 15]; + if (d.id == 0 || drained > 1 || + (shape != static_cast(CellularDepositShape::pool) && + shape != static_cast(CellularDepositShape::bubble)) || + (!m.deposits.empty() && m.deposits.back().id >= d.id)) + return std::unexpected(SessionCodecError::invalid_value); + d.shape = static_cast(shape); + d.drained = drained == 1; + for (std::size_t c = 0; c < d.amount_codes.size(); ++c) + d.amount_codes.at(c) = + static_cast(get(payload, offset + 16 + c * 2, 2)); + m.deposits.push_back(d); + } + return m; + } + m.patches.reserve(count); for (std::size_t i = 0; i < count; ++i) { CellularPerceivedPatch patch; patch.x_um = static_cast(get(payload, offset, 4)); @@ -830,7 +888,7 @@ std::expected decode_session(std::span static_cast(ActionResult::committed) || (payload[8] == static_cast(ActionResult::committed) && wire_version != session_protocol_v7 && wire_version != session_protocol_v8 && - wire_version != session_protocol_v9 && wire_version != session_protocol_v10)) + wire_version != session_protocol_v9 && !cellular_v10_family(wire_version))) return std::unexpected(SessionCodecError::invalid_value); const ActionOutcome m{get(payload, 0, 8), static_cast(payload[8]), get(payload, 9, 8), get(payload, 17, 8)}; diff --git a/src/persistence/cellular_checkpoint_store.cpp b/src/persistence/cellular_checkpoint_store.cpp index fabc23f..f4720d2 100644 --- a/src/persistence/cellular_checkpoint_store.cpp +++ b/src/persistence/cellular_checkpoint_store.cpp @@ -168,6 +168,11 @@ provision_cellular_region(Postgres& owner, const FilesystemObjectStore& objects, // 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_presence_format && + opening.rules_version() == server::cellular_lives_foraging_rules) { + // ADR-0136 step A: a rules-8 region starts on the v9 bundle with genome revisions. + manifest->cellular_versions = cellular_v9_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_reproduction_rules) { // ADR-0137: a rules-7 region starts on the v8 bundle with genome revisions. diff --git a/src/persistence/region_checkpoint.cpp b/src/persistence/region_checkpoint.cpp index 9d8d62c..46941a7 100644 --- a/src/persistence/region_checkpoint.cpp +++ b/src/persistence/region_checkpoint.cpp @@ -74,7 +74,8 @@ bool structural(const CheckpointManifest& m) noexcept { m.cellular_versions != cellular_v5_versions && m.cellular_versions != cellular_v6_versions && m.cellular_versions != cellular_v7_versions && - m.cellular_versions != cellular_v8_versions) || + m.cellular_versions != cellular_v8_versions && + m.cellular_versions != cellular_v9_versions) || (cellular && m.versions != environmental_v1_versions)) return false; if (primitive && (m.manifest_version != 2 || m.tick_microseconds != 50000 || @@ -171,7 +172,8 @@ bool supported(const CheckpointManifest& m) noexcept { m.cellular_versions == cellular_v5_versions || m.cellular_versions == cellular_v6_versions || m.cellular_versions == cellular_v7_versions || - m.cellular_versions == cellular_v8_versions) && + m.cellular_versions == cellular_v8_versions || + m.cellular_versions == cellular_v9_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/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index 9e8827e..11be808 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -535,7 +535,11 @@ 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 reproduction = profile == CellularLivesProfile::reproduction; // Rules 7. + const bool foraging = profile == CellularLivesProfile::foraging; // Rules 8. + // A rules-8 opening needs a deposit habitat, and only it may have one. + if (foraging != (habitat->config().format == biology::cellular_habitat_deposit_format)) + return std::unexpected{CellularLivesError::habitat}; + const bool reproduction = profile == CellularLivesProfile::reproduction || foraging; const bool balance = profile == CellularLivesProfile::balance || reproduction; // Rules 6+. const bool presence = profile == CellularLivesProfile::presence || balance; const bool budding = profile == CellularLivesProfile::budding || presence; @@ -550,12 +554,13 @@ CellularLives::create(const PrimitiveLives& opening, : budding ? cellular_lives_bud_format : engulf ? cellular_lives_engulf_format : cellular_lives_format, - reproduction ? cellular_lives_reproduction_rules - : balance ? cellular_lives_balance_rules - : presence ? cellular_lives_presence_rules - : budding ? cellular_lives_bud_rules - : engulf ? cellular_lives_engulf_rules - : cellular_lives_rules); + foraging ? cellular_lives_foraging_rules + : reproduction ? cellular_lives_reproduction_rules + : balance ? cellular_lives_balance_rules + : 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)}}; } @@ -984,7 +989,8 @@ CellularLives::restore(std::span bytes, std::uint64_t world, format_version == cellular_lives_presence_format && (rules_version == cellular_lives_presence_rules || rules_version == cellular_lives_balance_rules || - rules_version == cellular_lives_reproduction_rules); + rules_version == cellular_lives_reproduction_rules || + rules_version == cellular_lives_foraging_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 && @@ -1169,6 +1175,10 @@ CellularLives::restore(std::span bytes, std::uint64_t world, return std::unexpected{CellularLivesError::checksum}; return std::unexpected{CellularLivesError::habitat}; } + // Rules 8 run on a deposit habitat, and nothing else does (ADR-0136). + if ((rules_version >= cellular_lives_foraging_rules) != + ((*habitat)->config().format == biology::cellular_habitat_deposit_format)) + return std::unexpected{CellularLivesError::habitat}; auto archive = biology::LineageArchive::decode(archive_payload); if (!archive) { if (archive.error() == biology::ArchiveCodecError::version) @@ -1248,6 +1258,7 @@ 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 contact_rules = state_->rules_version >= cellular_lives_foraging_rules; const bool bud_rules = state_->rules_version >= cellular_lives_bud_rules; const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules; for (std::size_t i = 0; i < ordered.size(); ++i) { @@ -1319,8 +1330,9 @@ CellularLives::advance_tick_with_mutations(std::span i *membrane, life.source}); } - auto proposal = biology::propose_cellular_region_step(state_->config.tick, state_->config.area, - inputs, *state_->habitat, {engulf_rules}); + auto proposal = + biology::propose_cellular_region_step(state_->config.tick, state_->config.area, inputs, + *state_->habitat, {engulf_rules, contact_rules}); if (!proposal) return std::unexpected{CellularLivesError::region_step}; @@ -1606,13 +1618,25 @@ CellularLives::advance_tick_with_mutations(std::span i found->stock = update.stock; } // Rules 3 detritus at empty cells becomes new patches; create() revalidates the map. - for (const auto& made : proposal->new_patches) { + // Format 2 (ADR-0136): new bubbles take the next deposit ids, and a deposit emptied this + // tick is gone. + const bool deposits = habitat_config.format == biology::cellular_habitat_deposit_format; + for (auto made : proposal->new_patches) { const auto at = std::ranges::lower_bound(habitat_config.patches, made.address, {}, [](const auto& patch) { return patch.address; }); if (at != habitat_config.patches.end() && at->address == made.address) return std::unexpected{CellularLivesError::habitat}; + if (deposits) { + if (habitat_config.next_deposit == std::numeric_limits::max()) + return std::unexpected{CellularLivesError::overflow}; + made.id = habitat_config.next_deposit++; + } habitat_config.patches.insert(at, made); } + if (deposits) + std::erase_if(habitat_config.patches, [](const biology::CellularPatch& patch) { + return patch.stock == accounting::Inventory{}; + }); auto next_habitat = biology::CellularHabitat::create(std::move(habitat_config)); if (!next_habitat) return std::unexpected{CellularLivesError::habitat}; diff --git a/src/server/lifecycle/wildlife_controller.cpp b/src/server/lifecycle/wildlife_controller.cpp index 1535a91..f6bae10 100644 --- a/src/server/lifecycle/wildlife_controller.cpp +++ b/src/server/lifecycle/wildlife_controller.cpp @@ -124,19 +124,34 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { const auto centre_y = static_cast(life.position.y_um) + extent / 2; std::optional nearest; std::uint64_t nearest_distance{}; + // Rules 8 (ADR-0136): deposits are discs at their centres, any non-empty one is food, + // and touching feeds; earlier rules seek energy patches and name them. + const bool deposits = state.rules_version() >= cellular_lives_foraging_rules; + const auto offset = deposits ? 0 : half_pitch; + std::optional chosen; for (const auto& patch : *perceived) { - if (patch.available.energy.value == 0) + if (deposits ? patch.available == accounting::Inventory{} + : patch.available.energy.value == 0) continue; - const auto dx = std::int64_t{patch.address.x_um} + half_pitch - centre_x; - const auto dy = std::int64_t{patch.address.y_um} + half_pitch - centre_y; + const auto dx = std::int64_t{patch.address.x_um} + offset - centre_x; + const auto dy = std::int64_t{patch.address.y_um} + offset - centre_y; const auto distance = static_cast(dx * dx + dy * dy); // Perception is ordered by address, so the first of equal distances wins. if (!nearest || distance < nearest_distance) { nearest = patch.address; nearest_distance = distance; + chosen = patch; } } - if (nearest) { + if (nearest && deposits && chosen) { + biology::CellularPatch disc{}; + disc.address = chosen->address; + disc.radius_um = chosen->radius_um; + disc.kind = chosen->kind; + if (!biology::cellular_patch_contact(life.position, extent, disc)) + intent.movement = wildlife_toward(std::int64_t{nearest->x_um} - centre_x, + std::int64_t{nearest->y_um} - centre_y); + } else if (nearest) { intent.intake_target = nearest; if (!overlaps(life.position.x_um, extent, nearest->x_um) || !overlaps(life.position.y_um, extent, nearest->y_um)) diff --git a/src/server/session/region_sessions.cpp b/src/server/session/region_sessions.cpp index 1a5ec43..5fe0163 100644 --- a/src/server/session/region_sessions.cpp +++ b/src/server/session/region_sessions.cpp @@ -153,7 +153,7 @@ struct RegionSessions::Impl { const network::SessionMessage& message) { for (const auto& c : connections) { if (c.state != State::established || - c.protocol_version != network::session_protocol_v10 || c.account_id != account) + !network::cellular_v10_family(c.protocol_version) || c.account_id != account) continue; const auto bytes = network::encode_session(message, c.protocol_version); return !bytes.empty() && endpoint->send_message(c.id, bytes).has_value(); @@ -447,7 +447,7 @@ struct RegionSessions::Impl { (c.protocol_version == network::session_protocol_v7 || c.protocol_version == network::session_protocol_v8 || c.protocol_version == network::session_protocol_v9 || - c.protocol_version == network::session_protocol_v10))))) + network::cellular_v10_family(c.protocol_version)))))) return close(c, SessionCloseReason::protocol, now); if (const auto* ack = std::get_if(&*decoded)) return replication.acknowledge(c.session, *ack); @@ -616,9 +616,9 @@ struct RegionSessions::Impl { ((wire_version == network::session_protocol_v7 || wire_version == network::session_protocol_v8 || wire_version == network::session_protocol_v9 || - wire_version == network::session_protocol_v10) && + network::cellular_v10_family(wire_version)) && !cellular_actions) || - wire_version > network::session_protocol_v10) + wire_version > network::session_protocol_v11) return close(c, SessionCloseReason::unsupported_version, now); } else if (wire_version != c.protocol_version) { return close(c, SessionCloseReason::unsupported_version, now); @@ -644,14 +644,14 @@ struct RegionSessions::Impl { if (c.protocol_version != network::session_protocol_v7 && c.protocol_version != network::session_protocol_v8 && c.protocol_version != network::session_protocol_v9 && - c.protocol_version != network::session_protocol_v10) + !network::cellular_v10_family(c.protocol_version)) return close(c, SessionCloseReason::protocol, now); if (const auto receipt = intents.admit(c.session, *m, admission())) answer(c, *receipt); return; } if (const auto* m = std::get_if(&*decoded)) { - if (c.protocol_version != network::session_protocol_v10 || + if (!network::cellular_v10_family(c.protocol_version) || !config.select_cellular_mutation) return close(c, SessionCloseReason::protocol, now); CellularMutationAnswer answer{ @@ -934,10 +934,15 @@ bool RegionSessions::send_cellular_perception(const network::AccountId& account, if (c.state != Impl::State::established || (c.protocol_version != network::session_protocol_v8 && c.protocol_version != network::session_protocol_v9 && - c.protocol_version != network::session_protocol_v10) || + !network::cellular_v10_family(c.protocol_version)) || c.account_id != account) continue; auto delivered = perception; + // v11 sees deposits (ADR-0136), earlier versions square patches; never both. + if (c.protocol_version == network::session_protocol_v11) + delivered.patches.clear(); + else + delivered.deposits.clear(); if (c.protocol_version == network::session_protocol_v8) delivered.diagnostics.reset(); if (c.protocol_version == network::session_protocol_v9 && delivered.diagnostics) { @@ -975,7 +980,7 @@ void RegionSessions::clear_cellular_perceptions(std::uint64_t tick) { if (c.state == Impl::State::established && (c.protocol_version == network::session_protocol_v8 || c.protocol_version == network::session_protocol_v9 || - c.protocol_version == network::session_protocol_v10)) + network::cellular_v10_family(c.protocol_version))) m.send(c, cleared); } diff --git a/tests/cellular_intent_protocol_tests.cpp b/tests/cellular_intent_protocol_tests.cpp index 92fac67..a547df2 100644 --- a/tests/cellular_intent_protocol_tests.cpp +++ b/tests/cellular_intent_protocol_tests.cpp @@ -1,10 +1,13 @@ #include "evo/network/session_protocol.hpp" #include +#include #include +#include #include #include #include +#include namespace { using namespace evo::network; @@ -429,6 +432,60 @@ void v10_mutation_offer_is_owner_only_and_canonical() { } } // namespace +// ADR-0136 (v11): the owner's view carries pools and bubbles by ascending id, with 16-bit +// amount codes; v10 never carries deposits and v11 never carries square patches. +void v11_perception_carries_deposits() { + CHECK(deposit_amount_code(0) == 0 && deposit_amount_value(0) == 0); + CHECK(deposit_amount_value(deposit_amount_code(1)) == 1); + for (const std::uint64_t value : + {std::uint64_t{7}, std::uint64_t{1'000}, std::uint64_t{123'456'789}, + std::uint64_t{5'000'000'000}, std::numeric_limits::max()}) { + const auto back = deposit_amount_value(deposit_amount_code(value)); + CHECK(back <= value && value - back <= value / 256); // Within 0.4 %. + CHECK(deposit_amount_code(back) == deposit_amount_code(value)); + } + CellularLifeDiagnostics d; + d.reserve_energy_pj = 9; + CellularPerception view{77, 7, {}, d}; + view.deposits.push_back({3, + 1'500, + 2'500, + 30, + CellularDepositShape::bubble, + true, + {deposit_amount_code(4'000'000), 0, 0, 0, 0}}); + view.deposits.push_back( + {9, 9'000, 400, 1'200, CellularDepositShape::pool, false, {1, 2, 3, 4, 5}}); + const auto bytes = encode_session(SessionMessage{view}, session_protocol_v11); + CHECK(bytes.size() == session_header_bytes + 18 + 64 + 40 + std::size_t{2} * 26); + std::uint16_t version{}; + const auto decoded = decode_session(bytes, &version); + CHECK(decoded && version == session_protocol_v11 && + std::get(*decoded) == view); + // v10 cannot carry deposits; v11 cannot carry patches. + CHECK(encode_session(SessionMessage{view}, session_protocol_v10).empty()); + auto patched = view; + patched.patches.push_back({0, 0, 1, {}}); + CHECK(encode_session(SessionMessage{patched}, session_protocol_v11).empty()); + // Ids must ascend; a zero id or unknown shape is refused on both sides. + auto unordered = view; + std::swap(unordered.deposits[0], unordered.deposits[1]); + CHECK(encode_session(SessionMessage{unordered}, session_protocol_v11).empty()); + auto bad = bytes; + bad[session_header_bytes + 122 + 14] = 7; // First entry's shape. + CHECK(!decode_session(bad)); + bad = bytes; + bad[session_header_bytes + 122 + 15] = 2; // First entry's drained flag. + CHECK(!decode_session(bad)); + // A cleared view and the other v10 messages are unchanged in v11. + CHECK(decode_session(encode_session(SessionMessage{CellularPerception{78, 0, {}, std::nullopt}}, + session_protocol_v11))); + const CellularLifeEnded ended{41, 7, CellularDeathReason::starved}; + const auto ended_bytes = encode_session(SessionMessage{ended}, session_protocol_v11); + CHECK(!ended_bytes.empty() && + std::get(*decode_session(ended_bytes)) == ended); +} + int main() { try { round_trip_and_version_gate(); @@ -441,6 +498,7 @@ int main() { v10_mutation_choice_is_a_strict_reliable_action(); v10_mutation_offer_is_owner_only_and_canonical(); v10_effects_and_life_end_are_owner_only(); + v11_perception_carries_deposits(); std::puts( "PASS cellular protocol: v6 intention, v7 action, v8-v10 perception/action framing"); } catch (const std::exception& error) { diff --git a/tests/cellular_lives_tests.cpp b/tests/cellular_lives_tests.cpp index 5ee9edd..1fe62ab 100644 --- a/tests/cellular_lives_tests.cpp +++ b/tests/cellular_lives_tests.cpp @@ -1121,6 +1121,95 @@ void twin_roll_follows_reproduction() { CHECK(founder > 800 && founder < 1'200); // About 1,000 of 4,000. CHECK(full > 1'800 && full < 2'200 && full > founder); } +// ADR-0136 step A (rules 8): a deposit habitat is scattered reproducibly; a cell feeds by +// touching bubbles and pools with no target (a pool at most at a quarter rate), an emptied +// bubble disappears, a starved cell breaks into new bubbles, and totals never change. +void rules_eight_cells_forage_by_contact() { + using namespace evo::biology; + CellularHabitatConfig base{98, 1, 7, 6'000, 6'000, {}}; + // A pool far from the founder's site, and a line of small energy bubbles east of it. + CellularPatch pool{}; + pool.address = {5'000, 5'000}; + pool.radius_um = 400; + pool.source = 31; + pool.stock = {{10'000'000'000}, {{{100'000'000}, {100'000'000}, {100'000'000}, {100'000'000}}}}; + const CellularMoteField field{40, 32, {{2'000'000}, {{{50'000}, {0}, {0}, {0}}}}, 0x5EED}; + const auto scattered = scatter_deposits(base, std::array{pool}, field); + CHECK(scattered && scattered->format == cellular_habitat_deposit_format && + scattered->patches.size() == 41 && scattered->next_deposit == 42); + CHECK(scatter_deposits(base, std::array{pool}, field) == scattered); // Reproducible. + auto other_seed = field; + other_seed.seed = 0x5EEE; + CHECK(scatter_deposits(base, std::array{pool}, other_seed) != scattered); + auto config = *scattered; + // A row of bubbles right in front of the founder: centres 120 um apart from x = 300. + for (std::uint32_t i = 0; i < 6; ++i) { + CellularPatch bubble{}; + bubble.address = {300 + 120 * i, 5}; // On the founder's path along y = 0. + bubble.radius_um = cellular_mote_radius_um; + bubble.kind = CellularDepositKind::mote; + bubble.source = 33; + bubble.stock.energy.value = 2'000; // Less than a tick of intake: one pass empties it. + bubble.id = config.next_deposit++; + config.patches.push_back(bubble); + } + std::ranges::sort(config.patches, {}, &CellularPatch::address); + auto habitat = CellularHabitat::create(config); + CHECK(habitat); + const auto restored = CellularHabitat::restore((*habitat)->snapshot(), 98, 1, 7); + CHECK(restored && (*restored)->config() == (*habitat)->config()); + + auto primitive = + PrimitiveLives::create({98, 1, 7, 17, founder_price(2), {{0, 0}, {3'000, 3'000}}}); + CHECK(primitive); + // A rules-8 opening needs a deposit habitat, and the reverse. + auto square = CellularHabitat::create({98, 1, 7, 6'000, 6'000, {}}); + CHECK(square); + CHECK(CellularLives::create(**primitive, std::move(*square), {{6'000, 6'000}, 0, 293'150}, + CellularLivesProfile::foraging) + .error() == CellularLivesError::habitat); + auto created = + CellularLives::create(**primitive, std::move(*habitat), {{6'000, 6'000}, 0, 293'150}, + CellularLivesProfile::foraging); + CHECK(created); + auto owner = std::move(*created); + CHECK(owner->rules_version() == cellular_lives_foraging_rules); + const std::span no_lives{}; + CHECK(owner->advance_tick(no_lives)); + LifeRequest request{}; + request.account.back() = 11; + request.action = 1; + auto born = owner->birth_candidate(request, {801, 801, 801, 801, {owner->tick()}}); + CHECK(born); + owner = std::move(*born); + CHECK(owner->lives().front().position == (CellularPosition{0, 0})); + const auto bubbles_before = owner->habitat().patches().size(); + // Swim east along the row: no intake target, yet the reserve gains energy and bubbles go. + CellularStepIntent east{}; + east.movement = {1'000, 0}; + bool fed = false; + for (int tick = 0; tick < 120; ++tick) { + CHECK(owner->advance_tick(std::array{CellularLifeIntent{801, east}})); + fed = fed || owner->last_tick_feedback().front().intake == CellularIntakeStatus::acquired; + CHECK(owner->current_total() == owner->opening_total()); + } + CHECK(fed); + CHECK(owner->habitat().patches().size() < bubbles_before); // Emptied bubbles are gone. + const auto saved = owner->snapshot(); + const auto again = CellularLives::restore(saved, 98, 1, 7, owner->tick()); + CHECK(again && (*again)->snapshot() == saved); + + // Starve: stand still where nothing lies. The corpse breaks into new bubbles with new ids. + const auto next_id = owner->habitat().config().next_deposit; + for (int tick = 0; tick < 20'000 && !owner->lives().empty(); ++tick) + CHECK(owner->advance_tick(std::array{CellularLifeIntent{801, CellularStepIntent{}}})); + CHECK(owner->lives().empty()); + CHECK(owner->habitat().config().next_deposit > next_id); + CHECK(std::ranges::any_of(owner->habitat().patches(), [&](const CellularPatch& patch) { + return patch.id >= next_id && patch.kind == CellularDepositKind::mote; + })); + CHECK(owner->current_total() == owner->opening_total()); +} } // namespace int main() { @@ -1137,6 +1226,7 @@ int main() { wildlife_steering_stays_within_the_intent_limit(); rules_seven_bud_twins_and_wildlife_hunts(); twin_roll_follows_reproduction(); + rules_eight_cells_forage_by_contact(); std::puts( "PASS cellular lives: feeding, tick ownership, terminal closure, rules 3, budding"); } catch (const std::exception& error) { diff --git a/tests/client_panels.cpp b/tests/client_panels.cpp index 4b7dd57..a09884f 100644 --- a/tests/client_panels.cpp +++ b/tests/client_panels.cpp @@ -453,6 +453,12 @@ void cellular_panels(const std::filesystem::path& review) { scene.patches.push_back({400, 260, 60, {0, 90, 0, 8, 0}, true, false, 2}); scene.cells.push_back({300, 300, 24, 2.5F, 2, 3, true, false, false, 901}); scene.cells.push_back({500, 220, 14, 4.0F, 0, 2, false, true, false, 77}); + // ADR-0136: a pool, a draining bubble, a still one and a pop draw under the HUD. + scene.deposits.push_back( + {620, 320, 50, {90000, 4000, 900, 300, 1200}, true, false, false, 5}); + scene.deposits.push_back({360, 330, 4, {0, 52000, 0, 0, 0}, false, true, false, 6}); + scene.deposits.push_back({380, 360, 4, {2000000, 0, 0, 0, 0}, false, false, false, 7}); + scene.pops.push_back({400, 300, 4, 0.4F, 3}); view.cellular_scene = &scene; PanelActions action; app->set_overlay([&] { action = draw_panels(view, form, display); }); diff --git a/tests/network_control.cpp b/tests/network_control.cpp index 487c00d..43d3779 100644 --- a/tests/network_control.cpp +++ b/tests/network_control.cpp @@ -371,7 +371,7 @@ void session_codec() { mutated.at(0) ^= 1; CHECK(refused(decode_session(mutated), SessionCodecError::bad_magic)); mutated = bytes; - mutated.at(4) = 11; // A future version; protocol versions through 10 are supported. + mutated.at(4) = 12; // A future version; protocol versions through 11 are supported. CHECK(refused(decode_session(mutated), SessionCodecError::unsupported_version)); mutated = bytes; mutated.at(7) = 1; diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index 15d6cab..d274d76 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,38,39,40,41,42"); + "25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43"); 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 0ca1952..ed13819 100644 --- a/tests/region_store_tests.cpp +++ b/tests/region_store_tests.cpp @@ -435,7 +435,7 @@ void provisioning_creates_the_life_allocator_once() { std::vector provision_cellular(const ServerRegion& r, const std::string& world, const std::string& opening, const std::string& build, const std::string& commit, const std::string& patch, - int& code) { + int& code, const std::string& food = "--patch") { const auto endowed = evo::biology::primitive_endowment(); CHECK(endowed); evo::accounting::Inventory funding = endowed->body; @@ -486,7 +486,7 @@ std::vector provision_cellular(const ServerRegion& r, const std::st "10000", "--ambient-temperature-mk", "293150", - "--patch", + food, patch}}; code = tool.wait_exit(30s); return tool.lines(); @@ -603,6 +603,27 @@ void cellular_v6_provisioning_uses_the_reproduction_bundle() { manifest->history_profile == cellular_revision_history_profile); } +// ADR-0136 step A: cellular-v7 is the rules-8 opening (pools and bubbles, no square +// patches) on the v9 bundle (schema v43); a --patch is refused. +void cellular_v7_provisioning_scatters_bubbles() { + const ServerRegion r{{9774, 1}, fresh("cellular-v7-provision-9774")}; + const std::string build(64, 'e'); + const std::string commit = "b0b81e5c0f7e1d2ba1a0ce5c0f7e1d2c"; // Unique to this test. + int code = -1; + const auto patched = provision_cellular(r, "9774", "cellular-v7", build, commit, + "3000,3000,2,1000,1000,1000,1000,1000", code); + CHECK(code != 0); + const auto first = provision_cellular(r, "9774", "cellular-v7", build, commit, + "40,1,2000000,50000,20000,0,0", code, "--motes"); + CHECK(code == 0 && has(first, "provisioned world=9774 region=1 sequence=0 tick=0")); + 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_v9_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, @@ -638,6 +659,7 @@ void run_region_store_tests() { cellular_v4_provisioning_uses_the_presence_bundle(); cellular_v5_provisioning_uses_the_balance_bundle(); cellular_v6_provisioning_uses_the_reproduction_bundle(); + cellular_v7_provisioning_scatters_bubbles(); 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 860be0a..518945f 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,38,39,40,41,42 +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,39,40,41,42,43 # 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")" = 42: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,39,40,41,42 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 43: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,39,40,41,42,43 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,38,39,40,41,42 +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,39,40,41,42,43 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=43 WHERE version=42' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=44 WHERE version=43' 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=42 WHERE version=43" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=43 WHERE version=44" 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 bacf671..6b072ca 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -96,6 +96,8 @@ digest_41="$(sha256sum "$root/migrations/0041_cellular_v7_balance_bundle.sql")" digest_41="${digest_41%% *}" digest_42="$(sha256sum "$root/migrations/0042_cellular_v8_reproduction_bundle.sql")" digest_42="${digest_42%% *}" +digest_43="$(sha256sum "$root/migrations/0043_cellular_v9_foraging_bundle.sql")" +digest_43="${digest_43%% *}" 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" \ @@ -131,5 +133,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_40=$digest_40" \ --set="migration_sha_41=$digest_41" \ --set="migration_sha_42=$digest_42" \ + --set="migration_sha_43=$digest_43" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"