diff --git a/apps/evo-client/cellular_controls.hpp b/apps/evo-client/cellular_controls.hpp index bef0a17..7f31e9d 100644 --- a/apps/evo-client/cellular_controls.hpp +++ b/apps/evo-client/cellular_controls.hpp @@ -38,6 +38,7 @@ steer_cellular(const CellularControls& controls, client::Intention intention, const double y = static_cast(own->voxel.y) * 1'000'000 + static_cast(own->y.value); const double extent = static_cast(own->phenotype.extent); + bool target_has_energy = false; for (const auto& p : perception->patches) { if (p.energy_pj == 0 && std::ranges::all_of(p.matter_fg, [](auto v) { return v == 0; })) @@ -46,8 +47,11 @@ steer_cellular(const CellularControls& controls, client::Intention intention, std::max({static_cast(p.x_um) - x - extent, x - p.x_um - 1000, 0.0}); const double dy = std::max({static_cast(p.y_um) - y - extent, y - p.y_um - 1000, 0.0}); - if (controls.auto_feed && !result.patch && dx == 0 && dy == 0) + if (controls.auto_feed && dx == 0 && dy == 0 && + (!result.patch || (!target_has_energy && p.energy_pj != 0))) { result.patch = {p.x_um, p.y_um}; + target_has_energy = p.energy_pj != 0; + } // Presentation preference: approach food at at most 500 um/s (25 um/tick). // Recomputed from the current phenotype after every mutation. Authority // still determines displacement, contact, funding and intake. diff --git a/apps/evo-client/cellular_play.hpp b/apps/evo-client/cellular_play.hpp index 6dbecd6..5c5ae17 100644 --- a/apps/evo-client/cellular_play.hpp +++ b/apps/evo-client/cellular_play.hpp @@ -33,6 +33,10 @@ struct CellActionRecord { MutationChoice choice{}; network::AdmitStatus refusal{network::AdmitStatus::admitted}; }; +struct CellEnergyChange { + std::uint64_t from_tick{}, to_tick{}, amount{}; + bool falling{}; +}; class CellularPlay { public: @@ -54,6 +58,8 @@ class CellularPlay { void disconnected() { connected_ = false; fresh_ = false; + energy_sample_.reset(); + energy_change_.reset(); offer_.reset(); if (pending_) { if (pending_->state == CellActionState::queued) { @@ -71,6 +77,20 @@ class CellularPlay { fresh_ = true; if (ended_ && view.life_identity == ended_->life_identity) return; // A retained pre-death view must never revive this identity. + if (view.life_identity != 0 && view.diagnostics) { + const auto energy = view.diagnostics->reserve_energy_pj; + if (energy_sample_ && energy_sample_->life == view.life_identity) { + if (view.tick > energy_sample_->tick) + energy_change_ = CellEnergyChange{energy_sample_->tick, view.tick, + energy < energy_sample_->energy + ? energy_sample_->energy - energy + : energy - energy_sample_->energy, + energy < energy_sample_->energy}; + } else { + energy_change_.reset(); + } + energy_sample_ = EnergySample{view.life_identity, view.tick, energy}; + } // Never replay an intention onto a later life. Keep its uncertain result visible. if (life_ != view.life_identity) { offer_.reset(); @@ -95,6 +115,7 @@ class CellularPlay { } if (life_ != 0) { birth_pending_ = false; + birth_result_ = network::PrimitiveLifeResult::born; if (ended_ && ended_->life_identity != life_) ended_.reset(); } @@ -201,7 +222,11 @@ class CellularPlay { finish(); } [[nodiscard]] bool can_restart() const { - return connected_ && fresh_ && life_ == 0 && !birth_pending_; + const bool refused = birth_result_ == network::PrimitiveLifeResult::insufficient_funding || + birth_result_ == network::PrimitiveLifeResult::no_placement || + birth_result_ == network::PrimitiveLifeResult::cancelled; + return connected_ && (fresh_ || refused) && life_ == 0 && !birth_pending_ && + (birth_result_ != network::PrimitiveLifeResult::existing_life || ended_); } [[nodiscard]] bool restart() { if (!can_restart()) @@ -211,6 +236,7 @@ class CellularPlay { return false; birth_request_ = id; birth_pending_ = true; + birth_result_ = network::PrimitiveLifeResult::pending; return true; } void birth(const network::PrimitiveLifeOutcome& result) { @@ -258,6 +284,9 @@ class CellularPlay { [[nodiscard]] const auto& bud_feedback() const { return bud_feedback_; } + [[nodiscard]] const auto& energy_change() const { + return energy_change_; + } private: void finish() { @@ -277,5 +306,10 @@ class CellularPlay { std::deque history_; std::optional> engulf_feedback_; std::optional> bud_feedback_; + struct EnergySample { + std::uint64_t life{}, tick{}, energy{}; + }; + std::optional energy_sample_; + std::optional energy_change_; }; } // namespace evo::client_app diff --git a/apps/evo-client/cellular_scene.hpp b/apps/evo-client/cellular_scene.hpp index 053ccf1..fda5198 100644 --- a/apps/evo-client/cellular_scene.hpp +++ b/apps/evo-client/cellular_scene.hpp @@ -5,12 +5,12 @@ #include namespace evo::client_app { -inline constexpr std::size_t patch_rectangles = 3; +inline constexpr std::size_t patch_rectangles = 11; // The border keeps the 1 mm contact footprint readable; the inset is decorative. -// No stock percentage is invented: the centre mark means some stock remains. +// E (gold) and M (teal) identify energy and matter stock, without invented percentages. inline void patch_box(std::vector& out, client::ScreenPoint low, - client::ScreenPoint high, bool stocked, bool selected, double width, - double height, bool stale = false) { + client::ScreenPoint high, bool energy, bool matter, bool selected, + double width, double height, bool stale = false) { const double minimum = selected ? 5 : 3; const double hx = std::max((high.x - low.x) / 2, minimum); const double hy = std::max((low.y - high.y) / 2, minimum); @@ -30,18 +30,34 @@ inline void patch_box(std::vector& out, client::ScreenPoint l static_cast(b - t), color}); }; rect(x - hx, y - hy, x + hx, y + hy, - selected ? render::Color{233, 182, 85, 255} - : stocked ? render::Color{49, 112, 105, 255} - : render::Color{58, 69, 77, 255}); + selected ? render::Color{233, 182, 85, 255} + : energy ? render::Color{155, 117, 45, 255} + : matter ? render::Color{49, 112, 105, 255} + : render::Color{58, 69, 77, 255}); if (hx <= 6 || hy <= 6) return; const double border = selected ? 2 : 1; rect(x - hx + border, y - hy + border, x + hx - border, y + hy - border, selected ? render::Color{53, 49, 31, 255} : render::Color{17, 40, 43, 255}); - if (stocked) { - const double mark = std::clamp(std::min(hx, hy) * 0.08, 2.0, 5.0); - rect(x - mark, y - mark, x + mark, y + mark, - selected ? render::Color{233, 182, 85, 255} : render::Color{90, 185, 150, 255}); + if (hx >= 16 && hy >= 16) { + const double top = y - hy + 7; + if (energy) { + const double left = matter ? x - 12 : x - 4; + const render::Color gold{233, 182, 85, 255}; + rect(left, top, left + 2, top + 12, gold); + rect(left + 2, top, left + 8, top + 2, gold); + rect(left + 2, top + 5, left + 7, top + 7, gold); + rect(left + 2, top + 10, left + 8, top + 12, gold); + } + if (matter) { + const double left = energy ? x + 3 : x - 5; + const render::Color teal{90, 185, 150, 255}; + rect(left, top, left + 2, top + 12, teal); + rect(left + 8, top, left + 10, top + 12, teal); + rect(left + 2, top + 2, left + 4, top + 5, teal); + rect(left + 6, top + 2, left + 8, top + 5, teal); + rect(left + 4, top + 4, left + 6, top + 7, teal); + } } } } // namespace evo::client_app diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index 79508fa..62e8dbf 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -642,10 +642,8 @@ int main(int argc, char** argv) try { (static_cast(patch.y_um) + 1000) / 1000}); if (low && high) evo::client_app::patch_box( - boxes, *low, *high, - patch.energy_pj != 0 || - std::ranges::any_of(patch.matter_fg, - [](auto v) { return v != 0; }), + boxes, *low, *high, patch.energy_pj != 0, + std::ranges::any_of(patch.matter_fg, [](auto v) { return v != 0; }), cellular_feed_target && cellular_feed_target->first == patch.x_um && cellular_feed_target->second == patch.y_um, width, height, !remote->cellular_play().fresh()); diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index 948bf25..71f7015 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -568,6 +568,23 @@ void cell_vitals(const PanelView& v) { ImGui::PushFont(nullptr, 24); ImGui::TextWrapped("%llu pJ", static_cast(d.reserve_energy_pj)); ImGui::PopFont(); + if (const auto& change = play->energy_change(); change) { + ImGui::TextColored(change->falling ? amber : green, "%s%llu pJ net", + change->falling ? "-" : "+", + static_cast(change->amount)); + ImGui::TextDisabled("Across %llu observed ticks", + static_cast(change->to_tick - change->from_tick)); + if (change->falling) + disabled_wrapped( + "Energy is falling. Feeding may not cover upkeep, movement or actions."); + } + if (v.cellular_feed_target) { + const auto patch = std::ranges::find_if(p->patches, [&](const auto& candidate) { + return v.cellular_feed_target == std::pair{candidate.x_um, candidate.y_um}; + }); + if (patch != p->patches.end() && patch->energy_pj == 0) + ImGui::TextWrapped("FEED TARGET HAS NO ENERGY. Check Food for another patch."); + } ImGui::Separator(); if (ImGui::BeginTable("matter", 2, ImGuiTableFlags_SizingStretchSame)) { constexpr std::array names{"Carbon", "Nitrogen", "Phosphorus", "Other matter"}; @@ -588,8 +605,8 @@ void cell_vitals(const PanelView& v) { static_cast(d.movement_cost_pj)); constexpr std::array movement{"Unavailable", "Resting", "Moving", "Movement blocked", "Not enough energy to move"}; - constexpr std::array intake{"Unavailable", "Not feeding", "Food absorbed", "Food patch missing", - "Move into contact to feed"}; + constexpr std::array intake{"Unavailable", "Not feeding", "Feeding attempt processed", + "Food patch missing", "Move into contact to feed"}; constexpr std::array engulf{"Unavailable", "Not requested", "Prey engulfed", @@ -606,6 +623,8 @@ void cell_vitals(const PanelView& v) { "No space for a bud"}; ImGui::TextWrapped("%s", movement.at(static_cast(d.movement))); ImGui::TextWrapped("%s", intake.at(static_cast(d.intake))); + if (d.intake == network::CellularIntakeResult::acquired) + disabled_wrapped("A feeding attempt can yield zero energy. Watch the reserve change."); if (const auto& feedback = play->engulf_feedback(); feedback) ImGui::TextWrapped("%s (tick %llu)", engulf.at(static_cast(feedback->second)), static_cast(feedback->first)); @@ -620,8 +639,12 @@ void cell_food(const PanelView& v, PanelActions& a, FormBuffers& form) { ImGui::Checkbox("Precision steering (20%)", &form.cellular_controls.precision); ImGui::SetNextItemWidth(-1); ImGui::SliderInt("##speed", &form.cellular_controls.speed_percent, 1, 100, "Speed: %d%%"); - disabled_wrapped("Steer onto food. Automatic feeding targets a stocked patch touching your " - "cell. Choose a patch below to switch to manual feeding."); + disabled_wrapped( + "Map key: gold E = energy, teal M = matter; no letters = empty (zoom in to " + "see letters). Auto feed prefers energy in contact. Choose a patch for manual feeding."); + disabled_wrapped("Patch stock is finite and shared. Matter does not replenish energy. Uptake " + "is limited by your cell; stock is not a promise of gain each tick. Upkeep is " + "paid before feeding."); const bool active = v.cellular_play && v.cellular_play->fresh() && v.cellular_play->life() != 0; ImGui::BeginDisabled(!active); if (v.cellular_feed_target && ImGui::Button("Stop feeding", {-1, 0})) @@ -634,7 +657,13 @@ void cell_food(const PanelView& v, PanelActions& a, FormBuffers& form) { ImGui::PushID(static_cast(patch.y_um)); ImGui::Separator(); ImGui::Text("Patch %u / %u um", patch.x_um, patch.y_um); - ImGui::Text("%llu pJ", static_cast(patch.energy_pj)); + const bool has_matter = + std::ranges::any_of(patch.matter_fg, [](auto amount) { return amount != 0; }); + ImGui::TextColored(patch.energy_pj != 0 ? amber : green, "%s", + patch.energy_pj != 0 ? "E ENERGY AVAILABLE" + : has_matter ? "M MATTER ONLY / NO ENERGY" + : "EMPTY / DEPLETED"); + ImGui::Text("Energy stock: %llu pJ", static_cast(patch.energy_pj)); ImGui::TextWrapped("C %llu / N %llu / P %llu / other %llu fg", static_cast(patch.matter_fg[0]), static_cast(patch.matter_fg[1]), @@ -693,6 +722,10 @@ void cell_evolution(const PanelView& v, PanelActions& a) { : cause == network::CellularDeathReason::engulfed ? "Your cell was engulfed." : "The cause was not recorded."); + if (cause == network::CellularDeathReason::starved) + disabled_wrapped("Your reserve could not pay upkeep before feeding. A patch can " + "still hold matter after its energy runs out; intake can also be " + "slower than your energy spending."); ImGui::TextWrapped("Its history and descendants remain. Your next life begins as a new " "primitive cell."); } else { @@ -705,6 +738,10 @@ void cell_evolution(const PanelView& v, PanelActions& a) { if (ImGui::Button("Start new life", {-1, px(38)})) a.restart_life = true; ImGui::EndDisabled(); + if (play->birth_pending()) + disabled_wrapped( + "Waiting for the server. Rechecking this same birth request every " + "2 seconds. Reconnecting or creating an account cannot refill a nursery."); if (v.remote && !v.remote->cellular_action.empty()) ImGui::TextWrapped("%s", v.remote->cellular_action.c_str()); return; diff --git a/apps/evo-client/remote_session.hpp b/apps/evo-client/remote_session.hpp index bf16ba9..30ccf5c 100644 --- a/apps/evo-client/remote_session.hpp +++ b/apps/evo-client/remote_session.hpp @@ -235,6 +235,7 @@ class RemoteSession { return false; cellular_feed_target_.reset(); birth_check_at_ = {}; + cellular_action_status_ = "New life requested; waiting for the server"; return true; } void keep_cellular_unknown() { @@ -620,7 +621,8 @@ class RemoteSession { "Cell founded (life " + std::to_string(outcome.life_identity) + ")"; break; case network::PrimitiveLifeResult::insufficient_funding: - cellular_action_status_ = "Birth refused: nursery funding is insufficient"; + cellular_action_status_ = "Birth refused: the region nursery lacks resources. " + "A new account cannot restore them."; break; case network::PrimitiveLifeResult::no_placement: cellular_action_status_ = "Birth refused: no open spawn site"; @@ -632,7 +634,8 @@ class RemoteSession { cellular_action_status_ = "Birth request cancelled"; break; case network::PrimitiveLifeResult::pending: - cellular_action_status_ = "Cell birth is being committed"; + cellular_action_status_ = + "Birth is pending on the server; no new cell confirmed yet"; break; case network::PrimitiveLifeResult::unknown: cellular_action_status_ = "Birth outcome is unknown; retrying exact request"; diff --git a/docs/adr/0127-cellular-permadeath-and-restart.md b/docs/adr/0127-cellular-permadeath-and-restart.md index ff34f57..ac6eaff 100644 --- a/docs/adr/0127-cellular-permadeath-and-restart.md +++ b/docs/adr/0127-cellular-permadeath-and-restart.md @@ -52,6 +52,27 @@ after each death. - While a life is active, a new request is still a permanent `existing_life` refusal for that request id. +#### Birth refusal scheduling clarification (2026-10-15) + +An expected nursery funding, placement, or existing-life refusal must not reject +the entire region tick. The scheduler's `append_with_birth_refusals` separates +these requests from accepted births, advances the ordinary tick, and returns +transient refusal reports. Strict `append` retains its all-or-nothing contract. +Malformed input or unexpected biological errors still reject the append. + +After confirmed publication, the host removes refused requests from its spawn +queue and records the existing lease-fenced `reject_primitive_life` result. An +uncertain database answer stays unknown; a bounded transient cache withholds the +request from spawning while an exact request/query reconciles it, including after +account control takeover. After cache eviction or process recovery, the durable +reservation is checked again before any retry. No refusal is reported as final +until the store confirms it. A lost, unacknowledged report may be re-evaluated; +a durable refusal remains final for that request ID. + +No nursery refill, alternate spawn rule, protocol/schema revision, simulation +version or replay format is introduced. Refused births are absent from the +committed trace; accepted births still use the existing publication transaction. + ### Old sessions - A carried action whose account has no living life, or that names a patch the life diff --git a/docs/architecture/CLIENT_ARCHITECTURE.md b/docs/architecture/CLIENT_ARCHITECTURE.md index af30d6c..4269568 100644 --- a/docs/architecture/CLIENT_ARCHITECTURE.md +++ b/docs/architecture/CLIENT_ARCHITECTURE.md @@ -96,3 +96,11 @@ return requested actions; the app owns sessions, fixture and selection. M9.8d (ADR-0085) adds SDL-free bindings (actions vs HID key usages, validation, versioned controls file) to `evo_client_controls`; the adapter maps keys through them and offers binding capture ahead of toolkit and world input. + +The v10 cellular app shows observed reserve differences as **net** changes across +the named tick interval, never as measured intake. Duplicate views retain the last +change; reconnect and a different life reset its baseline. Energy/matter patch +markers and stock cards use copied sensor data only. A final birth refusal permits +an explicit new request even before a perception arrives; pending/unknown requests +retain their ID and an existing-life result waits for that life. These are app +presentation/control policies, not biological rules. diff --git a/docs/engineering/CLIENT.md b/docs/engineering/CLIENT.md index 0e7f911..b5f5b45 100644 --- a/docs/engineering/CLIENT.md +++ b/docs/engineering/CLIENT.md @@ -83,6 +83,24 @@ death notices are not a historical death query. Automatic feeding uses observed contact, so a patch crossed entirely between observations can still be missed; slowing near food reduces that risk without predicting authority. +Food reading (2026-10-15): zoomed-in patches carry a gold `E` for remaining energy +and a teal `M` for remaining matter. The Food tab shows energy stock and all four +matter channels, and explicitly labels matter-only and depleted patches. Auto-feed +prefers an energy-bearing patch when several stocked patches touch the cell; +manual selection remains available. These stocks are shared and finite. Uptake +is capacity-limited and maintenance precedes feeding, so processing a feeding +attempt does not guarantee gaining energy or surviving. The Cell tab reports +net reserve change across successive observed ticks (including all spending), +last-tick upkeep/movement, and an energy-free target warning. It does not claim an +exact intake amount that v10 does not carry. + +Pending birth feedback now says that the server has not confirmed a cell. The +client rechecks the same request every two seconds. A confirmed funding/placement +refusal or cancellation enables an explicit new request without requiring a first +world view. An existing-life result waits for that life instead. The scheduler +fix in ADR-0127 is also required on the server: a client upgrade cannot repair a +region tick blocked by an unfulfillable nursery request or replenish its nursery. + Coordinate contract discrepancy found during this work: the cellular bridge sends ADR-0102 lower-left footprint coordinates through the general presentation's centre-offset fields. Assistance deliberately interprets only cellular-session diff --git a/docs/engineering/M11_3_DELIVERY_PLAN.md b/docs/engineering/M11_3_DELIVERY_PLAN.md index 62aa356..e0c914c 100644 --- a/docs/engineering/M11_3_DELIVERY_PLAN.md +++ b/docs/engineering/M11_3_DELIVERY_PLAN.md @@ -334,6 +334,9 @@ scoped change before starting the next segment. leaves the builder unchanged. Tests cover empty-region birth replay and duplicate request refusal. The server still needs to route v5 requests into this queue and run/publish the scheduler tick. + 2026-10-15 correction: strict `append` keeps that contract; the live scheduler + uses `append_with_birth_refusals` so expected nursery refusals cannot stall the + region. The host records those refusals after confirmed publication (ADR-0127). - 11.3d-7k: region sessions can now enable the reliable v5 life-request callbacks and v7 cellular action ledger together. Admission remains per negotiated connection; unsupported v5/v6/v7 modes still fail closed. QUIC diff --git a/include/evo/server/cellular_region_host.hpp b/include/evo/server/cellular_region_host.hpp index 2e36519..9d28536 100644 --- a/include/evo/server/cellular_region_host.hpp +++ b/include/evo/server/cellular_region_host.hpp @@ -110,6 +110,10 @@ class CellularRegionHost { [[nodiscard]] network::PrimitiveLifeOutcome query_primitive_life(const persistence::Uuid& account, std::uint64_t generation, std::uint64_t request); + // Call only after the scheduler's batch is confirmed published. Persists expected + // birth refusals without blocking the region; uncertain replies stay out of the birth + // queue and reconcile on the account's next exact request/query (including takeover). + void refuse_births(std::span refusals); [[nodiscard]] std::span queued_births() const noexcept { return queued_births_; } @@ -159,6 +163,7 @@ class CellularRegionHost { std::unique_ptr pending_; std::vector finalized_actions_; std::vector queued_births_; + std::vector pending_birth_refusals_; std::vector queued_mutations_; // A reservation may exist that the queue does not show; reload before publishing. bool mutations_uncertain_{}; diff --git a/include/evo/server/cellular_session_batch.hpp b/include/evo/server/cellular_session_batch.hpp index 21b899c..a7b9ad8 100644 --- a/include/evo/server/cellular_session_batch.hpp +++ b/include/evo/server/cellular_session_batch.hpp @@ -58,6 +58,17 @@ class CellularSessionBatchBuilder { std::span actions, std::span births = {}, std::span mutations = {}); + // Scheduler path: expected placement/funding/existing-life refusals are reported + // separately, so they cannot prevent other births or the ordinary tick. Unexpected + // failures retain append's all-or-nothing behavior. Persist reports only after publish. + [[nodiscard]] std::expected append_with_birth_refusals( + std::uint64_t tick, std::span baseline, + std::span actions, + std::span births = {}, + std::span mutations = {}); + [[nodiscard]] std::span refused_births() const noexcept { + return refused_births_; + } [[nodiscard]] const CellularBatch& batch() const noexcept { return batch_; } @@ -72,11 +83,18 @@ class CellularSessionBatchBuilder { } private: + [[nodiscard]] std::expected + append_impl(std::uint64_t tick, std::span baseline, + std::span actions, + std::span births, + std::span mutations, + bool allow_refusals); explicit CellularSessionBatchBuilder(std::unique_ptr working) : working_{std::move(working)} {} std::unique_ptr working_; CellularBatch batch_; std::vector actions_; std::vector mutation_actions_; + std::vector refused_births_; }; } // namespace evo::server diff --git a/include/evo/server/lifecycle/cellular_batch.hpp b/include/evo/server/lifecycle/cellular_batch.hpp index a41feb8..50d1b5f 100644 --- a/include/evo/server/lifecycle/cellular_batch.hpp +++ b/include/evo/server/lifecycle/cellular_batch.hpp @@ -38,6 +38,12 @@ struct CellularTickIntents { std::vector mutations; friend bool operator==(const CellularTickIntents&, const CellularTickIntents&) = default; }; +// Transient scheduler report, not part of the replay trace. A refused birth changes +// no biology; its final request result is recorded in the existing reservation store. +struct CellularBirthRefusal { + CellularTickIntents::Birth birth; + CellularLivesError reason{}; +}; struct CellularBatch { CellularBatchHeader header{}; std::vector ticks; diff --git a/src/server/cellular_region_host.cpp b/src/server/cellular_region_host.cpp index 008899f..6698b57 100644 --- a/src/server/cellular_region_host.cpp +++ b/src/server/cellular_region_host.cpp @@ -612,6 +612,10 @@ CellularRegionHost::publish(const CellularBatch& batch, } void CellularRegionHost::queue_birth(const CellularTickIntents::Birth& birth) { + if (std::ranges::any_of(pending_birth_refusals_, [&](const auto& refusal) { + return refusal.birth.account == birth.account && refusal.birth.request == birth.request; + })) + return; const auto found = std::ranges::find_if(queued_births_, [&](const auto& queued) { return queued.account == birth.account && queued.request == birth.request; }); @@ -627,6 +631,27 @@ void CellularRegionHost::finalize_births(std::span refusals) { + for (const auto& refusal : refusals) { + if (refusal.reason != CellularLivesError::insufficient_funding && + refusal.reason != CellularLivesError::no_placement && + refusal.reason != CellularLivesError::life_exists) + continue; + if (std::ranges::find(queued_births_, refusal.birth) == queued_births_.end()) + continue; + // Remove before the database call: an uncertain refusal must never race a spawn. + std::erase(queued_births_, refusal.birth); + std::erase_if(pending_birth_refusals_, [&](const auto& previous) { + return previous.birth.account == refusal.birth.account; + }); + if (pending_birth_refusals_.size() == biology::max_cellular_tick_lives) + pending_birth_refusals_.erase(pending_birth_refusals_.begin()); + pending_birth_refusals_.push_back(refusal); + static_cast(query_birth(refusal.birth.account, refusal.birth.generation, + refusal.birth.request, false)); + } +} + network::PrimitiveLifeOutcome CellularRegionHost::query_birth(const persistence::Uuid& account, std::uint64_t generation, std::uint64_t request, bool enqueue) { @@ -661,6 +686,30 @@ network::PrimitiveLifeOutcome CellularRegionHost::query_birth(const persistence: if (outcome.reservation.region != config_.key.region) return unknown(); const auto result = life_result(outcome.reservation.refusal); + const auto refused = std::ranges::find_if(pending_birth_refusals_, [&](const auto& entry) { + return entry.birth.account == account && entry.birth.request == request; + }); + if (refused != pending_birth_refusals_.end()) { + if (result != PrimitiveLifeResult::pending) { + pending_birth_refusals_.erase(refused); + } else { + const auto reason = refused->reason == CellularLivesError::insufficient_funding + ? persistence::LifeRefusal::insufficient_funding + : refused->reason == CellularLivesError::no_placement + ? persistence::LifeRefusal::no_placement + : persistence::LifeRefusal::existing_life; + const auto recorded = + persistence::reject_primitive_life(*db_, config_.key, *grant, account, generation, + request, reason, config_.lease.commit_timeout); + if (!recorded) { + db_.reset(); + ++status_.store_failures; + return unknown(); + } + pending_birth_refusals_.erase(refused); + return {request, life_result(*recorded), outcome.reservation.identity, 0}; + } + } if (result == PrimitiveLifeResult::pending && enqueue) queue_birth({account, request, generation, outcome.reservation.identity}); return {request, result, outcome.reservation.identity, 0}; diff --git a/src/server/session/cellular_session_batch.cpp b/src/server/session/cellular_session_batch.cpp index 6b5a36d..59e0457 100644 --- a/src/server/session/cellular_session_batch.cpp +++ b/src/server/session/cellular_session_batch.cpp @@ -170,6 +170,21 @@ std::expected CellularSessionBatchBuilder::appe std::span actions, std::span births, std::span mutations) { + return append_impl(tick, baseline, actions, births, mutations, false); +} +std::expected +CellularSessionBatchBuilder::append_with_birth_refusals( + std::uint64_t tick, std::span baseline, + std::span actions, + std::span births, + std::span mutations) { + return append_impl(tick, baseline, actions, births, mutations, true); +} +std::expected CellularSessionBatchBuilder::append_impl( + std::uint64_t tick, std::span baseline, + std::span actions, + std::span births, + std::span mutations, bool allow_refusals) { if (batch_.ticks.size() >= max_cellular_batch_ticks) return std::unexpected{CellularSessionBatchError::batch_full}; if (actions_.size() + actions.size() > max_cellular_action_records) @@ -204,6 +219,11 @@ std::expected CellularSessionBatchBuilder::appe return std::unexpected{CellularSessionBatchError::invalid_birth}; if (i > 0 && prepared->intents.births[i - 1].account == birth.account) return std::unexpected{CellularSessionBatchError::duplicate_birth}; + if (std::ranges::any_of(refused_births_, [&](const auto& previous) { + return previous.birth.account == birth.account || + previous.birth.identity == birth.identity; + })) + return std::unexpected{CellularSessionBatchError::duplicate_birth}; for (const auto& previous_tick : batch_.ticks) if (std::ranges::any_of(previous_tick.births, [&](const auto& previous) { return previous.account == birth.account || previous.identity == birth.identity; @@ -217,15 +237,26 @@ std::expected CellularSessionBatchBuilder::appe !(*next)->advance_tick_with_mutations(prepared->intents.lives, prepared->intents.mutations)) return std::unexpected{CellularSessionBatchError::biology}; + std::vector accepted_births; + std::vector refused_births; for (const auto& birth : prepared->intents.births) { const LifeRequest request{birth.account, birth.request}; const LifeAllocation allocation{ birth.identity, birth.identity, birth.identity, birth.identity, {tick}}; auto created = (*next)->birth_candidate(request, allocation); + if (!created && allow_refusals && + (created.error() == CellularLivesError::insufficient_funding || + created.error() == CellularLivesError::no_placement || + created.error() == CellularLivesError::life_exists)) { + refused_births.push_back({birth, created.error()}); + continue; + } if (!created) return std::unexpected{CellularSessionBatchError::invalid_birth}; *next = std::move(*created); + accepted_births.push_back(birth); } + prepared->intents.births = std::move(accepted_births); auto next_batch = batch_; next_batch.ticks.push_back(std::move(prepared->intents)); @@ -245,6 +276,7 @@ std::expected CellularSessionBatchBuilder::appe batch_ = std::move(next_batch); actions_.insert(actions_.end(), prepared->actions.begin(), prepared->actions.end()); mutation_actions_ = next_mutation_actions; + refused_births_.insert(refused_births_.end(), refused_births.begin(), refused_births.end()); return {}; } } // namespace evo::server diff --git a/tests/cellular_publication_tests.cpp b/tests/cellular_publication_tests.cpp index b7baa63..8534144 100644 --- a/tests/cellular_publication_tests.cpp +++ b/tests/cellular_publication_tests.cpp @@ -875,6 +875,27 @@ void cellular_death_is_final_and_account_restarts() { // While the second life lives, a third request is an existing-life refusal. CHECK(host->create_primitive_life(account, control->generation, 13).result == evo::network::PrimitiveLifeResult::existing_life); + // A fresh account still cannot create energy from an exhausted nursery. The + // expected refusal must not stall the living cell's tick or stay pending forever. + const auto newcomer = filled<16>(0x95); + const auto newcomer_control = claim_account_control( + *runtime, key, checked_value(host->authority()), newcomer, 1, 2, 60'000ms, 5s); + CHECK(newcomer_control); + CHECK(host->create_primitive_life(newcomer, newcomer_control->generation, 21).result == + evo::network::PrimitiveLifeResult::pending); + const auto before_tick = host->state()->tick(); + const std::array refusals{CellularBirthRefusal{host->queued_births().front(), + CellularLivesError::insufficient_funding}}; + CellularBatch continued; + continued.header = header(1); + continued.ticks.push_back({{{second, {}}}, {}, {}}); + CHECK(host->publish(continued)); + host->refuse_births(refusals); + CHECK(host->state()->tick() == before_tick + 1 && host->queued_births().empty()); + CHECK(host->query_primitive_life(newcomer, newcomer_control->generation, 21).result == + evo::network::PrimitiveLifeResult::insufficient_funding); + CHECK(host->create_primitive_life(newcomer, newcomer_control->generation, 21).result == + evo::network::PrimitiveLifeResult::insufficient_funding); const auto snapshot = host->state()->snapshot(); host->drain(); host.reset(); diff --git a/tests/cellular_session_batch_tests.cpp b/tests/cellular_session_batch_tests.cpp index ced6c7b..5a0798c 100644 --- a/tests/cellular_session_batch_tests.cpp +++ b/tests/cellular_session_batch_tests.cpp @@ -310,12 +310,66 @@ void builder_batches_reserved_birth_after_empty_tick() { CellularSessionBatchError::duplicate_birth); CHECK(builder->candidate().snapshot() == snapshot && builder->batch().ticks.size() == 1); } +void unavailable_birth_does_not_freeze_the_tick() { + for (const bool funded : {false, true}) { + auto primitive = + PrimitiveLives::create({94, 1, 1, 17, founder_price(funded ? 2 : 1), {{0, 0}}}); + CHECK(primitive); + LifeRequest request{}; + request.account.back() = 1; + request.action = 1; + CHECK((*primitive)->spawn(request, {101, 101, 101, 101, {1}})); + auto habitat = biology::CellularHabitat::create({94, 1, 1, 1000, 1000, {}}); + CHECK(habitat); + auto state = + CellularLives::create(**primitive, std::move(*habitat), {{1000, 1000}, 1, 293150}); + CHECK(state); + persistence::RegionHead head{}; + head.frame = 1; + head.end_tick = 1; + head.commit.fill(1); + head.digest.fill(2); + CellularTickIntents::Birth birth{}; + birth.account.back() = 2; + birth.request = 1; + birth.generation = 1; + birth.identity = 102; + const std::array births{birth}; + // Movement vacates the nursery in the underfunded case, isolating each refusal. + const std::array baseline{ + CellularLifeIntent{101, {{static_cast(funded ? 0 : 1000), 0}, {}}}}; + // A founder moves only a few um per tick: first move it fully away from the site. + if (!funded) { + for (int i = 0; i < 100; ++i) + CHECK((*state)->advance_tick(baseline)); + head.end_tick = (*state)->tick(); + } + auto strict = CellularSessionBatchBuilder::create(**state, head); + CHECK(strict); + CHECK(strict->append(head.end_tick + 1, baseline, {}, births).error() == + CellularSessionBatchError::invalid_birth); + CHECK(strict->candidate().tick() == head.end_tick); + auto builder = CellularSessionBatchBuilder::create(**state, head); + CHECK(builder && + builder->append_with_birth_refusals(head.end_tick + 1, baseline, {}, births)); + CHECK(builder->refused_births().size() == 1 && builder->refused_births()[0].birth == birth); + CHECK( + builder->refused_births()[0].reason == + (funded ? CellularLivesError::no_placement : CellularLivesError::insufficient_funding)); + CHECK(builder->candidate().tick() == head.end_tick + 1 && + builder->candidate().lives().size() == 1); + CHECK(builder->batch().ticks.back().births.empty()); + const auto replay = replay_cellular_batch(**state, builder->batch()); + CHECK(replay && (*replay)->snapshot() == builder->candidate().snapshot()); + } +} } // namespace int main() try { actions_bind_to_owned_life_and_preserve_other_inputs(); durable_mutation_reservations_bind_to_the_exact_offer(); builder_batches_reserved_birth_after_empty_tick(); + unavailable_birth_does_not_freeze_the_tick(); std::puts("cellular session batch: ok"); } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); diff --git a/tests/client_panels.cpp b/tests/client_panels.cpp index 79cc846..c82a1b3 100644 --- a/tests/client_panels.cpp +++ b/tests/client_panels.cpp @@ -378,7 +378,8 @@ void cellular_panels(const std::filesystem::path& review) { camera->world_to_screen({static_cast(x), static_cast(y)}); const auto high = camera->world_to_screen({x + 1.0, y + 1.0}); CHECK(low && high); - patch_box(boxes, *low, *high, (x + y) % 4 != 0, x == 2 && y == 3, width, height); + patch_box(boxes, *low, *high, (x + y) % 4 != 0, (x + y) % 3 != 0, x == 2 && y == 3, + width, height); } OrganismCell organism; organism.id = 901; @@ -416,7 +417,10 @@ void cellular_panels(const std::filesystem::path& review) { diagnostics.intake = network::CellularIntakeResult::acquired; diagnostics.engulf = network::CellularEngulfResult::membrane_too_thick; network::CellularPerception perception{ - 102, 901, {{1000, 2000, 50000, {100, 20, 10, 40}}}, diagnostics}; + 102, + 901, + {{1000, 2000, 50000, {100, 20, 10, 40}}, {2000, 3000, 0, {90, 20, 8, 30}}}, + diagnostics}; play.observe(perception); play.observe_offer(network::CellularMutationOffer{ 102, @@ -450,16 +454,53 @@ void cellular_panels(const std::filesystem::path& review) { }; for (int i = 0; i < 3; ++i) draw(); - const auto* journal = ImGui::FindWindowByName("Cellular field journal"); + auto* journal = ImGui::FindWindowByName("Cellular field journal"); CHECK(journal && journal->Active && journal->ScrollMax.x == 0); CHECK(journal->Pos.x >= 0 && journal->Pos.y >= 0 && journal->Pos.x + journal->Size.x <= static_cast(width) && journal->Pos.y + journal->Size.y <= static_cast(height)); if (!review.empty()) { std::filesystem::create_directories(review); + auto later = perception; + ++later.tick; + later.diagnostics->reserve_energy_pj -= 50; + play.observe(later); + view.cellular_feed_target = {{2000, 3000}}; CHECK(app->request_screenshot( (review / ("cellular-" + std::to_string(width) + ".bmp")).string())); draw(); + auto* tabs = GImGui->TabBars.GetByKey(journal->GetID("cell-tabs")); + CHECK(tabs); + const auto choose_tab = [&](const char* name) { + for (auto& tab : tabs->Tabs) + if (std::string_view{ImGui::TabBarGetTabName(tabs, &tab)} == name) { + const float x = tabs->BarRect.Min.x + tab.Offset + tab.Width / 2; + const float y = tabs->BarRect.GetCenter().y; + mouse(id, SDL_EVENT_MOUSE_MOTION, x, y); + draw(); + mouse(id, SDL_EVENT_MOUSE_BUTTON_DOWN, x, y); + draw(); + mouse(id, SDL_EVENT_MOUSE_BUTTON_UP, x, y); + for (int i = 0; i < 3; ++i) + draw(); + CHECK(tabs->SelectedTabId == tab.ID); + return; + } + CHECK(false); + }; + choose_tab("Food"); + CHECK(journal->ScrollMax.x == 0); + CHECK(app->request_screenshot( + (review / ("cellular-food-" + std::to_string(width) + ".bmp")).string())); + draw(); + choose_tab("Cell"); + play.disconnected(); + play.connected(); + ++perception.tick; + play.observe(perception); + view.cellular_feed_target.reset(); + for (int i = 0; i < 3; ++i) + draw(); } if (width != 960) continue; diff --git a/tests/client_remote_session.cpp b/tests/client_remote_session.cpp index 510d8f9..1f1640c 100644 --- a/tests/client_remote_session.cpp +++ b/tests/client_remote_session.cpp @@ -502,6 +502,38 @@ void crossing_regions(const Files& f) { CHECK(a.phase() == LaunchPhase::failed && world.probes.at(dana).owner == 2); CHECK(db1.claims == region1_claims && db2.claims == region2_claims + 1); } +void cellular_birth_without_view(const Files& files) { + test::WorldDb world; + test::RegionDb control{world, region}; + const auto owner = account(0xD1); + std::vector requests; + auto answer = PrimitiveLifeResult::pending; + Region r{files, [&](server::RegionSessionsConfig& config) { + config.ledger = &control; + config.accept_cellular_actions = true; + config.create_primitive_life = [&](const AccountId& a, std::uint64_t generation, + std::uint64_t id) { + CHECK(a == owner && generation != 0); + requests.push_back(id); + return PrimitiveLifeOutcome{id, answer, 901, 0}; + }; + config.query_primitive_life = config.create_primitive_life; + }}; + Client c; + CHECK(c.host.connect(RemoteSession::open(r.material({r.grant(owner, 1)}), true))); + CHECK(c.until(r, [&] { return requests.size() >= 2; })); + auto& remote = *c.host.session(); + CHECK(requests[0] == requests[1] && !remote.cellular_play().can_restart() && + !remote.cellular_perception()); + answer = PrimitiveLifeResult::insufficient_funding; + CHECK(c.until(r, [&] { return remote.cellular_play().can_restart(); })); + CHECK(!remote.cellular_play().fresh() && + remote.status().cellular_action.find("nursery lacks resources") != std::string::npos); + CHECK(remote.restart_cellular() && !remote.restart_cellular()); + answer = PrimitiveLifeResult::no_placement; + CHECK(c.until(r, [&] { return remote.cellular_play().can_restart(); })); + CHECK(requests.back() != requests.front() && !remote.cellular_perception()); +} // Real RemoteSession over QUIC; the fixture records authority answers without simulating biology. void cellular_v10(const Files& files) { using namespace evo::client_app; @@ -680,6 +712,7 @@ int main() try { } crossing_regions(files); cellular_v10(files); + cellular_birth_without_view(files); std::filesystem::remove_all(files.dir); std::puts("client remote session tests passed"); return 0; diff --git a/tests/client_ui_model.cpp b/tests/client_ui_model.cpp index 066f86e..ab4e39d 100644 --- a/tests/client_ui_model.cpp +++ b/tests/client_ui_model.cpp @@ -107,6 +107,12 @@ void cellular_assistance() { CHECK(!steer_cellular(controls, {}, &view, &population, {}).patch); view.patches[0].matter_fg[2] = 1; CHECK(steer_cellular(controls, {}, &view, &population, {}).patch); + view.patches.push_back({0, 2000, 100, {}}); + CHECK(steer_cellular(controls, {}, &view, &population, {}).patch == + std::pair{0, 2000}); + view.patches.back().energy_pj = 0; + CHECK(steer_cellular(controls, {}, &view, &population, {}).patch == + std::pair{1000, 2000}); view.life_identity = 0; CHECK(!steer_cellular(controls, {}, &view, &population, {}).patch); network::CellularOfferedCandidate candidate; @@ -122,7 +128,7 @@ void cellular_assistance() { reserve.reserve_energy_pj = 9; CHECK(!can_fund(candidate, reserve)); std::vector scene; - patch_box(scene, {-10, 100}, {100, -10}, true, true, 80, 80); + patch_box(scene, {0, 80}, {80, 0}, true, true, true, 80, 80); CHECK(scene.size() == patch_rectangles); for (const auto& r : scene) CHECK(r.x >= 0 && r.y >= 0 && r.x + r.width <= 80 && r.y + r.height <= 80); @@ -465,6 +471,44 @@ void cellular_play() { exhausted.initialize(std::numeric_limits::max()); CHECK(exhausted.allocate_id() == 0 && exhausted.allocate_id() == 0); } +void cellular_energy_and_birth_wait() { + using namespace evo::client_app; + using namespace evo::network; + CellularPlay play; + play.initialize(1); + play.connected(); + CHECK(!play.can_restart()); + play.birth({1, PrimitiveLifeResult::pending, 7, 0}); + CHECK(!play.can_restart()); + play.birth({1, PrimitiveLifeResult::insufficient_funding, 7, 0}); + CHECK(!play.fresh() && play.can_restart()); // Refusal arrives without any world view. + CHECK(play.restart() && play.birth_request() == 2 && !play.restart()); + play.birth({1, PrimitiveLifeResult::no_placement, 7, 0}); + CHECK(play.birth_pending()); // Delayed answer to an older request is ignored. + play.birth({2, PrimitiveLifeResult::existing_life, 9, 0}); + CHECK(!play.can_restart()); // Wait for that existing life instead of offering another birth. + CellularLifeDiagnostics d; + d.reserve_energy_pj = 200; + play.observe({10, 9, {}, d}); + CHECK(!play.energy_change()); + play.observe({11, 0, {}, {}}); // The bridge may clear a view before sending its replacement. + d.reserve_energy_pj = 150; + play.observe({11, 9, {}, d}); + CHECK(required(play.energy_change()).falling && required(play.energy_change()).amount == 50); + play.observe({11, 9, {}, d}); + CHECK(required(play.energy_change()).amount == 50); // Duplicate views retain the change. + d.reserve_energy_pj = 175; + play.observe({15, 9, {}, d}); + CHECK(!required(play.energy_change()).falling && required(play.energy_change()).amount == 25 && + required(play.energy_change()).from_tick == 11); + play.disconnected(); + CHECK(!play.energy_change()); + play.connected(); + play.observe({16, 9, {}, d}); + CHECK(!play.energy_change()); + play.observe({17, 10, {}, d}); + CHECK(!play.energy_change()); // A different life starts a new baseline. +} } // namespace int main() try { @@ -474,6 +518,7 @@ int main() try { outcome_log(); session_host(); cellular_play(); + cellular_energy_and_birth_wait(); cellular_assistance(); std::puts("client UI model tests passed"); return 0;