Cellular rules 8: pools and bubbles fed by contact (ADR-0136 step A)
Foundation / checks (checks) (push) Successful in 47m40s
Foundation / checks (client) (push) Successful in 17m27s
Foundation / checks (deploy) (push) Successful in 4m17s
Foundation / checks (ecs) (push) Successful in 4m31s
Foundation / checks (network) (push) Successful in 22m1s
Foundation / checks (tsan) (push) Successful in 13m10s
Foundation / checks (postgres) (push) Successful in 20m54s
Foundation / image (push) Successful in 4m15s
Foundation / postgres-tools (push) Successful in 5m32s
Foundation / server-image (push) Successful in 7m15s

Square patches invited camping and left the space between them empty. Rules 8 run on a
format-2 habitat of deposits:
- pools and single-nutrient bubbles at free micrometre centres, each with a stable id
  and a contact radius; the cellular-v7 opening scatters bubbles reproducibly from the
  genesis commit (three in ten in loose clumps) and lists pools with --pool;
- every cell drains what it touches, up to its intake rate per tick, with no target; a
  pool gives at most a quarter of that rate; an emptied deposit disappears;
- a dead cell's detritus breaks into one bubble per non-empty channel;
- wildlife swims to the nearest non-empty deposit and feeds by touch.

Bundle v9 (habitat 2) and schema v43 admit it. Session v11 carries the owner's 512
nearest deposits (id, centre, radius, shape, a drained flag and 16-bit amount codes)
instead of patches; every other cellular message is v10's. The client asks for v11,
draws bubbles (nutrient-coloured, pulsing while drained, popping when gone) and pools as
puddles, slows near food and sends no feed target; the HUD summarises food in range.
Earlier rules, regions and v10 clients are unchanged.

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