diff --git a/CMakeLists.txt b/CMakeLists.txt index b3fde45..8beba04 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -89,7 +89,8 @@ add_library(evo_lifecycle STATIC src/server/lifecycle/primitive_lives.cpp src/server/lifecycle/primitive_batch.cpp src/server/lifecycle/cellular_lives.cpp src/server/lifecycle/cellular_batch.cpp src/server/lifecycle/wildlife_controller.cpp src/server/lifecycle/cellular_play_summary.cpp src/server/lifecycle/cellular_population.cpp - src/server/lifecycle/cellular_population_codec.cpp src/server/lifecycle/cellular_population_policy.cpp) + src/server/lifecycle/cellular_population_codec.cpp src/server/lifecycle/cellular_population_policy.cpp + src/server/lifecycle/cellular_schedule.cpp) add_library(evo::lifecycle ALIAS evo_lifecycle) target_link_libraries(evo_lifecycle PUBLIC evo::biology) evo_owned_target(evo_lifecycle) @@ -672,6 +673,10 @@ if(BUILD_TESTING) "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/population-restart" -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake") set_tests_properties(cellular-population-process-restart PROPERTIES TIMEOUT 180) + add_executable(evo-cellular-schedule-tests tests/cellular_schedule_tests.cpp) + target_link_libraries(evo-cellular-schedule-tests PRIVATE evo::lifecycle) + evo_owned_target(evo-cellular-schedule-tests) + add_test(NAME cellular-unattended-schedule COMMAND evo-cellular-schedule-tests) endif() add_executable(evo-chunk-layout experiments/world/chunk_layout.cpp) diff --git a/apps/evo-server/main.cpp b/apps/evo-server/main.cpp index ecd295e..30c98bb 100644 --- a/apps/evo-server/main.cpp +++ b/apps/evo-server/main.cpp @@ -55,6 +55,7 @@ #include "evo/biology/founder.hpp" #include "evo/processes/development_opening.hpp" #include "evo/server/cellular_session_batch.hpp" +#include "evo/server/lifecycle/cellular_schedule.hpp" #include "evo/server/lifecycle/primitive_lives.hpp" #include "evo/server/lifecycle/wildlife_controller.hpp" #include "evo/server/ops_http.hpp" @@ -927,7 +928,7 @@ int serve_cellular(Options& o) { } bool ready = false; std::optional phase; - std::optional next_tick; + server::CellularTickSchedule schedule; std::vector awaiting_outcomes; // A tick that cannot be built is retried every 50 ms; name each distinct cause once. std::optional> stalled; @@ -1022,8 +1023,14 @@ int serve_cellular(Options& o) { : server::OpsResponse{ 503, std::string("not ready: ") + server::phase_name(current.phase) + "\n"}; - if (path == "/metrics") - return {200, server::render_metrics(current, {})}; + if (path == "/metrics") { + auto paced = current; + paced.tick_debt = schedule.status().debt; + paced.max_tick_debt = schedule.status().max_debt; + server::OpsCounters counters; + counters.checkpoint_age_ms = schedule.status().head_age_us / 1000; + return {200, server::render_metrics(paced, counters)}; + } return {404, "not found\n"}; }; ops->serve(handler); @@ -1033,15 +1040,11 @@ int serve_cellular(Options& o) { const auto* state = host.state(); bool player_present = false; - // ADR-0128: a lingering life keeps the region ticking until its linger completes. - bool lingering_present = false; if (status.ready && state) { for (const auto& life : state->lives()) { network::AccountId account; account.bytes = life.account; player_present = player_present || bridge->sessions().holder(account); - lingering_present = - lingering_present || life.presence == server::CellularPresence::lingering; } } // A queued birth publishes only while its account holds a session here: the @@ -1057,11 +1060,23 @@ int serve_cellular(Options& o) { held_births.push_back(birth); } const bool birth_waiting = !held_births.empty(); - if (status.ready && state && (player_present || birth_waiting || lingering_present)) { - const auto now = std::chrono::steady_clock::now(); - if (!next_tick) - next_tick = now + std::chrono::milliseconds{50}; - if (now >= *next_tick && state->tick() != UINT64_MAX) { + const bool needed = state && (player_present || birth_waiting || + server::cellular_unattended_tick_needed(*state)); + const auto monotonic_us = [] { + return static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count()); + }; + const auto paced = schedule.observe(monotonic_us(), status.epoch, + state ? state->tick() : status.committed_tick, needed, + status.ready && state); + if (!paced) { + std::puts("error cellular-schedule"); + return finish(4); + } + if (status.ready && state && needed) { + if (paced->due && state->tick() != UINT64_MAX) { const auto tick = state->tick() + 1; std::vector baseline; baseline.reserve(state->lives().size()); @@ -1150,12 +1165,11 @@ int serve_cellular(Options& o) { deliver_finalized(); } } - *next_tick = std::chrono::steady_clock::now() + - std::chrono::microseconds{static_cast( - biology::cellular_motion_tick_microseconds)}; + // Only a confirmed head consumes pacing debt. Retry failures with bounded + // frequency while retaining debt; never reset a deadline to now + quantum. + if (!host.state() || host.state()->tick() < tick) + schedule.defer(monotonic_us()); } - } else { - next_tick.reset(); // A disconnected life does not accumulate offline ticks. } if (const auto* committed_state = host.state(); committed_state) bridge->replicate(*committed_state); diff --git a/docs/STATUS.md b/docs/STATUS.md index 8d44c7b..93b36db 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,22 @@ # Project status and next steps +## M12.4a current-worker unattended scheduling - 2026-10-17 + +The cellular worker now keeps ticking for funded wildlife after players suspend, +and active offline cells can start their freeze/linger transition. Running +publication latency no longer discards tick debt; confirmed heads consume it, +with bounded retries, fixed 50 ms steps and debt/checkpoint-age metrics. Legacy +profiles without offline freeze retain their prior session-driven behavior. +Release tests pass 75/75; clang-format/tidy 19, ASan/UBSan and the full private +PostgreSQL/process/backup/DR/upgrade suite pass. ADR-0141 records scope. + +**M12 is not complete.** The [remaining-gate audit](engineering/M12_REMAINING_GATES.md) +specifies the population publication profile/adapter, biological escrow, +environment coupling, global history/extinction reconciliation and actual +multi-day/product evidence still required. M11.9 stays closed for now; this is +not another approval hold. Current code does not enable the live cohort selector, +deploy changes or authorize M13/World0 promotion. + ## M12.3a exact conversion recovery - 2026-10-17 Population envelope 1 retains biology, cohort membership, policy and conversion diff --git a/docs/adr/0141-cellular-unattended-demand-and-pacing.md b/docs/adr/0141-cellular-unattended-demand-and-pacing.md new file mode 100644 index 0000000..f089b83 --- /dev/null +++ b/docs/adr/0141-cellular-unattended-demand-and-pacing.md @@ -0,0 +1,55 @@ +# ADR-0141: Cellular unattended tick demand and confirmed-head pacing + +## Status + +Accepted for the existing cellular worker, 2026-10-17. No biological rule, +checkpoint format, schema, deployment or World0 change. This is M12.4a, not +completion of population publication, durable interval admission or migration. + +## Context + +The worker only steps while it finds a player, a held birth or lingering cell. +Consequently wildlife stops when the last player leaves and linger completes. +An active offline cell restored without a session also never starts its freeze +transition. Resetting the deadline to completion time plus 50 ms further discards +running scheduling debt when work or publication is slow. + +## Decision + +For profiles supporting offline freeze (rules 5+), demand includes every unowned +descendant and each active/lingering controlled life. Suspended controlled stock +alone supplies no demand. A returning session or held birth still wakes the +worker. Historical profiles lacking freeze retain their previous session-driven +behavior; do not newly advance disconnected biology under those profiles. + +Keep the existing shared wildlife controller, frozen controlled baseline, batch +builder and fenced PostgreSQL publication path. No new biological intent or +background balance is invented. There is at most one tick attempt per worker +loop, at the existing 50 ms quantum; batching or a larger timestep is not implied. + +Use a portable pacing object that reads caller-supplied monotonic microseconds, +current authority epoch and confirmed head. It counts due ticks from a fixed +running origin. Only a confirmed head advance consumes debt. Refused work retries +at most once per quantum while preserving debt. Do not cap away accumulated debt, +delete lives to catch up or advance from an unconfirmed candidate. Reject clock +regression, same-epoch head regression and an unfenced ready origin. Tick/count +arithmetic must remain bounded at u64 limits. + +Authority unavailability, epoch replacement, process restart and no tick demand +pause unadmitted wall time under ADR-0133. Existing uncertain publications still +resolve through the host's exact pending record before it becomes ready. This +pacer is not a durable interval queue or cross-worker fence. The existing host +continues to own that authority; no outage catch-up policy is introduced. + +Expose debt and maximum debt through existing fixed-cardinality region metrics. +Checkpoint age measures time since the last confirmed head change/recovery; +readiness still independently states whether output may originate. + +## Remaining M12.4 work + +Population envelope publication and durable interval admission/recovery require +their own profile and store work. Biological migration needs exact genome/history +closure, source escrow and idempotent destination installation under both region +fences; the existing non-biological probe transfer is not that implementation. +No live biological migration, partition qualification or days-long ecology proof +follows from these scheduler checks. diff --git a/docs/adr/README.md b/docs/adr/README.md index 492e8fd..dd9753e 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -159,3 +159,5 @@ design. No unadopted candidate is a link dependency of the proof. - [ADR-0139: Exact cellular local cohorts](0139-exact-cellular-local-cohorts.md) - [ADR-0140: Exact population checkpoint and policy](0140-exact-population-checkpoint-and-policy.md) + +- [ADR-0141: Cellular unattended demand and pacing](0141-cellular-unattended-demand-and-pacing.md) diff --git a/docs/engineering/M12_DELIVERY_PLAN.md b/docs/engineering/M12_DELIVERY_PLAN.md index 4be0042..198858d 100644 --- a/docs/engineering/M12_DELIVERY_PLAN.md +++ b/docs/engineering/M12_DELIVERY_PLAN.md @@ -1,4 +1,4 @@ -# M12.1-12.5 delivery and prerequisite conflicts +# M12 delivery and prerequisite conflicts Requested scope: ecological identity, population qualification, durable automatic tier transitions, unattended scheduling/migration and environmental coupling. @@ -11,8 +11,17 @@ Commit and push each validated scoped segment separately. | 12.1 | Engineering evidence policy and explicit deferrals documented | ADR-0133, identity/time contract and worked histories; no new game rules or runtime versions. | | 12.2 | Exact local model selected and paired qualification implemented (12.2d); production cost gate open | ADR-0139, exact canonical equality across 196,608 paired ticks per platform. Regional approximation disabled; no compression claim. Deployment-host capacity and fuller interaction coverage remain open. | | 12.3 | Portable exact conversion closure, automatic policy and process recovery implemented | ADR-0140, population envelope 1. Dedicated PostgreSQL profile/trace/publication adapter and fault injection remain required before enabling the live selector. | -| 12.4 | Blocked on 12.2-12.3 | Existing cellular worker pauses without sessions/lingering players; bounded unattended recovery and biological migration escrow remain unimplemented. | +| 12.4 | Current-worker unattended demand and confirmed-head pacing implemented (12.4a) | ADR-0141. Population durable intervals and biological migration escrow remain unimplemented. | | 12.5 | Blocked on 12.2-12.4 | Finite M6 process fixtures do not qualify coupled persistent cellular/cohort atmosphere/water budgets. | +| 12.6 | Existing local archive retained; integrated population history open | World-level durable event/query/client path remains required. | +| 12.7 | Evidence policy defined; reconciler open | Complete durable world watermark and every viable/in-flight store remain required. | +| 12.8 | Not qualified | Actual multi-day integrated ecology/restart/clone evidence remains required. | +| 12.9 | Not accepted | Returning-player product evidence and expansion review remain required; World0 stays separately blocked. | + +The [remaining-gate audit](M12_REMAINING_GATES.md) identifies the exact publication +boundary and concrete integration work. This is not an approval hold or a request +to reopen M11.9. Do not mark portable recovery, current-worker pacing or a short +research run as completion of the dependent durable ecology/product gates. The maintainer explicitly closes M11.9 for now on 2026-10-17 and authorizes M12 continuation; see the [closure decision](M11_9_DELIVERY_PLAN.md). The recorded diff --git a/docs/engineering/M12_REMAINING_GATES.md b/docs/engineering/M12_REMAINING_GATES.md new file mode 100644 index 0000000..a3c8bae --- /dev/null +++ b/docs/engineering/M12_REMAINING_GATES.md @@ -0,0 +1,55 @@ +# M12 integration and evidence still required + +This is the current completion audit following the maintainer's request to try +all of M12. M11.9 remains closed for now. M12.2 decisions are delegated and recorded +in ADR-0139; no additional product approval is inferred as a coding prerequisite. +Completed scoped commits do not mean their entire roadmap gates have passed. + +## Persistence boundary before expansion + +The new exact population envelope cannot be labeled as the existing profile-4 +CellularLives payload. The live publisher/recovery path, immutable manifest, +database validators and trace currently agree on that raw cellular format. A +population checkpoint containing ownership tags and policy needs a dedicated +profile and versioned transition/publication adapter. Reinterpreting profile 4 +would violate REGION_DURABILITY and break retained recovery evidence. + +Resolution: add an opt-in population profile and an explicit no-tick migration +from the accepted rules-8 cellular state, retaining identities, archive, funding +and balances. Publish its complete immutable payload, bound trace and permanent +events under the current region fence. Replay must retain recorded intentions +and exact membership samples, rather than rerunning a decision after an uncertain +commit. Verify lost replies and pre-upload/pre-transaction/post-commit/post-ACK +process death against a private PostgreSQL fixture. Keep production disabled until +these and target-host budgets pass. A portable codec is not a substitute for this +adapter. This is remaining M12.3 implementation, not a user-permission hold. + +## Dependent ecological integration + +| Gate | Existing useful basis | Work/evidence still required | +|---|---|---| +| 12.2 | Exact cellular model and paired matrix; local samples through 256 lives | Deployment-host tail costs including publication; larger wildlife cohorts, predation/twins and contention coverage; useful compression remains unimplemented. | +| 12.3 | Complete population codec, exact conversion candidates, automatic policy and fresh-process continuation | Dedicated durable profile/trace/store/host integration and fault-injected atomic publication described above. | +| 12.4 | Current worker advances unattended wildlife and preserves running scheduling debt | Durable ecological interval admission/backlog recovery; exact biological source/destination escrow, partition/duplicate settlement and stock-in-transit audits. | +| 12.5 | Finite cellular contact feeding/decay and separate M6 producer/consumer resource owner | One jointly owned cellular/environment budget, explicit effective depth and source entitlements, versioned water/atmosphere species mapping and producer coefficients, plus closed/open and nutrient-exhaustion comparisons. | +| 12.6 | Retained genome/organism archive with ancestry and common-ancestor queries | Append-only population census/history events in the same durable commit, bounded world history queries/indexing and client presentation; no account power or invented precise statistical ancestry. | +| 12.7 | ADR-0133's viability/unknown semantics | Durable region-set/watermark reconciliation covering every owned representation, suspended/viable stock and migration escrow. Missing/stale regions must prevent terminal extinction. | +| 12.8 | Deterministic seed/regime drivers and separate-process exact continuation | Reproducible integrated worlds running for actual days, real restarts/clone comparisons and retained accounting/diversity/cost audits. Accelerated tests cannot supply elapsed days. | +| 12.9 | M11 feedback and current UI review retained | Returning-player samples on the integrated ecology and explicit product/3D readiness decision after soak evidence. No M12 product acceptance or World0 promotion is inferred. | + +Do not couple the current cellular habitat to a copied M6 stock view: two owners +would then spend the same resources. M6 currently owns ten finite field channels +and exactly two configured actors; cellular lives own energy and C/N/P/other plus +finite deposits. Their geometry, ownership and chemical units need a versioned +mapping, not a renamed fixture. ADR-0136 step A is implemented; proposed infall +and photosynthesis steps B/C do not silently become accepted M12 mechanics. + +The engineering constitution requires stopping expansion at this architectural +boundary and documenting the resolution. That does not prevent the independent +worker scheduling correction, which uses the existing raw cellular publication +path. The outstanding population integration is the next substantive coding +segment; none of the rows above is closed by adding a placeholder service. + +Current expansion readiness: **no-go for M13 integration or World0 promotion** +while these M12 integration/evidence gates remain open. This records the present +engineering evidence, not a substitute for the later maintainer product review. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 46a8de4..fb97bf1 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1,5 +1,44 @@ # Validation report +## 2026-10-17 - M12.4a unattended demand and confirmed-head pacing + +ADR-0141 changes the existing cellular worker's demand/pacing and metrics, with +portable helpers. Rules 5+ wildlife now supplies tick demand after players +suspend; active offline cells can enter/finish freeze. Historical profiles lacking +freeze are not opted into unattended work. Biology, profile-4 persistence and +database schema are unchanged. No deploy, World0 operation or new dependency. + +Executed: + +- MSVC 19.44 Release configure/build and **75/75 CTests**, including corrected + legacy-founder fixture, per-boundary offline demand, long cohort conversion + case and separate-process population continuation. +- GCC Release demand/pacing and population-transition tests. Actual QUIC-enabled + PostgreSQL `evo-server` and `evo-postgres-tests` build in `build/m97-postgres`. +- Full `tools/ci/postgres-check.sh` private disposable-cluster suite **passed, + exit 0, 494 s**: migrations/rollback, permissions, fencing, cellular publication, + process/session tests, reservations, backup/restore, DR, upgrade, migration + history and checksum drift. This run includes unattended demand and confirmed + head pacing; the final legacy-guard/freshness refinements have direct final + tests and the final Clang server build/static analysis below. +- Final Clang 19 QUIC/PostgreSQL worker build in `build/tidy-postgres`, followed + by explicit `clang-tidy-19 -p build/tidy-postgres apps/evo-server/main.cpp + --warnings-as-errors=*` (the cached build itself has automatic tidy disabled). +- Analysis-preset clang-tidy 19 for the portable implementation/tests, repository + clang-format 19 check, and scheduler CTest passed. ASan/UBSan scheduler CTest + passed (0.24 s), no reports; population transition regression also passed + ASan/UBSan (8.37 s) during this segment. +- New documentation links and `git diff --check` passed. Explicit NDEBUG checks + exercise fixed-clock debt/retry/confirmed-head accounting, freshness, pause, + epoch change, regressing head/clock and u64 terminal boundaries. + +The actual-private-DB suite is a regression check, not a live no-player ecology +soak or deployment-host capacity measurement. Specific new unattended behavior +has direct demand/clock and real funded-descendant/suspension tests, not a new +multi-region biological process test. No durable population-profile publication, +cross-region biological escrow, global extinction or multi-day soak is claimed. +Remaining integration/evidence: [M12_REMAINING_GATES](M12_REMAINING_GATES.md). + ## 2026-10-17 - M12.3a exact population checkpoint closure ADR-0140 adds population envelope 1, detached conversion candidates and opt-in diff --git a/include/evo/server/lifecycle/cellular_schedule.hpp b/include/evo/server/lifecycle/cellular_schedule.hpp new file mode 100644 index 0000000..7ea31df --- /dev/null +++ b/include/evo/server/lifecycle/cellular_schedule.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include "evo/server/lifecycle/cellular_lives.hpp" + +#include +#include + +namespace evo::server { +// Unowned descendants progress without sessions. Owned active/lingering cells +// need ticks to enter/finish suspension; suspended cells alone need none. +// Historical profiles without offline freeze are not opted into unattended work. +[[nodiscard]] bool cellular_unattended_tick_needed(const CellularLives& state) noexcept; + +enum class CellularScheduleError : std::uint8_t { clock_regression, head_regression, authority }; +struct CellularScheduleStatus { + bool due{}; + std::uint64_t debt{}, max_debt{}; + std::uint64_t head_age_us{}; // Since the last confirmed head change/recovery. +}; +// Pure local pacing, not an authority or durable admission queue. The caller +// supplies monotonic microseconds and only the CONFIRMED head. One due tick may +// be attempted per poll. Rejected work does not consume debt. Authority loss, +// restart or absence of tick demand pauses wall-time (ADR-0133); committed +// intervals and uncertain outcomes remain the fenced host's responsibility. +class CellularTickSchedule { + public: + [[nodiscard]] std::expected + observe(std::uint64_t now_us, std::uint64_t epoch, std::uint64_t committed_tick, bool needed, + bool authoritative); + void defer(std::uint64_t now_us) noexcept; + [[nodiscard]] CellularScheduleStatus status() const noexcept; + + private: + bool observed_{}, anchored_{}; + bool have_receipt_{}, was_authoritative_{}; + std::uint64_t last_us_{}, origin_us_{}, origin_tick_{}, head_{}, epoch_{}, retry_us_{}; + std::uint64_t receipt_us_{}, receipt_tick_{}, receipt_epoch_{}; + CellularScheduleStatus status_; +}; +} // namespace evo::server diff --git a/src/server/lifecycle/cellular_schedule.cpp b/src/server/lifecycle/cellular_schedule.cpp new file mode 100644 index 0000000..d6a29e4 --- /dev/null +++ b/src/server/lifecycle/cellular_schedule.cpp @@ -0,0 +1,71 @@ +#include "evo/server/lifecycle/cellular_schedule.hpp" + +#include +#include + +namespace evo::server { +bool cellular_unattended_tick_needed(const CellularLives& state) noexcept { + // Historical trial profiles lack the offline freeze. Do not opt them into + // unattended stepping and accidentally advance disconnected controlled cells. + if (state.rules_version() < cellular_lives_presence_rules) + return false; + return std::ranges::any_of(state.lives(), [](const auto& life) { + return life.account == LifeAccount{} || life.presence != CellularPresence::suspended; + }); +} + +std::expected +CellularTickSchedule::observe(std::uint64_t now_us, std::uint64_t epoch, + std::uint64_t committed_tick, bool needed, bool authoritative) { + if (observed_ && now_us < last_us_) + return std::unexpected(CellularScheduleError::clock_regression); + if (authoritative && epoch == 0) + return std::unexpected(CellularScheduleError::authority); + if (anchored_ && authoritative && epoch == epoch_ && committed_tick < head_) + return std::unexpected(CellularScheduleError::head_regression); + observed_ = true; + last_us_ = now_us; + if (authoritative && + (!was_authoritative_ || epoch != receipt_epoch_ || committed_tick != receipt_tick_)) { + have_receipt_ = true; + receipt_us_ = now_us; + receipt_tick_ = committed_tick; + receipt_epoch_ = epoch; + } + was_authoritative_ = authoritative; + status_.head_age_us = have_receipt_ ? now_us - receipt_us_ : 0; + status_.due = false; + status_.debt = 0; + if (!authoritative || !needed) { + anchored_ = false; + retry_us_ = 0; + return status_; + } + if (!anchored_ || epoch != epoch_) { + anchored_ = true; + origin_us_ = now_us; + origin_tick_ = committed_tick; + epoch_ = epoch; + retry_us_ = 0; + } + head_ = committed_tick; + const auto elapsed_ticks = (now_us - origin_us_) / biology::cellular_motion_tick_microseconds; + const auto completed_ticks = committed_tick - origin_tick_; + const auto remaining = std::numeric_limits::max() - committed_tick; + status_.debt = + elapsed_ticks > completed_ticks ? std::min(elapsed_ticks - completed_ticks, remaining) : 0; + status_.max_debt = std::max(status_.max_debt, status_.debt); + status_.due = status_.debt > 0 && now_us >= retry_us_; + return status_; +} +void CellularTickSchedule::defer(std::uint64_t now_us) noexcept { + constexpr auto maximum = std::numeric_limits::max(); + retry_us_ = now_us > maximum - biology::cellular_motion_tick_microseconds + ? maximum + : now_us + biology::cellular_motion_tick_microseconds; + status_.due = false; +} +CellularScheduleStatus CellularTickSchedule::status() const noexcept { + return status_; +} +} // namespace evo::server diff --git a/tests/cellular_population_tests.cpp b/tests/cellular_population_tests.cpp index 09e46c6..fa3cc51 100644 --- a/tests/cellular_population_tests.cpp +++ b/tests/cellular_population_tests.cpp @@ -1,4 +1,5 @@ #include "evo/server/lifecycle/cellular_population.hpp" +#include "evo/server/lifecycle/cellular_schedule.hpp" #include "fixtures/cellular_ecology.hpp" #include @@ -152,6 +153,13 @@ void automatic_and_restart() { } } require(cohort_ticks > 0, "suspended observers prevented unattended cohort collapse"); + require(std::ranges::all_of(policy->state().lives(), + [](const auto& life) { + return life.account == LifeAccount{} || + life.presence == CellularPresence::suspended; + }) && + cellular_unattended_tick_needed(policy->state()), + "funded wildlife lost scheduling demand after players suspended"); } void write(const char* path, const CellularPopulation& population) { const auto bytes = population.snapshot(); diff --git a/tests/cellular_schedule_tests.cpp b/tests/cellular_schedule_tests.cpp new file mode 100644 index 0000000..5679f10 --- /dev/null +++ b/tests/cellular_schedule_tests.cpp @@ -0,0 +1,99 @@ +#include "evo/server/lifecycle/cellular_schedule.hpp" +#include "fixtures/cellular_ecology.hpp" + +#include + +namespace { +using namespace evo; +using namespace evo::server; +using namespace evo::fixture; +void pacing() { + CellularTickSchedule schedule; + auto sample = checked(schedule.observe(0, 1, 100, true, true), "schedule start"); + require(!sample.due && sample.debt == 0, "first tick was free"); + require(!checked(schedule.observe(49'999, 1, 100, true, true), "before boundary").due, + "early tick"); + sample = checked(schedule.observe(50'000, 1, 100, true, true), "first due tick"); + require(sample.due && sample.debt == 1, "tick boundary missed"); + sample = checked(schedule.observe(500'000, 1, 100, true, true), "slow publication"); + require(sample.due && sample.debt == 10, "publication latency discarded debt"); + require(sample.head_age_us == 500'000, "stalled head appeared fresh"); + schedule.defer(500'000); + sample = checked(schedule.observe(549'999, 1, 100, true, true), "bounded retry"); + require(!sample.due && sample.debt == 10, "retry consumed debt"); + sample = checked(schedule.observe(550'000, 1, 100, true, true), "retry due"); + require(sample.due && sample.debt == 11, "retry lost ticks"); + for (std::uint64_t tick = 101; tick <= 111; ++tick) { + sample = checked(schedule.observe(550'000, 1, tick, true, true), "committed catchup"); + require(sample.debt == 111 - tick, "confirmed head did not consume exact debt"); + require(sample.head_age_us == 0, "new confirmed head age was not reset"); + } + require(!sample.due && sample.max_debt == 11, "catchup failed"); + require(!schedule.observe(549'999, 1, 111, true, true), "regressing clock accepted"); + require(!schedule.observe(550'000, 1, 110, true, true), "regressing committed head accepted"); + require(!schedule.observe(550'000, 0, 111, true, true), "unfenced origin accepted"); + sample = checked(schedule.observe(600'000, 1, 111, false, true), "no ecology demand"); + require(!sample.due && sample.debt == 0, "suspended-only region accumulated ticks"); + sample = checked(schedule.observe(60'000'000, 1, 111, true, true), "new demand"); + require(!sample.due && sample.debt == 0, "pause caught up wall time"); + checked(schedule.observe(60'050'000, 1, 111, true, false), "authority loss"); + sample = checked(schedule.observe(90'000'000, 2, 112, true, true), "new fenced owner"); + require(!sample.due && sample.debt == 0, "new epoch inherited unadmitted wall time"); + CellularTickSchedule exhausted; + constexpr auto maximum = std::numeric_limits::max(); + checked(exhausted.observe(0, 3, maximum - 1, true, true), "last tick origin"); + require( + checked(exhausted.observe(maximum - 1, 3, maximum - 1, true, true), "large monotonic range") + .debt == 1, + "tick overflow"); + sample = checked(exhausted.observe(maximum, 3, maximum, true, true), "terminal tick"); + require(!sample.due && sample.debt == 0, "tick wrapped"); + exhausted.defer(maximum); +} +void offline_demand() { + auto state = opening(0, true); + require(cellular_unattended_tick_needed(*state), "active offline life cannot start freeze"); + for (std::uint64_t tick = 0; tick <= cellular_linger_ticks; ++tick) { + std::vector frozen; + for (const auto& life : state->lives()) { + CellularLifeIntent intent{life.identity.life, {}}; + intent.intent.frozen = true; + frozen.push_back(intent); + } + checked(state->advance_tick(frozen), "offline demand step"); + require(cellular_unattended_tick_needed(*state) == (tick < cellular_linger_ticks), + "linger/suspend demand mismatch"); + } + const auto before = state->snapshot(); + auto resumed = restore(*state); + require(resumed->snapshot() == before && !cellular_unattended_tick_needed(*resumed), + "restore woke suspended lives"); +} +void historical_profile_is_not_opted_in() { + const auto endowment = checked(biology::primitive_endowment(), "legacy endowment"); + auto funding = endowment.body; + funding.energy.value = endowment.reserve.energy.value + endowment.construction.value; + auto primitive = + checked(PrimitiveLives::create({7, 1, 1, 1, funding, {{100, 100}}}), "legacy nursery"); + LifeRequest request{}; + request.account.back() = 1; + request.action = 1; + checked(primitive->spawn(request, {1, 1, 1, 1, {1}}), "legacy funded life"); + auto habitat = + checked(biology::CellularHabitat::create({7, 1, 1, 6000, 6000, {}}), "legacy habitat"); + auto state = + checked(CellularLives::create(*primitive, std::move(habitat), {{6000, 6000}, 1, 293150}), + "legacy owner"); + require(!state->lives().empty() && !cellular_unattended_tick_needed(*state), + "legacy profile without offline freeze was enabled"); +} +} // namespace +int main() try { + pacing(); + offline_demand(); + historical_profile_is_not_opted_in(); + return 0; +} catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; +}