diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index f566c5c..4ba3664 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -1,5 +1,6 @@ #include "cellular_scene.hpp" #include "controls_flow.hpp" +#include "evo/biology/cellular_currents.hpp" #include "evo/client/application.hpp" #include "evo/client/auth.hpp" #include "evo/client/launcher.hpp" @@ -486,6 +487,12 @@ int main(int argc, char** argv) try { std::uint64_t seen_deposit_tick{}; std::vector live_pops; bool scene_active = false; + // Rules 12: the region's current field, regenerated when the perceived configuration + // changes, and when the latest perception arrived (to carry bubbles between views). + std::optional flow_config; + std::optional flow_field; + std::uint64_t flow_view_tick = 0; + auto flow_view_at = std::chrono::steady_clock::now(); evo::client_app::PanelActions actions; (*app)->set_overlay([&] { evo::client_app::PanelView view; @@ -741,6 +748,7 @@ int main(int argc, char** argv) try { const double width = state.logical_width, height = state.logical_height; // 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.flows.clear(); scene.patches.clear(); scene.deposits.clear(); scene.pops.clear(); @@ -773,9 +781,65 @@ int main(int argc, char** argv) try { p.seed = (static_cast(patch.x_um) << 32U) ^ patch.y_um; scene.patches.push_back(p); } + // Rules 12 (v13): the current field from the perceived configuration, drawn + // as streaks across the visible area. + if (const auto* perception = cellular_remote->cellular_perception()) { + if (perception->currents != flow_config) { + flow_config = perception->currents; + flow_field.reset(); + if (const auto& c = flow_config) { + auto made = evo::biology::CellularFlowField::generate( + {c->seed, c->width_um, c->height_um, c->pitch_um, c->min_count, + c->max_count, c->min_route_width_um, c->max_route_width_um, + c->min_speed_um_per_s, c->max_speed_um_per_s}); + if (made) + flow_field = std::move(*made); + } + } + if (perception->tick != flow_view_tick) { + flow_view_tick = perception->tick; + flow_view_at = std::chrono::steady_clock::now(); + } + const auto low = camera->screen_to_world({0, height}); + const auto high = camera->screen_to_world({width, 0}); + if (flow_field && low && high) { + const double span = std::max(high->x_mm - low->x_mm, 0.001); + const double step = std::max(0.4, span / 28); + for (double y = std::floor(low->y_mm / step) * step; y <= high->y_mm; + y += step) + for (double x = std::floor(low->x_mm / step) * step; x <= high->x_mm; + x += step) { + const auto flow = + flow_field->sample(static_cast(x * 1000), + static_cast(y * 1000)); + const double vx = flow.x_q10 / 1024.0, vy = flow.y_q10 / 1024.0; + const double speed = std::hypot(vx, vy); + if (speed < 5) + continue; + const auto at = camera->world_to_screen({x, y}); + const auto ahead = camera->world_to_screen( + {x + vx / speed * 0.001, y + vy / speed * 0.001}); + if (!at || !ahead) + continue; + const double sx = ahead->x - at->x, sy = ahead->y - at->y; + const double norm = std::max(std::hypot(sx, sy), 1e-9); + const double length = 8 + std::min(speed, 300.0) / 300 * 16; + scene.flows.push_back( + {static_cast(at->x), static_cast(at->y), + static_cast(sx / norm * length), + static_cast(sy / norm * length), + static_cast(std::min(speed, 300.0) / 300), + static_cast(x * 7919 + y * 104729)}); + } + } + } // 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(); + // Rules 12: carry each bubble along its perceived velocity since the view + // arrived (at most 300 ms), so moving food glides between perceptions. + const double carried = std::min( + std::chrono::duration(now_pop - flow_view_at).count(), 0.3); std::map current; for (const auto& d : perception->deposits) { std::array stock{}; @@ -785,13 +849,13 @@ int main(int argc, char** argv) try { 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, - d.drained, - d.shape == - evo::network::CellularDepositShape::bubble}; + const SeenDeposit seen{ + (static_cast(d.x_um) + d.velocity_x_um_s * carried) / 1000, + (static_cast(d.y_um) + d.velocity_y_um_s * carried) / 1000, + d.radius_um, + channel, + d.drained, + d.shape == evo::network::CellularDepositShape::bubble}; current[d.id] = seen; const auto centre = camera->world_to_screen({seen.x_mm, seen.y_mm}); const auto edge = camera->world_to_screen( diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index 86d851b..5ed2120 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -89,7 +89,7 @@ std::string controls_hint(const client::Bindings& b) { return "Click selects, wheel zooms. Move " + k(Action::move_up) + " " + k(Action::move_left) + " " + k(Action::move_down) + " " + k(Action::move_right) + "; pan " + k(Action::pan_up) + " " + k(Action::pan_left) + " " + k(Action::pan_down) + " " + k(Action::pan_right) + - "; UI capture " + k(Action::toggle_capture) + "."; + "; brake " + k(Action::brake) + "; UI capture " + k(Action::toggle_capture) + "."; } // Fixed wording only (never echoes paths or file bytes); wraps inside the launcher. void error_text(client::LaunchError error) { @@ -939,11 +939,24 @@ void inspect_cell(ImDrawList& list, const SceneCell& c) { } ImGui::EndTooltip(); } +// Rules 12: currents as faint drifting streaks under the food, so the flow is readable before +// a cell commits to it. Specks are thin lines, never discs, so they never read as food. +void draw_flows(ImDrawList& list, const std::vector& flows, float time) { + for (const auto& f : flows) { + const float phase = std::fmod(time * 0.5F + static_cast(f.seed % 97U) / 97.0F, 1.0F); + const float fade = std::sin(phase * 3.14159265F); + const auto alpha = static_cast((24.0F + 80.0F * f.strength) * fade); + const ImVec2 from{f.x + f.dx * (phase - 0.5F), f.y + f.dy * (phase - 0.5F)}; + const ImVec2 to{from.x + f.dx * 0.6F, from.y + f.dy * 0.6F}; + list.AddLine(from, to, IM_COL32(140, 200, 235, alpha), 1.4F); + } +} void draw_scene(const PanelView& v) { if (!v.cellular_scene) return; auto& list = *ImGui::GetBackgroundDrawList(); const auto time = static_cast(ImGui::GetTime()); + draw_flows(list, v.cellular_scene->flows, time); for (const auto& patch : v.cellular_scene->patches) draw_patch(list, patch); for (const auto& deposit : v.cellular_scene->deposits) diff --git a/apps/evo-client/panels.hpp b/apps/evo-client/panels.hpp index 1aed144..59d23e9 100644 --- a/apps/evo-client/panels.hpp +++ b/apps/evo-client/panels.hpp @@ -56,7 +56,13 @@ struct ScenePop { float x{}, y{}, radius{}, age{}; // Age 0..1 over the pop's life. int channel{}; }; +// Rules 12: one streak of the local current; dx/dy in pixels, strength 0..1 by speed. +struct SceneFlow { + float x{}, y{}, dx{}, dy{}, strength{}; + std::uint32_t seed{}; +}; struct CellularScene { + std::vector flows; std::vector patches; std::vector deposits; std::vector pops; diff --git a/apps/evo-client/remote_session.hpp b/apps/evo-client/remote_session.hpp index c6f25eb..3b2ede9 100644 --- a/apps/evo-client/remote_session.hpp +++ b/apps/evo-client/remote_session.hpp @@ -501,8 +501,8 @@ class RemoteSession { return false; client::RegionSessionClientConfig config; if (cellular_trial_) - // ADR-0176: v12 is v11 (deposits) plus captured light and visible producers. - config.protocol_version = network::session_protocol_v12; + // Rules 12: v13 is v12 (deposits, light, producers) plus liquid motion and brake. + config.protocol_version = network::session_protocol_v13; 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. @@ -632,9 +632,9 @@ class RemoteSession { organisms_.current(), cellular_feed_target_); cellular_feed_target_ = steering.patch; const auto id = cellular_play_.allocate_id(); - if (id == 0 || - !client_->send_cellular_action(id, tick, steering.intention.move_x, - steering.intention.move_y, cellular_feed_target_)) + if (id == 0 || !client_->send_cellular_action( + id, tick, steering.intention.move_x, steering.intention.move_y, + cellular_feed_target_, false, false, steering.intention.brake)) return; sent_tick_ = server_tick_; cellular_sent_tick_ = tick; diff --git a/apps/evo-server/cellular_bridge.hpp b/apps/evo-server/cellular_bridge.hpp index 970e2e8..54f5156 100644 --- a/apps/evo-server/cellular_bridge.hpp +++ b/apps/evo-server/cellular_bridge.hpp @@ -27,6 +27,9 @@ #include namespace evo::server_app { +// Rules 12: moving bubbles listed per perception, nearest first (the tuning file's trial +// food.visible_moving_bubbles). Pools are always listed. +inline constexpr std::size_t cellular_visible_moving_bubbles = 256; // Profile-4 network boundary. Biology and persistence remain owned by the cellular host; // this bridge handles admission, v7-v9 action receipts, public cell replication and // owner-filtered v8/v9 perception. @@ -257,6 +260,25 @@ class CellularBridge { diagnostics.bud = feedback->bud ? bud_outcome(*feedback->bud) : network::CellularBudOutcome::not_requested; } + // Rules 12 (v13): the authoritative motion state and the region's currents, from + // which the client regenerates the identical flow field. + const auto* field = state.flow_field(); + if (field) { + diagnostics.velocity_x_q10 = life.motion.velocity_x_q10; + diagnostics.velocity_y_q10 = life.motion.velocity_y_q10; + diagnostics.heading = life.motion.heading; + const auto& c = state.liquid_rules().currents; + view.currents = network::CellularCurrentsView{c.seed, + c.width_um, + c.height_um, + c.pitch_um, + c.min_count, + c.max_count, + c.min_route_width_um, + c.max_route_width_um, + c.min_speed_um_per_s, + c.max_speed_um_per_s}; + } view.diagnostics = diagnostics; view.patches.reserve(perceived->size()); // ADR-0136 (rules 8): pools and bubbles go out as v11 deposits, the nearest 512 to @@ -284,16 +306,49 @@ class CellularBridge { 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; - })); + 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; + // Rules 12 (v13): a bubble's world velocity, current plus induced drift, so the + // client can carry it between perceptions. + if (field && patch.kind == biology::CellularDepositKind::mote) { + const auto flow = field->sample(patch.address.x_um, patch.address.y_um); + std::int64_t drift_x{}, drift_y{}; + if (const auto index = state.habitat().find(patch.address)) { + drift_x = state.habitat().patches()[*index].drift_x_q10; + drift_y = state.habitat().patches()[*index].drift_y_q10; + } + const auto um_s = [](std::int64_t q10) { + return static_cast(std::clamp( + q10 / biology::cellular_velocity_q10_per_um_s, -32'767, 32'767)); + }; + deposit.velocity_x_um_s = um_s(flow.x_q10 + drift_x); + deposit.velocity_y_um_s = um_s(flow.y_q10 + drift_y); + } 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); } + // Rules 12: every pool, but only the nearest moving bubbles (the tuning file's + // trial 256); the client carries the rest with the current. + if (field) { + const auto bubbles = std::ranges::partition(near, [](const auto& entry) { + return entry.second.shape == network::CellularDepositShape::pool; + }); + const auto keep = std::min(cellular_visible_moving_bubbles, + static_cast(bubbles.size())); + std::ranges::nth_element( + bubbles, bubbles.begin() + static_cast(keep), + [](const auto& a, const auto& b) { + return std::pair{a.first, a.second.id} < std::pair{b.first, b.second.id}; + }); + near.erase(bubbles.begin() + static_cast(keep), near.end()); + } if (near.size() > network::max_cellular_perceived_deposits) { std::ranges::nth_element( near, diff --git a/apps/evo-world-clone/main.cpp b/apps/evo-world-clone/main.cpp index 980684a..dcfbae3 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-v8 +// development-v1|primitive-v1|cellular-v1 to cellular-v9 // --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. @@ -25,6 +25,10 @@ // --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). +// cellular-v8 (ADR-0176) also requires --light-pj N. cellular-v9 (rules 12, ADR-0177) +// is cellular-v8 followed by the liquid upgrade: it also requires --tuning FILE (the Git +// tuning file, whose region size must match --width-um/--height-um) and accepts +// --current-seed N (default: derived from the --commit bytes). // 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. @@ -84,6 +88,8 @@ #include #include #include +#include +#include #include #include #include @@ -118,13 +124,20 @@ struct Options { std::vector cellular_patches; std::vector cellular_pools; // cellular-v7 std::optional cellular_motes; // cellular-v7 and v8 - std::optional light_pj; // cellular-v8: pJ per square um per tick + std::optional light_pj; // cellular-v8/v9: pJ per square um per tick + std::optional tuning_path; // cellular-v9: the Git tuning file + std::optional current_seed; + std::optional tuning; // Parsed from tuning_path. std::optional life_allocator_start; std::optional build; bool retain_build{}; bool crash{}; }; +// The openings that declare light: cellular-v8, and cellular-v9 which adds the liquid upgrade. +bool lit_opening(std::string_view opening) { + return opening == "cellular-v8" || opening == "cellular-v9"; +} std::optional number(std::string_view text) { std::uint64_t value{}; const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value); @@ -336,10 +349,14 @@ std::optional parse(int argc, char** argv) { (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-v7" || - value == "cellular-v8")) + value == "cellular-v8" || value == "cellular-v9")) o.opening = value; else if (o.command == "provision" && flag == "--light-pj" && n && *n > 0) o.light_pj = n; + else if (o.command == "provision" && flag == "--tuning" && !value.empty()) + o.tuning_path = std::string{value}; + else if (o.command == "provision" && flag == "--current-seed" && n) + o.current_seed = n; else if (o.command == "provision" && flag == "--frame" && n) o.primitive_frame = n; else if (o.command == "provision" && flag == "--source-id" && n) @@ -423,11 +440,36 @@ std::optional parse(int argc, char** argv) { return std::nullopt; if (cellular_options) return std::nullopt; - } else if (o.opening == "cellular-v7" || o.opening == "cellular-v8") { + } else if (o.opening == "cellular-v7" || lit_opening(o.opening)) { // Pools and bubbles only: square patches belong to the earlier openings. Only - // cellular-v8 (ADR-0176) declares light. - if ((o.opening == "cellular-v8") != o.light_pj.has_value()) + // cellular-v8 and v9 (ADR-0176) declare light; only v9 takes a tuning file. + if (lit_opening(o.opening) != o.light_pj.has_value() || + (o.opening == "cellular-v9") != o.tuning_path.has_value() || + (o.current_seed && o.opening != "cellular-v9")) return std::nullopt; + if (o.tuning_path) { + std::ifstream file(*o.tuning_path, std::ios::binary); + const std::string text{std::istreambuf_iterator(file), + std::istreambuf_iterator()}; + auto parsed = biology::parse_cellular_tuning(text); + if (!file.good() && !file.eof()) { + std::printf("tuning file unreadable: %s\n", o.tuning_path->c_str()); + return std::nullopt; + } + if (!parsed) { + std::printf("tuning file refused at line %zu (%s): %s\n", parsed.error().line, + parsed.error().key.c_str(), + std::string{biology::describe(parsed.error().kind)}.c_str()); + return std::nullopt; + } + if (!o.cellular_width_um || !o.cellular_height_um || + parsed->region_width_um != *o.cellular_width_um || + parsed->region_height_um != *o.cellular_height_um) { + std::puts("tuning region size differs from --width-um/--height-um"); + return std::nullopt; + } + o.tuning = *parsed; + } 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, @@ -548,21 +590,39 @@ std::vector probe_bytes() { return out; } +// cellular-v9 (rules 12): the liquid rules from the tuning file, for the opening's area and +// a current seed (given, or derived from the genesis commit's bytes 8-15). +std::optional liquid_rules(const Options& o) { + if (o.opening != "cellular-v9" || !o.tuning || !o.cellular_width_um || !o.cellular_height_um) + return std::nullopt; + std::uint64_t seed = o.current_seed.value_or(0); + if (!o.current_seed) { + const auto commit = o.commit.value_or(persistence::Uuid{}); + for (std::size_t i = 8; i < 16; ++i) + seed = (seed << 8U) | commit.at(i); + } + return server::cellular_liquid_rules(*o.tuning, {*o.cellular_width_um, *o.cellular_height_um}, + seed); +} + // ADR-0176 cellular-v8: a cellular-v7 genesis taken through one empty tick and the durable -// bundle 9 -> 10 -> 11 -> 12 -> 13 upgrades, declaring the region's light. Resumable: it -// continues from whichever bundle the head has reached, and does nothing at bundle 13. +// bundle 9 -> 10 -> 11 -> 12 -> 13 upgrades, declaring the region's light. cellular-v9 adds the +// 13 -> 14 liquid upgrade. Resumable: it continues from whichever bundle the head has reached, +// and does nothing at its target bundle. int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, const persistence::FilesystemObjectStore& store, std::uint64_t frame, const persistence::Sha256Digest& build, - std::uint64_t light_pj) { + std::uint64_t light_pj, + const std::optional& liquid) { const auto& key = o.source.key; + const auto target = + liquid ? persistence::cellular_v14_versions : persistence::cellular_v13_versions; // A finished opening needs no lease: a rerun (every Argo sync's provision hook) runs // while the region server holds it, and must report the region rather than fail. if (const auto current = persistence::load_region_checkpoint(db, key, timeout); current) { const auto manifest = persistence::decode_manifest(current->manifest); if (manifest && manifest->profile == persistence::CheckpointProfile::cellular_lives_v1 && - manifest->frame == frame && - manifest->cellular_versions == persistence::cellular_v13_versions) + manifest->frame == frame && manifest->cellular_versions == target) return 0; } auto lease = @@ -580,13 +640,13 @@ int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, auto head = persistence::load_region_checkpoint(db, key, timeout); if (!head) return finish(3); - for (unsigned step = 0; step < 6; ++step) { + for (unsigned step = 0; step < 7; ++step) { const auto manifest = persistence::decode_manifest(head->manifest); if (!manifest || manifest->profile != persistence::CheckpointProfile::cellular_lives_v1 || manifest->frame != frame) return finish(4); const auto& versions = manifest->cellular_versions; - if (versions == persistence::cellular_v13_versions) + if (versions == target) return finish(0); const auto id = [&] { persistence::Uuid made{}; @@ -637,6 +697,9 @@ int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, upgraded = persistence::migrate_cellular_photosynthesis_profile( db, store, *lease, *head, id, build, {light_pj, 1, {std::numeric_limits::max() / 2}}, timeout); + else if (versions == persistence::cellular_v13_versions && liquid) + upgraded = persistence::migrate_cellular_liquid_profile(db, store, *lease, *head, id, + build, *liquid, timeout); else return finish(4); if (!upgraded) { @@ -654,7 +717,7 @@ int provision(const Options& o) { 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-v7" || o.opening == "cellular-v8"; + o.opening == "cellular-v7" || lit_opening(o.opening); const auto primitive_frame = o.primitive_frame.value_or(0); if ((primitive || cellular) && primitive_frame == 0) return 2; @@ -749,7 +812,7 @@ 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" || o.opening == "cellular-v8") { + if (o.opening == "cellular-v7" || lit_opening(o.opening)) { // 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{}); @@ -771,7 +834,7 @@ 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-v7" || o.opening == "cellular-v8" + o.opening == "cellular-v7" || lit_opening(o.opening) ? server::CellularLivesProfile::foraging : o.opening == "cellular-v6" ? server::CellularLivesProfile::reproduction : o.opening == "cellular-v5" ? server::CellularLivesProfile::balance @@ -815,7 +878,7 @@ int provision(const Options& o) { std::puts("provision refused existing profile/frame mismatch"); return 4; } - if (o.opening == "cellular-v8") { + if (lit_opening(o.opening)) { if (manifest->sequence == 0 && !persistence::provision_cellular_region(*db, *store, o.source.key, primitive_frame, *cellular_opening, @@ -824,8 +887,9 @@ int provision(const Options& o) { "--commit to resolve genesis"); return 4; } - if (const auto finished = finish_photosynthesis_opening( - o, *db, *store, primitive_frame, build, o.light_pj.value_or(0)); + if (const auto finished = + finish_photosynthesis_opening(o, *db, *store, primitive_frame, build, + o.light_pj.value_or(0), liquid_rules(o)); finished != 0) return finished; auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout); @@ -877,9 +941,10 @@ int provision(const Options& o) { static_cast(made.error().kind)); return 4; } - if (o.opening == "cellular-v8") { - if (const auto finished = finish_photosynthesis_opening(o, *db, *store, primitive_frame, - build, o.light_pj.value_or(0)); + if (lit_opening(o.opening)) { + if (const auto finished = + finish_photosynthesis_opening(o, *db, *store, primitive_frame, build, + o.light_pj.value_or(0), liquid_rules(o)); finished != 0) return finished; auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout); diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index f861d04..85d85be 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-20261021T212858-ccf85ec3:1792632538"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261021T220859-3894c212:1792634939"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/docs/adr/0178-durable-liquid-region.md b/docs/adr/0178-durable-liquid-region.md new file mode 100644 index 0000000..55ea775 --- /dev/null +++ b/docs/adr/0178-durable-liquid-region.md @@ -0,0 +1,48 @@ +# ADR-0178: Durable liquid regions and session v13 + +## Status and scope + +Accepted 2026-10-21. Implements phases 1-2 of the +[region and movement plan](../../Cellular_Region_Movement_Plan.md) under +[ADR-0177](0177-cellular-regions-world-linkage.md): rules 12 on the raw profile-4 path, +schema 58, the `cellular-v9` opening and session protocol v13. Trial numbers come from the +Git tuning file. DEV-only; no World0 operation. + +## Decision + +**Biology.** Genome schema 6 carries the movement arrangement (001-010, 100 = founder); +development 6 and founder 5 use it. A shared integer motion step (velocity relative to the +liquid, heading, funded thrust and braking, drag to exactly zero, sub-micrometre carry) +runs identically on server and client. Seeded looping currents are a condition, not stock. +Habitat format 3 moves bubbles with the current and the drift moving cells induce, merges +touching bubbles up to a cap, keeps pools fixed and addresses unique. + +**Owner format 10, rules 12.** An explicit no-tick format-9/rules-11 upgrade declares the +liquid rules (current configuration, founder handling, deposit motion) taken from the +tuning file and a seed when the region opens; the server never reads the file. See +[schemas/cellular-lives-v10.md](../../schemas/cellular-lives-v10.md). Brake is a step +intent valid only under rules 12, carried in raw trace 4 as flag bit 1. + +**Bundle 14, schema 58.** Bundle 14 `(12, 10, 2, 1, 1, 6, 5, 2, 1)` is admitted by +parser-local normalization to bundle 13, with bundle 12/13's births and mutation results, +and an exact fenced 13 -> 14 upgrade whose only input, the liquid rules, recovery reads +from the target. Schema 58 also widens the canonical action input: byte 13 bit 0 is brake. +Population, census and migration profiles do not admit bundle 14 (raw path only, per the +maintainer). + +**Opening `cellular-v9`.** `cellular-v8` followed by the 13 -> 14 upgrade, with +`--tuning FILE` (region size must match) and an optional `--current-seed`; resumable and +idempotent at bundle 14. DEV mounts the tuning file into the provision Job as a generated +ConfigMap. + +**Session v13.** v12 plus liquid motion in the owner's perception (velocity, heading and +the current configuration), deposit world velocities and a brake on cellular actions. See +[schemas/network/session-v13-cellular-liquid.md](../../schemas/network/session-v13-cellular-liquid.md). + +## Consequences + +DEV region 10 (60 x 60 mm) replaces region 9 as the served region; regions 1-9 stay stored. +The v13 client draws currents and carries bubbles between perceptions. Remaining from the +plan: client-side prediction of the owner's motion with the shared step, the thermal map +(phase 3), movement mutations (phase 4), wildlife that plans with inertia (phase 5), logout +and region capacity (phase 6), and live retuning without reopening a region. diff --git a/docs/adr/README.md b/docs/adr/README.md index 3b75376..f3bbe51 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,5 +1,7 @@ # Architecture decision records +- [ADR-0178: Durable liquid regions and session v13](0178-durable-liquid-region.md) - rules 12 on owner format 10 (currents, moving food, liquid motion), raw bundle 14 and schema 58 with a 13 -> 14 upgrade from the Git tuning file, the `cellular-v9` opening and session v13 (motion, currents, brake). + - [ADR-0177: Cellular regions, world linkage and emergence](0177-cellular-regions-world-linkage.md) - maintainer-accepted direction: regions map to a world area rather than a voxel, currents and the thermal map are conditions not stock, capped regions refuse births, scaled emergence export, protected anchored logout; implementation pending. - [ADR-0176: Durable photosynthesis regions and session v12](0176-durable-photosynthesis-region.md) - schema 57 raw bundle 13 (rules 11, owner format 9) with a light-declaring 12 -> 13 upgrade, the resumable `cellular-v8` opening and session v12 (captured light, visible producers, photosynthesis offers). diff --git a/include/evo/client/bindings.hpp b/include/evo/client/bindings.hpp index 4ba2d9b..85afca5 100644 --- a/include/evo/client/bindings.hpp +++ b/include/evo/client/bindings.hpp @@ -22,9 +22,10 @@ enum class Action : std::uint8_t { pan_right, pan_up, pan_down, - toggle_capture + toggle_capture, + brake // Rules 12: appended so earlier controls files keep their meaning. }; -inline constexpr std::size_t action_count = 9; +inline constexpr std::size_t action_count = 10; using KeyCode = std::uint16_t; // HID usage; 0 means unbound. inline constexpr KeyCode no_key = 0; inline constexpr KeyCode escape_key = 41; // Reserved: cancels binding capture. diff --git a/include/evo/client/input.hpp b/include/evo/client/input.hpp index 129e954..9db7333 100644 --- a/include/evo/client/input.hpp +++ b/include/evo/client/input.hpp @@ -6,7 +6,18 @@ #include namespace evo::client { -enum class Key : std::uint8_t { left, right, up, down, pan_left, pan_right, pan_up, pan_down }; +// `brake` (rules 12) opposes the cell's velocity relative to the liquid while held. +enum class Key : std::uint8_t { + left, + right, + up, + down, + pan_left, + pan_right, + pan_up, + pan_down, + brake +}; enum class InputError : std::uint8_t { invalid_key, invalid_pointer, @@ -17,6 +28,7 @@ enum class InputError : std::uint8_t { struct Intention { std::uint64_t sequence{}, tick{}; std::int16_t move_x{}, move_y{}; // Signed unit vector *1000, local XY (+Y up). + bool brake{}; // Rules 12: held brake. }; struct Navigation { int x{}, y{}; @@ -49,7 +61,7 @@ class InputState { private: void clear() noexcept; - std::array keys_{}; + std::array keys_{}; bool admitted_{false}, captured_{false}; ScreenPoint pointer_{}; double wheel_{}; diff --git a/include/evo/client/region_session.hpp b/include/evo/client/region_session.hpp index ffe01e4..5dfe37f 100644 --- a/include/evo/client/region_session.hpp +++ b/include/evo/client/region_session.hpp @@ -65,7 +65,7 @@ class RegionSessionClient { send_cellular_action(std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, std::int16_t move_y, std::optional> intake_target = {}, - bool engulf = false, bool bud = false); + bool engulf = false, bool bud = false, bool brake = false); // Protocol v10 (ADR-0121): choose one candidate of the life's outstanding offer. The // receipt names the tick it publishes with; the outcome follows that commit. `tick` is // the client's latest simulated tick (after the offer); the server schedules the next. diff --git a/include/evo/network/session_protocol.hpp b/include/evo/network/session_protocol.hpp index 1bdbd26..2e2a44f 100644 --- a/include/evo/network/session_protocol.hpp +++ b/include/evo/network/session_protocol.hpp @@ -41,19 +41,28 @@ inline constexpr std::uint16_t session_protocol_v11 = 11; // v12 (ADR-0176) is v11 plus the owner's captured light and visible producers in its // perception, and the photosynthesis capability (7) in mutation offers. inline constexpr std::uint16_t session_protocol_v12 = 12; -// v10, v11 and v12 share every cellular message but the perception's contents. +// v13 (rules 12, ADR-0177) is v12 plus liquid motion: the owner's velocity and heading and the +// region's current configuration in its perception, each deposit's world velocity, and a brake +// flag on cellular actions. +inline constexpr std::uint16_t session_protocol_v13 = 13; +// v10 to v13 share every cellular message but the perception's contents and v13's brake. [[nodiscard]] constexpr bool cellular_v10_family(std::uint16_t version) noexcept { return version == session_protocol_v10 || version == session_protocol_v11 || - version == session_protocol_v12; + version == session_protocol_v12 || version == session_protocol_v13; } // Versions whose perception lists pools and bubbles (ADR-0136) instead of square patches. [[nodiscard]] constexpr bool cellular_deposit_version(std::uint16_t version) noexcept { - return version == session_protocol_v11 || version == session_protocol_v12; + return version == session_protocol_v11 || version == session_protocol_v12 || + version == session_protocol_v13; +} +// Versions that carry captured light and producers (ADR-0176). +[[nodiscard]] constexpr bool cellular_light_version(std::uint16_t version) noexcept { + return version == session_protocol_v12 || version == session_protocol_v13; } // The highest capability a version's mutation offers may name. [[nodiscard]] constexpr std::uint8_t cellular_offer_capability_limit(std::uint16_t version) noexcept { - return version == session_protocol_v12 ? 7 : 6; + return cellular_light_version(version) ? 7 : 6; } inline constexpr std::size_t max_cellular_perceived_patches = 256; inline constexpr std::size_t max_cellular_perceived_deposits = 512; @@ -197,7 +206,8 @@ struct CellularActionInput { bool has_intake_target{}; std::uint32_t intake_x_um{}, intake_y_um{}; bool engulf{}; - bool bud{}; // Kind 3 (ADR-0125): fund one wildlife bud, zero coordinates, v10 only. + bool bud{}; // Kind 3 (ADR-0125): fund one wildlife bud, zero coordinates, v10 only. + bool brake{}; // Byte 13 bit 0 (schema 58, rules 12): oppose relative velocity. friend bool operator==(const CellularActionInput&, const CellularActionInput&) = default; }; inline constexpr std::size_t cellular_action_input_bytes = 24; @@ -212,6 +222,8 @@ struct CellularAction { bool engulf{}; // v10 (ADR-0125): fund one wildlife bud; exclusive with intake and engulfment. bool bud{}; + // v13 (rules 12): brake against relative velocity instead of following the movement. + bool brake{}; friend bool operator==(const CellularAction&, const CellularAction&) = default; }; // v10 reliable choice. The server binds these values to the authenticated account and @@ -270,6 +282,8 @@ struct CellularPerceivedDeposit { CellularDepositShape shape{CellularDepositShape::bubble}; bool drained{}; std::array amount_codes{}; // Energy, then C, N, P, other. + // v13 only: world velocity in um/s (current plus induced drift); zero for pools. + std::int16_t velocity_x_um_s{}, velocity_y_um_s{}; friend bool operator==(const CellularPerceivedDeposit&, const CellularPerceivedDeposit&) = default; }; @@ -339,6 +353,10 @@ struct CellularLifeDiagnostics { std::uint64_t bud_cost_energy_pj{}; std::array bud_cost_matter_fg{}; std::uint64_t light_pj{}; // v12 only (ADR-0176): light this cell captured last tick. + // v13 only (rules 12): velocity relative to the liquid (Q10 um/s) and heading (65,536 per + // turn), the authoritative motion state the client predictor reconciles against. + std::int32_t velocity_x_q10{}, velocity_y_q10{}; + std::uint16_t heading{}; friend bool operator==(const CellularLifeDiagnostics&, const CellularLifeDiagnostics&) = default; }; @@ -350,6 +368,16 @@ struct CellularPerceivedProducer { friend bool operator==(const CellularPerceivedProducer&, const CellularPerceivedProducer&) = default; }; +// v13 (rules 12): the region's current configuration; the client regenerates the identical +// flow field from it (biology::CellularFlowField). +struct CellularCurrentsView { + std::uint64_t seed{}; + std::uint32_t width_um{}, height_um{}, pitch_um{}; + std::uint32_t min_count{}, max_count{}; + std::uint32_t min_route_width_um{}, max_route_width_um{}; + std::uint32_t min_speed_um_per_s{}, max_speed_um_per_s{}; + friend bool operator==(const CellularCurrentsView&, const CellularCurrentsView&) = default; +}; struct CellularPerception { std::uint64_t tick{}, life_identity{}; // zero life plus no patches clears the view. std::vector patches; // strictly ordered by (x_um, y_um). @@ -360,6 +388,8 @@ struct CellularPerception { std::vector deposits{}; // v12 only: visible producers by ascending organism. std::vector producers{}; + // v13 only, with an owner life in a liquid region. + std::optional currents{}; friend bool operator==(const CellularPerception&, const CellularPerception&) = default; }; struct IntentionReceipt { diff --git a/include/evo/persistence/checkpoint_store.hpp b/include/evo/persistence/checkpoint_store.hpp index 5c28bd0..8c074ae 100644 --- a/include/evo/persistence/checkpoint_store.hpp +++ b/include/evo/persistence/checkpoint_store.hpp @@ -286,6 +286,12 @@ migrate_cellular_photosynthesis_profile(Postgres&, const FilesystemObjectStore&, const Sha256Digest& build, server::CellularLight light, std::chrono::milliseconds timeout, const PublishHooks& hooks = {}); +// Rules 12: explicit raw-only bundle 13 -> 14, declaring the region's liquid rules. +[[nodiscard]] std::expected +migrate_cellular_liquid_profile(Postgres&, const FilesystemObjectStore&, const LeaseGrant&, + const CommittedCheckpoint&, Uuid commit, const Sha256Digest& build, + const server::CellularLiquidRules& rules, + std::chrono::milliseconds timeout, const PublishHooks& hooks = {}); // Verify the recorded no-tick operation under current authority, replaying its // entire source/target payload. Version upgrades and profile transitions retain // separate evidence; neither is inferred solely from the target tuple. diff --git a/include/evo/persistence/region_checkpoint.hpp b/include/evo/persistence/region_checkpoint.hpp index eae4795..45edb6d 100644 --- a/include/evo/persistence/region_checkpoint.hpp +++ b/include/evo/persistence/region_checkpoint.hpp @@ -87,9 +87,11 @@ inline constexpr CellularVersionBundle cellular_v11_versions{9, 7, 2, 1, 1, 4, 3 inline constexpr CellularVersionBundle cellular_v12_versions{10, 8, 2, 1, 1, 4, 3, 2, 1}; // ADR-0175/0176: rules 11 on owner format 9 (declared light), development 5, founder 4. inline constexpr CellularVersionBundle cellular_v13_versions{11, 9, 2, 1, 1, 5, 4, 2, 1}; +// Rules 12 on owner format 10 (liquid region), development 6, founder 5 (ADR-0177). +inline constexpr CellularVersionBundle cellular_v14_versions{12, 10, 2, 1, 1, 6, 5, 2, 1}; // Raw-only retained-plan bundles, which use trace 4 and their own SQL admission. [[nodiscard]] constexpr bool cellular_plan_bundle(const CellularVersionBundle& b) noexcept { - return b == cellular_v12_versions || b == cellular_v13_versions; + return b == cellular_v12_versions || b == cellular_v13_versions || b == cellular_v14_versions; } // Zero means this bundle has no population representation. [[nodiscard]] constexpr std::uint32_t @@ -293,6 +295,17 @@ cellular_photosynthesis_upgrade_manifest(const CheckpointManifest& predecessor, cellular_photosynthesis_upgrade_payload(std::span payload, const CheckpointManifest& predecessor, const server::CellularLight& light); +// Rules 12: explicit raw-only bundle 13 -> 14 upgrade declaring the region's liquid rules. As +// with light, the rules are the only input; recovery reads them from the target. +[[nodiscard]] std::expected +cellular_liquid_upgrade_manifest(const CheckpointManifest& predecessor, + const Sha256Digest& predecessor_digest, Uuid commit, + const LeaseGrant& lease, const Sha256Digest& build, + std::uint64_t payload_bytes, const Sha256Digest& payload_sha256); +[[nodiscard]] std::expected, CheckpointError> +cellular_liquid_upgrade_payload(std::span payload, + const CheckpointManifest& predecessor, + const server::CellularLiquidRules& rules); // ADR-0174: explicit one-way, no-tick profile 5 -> 6 transition. The payload wraps the // identical population with its declared environment; bundle and policy are unchanged. [[nodiscard]] std::expected diff --git a/migrations/0058_liquid_bundle.sql b/migrations/0058_liquid_bundle.sql new file mode 100644 index 0000000..52c30bf --- /dev/null +++ b/migrations/0058_liquid_bundle.sql @@ -0,0 +1,247 @@ +-- Rules 12 (ADR-0177, Cellular_Region_Movement_Plan.md): raw-only bundle 14 (rules 12 on owner +-- format 10: liquid region with moving food) and exact bundle 13 -> 14 upgrades declaring the +-- region's liquid rules. Normalization is parser-local; stored evidence and retries retain real +-- bytes. Raw trace 4 is unchanged: its brake is a flag bit SQL never parses. + +-- Byte 13 of the canonical cellular action input becomes a flags byte: bit 0 brake (rules +-- 12). Widening cannot invalidate an existing row; earlier inputs keep byte 13 zero. +CREATE OR REPLACE FUNCTION evolution.valid_cellular_action_input(p_input bytea, p_tick evolution.u64) +RETURNS boolean LANGUAGE plpgsql IMMUTABLE STRICT +SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + IF octet_length(p_input) <> 24 THEN + RETURN false; + END IF; + IF evolution.manifest_uint(p_input, 0, 8) = 0 + OR evolution.manifest_uint(p_input, 0, 8) <> p_tick OR get_byte(p_input, 12) > 3 + OR get_byte(p_input, 13) > 1 OR substring(p_input FROM 15 FOR 2) <> '\x0000' THEN + RETURN false; + END IF; + IF get_byte(p_input, 12) <> 1 AND substring(p_input FROM 17 FOR 8) <> '\x0000000000000000' THEN + RETURN false; + END IF; + RETURN true; +END $$; + +ALTER FUNCTION evolution.parse_checkpoint_manifest(bytea) RENAME TO parse_checkpoint_manifest_v57; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest_v57(bytea) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.parse_checkpoint_manifest(m bytea) +RETURNS evolution.checkpoint_manifest LANGUAGE plpgsql IMMUTABLE +SET search_path=pg_catalog,pg_temp AS $$ +DECLARE c evolution.checkpoint_manifest; + b13 constant bytea := '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'; + b14 constant bytea := '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'; +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)=b14 THEN + c := evolution.parse_checkpoint_manifest_v57(overlay(m PLACING b13 FROM 161 FOR 36)); + c.versions := b14; + RETURN c; + END IF; + RETURN evolution.parse_checkpoint_manifest_v57(m); +END $$; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC; + +ALTER FUNCTION evolution.cellular_births(bytea,bytea) RENAME TO cellular_births_v57; +REVOKE ALL ON FUNCTION evolution.cellular_births_v57(bytea,bytea) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.cellular_births(t bytea,m bytea) +RETURNS TABLE(account_id uuid,request_id evolution.u64,generation evolution.u64,identity evolution.u64,born evolution.u64) +LANGUAGE plpgsql IMMUTABLE SET search_path=pg_catalog,pg_temp AS $$ +DECLARE c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m); +BEGIN + IF c.versions='\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea THEN + m := overlay(m PLACING '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea FROM 161 FOR 36); + END IF; + RETURN QUERY SELECT * FROM evolution.cellular_births_v57(t,m); +END $$; +REVOKE ALL ON FUNCTION evolution.cellular_births(bytea,bytea) FROM PUBLIC; + +-- Results 1 life died, 3 declined, 4 offspring plan applied, for bundles 12, 13 and 14. +CREATE OR REPLACE FUNCTION evolution.check_cellular_mutation_block(p_manifest bytea, p_trace bytea, + p_mutations bytea, p_results bytea) +RETURNS integer LANGUAGE plpgsql STABLE SECURITY INVOKER +SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + n integer; + account uuid; + account_bytes bytea; + action numeric; + tick numeric; + input bytea; + previous_tick numeric := -1; + previous_account bytea := ''::bytea; + previous_action numeric := -1; + r evolution.cellular_mutation_reservations%ROWTYPE; +BEGIN + IF p_mutations IS NULL OR p_results IS NULL OR octet_length(p_mutations) = 0 + OR octet_length(p_mutations) % 64 <> 0 OR octet_length(p_mutations) / 64 > 1024 + OR octet_length(p_results) <> octet_length(p_mutations) / 64 THEN + RAISE EXCEPTION 'invalid cellular mutation block' USING ERRCODE = '22023'; + END IF; + n := octet_length(p_mutations) / 64; + IF (SELECT count(*) FROM evolution.cellular_mutation_selections(p_trace, p_manifest)) <> n THEN + RAISE EXCEPTION 'cellular mutation block does not cover the trace' USING ERRCODE = '22023'; + END IF; + FOR i IN 0 .. n - 1 LOOP + account_bytes := substring(p_mutations FROM 64 * i + 1 FOR 16); + account := encode(account_bytes, 'hex')::uuid; + action := evolution.manifest_uint(p_mutations, 64 * i + 16, 8); + input := substring(p_mutations FROM 64 * i + 25 FOR 34); + tick := evolution.manifest_uint(input, 0, 8); + IF account = '00000000-0000-0000-0000-000000000000' OR action = 0 + OR NOT evolution.valid_cellular_mutation_input(input) + OR substring(p_mutations FROM 64 * i + 59 FOR 6) <> '\x000000000000' + OR (c.versions IN ('\x0a0000000800000002000000010000000100000004000000030000000200000001000000'::bytea, + '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea, + '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea) + AND (get_byte(p_results,i) NOT IN (1,3,4) + OR (evolution.manifest_uint(input,32,2)=0 AND get_byte(p_results,i) NOT IN (1,3)) + OR (evolution.manifest_uint(input,32,2)<>0 AND get_byte(p_results,i) NOT IN (1,4)))) + OR (c.versions NOT IN ('\x0a0000000800000002000000010000000100000004000000030000000200000001000000'::bytea, + '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea, + '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea) + AND get_byte(p_results,i)>3) + OR tick <= c.begin_tick OR tick > c.end_tick + OR (tick, account_bytes, action) <= (previous_tick, previous_account, previous_action) THEN + RAISE EXCEPTION 'invalid cellular mutation record' USING ERRCODE = '22023'; + END IF; + previous_tick := tick; + previous_account := account_bytes; + previous_action := action; + SELECT * INTO r FROM evolution.cellular_mutation_reservations x + WHERE x.world_id = c.world_id AND x.account_id = account AND x.action_id = action; + IF NOT FOUND OR r.region_id <> c.region_id OR r.input_bytes <> input + OR r.target_tick <> evolution.manifest_uint(input, 0, 8) THEN + RAISE EXCEPTION 'cellular mutation reservation conflicts' USING ERRCODE = 'EVL16'; + END IF; + IF NOT EXISTS (SELECT 1 FROM evolution.cellular_mutation_selections(p_trace, p_manifest) s + WHERE s.tick = r.target_tick AND s.successor_identity = r.successor_identity + AND s.life_id = evolution.manifest_uint(input, 8, 8) + AND s.event_index = evolution.manifest_uint(input, 16, 8) + AND s.offer_tick = evolution.manifest_uint(input, 24, 8) + AND s.operator_id = evolution.manifest_uint(input, 32, 2)) THEN + RAISE EXCEPTION 'cellular mutation differs from its trace' USING ERRCODE = '22023'; + END IF; + END LOOP; + RETURN n; +END $$; + +ALTER FUNCTION evolution.publish_cellular_profile_migration(bytea) RENAME TO publish_cellular_profile_migration_v57; +REVOKE ALL ON FUNCTION evolution.publish_cellular_profile_migration_v57(bytea) FROM PUBLIC, :"runtime_role"; +CREATE OR REPLACE FUNCTION evolution.publish_cellular_profile_migration(p_manifest bytea) +RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid, + head_digest text, head_tick evolution.u64) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + s evolution.checkpoint_manifest; + h evolution.region_heads%ROWTYPE; + p evolution.region_commits%ROWTYPE; + old evolution.region_commits%ROWTYPE; + frame evolution.u64; + d bytea := sha256(p_manifest); + source_bundle constant bytea := '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'; + target_bundle constant bytea := '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'; + zero32 constant bytea := decode(repeat('00', 32), 'hex'); +BEGIN + IF c.versions <> target_bundle THEN + RETURN QUERY SELECT * FROM evolution.publish_cellular_profile_migration_v57(p_manifest); + RETURN; + END IF; + IF c.profile <> 4 OR c.commit_sequence = 0 OR c.begin_tick <> c.end_tick + OR c.end_tick = 0 OR c.versions <> target_bundle + OR evolution.manifest_uint(p_manifest, 228, 4) <> 0 + OR evolution.manifest_uint(p_manifest, 232, 4) <> (CASE c.profile WHEN 4 THEN 4 ELSE 5 END) + OR evolution.manifest_uint(p_manifest, 236, 4) <> 1 + OR c.trace_bytes <> 0 OR c.trace_sha256 <> zero32 + OR c.decision_count <> 0 OR c.decisions_sha256 <> zero32 THEN + RAISE EXCEPTION 'invalid liquid profile migration' USING ERRCODE = '22023'; + END IF; + PERFORM evolution.check_region_lease(c.world_id, c.region_id, c.holder, c.epoch); + SELECT * INTO old FROM evolution.region_commits r WHERE r.commit_id = c.commit_id; + IF FOUND THEN + IF old.manifest <> p_manifest THEN + RAISE EXCEPTION 'cellular profile migration identity reused' USING ERRCODE = 'EVL07'; + END IF; + SELECT * INTO p FROM evolution.region_commits r + WHERE r.world_id = old.world_id AND r.region_id = old.region_id + AND r.commit_sequence = old.commit_sequence - 1; + IF NOT FOUND OR NOT EXISTS ( + SELECT 1 FROM evolution.cellular_profile_migrations m + WHERE m.target_commit = c.commit_id AND m.world_id = c.world_id + AND m.region_id = c.region_id AND m.source_sequence = p.commit_sequence + AND m.source_commit = p.commit_id AND m.source_manifest_sha256 = p.commit_digest + AND m.source_payload_sha256 = p.payload_sha256 AND m.source_versions = p.versions + AND m.target_sequence = old.commit_sequence AND m.target_manifest_sha256 = d + AND m.target_payload_sha256 = old.payload_sha256 AND m.target_versions = old.versions + AND m.source_commit = c.predecessor_commit + AND m.source_manifest_sha256 = c.predecessor_digest) THEN + RAISE EXCEPTION 'cellular profile migration identity reused' USING ERRCODE = 'EVL07'; + END IF; + SELECT l.frame_id INTO frame FROM evolution.region_leases l + WHERE l.world_id = c.world_id AND l.region_id = c.region_id; + RETURN QUERY SELECT frame, old.commit_sequence, old.commit_id, + encode(old.commit_digest, 'hex'), old.end_tick; + RETURN; + END IF; + IF EXISTS (SELECT 1 FROM evolution.population_interval_pending x + WHERE x.world_id = c.world_id AND x.region_id = c.region_id) THEN + RAISE EXCEPTION 'liquid upgrade waits for interval' USING ERRCODE = 'EVL18'; + END IF; + IF EXISTS (SELECT 1 FROM evolution.cellular_mutation_reservations x + WHERE x.world_id=c.world_id AND x.region_id=c.region_id AND NOT EXISTS + (SELECT 1 FROM evolution.cellular_mutation_action_publications a + WHERE a.world_id=x.world_id AND a.account_id=x.account_id AND a.action_id=x.action_id)) THEN + RAISE EXCEPTION 'liquid upgrade waits for mutation choice' USING ERRCODE='EVL18'; + END IF; + SELECT * INTO h FROM evolution.region_heads r + WHERE r.world_id = c.world_id AND r.region_id = c.region_id FOR UPDATE; + IF NOT FOUND OR h.commit_sequence = 18446744073709551615 + OR c.commit_sequence <> h.commit_sequence + 1 OR c.predecessor_commit <> h.commit_id + OR c.predecessor_digest <> h.digest OR c.begin_tick <> h.end_tick THEN + RAISE EXCEPTION 'region head moved' USING ERRCODE = 'EVL03'; + END IF; + SELECT * INTO p FROM evolution.region_commits r + WHERE r.world_id = c.world_id AND r.region_id = c.region_id + AND r.commit_sequence = h.commit_sequence; + IF NOT FOUND THEN + RAISE EXCEPTION 'missing migration predecessor' USING ERRCODE = 'XX000'; + END IF; + s := evolution.parse_checkpoint_manifest(p.manifest); + IF s.profile <> c.profile OR s.versions <> source_bundle OR p.versions <> source_bundle + OR c.frame_id <> s.frame_id OR c.tick_microseconds <> s.tick_microseconds + OR s.commit_id <> c.predecessor_commit OR s.end_tick <> c.end_tick + OR evolution.manifest_uint(p.manifest, 232, 4) <> (CASE c.profile WHEN 4 THEN 4 ELSE 5 END) + OR NOT EXISTS (SELECT 1 FROM evolution.retained_builds b + WHERE b.build_identity = c.build_identity) THEN + RAISE EXCEPTION 'unsupported liquid profile migration' USING ERRCODE = 'EVL06'; + END IF; + SELECT l.frame_id INTO frame FROM evolution.region_leases l + WHERE l.world_id = c.world_id AND l.region_id = c.region_id; + IF c.frame_id <> frame THEN + RAISE EXCEPTION 'foreign frame' USING ERRCODE = '22023'; + END IF; + INSERT INTO evolution.cellular_profile_migrations(target_commit, world_id, region_id, + source_sequence, source_commit, source_manifest_sha256, source_payload_sha256, + source_versions, target_sequence, target_manifest_sha256, target_payload_sha256, + target_versions) + VALUES (c.commit_id, c.world_id, c.region_id, p.commit_sequence, p.commit_id, + p.commit_digest, p.payload_sha256, p.versions, c.commit_sequence, d, + c.payload_sha256, c.versions); + INSERT INTO evolution.region_commits(world_id, region_id, commit_sequence, commit_id, + commit_digest, manifest, begin_tick, end_tick, published_epoch, tick_microseconds, + versions, build_identity, payload_bytes, payload_sha256) + VALUES (c.world_id, c.region_id, c.commit_sequence, c.commit_id, d, p_manifest, + c.begin_tick, c.end_tick, c.epoch, c.tick_microseconds, c.versions, + c.build_identity, c.payload_bytes, c.payload_sha256); + UPDATE evolution.region_heads r + SET commit_sequence = c.commit_sequence, commit_id = c.commit_id, digest = d, + end_tick = c.end_tick, published_epoch = c.epoch + WHERE r.world_id = c.world_id AND r.region_id = c.region_id; + RETURN QUERY SELECT frame, c.commit_sequence, c.commit_id, encode(d, 'hex'), c.end_tick; +END $$; +REVOKE ALL ON FUNCTION evolution.publish_cellular_profile_migration(bytea) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.publish_cellular_profile_migration(bytea) TO :"runtime_role"; + +INSERT INTO evolution.schema_migrations(version,sha256) VALUES(58,:'migration_sha_58'); diff --git a/migrations/apply.sql b/migrations/apply.sql index f35047d..a7a9fdd 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -133,6 +133,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v54' || ',55:' || :'migration_sha_55' AS history_v55 \gset SELECT :'history_v55' || ',56:' || :'migration_sha_56' AS history_v56 \gset SELECT :'history_v56' || ',57:' || :'migration_sha_57' AS history_v57 \gset + SELECT :'history_v57' || ',58:' || :'migration_sha_58' AS history_v58 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -168,8 +169,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v54' AS at_v54, :'history' = :'history_v55' AS at_v55, :'history' = :'history_v56' AS at_v56, - :'history' = :'history_v57' AS at_v57 \gset - \if :at_v57 + :'history' = :'history_v57' AS at_v57, + :'history' = :'history_v58' AS at_v58 \gset + \if :at_v58 + \elif :at_v57 \elif :at_v56 \elif :at_v55 \elif :at_v54 @@ -577,7 +580,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 54 AS at_v54, coalesce(max(version), 0) = 55 AS at_v55, coalesce(max(version), 0) = 56 AS at_v56, - coalesce(max(version), 0) = 57 AS at_v57 + coalesce(max(version), 0) = 57 AS at_v57, + coalesce(max(version), 0) = 58 AS at_v58 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -803,6 +807,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \elif :at_v55 \elif :at_v56 \elif :at_v57 +\elif :at_v58 \else \echo 'Unknown or changed migration history after v43' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; @@ -863,6 +868,10 @@ SELECT coalesce(max(version), 0) = 56 AS needs_v57 FROM evolution.schema_migrati \if :needs_v57 \ir 0057_photosynthesis_bundle.sql \endif +SELECT coalesce(max(version), 0) = 57 AS needs_v58 FROM evolution.schema_migrations \gset +\if :needs_v58 + \ir 0058_liquid_bundle.sql +\endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes -- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC -- grants or SET-able memberships would bypass the fenced functions. Checks the diff --git a/schemas/cellular-lives-v10.md b/schemas/cellular-lives-v10.md new file mode 100644 index 0000000..c680f92 --- /dev/null +++ b/schemas/cellular-lives-v10.md @@ -0,0 +1,27 @@ +# Cellular owner format 10: liquid region + +Authority: [ADR-0178](../docs/adr/0178-durable-liquid-region.md). Format 10 is exactly +rules 12. It is [format 9](cellular-lives-v9.md) with magic `AEVCLV10`, an 88-byte liquid +block after the light block, 20 more bytes per life and a format-3 habitat; every other +record, length rule and validation is format 9's. + +| Offset | Bytes | Field | +|---:|---:|---| +| 356 | 8 | Current seed | +| 364 | 4 each | Current width, height (the owner's area), grid pitch, minimum and maximum count, minimum and maximum route width (um), minimum and maximum speed (um/s) | +| 400 | 4 each | Founder handling per 50 ms tick: thrust (Q10 um/s), reverse thrust (Q10 um/s), forward drag (ppm), lateral drag (ppm), turn (heading units, at most 32,768) | +| 420 | 4 each | Deposit motion: drift radius (um), maximum drift (Q10 um/s), drift decay (ppm per tick), merged cap (at most 65,535), bubble radius (um) | +| 440 | 4 | Reserved zero | +| 444 | 8 each | Sorted spawn sites, then lives, corpses and the rest as in format 9 | + +Each life record appends its motion state after the offspring genome: velocity relative to +the liquid x and y (signed Q10 um/s, within +/- 1 m/s), heading (u16, 65,536 per turn), +reserved u16 zero, and the sub-micrometre carry x and y (u32, below 1,024,000,000). + +The habitat is format 3: format 2 deposits with induced drift, carry and a merged count +(see `evo/biology/cellular_habitat.hpp`). Restore regenerates the current field from the +block and refuses one that does not generate. Currents and the field are conditions, not +stock: closure is format 9's. + +Format 10 arises only from the explicit no-tick format-9/rules-11 liquid upgrade, which +converts the habitat to format 3 (every deposit one merged bubble) and starts lives at rest. diff --git a/schemas/network/session-v13-cellular-liquid.md b/schemas/network/session-v13-cellular-liquid.md new file mode 100644 index 0000000..260793e --- /dev/null +++ b/schemas/network/session-v13-cellular-liquid.md @@ -0,0 +1,27 @@ +# Session v13: liquid motion + +Authority: [ADR-0178](../../docs/adr/0178-durable-liquid-region.md). v13 is +[v12](session-v12-cellular-producers.md) with liquid motion; every other message and rule is +v12's. Older versions keep their exact layouts. + +**Perception.** The v12 prefix is followed by a 56-byte liquid block: + +| Bytes | Field | +|---:|---| +| 4 | Owner velocity relative to the liquid, x (signed Q10 um/s) | +| 4 | Owner velocity, y | +| 2 | Owner heading (65,536 per turn) | +| 1 | Flags: bit 0 currents present; other bits zero | +| 1 | Reserved zero | +| 8 | Current seed | +| 4 each | Width, height, pitch, minimum and maximum count, minimum and maximum route width, minimum and maximum speed | + +Without an owner life the flag and every field are zero. With the flag clear the current +fields are zero. A client regenerates the identical field from the configuration with +`biology::CellularFlowField`. Each deposit entry appends its world velocity (current plus +induced drift) as two signed 16-bit um/s values, zero for pools: 30 bytes per entry. A +rules-12 server lists every pool and only the nearest 256 moving bubbles. + +**Cellular action.** Byte 37 (reserved through v12) is a flags byte: bit 0 brake. A brake +opposes the cell's velocity relative to the liquid instead of following the movement; the +canonical 24-byte action input stores it as byte 13 bit 0 (schema 58). diff --git a/src/client/input/bindings.cpp b/src/client/input/bindings.cpp index 47289b5..7eda407 100644 --- a/src/client/input/bindings.cpp +++ b/src/client/input/bindings.cpp @@ -121,6 +121,7 @@ constexpr std::array actions{{ {"pan_up", "Pan up"}, {"pan_down", "Pan down"}, {"toggle_capture", "Toggle UI capture"}, + {"brake", "Brake"}, }}; constexpr KeySlots default_slots{{ {4, no_key}, // A @@ -132,6 +133,7 @@ constexpr KeySlots default_slots{{ {82, no_key}, // Up {81, no_key}, // Down {43, no_key}, // Tab + {44, no_key}, // Space }}; constexpr std::string_view header = "evo-controls"; @@ -327,6 +329,19 @@ std::expected parse_bindings(std::string_view text) { return std::unexpected(problem(BindingError::malformed, action)); slot = {*primary, *secondary}; } + // A file written before an action existed (brake, rules 12) takes that action's default + // key when no other action uses it; otherwise Bindings::make reports it as missing. The + // original version-1 actions stay required. + for (auto k = static_cast(Action::brake); k < action_count; ++k) { + if (seen[k]) + continue; + const auto key = default_slots[k].primary; + const bool taken = std::ranges::any_of(slots, [key](const KeySlot& other) { + return other.primary == key || other.secondary == key; + }); + if (!taken) + slots[k] = {key, no_key}; + } if (!versioned) return std::unexpected(problem(BindingError::malformed)); return Bindings::make(slots); // Missing actions have no primary. diff --git a/src/client/input/input.cpp b/src/client/input/input.cpp index 48c11b9..dea45d9 100644 --- a/src/client/input/input.cpp +++ b/src/client/input/input.cpp @@ -69,6 +69,6 @@ std::expected InputState::sample(std::uint64_t tick) { const int magnitude = x != 0 && y != 0 ? 707 : 1000; tick_ = tick; return Intention{++sequence_, tick, static_cast(x * magnitude), - static_cast(y * magnitude)}; + static_cast(y * magnitude), keys_[8]}; } } // namespace evo::client diff --git a/src/client/platform/application.cpp b/src/client/platform/application.cpp index 795f320..67286cd 100644 --- a/src/client/platform/application.cpp +++ b/src/client/platform/application.cpp @@ -19,6 +19,8 @@ bool runtime_owned = false; // Process main-thread-only contract; no hidden thre std::optional held_key(Action action) noexcept { if (action == Action::toggle_capture) return std::nullopt; + if (action == Action::brake) + return Key::brake; return static_cast(static_cast(action)); } static_assert(static_cast(Action::pan_down) == static_cast(Key::pan_down)); diff --git a/src/client/session/region_session.cpp b/src/client/session/region_session.cpp index 449c0b5..b0e2edc 100644 --- a/src/client/session/region_session.cpp +++ b/src/client/session/region_session.cpp @@ -308,17 +308,20 @@ bool RegionSessionClient::send_action(std::uint64_t action_id, network::ActionKi bool RegionSessionClient::send_cellular_action( std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, std::int16_t move_y, - std::optional> intake_target, bool engulf, bool bud) { + std::optional> intake_target, bool engulf, bool bud, + bool brake) { auto& m = *impl_; return (m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || 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(), - intake_target ? intake_target->first : 0, - intake_target ? intake_target->second : 0, engulf, bud}); + m.send(network::CellularAction{ + m.welcome->session, m.welcome->epoch, action_id, tick, move_x, move_y, + intake_target.has_value(), intake_target ? intake_target->first : 0, + intake_target ? intake_target->second : 0, engulf, bud, + // A brake needs v13; older sessions never send one. + brake && m.protocol_version == network::session_protocol_v13}); } bool RegionSessionClient::send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick, diff --git a/src/network/protocol/intent_admission.cpp b/src/network/protocol/intent_admission.cpp index dc7cdd3..ca438e9 100644 --- a/src/network/protocol/intent_admission.cpp +++ b/src/network/protocol/intent_admission.cpp @@ -240,7 +240,7 @@ ActionReceipt IntentAdmission::action(std::uint64_t session, const CellularActio static_cast(ActionKind::cellular), m.tick}; const auto bytes = encode_cellular_action_input({m.tick, m.move_x, m.move_y, m.has_intake_target, - m.intake_x_um, m.intake_y_um, m.engulf, m.bud}); + m.intake_x_um, m.intake_y_um, m.engulf, m.bud, m.brake}); auto* s = find(session); if (!s) return {m.action_id, AdmitStatus::unknown_session, facts.server_tick, m.tick}; @@ -282,7 +282,7 @@ std::optional IntentAdmission::admit(std::uint64_t session, const static_cast(ActionKind::cellular), m.tick}; const auto bytes = encode_cellular_action_input({m.tick, m.move_x, m.move_y, m.has_intake_target, - m.intake_x_um, m.intake_y_um, m.engulf, m.bud}); + m.intake_x_um, m.intake_y_um, m.engulf, m.bud, m.brake}); auto* s = find(session); if (!s) return ActionReceipt{m.action_id, AdmitStatus::unknown_session, facts.server_tick, m.tick}; diff --git a/src/network/protocol/session_protocol.cpp b/src/network/protocol/session_protocol.cpp index 2456cee..e329039 100644 --- a/src/network/protocol/session_protocol.cpp +++ b/src/network/protocol/session_protocol.cpp @@ -32,9 +32,17 @@ constexpr std::size_t cellular_perception_v12_prefix_bytes = cellular_perception_v10_prefix_bytes + 8 + 2 + 6; // v12: organism, photosynthesis per thousand and 6 reserved bytes. constexpr std::size_t cellular_perceived_producer_bytes = 8 + 2 + 6; +// v13 (rules 12) appends the owner's velocity (2 x i32) and heading (u16), a flags byte +// (bit 0: currents present), a reserved byte, and the current seed and nine u32 fields. +constexpr std::size_t cellular_liquid_block_bytes = 4 + 4 + 2 + 1 + 1 + 8 + (9 * 4); +constexpr std::size_t cellular_perception_v13_prefix_bytes = + cellular_perception_v12_prefix_bytes + cellular_liquid_block_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); +// v13: the same plus world velocity as two 16-bit um/s values. +constexpr std::size_t cellular_perceived_liquid_deposit_bytes = + cellular_perceived_deposit_bytes + 4; 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; @@ -227,8 +235,20 @@ std::vector encode_session(const SessionMessage& message, std::uin !cellular_v10_family(version) && std::holds_alternative(message)) return {}; if (const auto* perception = std::get_if(&message)) { - // v12 alone carries captured light and producers (ADR-0176). - const bool producers = version == session_protocol_v12; + // v12 and v13 carry captured light and producers (ADR-0176); v13 alone carries + // liquid motion. + const bool producers = cellular_light_version(version); + const bool liquid = version == session_protocol_v13; + if (!liquid && (perception->currents || + (perception->diagnostics && (perception->diagnostics->velocity_x_q10 || + perception->diagnostics->velocity_y_q10 || + perception->diagnostics->heading)) || + std::ranges::any_of(perception->deposits, [](const auto& d) { + return d.velocity_x_um_s != 0 || d.velocity_y_um_s != 0; + }))) + return {}; + if (perception->currents && !perception->life_identity) + return {}; if ((!producers && (!perception->producers.empty() || (perception->diagnostics && perception->diagnostics->light_pj))) || perception->producers.size() > max_cellular_perceived_producers || @@ -337,7 +357,8 @@ std::vector encode_session(const SessionMessage& message, std::uin put(out, static_cast(m.move_x), 2); put(out, static_cast(m.move_y), 2); out.push_back(m.has_intake_target ? 1 : m.engulf ? 2 : m.bud ? 3 : 0); // Target kind. - put(out, 0, 3); + out.push_back(m.brake ? 1 : 0); // v13 flags: bit 0 brake. + put(out, 0, 2); put(out, m.intake_x_um, 4); put(out, m.intake_y_um, 4); return out; @@ -386,12 +407,15 @@ 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_v12 ? cellular_perception_v12_prefix_bytes - : cellular_v10_family(version) ? cellular_perception_v10_prefix_bytes - : version == session_protocol_v9 ? cellular_perception_v9_prefix_bytes - : cellular_perception_prefix_bytes) + + (version == session_protocol_v13 ? cellular_perception_v13_prefix_bytes + : version == session_protocol_v12 ? cellular_perception_v12_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.deposits.size() * cellular_perceived_deposit_bytes + + m.deposits.size() * (version == session_protocol_v13 + ? cellular_perceived_liquid_deposit_bytes + : cellular_perceived_deposit_bytes) + m.producers.size() * cellular_perceived_producer_bytes, version); put(out, m.tick, 8); @@ -417,11 +441,25 @@ std::vector encode_session(const SessionMessage& message, std::uin for (const auto value : d ? d->bud_cost_matter_fg : std::array{}) put(out, value, 8); - if (version == session_protocol_v12) { + if (cellular_light_version(version)) { put(out, d ? d->light_pj : 0, 8); put(out, m.producers.size(), 2); put(out, 0, 6); } + if (version == session_protocol_v13) { + put(out, static_cast(d ? d->velocity_x_q10 : 0), 4); + put(out, static_cast(d ? d->velocity_y_q10 : 0), 4); + put(out, d ? d->heading : 0, 2); + out.push_back(m.currents ? 1 : 0); + out.push_back(0); + const auto c = m.currents.value_or(CellularCurrentsView{}); + put(out, c.seed, 8); + for (const auto value : + {c.width_um, c.height_um, c.pitch_um, c.min_count, c.max_count, + c.min_route_width_um, c.max_route_width_um, c.min_speed_um_per_s, + c.max_speed_um_per_s}) + put(out, value, 4); + } } else { put(out, 0, 5); } @@ -442,6 +480,10 @@ std::vector encode_session(const SessionMessage& message, std::uin out.push_back(deposit.drained ? 1 : 0); for (const auto code : deposit.amount_codes) put(out, code, 2); + if (version == session_protocol_v13) { + put(out, static_cast(deposit.velocity_x_um_s), 2); + put(out, static_cast(deposit.velocity_y_um_s), 2); + } } for (const auto& producer : m.producers) { put(out, producer.organism, 8); @@ -679,12 +721,14 @@ 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] > (cellular_v10_family(wire_version) ? 3 : 1) || payload[37] != 0 || - payload[38] != 0 || payload[39] != 0) + if (payload[36] > (cellular_v10_family(wire_version) ? 3 : 1) || + payload[37] > (wire_version == session_protocol_v13 ? 1 : 0) || payload[38] != 0 || + payload[39] != 0) return std::unexpected(SessionCodecError::invalid_value); m.has_intake_target = payload[36] == 1; m.engulf = payload[36] == 2; m.bud = payload[36] == 3; + m.brake = payload[37] == 1; m.intake_x_um = static_cast(get(payload, 40, 4)); m.intake_y_um = static_cast(get(payload, 44, 4)); if (!m.session || !m.epoch || !m.action_id || !m.tick || @@ -778,16 +822,19 @@ std::expected decode_session(std::span= prefix ? static_cast(get( payload, cellular_perception_v10_prefix_bytes + 8, 2)) @@ -833,6 +880,14 @@ std::expected decode_session(std::span(static_cast(get(payload, at, 4))); + d.velocity_y_q10 = static_cast( + static_cast(get(payload, at + 4, 4))); + d.heading = static_cast(get(payload, at + 8, 2)); + } } d.movement = static_cast(payload[74]); d.intake = static_cast(payload[75]); @@ -847,7 +902,7 @@ std::expected decode_session(std::span decode_session(std::span fields{}; + for (std::size_t i = 0; i < fields.size(); ++i) + fields.at(i) = static_cast(get(payload, at + 10 + i * 4, 4)); + c.width_um = fields[0]; + c.height_um = fields[1]; + c.pitch_um = fields[2]; + c.min_count = fields[3]; + c.max_count = fields[4]; + c.min_route_width_um = fields[5]; + c.max_route_width_um = fields[6]; + c.min_speed_um_per_s = fields[7]; + c.max_speed_um_per_s = fields[8]; + if (flags > 1 || payload[at + 1] != 0 || (flags == 1 && !m.life_identity) || + (flags == 0 && c != CellularCurrentsView{})) + return std::unexpected(SessionCodecError::invalid_value); + if (flags == 1) + m.currents = c; + } std::size_t offset = prefix; if (deposits) { m.deposits.reserve(count); @@ -878,6 +956,12 @@ std::expected decode_session(std::span(get(payload, offset + 16 + c * 2, 2)); + if (liquid) { + d.velocity_x_um_s = static_cast( + static_cast(get(payload, offset + 26, 2))); + d.velocity_y_um_s = static_cast( + static_cast(get(payload, offset + 28, 2))); + } m.deposits.push_back(d); } if (!m.life_identity && producer_count) @@ -1083,7 +1167,8 @@ encode_cellular_action_input(const CellularActionInput& input) { : input.engulf ? 2 : input.bud ? 3 : 0); - put(bytes, 0, 3); + bytes.push_back(input.brake ? 1 : 0); // Flags (schema 58): bit 0 brake. + put(bytes, 0, 2); put(bytes, input.intake_x_um, 4); put(bytes, input.intake_y_um, 4); std::array out{}; @@ -1095,7 +1180,7 @@ std::expected decode_cellular_action_input(std::span bytes) { if (bytes.size() != cellular_action_input_bytes) return std::unexpected(SessionCodecError::wrong_length); - if (bytes[12] > 3 || bytes[13] != 0 || bytes[14] != 0 || bytes[15] != 0) + if (bytes[12] > 3 || bytes[13] > 1 || bytes[14] != 0 || bytes[15] != 0) return std::unexpected(SessionCodecError::invalid_value); CellularActionInput input; input.tick = get(bytes, 0, 8); @@ -1104,6 +1189,7 @@ decode_cellular_action_input(std::span bytes) { input.has_intake_target = bytes[12] == 1; input.engulf = bytes[12] == 2; input.bud = bytes[12] == 3; + input.brake = bytes[13] == 1; input.intake_x_um = static_cast(get(bytes, 16, 4)); input.intake_y_um = static_cast(get(bytes, 20, 4)); if (input.tick == 0 || diff --git a/src/persistence/cellular_checkpoint_store.cpp b/src/persistence/cellular_checkpoint_store.cpp index 7492dcc..a89c5a6 100644 --- a/src/persistence/cellular_checkpoint_store.cpp +++ b/src/persistence/cellular_checkpoint_store.cpp @@ -362,6 +362,17 @@ migrate_cellular_photosynthesis_profile(Postgres& db, const FilesystemObjectStor }, cellular_photosynthesis_upgrade_manifest); } +std::expected migrate_cellular_liquid_profile( + Postgres& db, const FilesystemObjectStore& objects, const LeaseGrant& lease, + const CommittedCheckpoint& predecessor, Uuid commit, const Sha256Digest& build, + const server::CellularLiquidRules& rules, milliseconds timeout, const PublishHooks& hooks) { + return migrate_rules_profile( + db, objects, lease, predecessor, commit, build, timeout, hooks, + [rules](std::span payload, const CheckpointManifest& previous) { + return cellular_liquid_upgrade_payload(payload, previous, rules); + }, + cellular_liquid_upgrade_manifest); +} std::expected migrate_cellular_profile_to_v2(Postgres& db, const FilesystemObjectStore& objects, @@ -650,11 +661,13 @@ verify_cellular_no_tick_checkpoint(Postgres& db, const FilesystemObjectStore& ob const bool maturation = m.cellular_versions == cellular_v11_versions; const bool inheritance = m.cellular_versions == cellular_v12_versions; const bool photosynthesis = m.cellular_versions == cellular_v13_versions; - const auto derive = photosynthesis ? cellular_photosynthesis_upgrade_manifest - : inheritance ? cellular_inheritance_upgrade_manifest - : maturation ? cellular_maturation_upgrade_manifest - : boundary ? cellular_boundary_upgrade_manifest - : cellular_profile_migration_manifest; + const bool liquid = m.cellular_versions == cellular_v14_versions; + const auto derive = liquid ? cellular_liquid_upgrade_manifest + : photosynthesis ? cellular_photosynthesis_upgrade_manifest + : inheritance ? cellular_inheritance_upgrade_manifest + : maturation ? cellular_maturation_upgrade_manifest + : boundary ? cellular_boundary_upgrade_manifest + : cellular_profile_migration_manifest; auto expected = derive(*source, *source_digest, m.commit, recorded, m.build, m.payload_bytes, m.payload_sha256); if (!expected || *expected != m) @@ -662,7 +675,16 @@ verify_cellular_no_tick_checkpoint(Postgres& db, const FilesystemObjectStore& ob auto bytes = objects.get({source->payload_sha256, source->payload_bytes}); if (!bytes) return fail(RecoveryError::tail); - if (photosynthesis) { + if (liquid) { + // The declared liquid rules are the upgrade's only input: read them from the target, + // then require the source to re-derive the exact target bytes with them. + auto target = restore_cellular_payload(payload, m); + if (!target) + return fail(RecoveryError::payload); + auto upgraded = cellular_liquid_upgrade_payload(*bytes, *source, (*target)->liquid_rules()); + if (!upgraded || !std::ranges::equal(*upgraded, payload)) + return fail(RecoveryError::history); + } else if (photosynthesis) { // The declared light is the upgrade's only input: read it from the target, then // require the source to re-derive the exact target bytes with it. auto target = restore_cellular_payload(payload, m); diff --git a/src/persistence/population_checkpoint.cpp b/src/persistence/population_checkpoint.cpp index 55b3bd6..ace1175 100644 --- a/src/persistence/population_checkpoint.cpp +++ b/src/persistence/population_checkpoint.cpp @@ -224,4 +224,31 @@ cellular_photosynthesis_upgrade_payload(std::span payload, return std::unexpected(CheckpointError::payload); return (*upgraded)->snapshot(); } +std::expected +cellular_liquid_upgrade_manifest(const CheckpointManifest& previous, + const Sha256Digest& previous_digest, Uuid commit, + const LeaseGrant& lease, const Sha256Digest& build, + std::uint64_t bytes, const Sha256Digest& digest) { + if (previous.profile != CheckpointProfile::cellular_lives_v1) + return std::unexpected(CheckpointError::unsupported); + return upgrade_manifest(previous, previous_digest, commit, lease, build, bytes, digest, + cellular_v13_versions, cellular_v14_versions); +} +std::expected, CheckpointError> +cellular_liquid_upgrade_payload(std::span payload, + const CheckpointManifest& previous, + const server::CellularLiquidRules& rules) { + if (!supported(previous) || previous.profile != CheckpointProfile::cellular_lives_v1 || + previous.cellular_versions != cellular_v13_versions) + return std::unexpected(CheckpointError::unsupported); + if (!encode_manifest(previous) || previous.sequence == 0 || previous.end_tick == 0) + return std::unexpected(CheckpointError::chain); + auto state = restore_cellular_payload(payload, previous); + if (!state) + return std::unexpected(state.error()); + auto upgraded = (*state)->liquid_upgrade_candidate(rules); + if (!upgraded) + return std::unexpected(CheckpointError::payload); + return (*upgraded)->snapshot(); +} } // namespace evo::persistence diff --git a/src/server/lifecycle/cellular_batch.cpp b/src/server/lifecycle/cellular_batch.cpp index 2166c4b..b3a117e 100644 --- a/src/server/lifecycle/cellular_batch.cpp +++ b/src/server/lifecycle/cellular_batch.cpp @@ -105,7 +105,8 @@ bool valid_action_input(const CellularActionRecord& action, std::uint64_t begin_ return !all_zero(action.account) && action.action_id != 0 && tick > begin_tick && tick <= end_tick && move_x >= -movement_limit && move_x <= movement_limit && move_y >= -movement_limit && move_y <= movement_limit && input[12] <= 3 && - all_zero(input.subspan(13, 3)) && (input[12] == 1 || all_zero(input.subspan(16, 8))); + input[13] <= 1 && all_zero(input.subspan(14, 2)) && + (input[12] == 1 || all_zero(input.subspan(16, 8))); } bool action_less(const CellularActionRecord& a, const CellularActionRecord& b) { const auto a_tick = action_tick(a); @@ -575,7 +576,7 @@ match_cellular_actions_to_trace(const CellularLives& predecessor, const Cellular intent->intent.movement.y != std::bit_cast(static_cast(get(input, 10, 2))) || intent->intent.intake_target != target || intent->intent.engulf != (input[12] == 2) || - intent->intent.bud != (input[12] == 3)) + intent->intent.bud != (input[12] == 3) || intent->intent.brake != (input[13] == 1)) return std::unexpected{CellularActionBlockError::mismatch}; } return {}; diff --git a/src/server/session/cellular_session_batch.cpp b/src/server/session/cellular_session_batch.cpp index bcc1631..e626c0d 100644 --- a/src/server/session/cellular_session_batch.cpp +++ b/src/server/session/cellular_session_batch.cpp @@ -76,6 +76,8 @@ prepare_cellular_session_tick(const CellularLives& state, std::uint64_t tick, owned_intent->intent.engulf = input->engulf; // ADR-0125: below rules 4 the owner ignores a bud intent. owned_intent->intent.bud = input->bud; + // Rules 12: below them the owner refuses a brake, so only v13 sessions send one. + owned_intent->intent.brake = input->brake; CellularActionRecord record; record.account = action.account.bytes; record.action_id = action.action_id; diff --git a/src/server/session/region_sessions.cpp b/src/server/session/region_sessions.cpp index 56a914a..93079d0 100644 --- a/src/server/session/region_sessions.cpp +++ b/src/server/session/region_sessions.cpp @@ -628,7 +628,7 @@ struct RegionSessions::Impl { wire_version == network::session_protocol_v9 || network::cellular_v10_family(wire_version)) && !cellular_actions) || - wire_version > network::session_protocol_v12) + wire_version > network::session_protocol_v13) return close(c, SessionCloseReason::unsupported_version, now); } else if (wire_version != c.protocol_version) { return close(c, SessionCloseReason::unsupported_version, now); @@ -954,12 +954,23 @@ bool RegionSessions::send_cellular_perception(const network::AccountId& account, delivered.patches.clear(); else delivered.deposits.clear(); - // Only v12 carries captured light and visible producers (ADR-0176). - if (c.protocol_version != network::session_protocol_v12) { + // Only v12 and v13 carry captured light and visible producers (ADR-0176). + if (!network::cellular_light_version(c.protocol_version)) { delivered.producers.clear(); if (delivered.diagnostics) delivered.diagnostics->light_pj = 0; } + // Only v13 carries liquid motion (rules 12). + if (c.protocol_version != network::session_protocol_v13) { + delivered.currents.reset(); + if (delivered.diagnostics) { + delivered.diagnostics->velocity_x_q10 = 0; + delivered.diagnostics->velocity_y_q10 = 0; + delivered.diagnostics->heading = 0; + } + for (auto& deposit : delivered.deposits) + deposit.velocity_x_um_s = deposit.velocity_y_um_s = 0; + } if (c.protocol_version == network::session_protocol_v8) delivered.diagnostics.reset(); if (c.protocol_version == network::session_protocol_v9 && delivered.diagnostics) { diff --git a/tests/cellular_intent_protocol_tests.cpp b/tests/cellular_intent_protocol_tests.cpp index fbc4a71..f688bd3 100644 --- a/tests/cellular_intent_protocol_tests.cpp +++ b/tests/cellular_intent_protocol_tests.cpp @@ -110,9 +110,14 @@ void v7_reliable_action_is_stable_and_strict() { auto malformed_input = canonical; malformed_input[12] = 2; CHECK(!decode_cellular_action_input(malformed_input)); + // Byte 13 is a flags byte (schema 58): bit 0 brake, every other bit refused. malformed_input = canonical; - malformed_input[13] = 1; + malformed_input[13] = 2; CHECK(!decode_cellular_action_input(malformed_input)); + auto braking_input = canonical; + braking_input[13] = 1; + const auto braking = decode_cellular_action_input(braking_input); + CHECK(braking && braking->brake && encode_cellular_action_input(*braking) == braking_input); malformed_input = canonical; // The canonical biological input itself requires a nonzero tick. std::fill(malformed_input.begin(), malformed_input.begin() + 8, std::uint8_t{0}); @@ -542,6 +547,66 @@ void v12_perception_carries_light_and_producers() { CHECK(encode_session(SessionMessage{offer}, session_protocol_v12).empty()); } +// Rules 12: v13 is v12 plus liquid motion: the owner's velocity and heading and the region's +// current configuration in its view, each deposit's world velocity, and a brake on actions. +// Earlier versions refuse every liquid field. +void v13_perception_carries_liquid_motion() { + CellularLifeDiagnostics d; + d.reserve_energy_pj = 9; + d.light_pj = 3; + d.velocity_x_q10 = -190 * 1'024; + d.velocity_y_q10 = 12; + d.heading = 49'152; + CellularPerception view{77, 7, {}, d}; + CellularPerceivedDeposit bubble{9, 9'000, 400, 30, CellularDepositShape::bubble, + false, {1, 0, 0, 4, 0}}; + bubble.velocity_x_um_s = -250; + bubble.velocity_y_um_s = 60; + view.deposits.push_back(bubble); + view.currents = CellularCurrentsView{5, 60'000, 60'000, 250, 2, 4, 3'000, 6'000, 60, 300}; + const auto bytes = encode_session(SessionMessage{view}, session_protocol_v13); + CHECK(bytes.size() == session_header_bytes + 18 + 64 + 40 + 16 + 56 + 30); + std::uint16_t version{}; + const auto decoded = decode_session(bytes, &version); + CHECK(decoded && version == session_protocol_v13 && + std::get(*decoded) == view); + // v12 has room for none of it. + CHECK(encode_session(SessionMessage{view}, session_protocol_v12).empty()); + auto still = view; + still.currents.reset(); + still.diagnostics->velocity_x_q10 = still.diagnostics->velocity_y_q10 = 0; + still.diagnostics->heading = 0; + still.deposits[0].velocity_x_um_s = still.deposits[0].velocity_y_um_s = 0; + CHECK(!encode_session(SessionMessage{still}, session_protocol_v12).empty()); + // A region without currents sends a v13 view with the liquid flag clear. + CHECK(std::get(*decode_session( + encode_session(SessionMessage{still}, session_protocol_v13))) == still); + // The flag is 0 or 1, the reserved byte zero, and a cleared view carries no currents. + constexpr std::size_t flags = session_header_bytes + 18 + 64 + 40 + 16 + 10; + auto bad = bytes; + bad[flags] = 2; + CHECK(!decode_session(bad)); + bad = bytes; + bad[flags + 1] = 1; + CHECK(!decode_session(bad)); + auto cleared = still; + cleared.life_identity = 0; + cleared.diagnostics.reset(); + cleared.deposits.clear(); + cleared.currents = view.currents; + CHECK(encode_session(SessionMessage{cleared}, session_protocol_v13).empty()); + + // A brake travels only on v13 actions. + CellularAction braking{1, 2, 3, 4, 500, 0, false, 0, 0}; + braking.brake = true; + const auto action = encode_session(SessionMessage{braking}, session_protocol_v13); + CHECK(std::get(*decode_session(action)) == braking); + auto old_brake = encode_session(SessionMessage{CellularAction{1, 2, 3, 4, 500, 0, false, 0, 0}}, + session_protocol_v12); + old_brake[session_header_bytes + 37] = 1; + CHECK(!decode_session(old_brake)); +} + int main() { try { round_trip_and_version_gate(); @@ -556,6 +621,7 @@ int main() { v10_effects_and_life_end_are_owner_only(); v11_perception_carries_deposits(); v12_perception_carries_light_and_producers(); + v13_perception_carries_liquid_motion(); std::puts( "PASS cellular protocol: v6 intention, v7 action, v8-v10 perception/action framing"); } catch (const std::exception& error) { diff --git a/tests/cellular_liquid_owner_tests.cpp b/tests/cellular_liquid_owner_tests.cpp index 7c65347..78281fe 100644 --- a/tests/cellular_liquid_owner_tests.cpp +++ b/tests/cellular_liquid_owner_tests.cpp @@ -15,7 +15,7 @@ using namespace evo::fixture; constexpr biology::CellularArea area{48'000, 48'000}; CellularLiquidRules rules(std::uint64_t seed = 5) { - return {.currents = {seed, area.width_um, area.height_um, 250, 2, 4, 3'000, 6'000, 60, 300}, + return {.currents = {seed, 48'000, 48'000, 250, 2, 4, 3'000, 6'000, 60, 300}, .founder = {.thrust_q10 = 20'480, .reverse_thrust_q10 = 20'480, .forward_drag_ppm = 95'163, diff --git a/tests/client_bindings.cpp b/tests/client_bindings.cpp index 8dc7d2b..f4d4a47 100644 --- a/tests/client_bindings.cpp +++ b/tests/client_bindings.cpp @@ -126,7 +126,15 @@ void file_format() { CHECK(refused(parse_bindings("move_up W\n"), BindingError::malformed)); CHECK(refused(parse_bindings("evo-controls 2\n"), BindingError::unsupported_version)); CHECK(refused(parse_bindings("evo-controls 1 extra\n"), BindingError::malformed)); + // Original actions stay required; one added later (brake) takes its default key when it + // is free, and is refused when another action already holds it. CHECK(refused(parse_bindings(without("pan_down")), BindingError::missing_primary)); + CHECK(parse_bindings(without("brake")) == *custom); + auto held = without("brake"); + const auto left = held.find("move_left A\n"); + CHECK(left != std::string::npos); + held.replace(left, 12, "move_left A Space\n"); + CHECK(refused(parse_bindings(held), BindingError::missing_primary)); CHECK(refused(parse_bindings(text + "move_up W\n"), BindingError::malformed)); CHECK(refused(parse_bindings(text + "jump Space\n"), BindingError::malformed)); CHECK(refused(parse_bindings(without("move_up") + "move_up w\n"), BindingError::malformed)); diff --git a/tests/network_control.cpp b/tests/network_control.cpp index d6fe123..8663d31 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) = 13; // A future version; protocol versions through 12 are supported. + mutated.at(4) = 14; // A future version; protocol versions through 13 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 e25eb5b..b3ef0b1 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -223,6 +223,7 @@ void upgrade_across_migration_and_barrier() { " -v migration_sha_55=$(s 0055_retained_cellular_plans.sql)" " -v migration_sha_56=$(s 0056_cellular_environment_publication.sql)" " -v migration_sha_57=$(s 0057_photosynthesis_bundle.sql)" + " -v migration_sha_58=$(s 0058_liquid_bundle.sql)" " -v runtime_role=evo_runtime_test -f migrations/apply.sql" " > /dev/null 2>&1") != 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7"); @@ -240,7 +241,7 @@ void upgrade_across_migration_and_barrier() { "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,43,44,45,46," - "47,48,49,50,51,52,53,54,55,56,57"); + "47,48,49,50,51,52,53,54,55,56,57,58"); 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 df85c5c..e5d6194 100644 --- a/tests/region_store_tests.cpp +++ b/tests/region_store_tests.cpp @@ -2,6 +2,7 @@ // the object volume's free-space reserve, a genuinely failing write, the // check-store probe (retention across runs, missing-volume refusal, privilege // boundary) and a server whose volume is full. Run by tools/ci/postgres-check.sh. +#include "evo/biology/cellular_tuning.hpp" #include "evo/persistence/account_control_store.hpp" #include "evo/persistence/checkpoint_store.hpp" #include "evo/persistence/region_checkpoint.hpp" @@ -13,6 +14,7 @@ #include "fixtures/server_process.hpp" #include #include +#include #include #include @@ -753,6 +755,126 @@ void cellular_v8_provisioning_declares_light() { #endif } +// Rules 12 (ADR-0177): cellular-v9 is cellular-v8 followed by the 13 -> 14 liquid upgrade from +// the Git tuning file, whose region size must match the opening; resumable and idempotent. +void cellular_v9_provisioning_declares_liquid() { + const ServerRegion r{{9777, 1}, fresh("cellular-v9-provision-9777")}; + const std::string build(64, 'e'); + const std::string commit = "b0b81e5c0f7e1d2ba1a0ce5c0f7e1d2e"; // Unique to this test. + const std::string motes = "40,1,2000000,50000,20000,0,0"; + const auto write_tuning = [&](std::uint32_t side) { + auto parsed = evo::biology::parse_cellular_tuning( + "tuning.version = 1\nregion.width_um = 60000\nregion.height_um = 60000\n" + "region.organism_cap = 2000\nregion.deposit_limit = 8192\n" + "region.perception_radius_um = 5000\nfounder.thrust_um_per_s2 = 400\n" + "founder.reverse_thrust_um_per_s2 = 400\nfounder.drag_ppm_per_tick = 95163\n" + "founder.lateral_drag_ppm_per_tick = 95163\nfounder.turn_heading_per_s = 65536\n" + "currents.min_count = 2\ncurrents.max_count = 4\ncurrents.min_width_um = 3000\n" + "currents.max_width_um = 6000\ncurrents.min_speed_um_per_s = 60\n" + "currents.max_speed_um_per_s = 300\ncurrents.grid_pitch_um = 250\n" + "food.merged_bubble_cap_multiple = 8\nfood.visible_moving_bubbles = 256\n" + "food.induced_drift_radius_um = 200\nfood.induced_drift_max_um_per_s = 100\n" + "food.induced_drift_decay_ppm_per_tick = 95163\nthermal.ambient_min_mk = 278150\n" + "thermal.ambient_max_mk = 313150\nfounder.preferred_mk = 293150\n" + "founder.comfort_band_mk = 5000\nfounder.body_tau_ms = 20000\n" + "founder.lethal_cold_mk = 273150\nfounder.lethal_heat_mk = 318150\n" + "thermal.off_preference_per_mille_per_k = 80\n" + "thermal.transition_per_mille_per_k = 40\nthermal.multiplier_cap_per_mille = 8000\n" + "lifecycle.logout_delay_ms = 10000\nmutation.step_points = 5\n" + "mutation.paired_points = 2\nmutation.recovery_floor_per_mille = 100\n" + "mutation.offer_interval_ms = 25000\nmutation.offer_options = 3\n"); + CHECK(parsed); + parsed->region_width_um = parsed->region_height_um = side; + const auto path = r.root / ("cellular-" + std::to_string(side) + ".tuning"); + std::ofstream{path, std::ios::binary} << evo::biology::encode_cellular_tuning(*parsed); + return path.string(); + }; + int code = -1; + provision_cellular(r, "9777", "cellular-v9", build, commit, motes, code, "--motes", + {"--light-pj", "40"}); + CHECK(code != 0); // cellular-v9 requires --tuning. + provision_cellular(r, "9777", "cellular-v9", build, commit, motes, code, "--motes", + {"--light-pj", "40", "--tuning", write_tuning(20'000)}); + CHECK(code != 0); // The tuning region size must match the opening's. + const auto tuning = write_tuning(10'000); + const auto first = provision_cellular(r, "9777", "cellular-v9", build, commit, motes, code, + "--motes", {"--light-pj", "40", "--tuning", tuning}); + CHECK(code == 0 && has(first, "provisioned world=9777 region=1 sequence=6 tick=1")); + const auto again = provision_cellular(r, "9777", "cellular-v9", build, commit, motes, code, + "--motes", {"--light-pj", "40", "--tuning", tuning}); + CHECK(code == 0 && has(again, "already-provisioned world=9777 region=1 sequence=6 tick=1")); + 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_v14_versions && + manifest->history_profile == cellular_revision_history_profile); +#ifdef EVO_POSTGRES_M10 + // A player is born on the liquid head and swims and brakes through the live server path: + // host reservation, session batch builder, host publication with a braking trace. + using namespace evo::server; + const auto connect = [&]() -> std::expected, PgFailure> { + return Postgres::connect({env("PGHOST"), + {}, + env("PGPORT"), + env("PGDATABASE"), + env("EVO_PG_RUNTIME_USER"), + {}, + {}}, + 5s); + }; + CHECK(db->query("INSERT INTO evolution.life_allocators VALUES(9777,1000)", {}, 5s)); + Sha256Digest digest{}; + digest.fill(0xEE); + auto objects = FilesystemObjectStore::open(r.root, r.key, max_cellular_lives_bytes); + CHECK(objects); + auto made = + CellularRegionHost::create({r.key, 9, {}, digest, {digest}}, connect, std::move(*objects)); + CHECK(made); + auto host = std::move(*made); + CHECK(host->step().ready && host->state() && + host->state()->rules_version() == cellular_lives_liquid_rules && + host->state()->flow_field() != nullptr); + auto runtime = connect(); + CHECK(runtime); + Uuid account{}; + account[0] = 0x9E; + account.back() = 0x14; + const auto control = + claim_account_control(**runtime, r.key, *host->authority(), account, 1, 1, 20'000ms, 5s); + CHECK(control); + CHECK(host->create_primitive_life(account, control->generation, 5).result == + evo::network::PrimitiveLifeResult::pending); + const std::vector births(host->queued_births().begin(), host->queued_births().end()); + auto builder = CellularSessionBatchBuilder::create(*host->state(), host->committed()->head); + CHECK(builder); + CHECK(builder->append_with_birth_refusals(host->state()->tick() + 1, {}, {}, births, {})); + CHECK(builder->refused_births().empty() && + builder->batch().format_version == cellular_batch_inheritance_format); + CHECK(host->publish(builder->batch(), builder->actions(), builder->mutation_actions())); + CHECK(host->query_primitive_life(account, control->generation, 5).result == + evo::network::PrimitiveLifeResult::born); + // Ticks of swimming then braking publish and leave the founder in motion state. + for (int tick = 0; tick < 6; ++tick) { + std::vector intents; + for (const auto& life : host->state()->lives()) { + CellularLifeIntent intent{life.identity.life, {}}; + intent.intent.movement = {1'000, 0}; + intent.intent.brake = tick >= 4; + intents.push_back(intent); + } + std::ranges::sort(intents, {}, &CellularLifeIntent::life_id); + auto next = CellularSessionBatchBuilder::create(*host->state(), host->committed()->head); + CHECK(next && next->append(host->state()->tick() + 1, intents, {})); + CHECK(host->publish(next->batch(), next->actions(), next->mutation_actions())); + } + CHECK(host->state()->lives().front().identity.genome != 0); + const auto genome = + host->state()->archive().find(host->state()->lives().front().identity.genome); + CHECK(genome && genome->schema_version() == evo::biology::genome_schema_v6); +#endif +} + #ifdef EVO_POSTGRES_M10 // A player on a cellular-v8 region feeds by contact until offered a mutation, chooses it // and publishes the choice, all through the host and session builder as evo-server does. @@ -884,6 +1006,7 @@ void run_region_store_tests() { cellular_v6_provisioning_uses_the_reproduction_bundle(); cellular_v7_provisioning_scatters_bubbles(); cellular_v8_provisioning_declares_light(); + cellular_v9_provisioning_declares_liquid(); #ifdef EVO_POSTGRES_M10 cellular_v8_player_chooses_a_mutation(); #endif diff --git a/tools/ci/history-domain-check.sh b/tools/ci/history-domain-check.sh index 33a731d..65d4586 100644 --- a/tools/ci/history-domain-check.sh +++ b/tools/ci/history-domain-check.sh @@ -58,7 +58,7 @@ for invalid in NULL "'00000000-0000-0000-0000-000000000000'"; do done # Reconstruct the exact pre-context metadata schema in this disposable database. # Restore the resulting real legacy backup through both supported workflows. -# Undo schema 57's bundle-13 wrappers, schema 56's joint profile, schema 55's plan validators, schema 54's three +# Undo schema 58's bundle-14 wrappers, schema 57's bundle-13 wrappers, schema 56's joint profile, schema 55's plan validators, schema 54's three # replacements and schema 53; the backup must contain the actual pre-context # function contracts and privileges. awk '/^CREATE FUNCTION evolution\.admit_population_interval\(/ {capture=1; sub(/^CREATE FUNCTION/,"CREATE OR REPLACE FUNCTION")} capture {print} capture && /^END \$\$;/ {capture=0}' \ @@ -68,8 +68,17 @@ awk '/^CREATE FUNCTION evolution\.(check_cellular_migration_trace|prepare_cellul "$root/migrations/0049_cellular_migration_publication.sql" | sql > /dev/null awk '/^CREATE OR REPLACE FUNCTION evolution\.(cellular_mutation_selections|check_cellular_mutation_block)\(/ {capture=1} capture {print} capture && /^END \$\$;/ {capture=0}' \ "$root/migrations/0040_cellular_mutation_decline.sql" | sql > /dev/null +# Schema 58 widened the canonical action input; restore schema 36's validator. +awk '/^CREATE OR REPLACE FUNCTION evolution\.valid_cellular_action_input\(/ {capture=1} capture {print} capture && /^END \$\$;/ {capture=0}' \ + "$root/migrations/0036_cellular_v5_budding_bundle.sql" | sql > /dev/null sql -v runtime_role="$EVO_PG_RUNTIME_ROLE" > /dev/null <<'SQL' DROP FUNCTION evolution.publish_cellular_profile_migration(bytea); +ALTER FUNCTION evolution.publish_cellular_profile_migration_v57(bytea) RENAME TO publish_cellular_profile_migration; +DROP FUNCTION evolution.cellular_births(bytea,bytea); +ALTER FUNCTION evolution.cellular_births_v57(bytea,bytea) RENAME TO cellular_births; +DROP FUNCTION evolution.parse_checkpoint_manifest(bytea); +ALTER FUNCTION evolution.parse_checkpoint_manifest_v57(bytea) RENAME TO parse_checkpoint_manifest; +DROP FUNCTION evolution.publish_cellular_profile_migration(bytea); ALTER FUNCTION evolution.publish_cellular_profile_migration_v56(bytea) RENAME TO publish_cellular_profile_migration; DROP FUNCTION evolution.cellular_births(bytea,bytea); ALTER FUNCTION evolution.cellular_births_v56(bytea,bytea) RENAME TO cellular_births; diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index faa783f..3bd834e 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -161,7 +161,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,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57 +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,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58 # 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%% *}" @@ -182,7 +182,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")" = 57: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,44,45,46,47,48,49,50,51,52,53,54,55,56,57 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 58: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,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58 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. @@ -236,7 +236,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,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57 +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,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58 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 @@ -294,9 +294,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.load_world_cellular_m expect_audit_failure 'GRANT EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) TO evo_runtime_test' 'REVOKE EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) FROM evo_runtime_test' 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=58 WHERE version=57' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=59 WHERE version=58' 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=57 WHERE version=58" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=58 WHERE version=59" 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 c6b08ca..2605812 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -126,6 +126,8 @@ digest_56="$(sha256sum "$root/migrations/0056_cellular_environment_publication.s digest_56="${digest_56%% *}" digest_57="$(sha256sum "$root/migrations/0057_photosynthesis_bundle.sql")" digest_57="${digest_57%% *}" +digest_58="$(sha256sum "$root/migrations/0058_liquid_bundle.sql")" +digest_58="${digest_58%% *}" 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" \ @@ -173,6 +175,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_52=$digest_52" \ --set="migration_sha_53=$digest_53" --set="migration_sha_54=$digest_54" \ --set="migration_sha_55=$digest_55" --set="migration_sha_56=$digest_56" \ - --set="migration_sha_57=$digest_57" \ + --set="migration_sha_57=$digest_57" --set="migration_sha_58=$digest_58" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"