M11.2a: fund equal primitive lives from finite spawn pools
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 2m44s
Foundation / checks (postgres) (push) Canceled after 0s
Foundation / checks (tsan) (push) Canceled after 0s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (network) (push) Canceled after 13s
Foundation / checks (checks) (push) Canceled after 3m9s
Foundation / checks (client) (push) Canceled after 3m8s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 2m44s
Foundation / checks (postgres) (push) Canceled after 0s
Foundation / checks (tsan) (push) Canceled after 0s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (network) (push) Canceled after 13s
Foundation / checks (checks) (push) Canceled after 3m9s
Foundation / checks (client) (push) Canceled after 3m8s
This commit is contained in:
@@ -73,6 +73,12 @@ target_link_libraries(evo_biology PUBLIC evo::accounting)
|
||||
target_compile_features(evo_biology PUBLIC cxx_std_23)
|
||||
evo_owned_target(evo_biology)
|
||||
|
||||
# M11.2 portable lifecycle orchestration; no dependency from the foundation proof.
|
||||
add_library(evo_lifecycle STATIC src/server/lifecycle/primitive_lives.cpp)
|
||||
add_library(evo::lifecycle ALIAS evo_lifecycle)
|
||||
target_link_libraries(evo_lifecycle PUBLIC evo::biology)
|
||||
evo_owned_target(evo_lifecycle)
|
||||
|
||||
add_library(evo_ecology STATIC src/ecology/cohort.cpp src/ecology/collapse.cpp src/ecology/population.cpp src/ecology/materialize.cpp)
|
||||
add_library(evo::ecology ALIAS evo_ecology)
|
||||
target_include_directories(evo_ecology PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
@@ -410,6 +416,10 @@ if(BUILD_TESTING)
|
||||
add_test(NAME development-contracts COMMAND evo-development-tests)
|
||||
set_tests_properties(development-contracts PROPERTIES TIMEOUT 60)
|
||||
add_executable(evo-metabolism-tests tests/metabolism_tests.cpp)
|
||||
add_executable(evo-primitive-lives-tests tests/primitive_lives_tests.cpp)
|
||||
target_link_libraries(evo-primitive-lives-tests PRIVATE evo::lifecycle)
|
||||
evo_owned_target(evo-primitive-lives-tests)
|
||||
add_test(NAME primitive-lives COMMAND evo-primitive-lives-tests)
|
||||
target_link_libraries(evo-metabolism-tests PRIVATE evo::processes)
|
||||
evo_owned_target(evo-metabolism-tests)
|
||||
add_test(NAME metabolism-contracts COMMAND evo-metabolism-tests)
|
||||
|
||||
+6
-3
@@ -35,10 +35,13 @@ the maintainer chose directional rounding):
|
||||
11.1 is complete.
|
||||
- **Next:** 11.2, primitive lives and persistent control. Server side only; client UI
|
||||
parts of 11.x are deferred to the maintainer. Its
|
||||
[delivery plan](engineering/M11_2_DELIVERY_PLAN.md) and proposed
|
||||
[delivery plan](engineering/M11_2_DELIVERY_PLAN.md) and accepted
|
||||
[ADR-0100](adr/0100-primitive-lives-and-persistent-control.md) identify the new
|
||||
checkpoint and atomic biological publication contracts needed. Founder funding
|
||||
remains a maintainer decision; implementation has not started.
|
||||
checkpoint and atomic biological publication contracts needed. The maintainer
|
||||
authorized finite spawn funding and implementation choices for later review.
|
||||
11.2a adds in-memory funded creation: full-grown primitive founders, equal
|
||||
energy-only reserves, conserved pool/body/heat and exact successful retries.
|
||||
Durable recovery, world-wide binding and session integration remain.
|
||||
|
||||
Open from M10 (BACKLOG):
|
||||
- the maintainer's native-client observation, moved to the later 2k drill;
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
## Status
|
||||
|
||||
Proposed for M11.2, 2026-10-09, following M11.1 commit `93e1ab0`.
|
||||
Server side only; client UI remains deferred to the maintainer. No implementation
|
||||
or gameplay rule is accepted by this proposal. Founder funding needs a maintainer
|
||||
decision; ADR-0099 explicitly leaves it to 11.2.
|
||||
Accepted direction for M11.2, 2026-10-09, following M11.1 commit `93e1ab0`.
|
||||
The maintainer authorized the recommendations and subsequent implementation
|
||||
choices, with review after the fact and a commit/push between subsections.
|
||||
Server side only; client UI remains deferred. Implementation progress and limits
|
||||
are recorded below; acceptance of the design does not claim completed durability.
|
||||
|
||||
## Context and architectural conflicts
|
||||
|
||||
@@ -25,7 +26,7 @@ Per AGENTS.md, implementation must not expand through conflicting contracts.
|
||||
The proposed resolution is a new cellular profile and an atomic publication
|
||||
contract for biological actions. Existing fixture/probe contracts remain intact.
|
||||
|
||||
## Proposed decision
|
||||
## Decision
|
||||
|
||||
### Identity and control
|
||||
|
||||
@@ -44,27 +45,34 @@ World-scoped identities need durable allocation and exhaustion checks. Independe
|
||||
region-local counters cannot guarantee uniqueness. Failed reservations may leave
|
||||
gaps but never reuse issued identities or publish unfunded organisms.
|
||||
|
||||
### Starting body and funding: pending gameplay decision
|
||||
### Starting body and funding
|
||||
|
||||
Recommendation, not an accepted rule:
|
||||
Accepted for founder-life rules 1; numerical choices are tunable and versioned:
|
||||
|
||||
- Every account starts with the same fully grown, undamaged primitive founder.
|
||||
- Derive body composition and construction energy from development version 2;
|
||||
do not duplicate biological constants in SQL or server code.
|
||||
- Give every founder the same versioned reserve. Specify its amount and recheck
|
||||
the first-bud target before implementation; "small reserve" is not a rule.
|
||||
- Give every founder 30 seconds of full-speed demand as energy only: 7,824,000 pJ
|
||||
with development 2. No spare matter. Phosphorus still binds the first bud at
|
||||
300, 600 and 901 seconds for the analyzed feeding shares; energy does not buy
|
||||
missing phosphorus.
|
||||
- Transfer body material, construction energy and reserve from an explicit finite
|
||||
spawn inventory. Construction energy goes to heat, not usable reserve.
|
||||
Allocation, placement or funding failure spends nothing.
|
||||
- Retain source and creation-event provenance. No automatic replenishment or
|
||||
account-age/ancestry bonus is implied.
|
||||
|
||||
Alternatives are local habitat withdrawal or an explicit external input per life.
|
||||
Rejected for this version: local habitat withdrawal or external input per life.
|
||||
External input must appear in the conservation equation, never as a transfer from
|
||||
an empty source. These choices determine whether depletion blocks entry and
|
||||
whether repeated lives inject resources. Starting growth, reserve, placement and
|
||||
any replenishment must be recorded as rules/tunables, not inferred from fixtures.
|
||||
Choosing a funding source alone does not select those other values.
|
||||
Placement uses a bounded, lexicographically ordered list of server-provisioned
|
||||
habitat sites in region/frame-local integer micrometres. Select the first free
|
||||
site; validate that 20 um founder squares do not overlap. This is an explicit
|
||||
initial nursery configuration, not a planet generation or organism movement rule.
|
||||
The pool has explicit provisioning provenance and no automatic refill. Each
|
||||
region owns a disjoint pool; inter-region funding is not implied.
|
||||
|
||||
### Atomic publication and retries
|
||||
|
||||
@@ -151,6 +159,23 @@ separate from the proven probe experiment.
|
||||
|
||||
## Consequences
|
||||
|
||||
Settle funding and this profile/publication resolution before enabling spawning.
|
||||
Only enable network spawning after the profile/publication integration is proven.
|
||||
The [delivery plan](../engineering/M11_2_DELIVERY_PLAN.md) lists acceptance evidence.
|
||||
No golden, simulation version, schema or deployed world changes in this proposal.
|
||||
Existing goldens, simulation versions, schemas and deployed worlds are unchanged.
|
||||
|
||||
## 11.2a: Funded creation
|
||||
|
||||
`biology::primitive_endowment` derives the full body, energy-only reserve and
|
||||
435,200 pJ construction price. `server::PrimitiveLives` owns the finite pool,
|
||||
heat, body/reserve pairs, genome archive, births and request/origin bindings.
|
||||
It is a portable server orchestration target, independent of transport/database
|
||||
and outside `evo::simulation`. A detached candidate is swapped only after every
|
||||
fallible operation succeeds, including ledger and archive admission.
|
||||
|
||||
Capacity is 256 retained lives and provisioned sites (engineering bound). Exact
|
||||
successful retries return the original allocation before checking capacity or
|
||||
funding. Another action for the same living account is refused. The host supplies
|
||||
world-allocated identities, never the client. This layer checks local collisions;
|
||||
world-wide allocation and authorization are enforced in 11.2c/d. Refusals here
|
||||
are in-memory errors, not durable action outcomes. There are no live ticks or
|
||||
death/logout transitions yet, so this subsection is not deployable gameplay.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Architecture decision records
|
||||
|
||||
- [ADR-0100: Primitive lives and persistent control](0100-primitive-lives-and-persistent-control.md) - proposed M11.2 cellular checkpoint and atomic spawn publication; founder funding pending maintainer decision. No implementation yet.
|
||||
- [ADR-0100: Primitive lives and persistent control](0100-primitive-lives-and-persistent-control.md) - accepted M11.2 direction: finite spawn pools, equal full-grown founders, new cellular checkpoint and atomic life publication. 11.2a adds in-memory funded creation; durability/integration follow.
|
||||
|
||||
- [ADR-0058: Region durability contract](0058-region-durability-contract.md) - accepted M7.1 full checkpoint batches and explicit state closure; storage implementation follows.
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# M11.2: Primitive lives and persistent control
|
||||
|
||||
2026-10-09. Server-side continuation of M11.1 at `93e1ab0`.
|
||||
[ADR-0100](../adr/0100-primitive-lives-and-persistent-control.md) is proposed.
|
||||
This plan does not close 11.2 or settle unaccepted game rules.
|
||||
[ADR-0100](../adr/0100-primitive-lives-and-persistent-control.md) is accepted in
|
||||
direction: the maintainer authorized recommendations and implementation choices
|
||||
for later review. This plan does not close 11.2.
|
||||
|
||||
## Contract review
|
||||
|
||||
|
||||
@@ -5477,3 +5477,26 @@ in the delivery plan. No C++/SQL/wire code changed; builds, CTest, clang-format,
|
||||
clang-tidy and sanitizers were not run for this documentation-only change.
|
||||
No environment limitation was encountered during these documentation checks.
|
||||
No deployment, world mutation or provisioning was performed.
|
||||
|
||||
## 2026-10-09 — M11.2a funded primitive creation
|
||||
|
||||
Implemented portable server lifecycle orchestration and the biology-derived
|
||||
founder endowment (ADR-0100). Tests independently check composition, reserve and
|
||||
heat, account equivalence, successful retries at exhausted capacity/funding,
|
||||
per-channel shortage rollback, identity conflicts, invalid/overlapping sites,
|
||||
empty funding and u64 channel bounds. No durable spawn or session integration
|
||||
is claimed yet. No existing golden or wire layout changed.
|
||||
|
||||
Executed:
|
||||
- Linux GCC 14 debug: 62/62 CTest checks; final test-literal revision rechecked.
|
||||
- Linux Clang 19 ASan+UBSan: 62/62.
|
||||
- Windows MSVC release (NDEBUG): 62/62.
|
||||
- clang-tidy 19 on changed sources/tests: clean after correcting a widened test
|
||||
multiplication; Clang also caught a signed initializer-list conversion, fixed.
|
||||
- Repository format-check and `git diff --check`: passed. The formatter first
|
||||
found a pre-existing mixed newline in session_window.hpp; normalization is
|
||||
semantically empty and produces no Git content diff.
|
||||
|
||||
Environment: the sandboxed Windows Ninja build stalled before compiler execution;
|
||||
the same release preset succeeded outside the sandbox. WSL required escalated
|
||||
access. No reference-worker load qualification or deployment was performed.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/biology/genome.hpp"
|
||||
#include "evo/biology/metabolism.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
@@ -28,4 +28,18 @@ inline constexpr std::uint32_t primitive_founder_development_version = 2;
|
||||
// an invalid identity (zero).
|
||||
[[nodiscard]] std::expected<Genome, GenomeError> primitive_founder(std::uint64_t id,
|
||||
std::uint64_t origin_event);
|
||||
|
||||
// M11.2 founder rules 1 (ADR-0100): fully grown, no damage or spare matter;
|
||||
// 30 seconds of full-speed demand as usable energy. Construction energy is paid
|
||||
// separately into heat. Tunable and versioned; not an account reward.
|
||||
inline constexpr std::uint32_t founder_life_rules = 1;
|
||||
inline constexpr std::uint64_t founder_reserve_seconds = 30;
|
||||
struct FounderEndowment {
|
||||
GrowthState growth{1000, 0};
|
||||
accounting::Inventory body{};
|
||||
accounting::Inventory reserve{};
|
||||
accounting::Picojoules construction{};
|
||||
auto operator<=>(const FounderEndowment&) const = default;
|
||||
};
|
||||
[[nodiscard]] std::expected<FounderEndowment, DevelopmentError> primitive_endowment();
|
||||
} // namespace evo::biology
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/biology/founder.hpp"
|
||||
#include "evo/biology/lineage.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
// Portable, single-owner server orchestration, not the foundation simulation.
|
||||
// M11.2a is an in-memory candidate; success is NOT a durable acknowledgement.
|
||||
// The host must authorize requests and publish the entire state plus bindings
|
||||
// atomically (ADR-0100). No network, database, clocks or implicit biology here.
|
||||
namespace evo::server {
|
||||
using LifeAccount = std::array<std::uint8_t, 16>;
|
||||
struct SpawnSite {
|
||||
std::int32_t x_um{}, y_um{}; // Region/frame-local, micrometres.
|
||||
auto operator<=>(const SpawnSite&) const = default;
|
||||
};
|
||||
inline constexpr std::size_t max_primitive_lives = 256;
|
||||
inline constexpr std::int32_t spawn_coordinate_limit_um = 1'000'000'000;
|
||||
struct NurseryConfig {
|
||||
std::uint64_t world{}, region{}, frame{}, source{};
|
||||
accounting::Inventory funding{}; // Explicit finite opening, never replenished here.
|
||||
std::vector<SpawnSite> sites; // Server-approved habitat; sorted lexicographically.
|
||||
};
|
||||
struct LifeRequest {
|
||||
LifeAccount account{};
|
||||
std::uint64_t action{};
|
||||
auto operator<=>(const LifeRequest&) const = default;
|
||||
};
|
||||
// Obtained from the world's durable allocator by the host, never from the client.
|
||||
// All identities are distinct namespaces. Gaps are allowed, reuse is not.
|
||||
struct LifeAllocation {
|
||||
std::uint64_t life{}, organism{}, genome{}, event{};
|
||||
Tick born{};
|
||||
auto operator<=>(const LifeAllocation&) const = default;
|
||||
};
|
||||
struct PrimitiveLife {
|
||||
LifeRequest request{};
|
||||
LifeAllocation identity{};
|
||||
std::uint64_t source{}; // Funding provenance, within config.world.
|
||||
SpawnSite site{};
|
||||
biology::GrowthState growth{};
|
||||
accounting::ReservoirId body{}, reserve{};
|
||||
auto operator<=>(const PrimitiveLife&) const = default;
|
||||
};
|
||||
enum class LifeError : std::uint8_t {
|
||||
invalid,
|
||||
capacity,
|
||||
occupied,
|
||||
existing_life,
|
||||
identity_conflict,
|
||||
insufficient_funding,
|
||||
overflow,
|
||||
biology,
|
||||
archive
|
||||
};
|
||||
|
||||
class PrimitiveLives {
|
||||
public:
|
||||
[[nodiscard]] static std::expected<std::unique_ptr<PrimitiveLives>, LifeError>
|
||||
create(NurseryConfig config);
|
||||
~PrimitiveLives();
|
||||
PrimitiveLives(const PrimitiveLives&) = delete;
|
||||
PrimitiveLives& operator=(const PrimitiveLives&) = delete;
|
||||
// Selects the first free provisioned site. Exact successful retry resolves
|
||||
// before allocation/site/funding checks, returning the original life.
|
||||
// Different action for an account already living is refused. On any refusal
|
||||
// (or allocation exception), every inventory and history entry is unchanged.
|
||||
[[nodiscard]] std::expected<PrimitiveLife, LifeError> spawn(LifeRequest request,
|
||||
LifeAllocation allocation);
|
||||
// References/spans are invalidated by a successful non-retry spawn.
|
||||
[[nodiscard]] const NurseryConfig& config() const noexcept;
|
||||
[[nodiscard]] std::span<const PrimitiveLife> lives() const noexcept;
|
||||
[[nodiscard]] std::span<const accounting::Inventory> balances() const noexcept;
|
||||
[[nodiscard]] accounting::Inventory totals() const noexcept;
|
||||
[[nodiscard]] const biology::LineageArchive& archive() const noexcept;
|
||||
|
||||
private:
|
||||
struct State;
|
||||
explicit PrimitiveLives(std::unique_ptr<State> state);
|
||||
std::unique_ptr<State> state_;
|
||||
};
|
||||
} // namespace evo::server
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "evo/biology/founder.hpp"
|
||||
|
||||
#include <limits>
|
||||
|
||||
namespace evo::biology {
|
||||
std::expected<Genome, GenomeError> primitive_founder(std::uint64_t id, std::uint64_t origin_event) {
|
||||
const auto& p = primitive_founder_parameters;
|
||||
@@ -16,4 +18,33 @@ std::expected<Genome, GenomeError> primitive_founder(std::uint64_t id, std::uint
|
||||
{Capability::target_size, p.target_size, 0}};
|
||||
return Genome::create(draft);
|
||||
}
|
||||
|
||||
std::expected<FounderEndowment, DevelopmentError> primitive_endowment() {
|
||||
// Identity does not enter development; the published genome gets allocated
|
||||
// identities at creation, not these analysis-only values.
|
||||
const auto genome = primitive_founder(1, 1);
|
||||
const auto rules = rules_for(primitive_founder_development_version);
|
||||
if (!genome || !rules)
|
||||
return std::unexpected{DevelopmentError::unsupported_rules};
|
||||
const auto budget = metabolic_budget(*genome, {1000, 0}, {rules->reference_temperature, {}});
|
||||
if (!budget)
|
||||
return std::unexpected{budget.error()};
|
||||
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
||||
if (budget->demand.value > maximum / founder_reserve_seconds)
|
||||
return std::unexpected{DevelopmentError::overflow};
|
||||
// Same construction pricing as development: floor(mass * price / 1000),
|
||||
// with checked intermediates. The founder pays its entire membrane too.
|
||||
const auto mass = budget->phenotype.total_mass;
|
||||
const auto price = rules->construction_per_kilogram;
|
||||
if (price != 0 && (mass / 1000 > maximum / price || mass % 1000 > maximum / price))
|
||||
return std::unexpected{DevelopmentError::overflow};
|
||||
const auto whole = mass / 1000 * price;
|
||||
const auto fraction = mass % 1000 * price / 1000;
|
||||
if (fraction > maximum - whole)
|
||||
return std::unexpected{DevelopmentError::overflow};
|
||||
return FounderEndowment{{1000, 0},
|
||||
budget->body,
|
||||
{{budget->demand.value * founder_reserve_seconds}, {}},
|
||||
{whole + fraction}};
|
||||
}
|
||||
} // namespace evo::biology
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
#include "evo/server/lifecycle/primitive_lives.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
|
||||
namespace evo::server {
|
||||
struct PrimitiveLives::State {
|
||||
NurseryConfig config;
|
||||
accounting::Ledger ledger;
|
||||
biology::LineageArchive archive;
|
||||
std::vector<PrimitiveLife> lives;
|
||||
};
|
||||
|
||||
PrimitiveLives::PrimitiveLives(std::unique_ptr<State> state) : state_{std::move(state)} {}
|
||||
PrimitiveLives::~PrimitiveLives() = default;
|
||||
|
||||
std::expected<std::unique_ptr<PrimitiveLives>, LifeError>
|
||||
PrimitiveLives::create(NurseryConfig config) {
|
||||
if (config.world == 0 || config.region == 0 || config.frame == 0 || config.source == 0 ||
|
||||
config.sites.empty() || config.sites.size() > max_primitive_lives ||
|
||||
!std::ranges::is_sorted(config.sites))
|
||||
return std::unexpected{LifeError::invalid};
|
||||
const auto founder = biology::primitive_founder(1, 1);
|
||||
if (!founder)
|
||||
return std::unexpected{LifeError::biology};
|
||||
const auto phenotype = biology::derive_phenotype(*founder, {1000, 0}, {});
|
||||
if (!phenotype)
|
||||
return std::unexpected{LifeError::biology};
|
||||
for (std::size_t i = 0; i < config.sites.size(); ++i) {
|
||||
const auto site = config.sites[i];
|
||||
if (site.x_um < -spawn_coordinate_limit_um || site.x_um > spawn_coordinate_limit_um ||
|
||||
site.y_um < -spawn_coordinate_limit_um || site.y_um > spawn_coordinate_limit_um)
|
||||
return std::unexpected{LifeError::invalid};
|
||||
for (std::size_t j = 0; j < i; ++j) {
|
||||
const auto dx = std::abs(std::int64_t{site.x_um} - config.sites[j].x_um);
|
||||
const auto dy = std::abs(std::int64_t{site.y_um} - config.sites[j].y_um);
|
||||
if (dx < phenotype->extent && dy < phenotype->extent)
|
||||
return std::unexpected{LifeError::occupied};
|
||||
}
|
||||
}
|
||||
std::vector<accounting::Inventory> opening(2 + 2 * config.sites.size());
|
||||
opening[0] = config.funding; // Source 1, heat 2; body/reserve pairs follow.
|
||||
auto ledger = accounting::Ledger::create(opening);
|
||||
if (!ledger)
|
||||
return std::unexpected{LifeError::overflow};
|
||||
auto state = std::make_unique<State>(State{std::move(config), std::move(*ledger), {}, {}});
|
||||
return std::unique_ptr<PrimitiveLives>{new PrimitiveLives{std::move(state)}};
|
||||
}
|
||||
|
||||
std::expected<PrimitiveLife, LifeError> PrimitiveLives::spawn(LifeRequest request,
|
||||
LifeAllocation allocation) {
|
||||
if (request.action == 0 || std::ranges::all_of(request.account, [](auto b) { return b == 0; }))
|
||||
return std::unexpected{LifeError::invalid};
|
||||
for (const auto& life : state_->lives) {
|
||||
if (life.request == request)
|
||||
return life;
|
||||
if (life.request.account == request.account)
|
||||
return std::unexpected{LifeError::existing_life};
|
||||
}
|
||||
if (allocation.life == 0 || allocation.organism == 0 || allocation.genome == 0 ||
|
||||
allocation.event == 0)
|
||||
return std::unexpected{LifeError::invalid};
|
||||
for (const auto& life : state_->lives) {
|
||||
const auto& old = life.identity;
|
||||
if (old.life == allocation.life || old.organism == allocation.organism ||
|
||||
old.genome == allocation.genome || old.event == allocation.event)
|
||||
return std::unexpected{LifeError::identity_conflict};
|
||||
}
|
||||
const auto slot = state_->lives.size();
|
||||
if (slot == state_->config.sites.size())
|
||||
return std::unexpected{LifeError::capacity};
|
||||
const auto endowed = biology::primitive_endowment();
|
||||
const auto genome = biology::primitive_founder(allocation.genome, allocation.event);
|
||||
if (!endowed || !genome)
|
||||
return std::unexpected{LifeError::biology};
|
||||
const auto body = accounting::ReservoirId{static_cast<std::uint32_t>(3 + 2 * slot)};
|
||||
const auto reserve = accounting::ReservoirId{body.value + 1};
|
||||
const PrimitiveLife life{
|
||||
request, allocation, state_->config.source, state_->config.sites[slot], endowed->growth,
|
||||
body, reserve};
|
||||
// Detached candidate: all fallible work, including allocations and archive
|
||||
// admission, precedes the single noexcept pointer swap.
|
||||
auto next = std::make_unique<State>(*state_);
|
||||
const std::array legs{accounting::Transfer{{1}, body, endowed->body},
|
||||
accounting::Transfer{{1}, reserve, endowed->reserve},
|
||||
accounting::Transfer{{1}, {2}, {endowed->construction, {}}}};
|
||||
const auto paid = next->ledger.transfer(slot + 1, legs);
|
||||
if (!paid)
|
||||
return std::unexpected{paid.error() == accounting::LedgerError::insufficient_inventory
|
||||
? LifeError::insufficient_funding
|
||||
: LifeError::overflow};
|
||||
if (!next->archive.admit(*genome) ||
|
||||
!next->archive.record_birth(allocation.organism, allocation.genome, allocation.born))
|
||||
return std::unexpected{LifeError::archive};
|
||||
next->lives.push_back(life);
|
||||
state_.swap(next);
|
||||
return life;
|
||||
}
|
||||
|
||||
const NurseryConfig& PrimitiveLives::config() const noexcept {
|
||||
return state_->config;
|
||||
}
|
||||
std::span<const PrimitiveLife> PrimitiveLives::lives() const noexcept {
|
||||
return state_->lives;
|
||||
}
|
||||
std::span<const accounting::Inventory> PrimitiveLives::balances() const noexcept {
|
||||
return state_->ledger.balances();
|
||||
}
|
||||
accounting::Inventory PrimitiveLives::totals() const noexcept {
|
||||
return state_->ledger.conserved_totals();
|
||||
}
|
||||
const biology::LineageArchive& PrimitiveLives::archive() const noexcept {
|
||||
return state_->archive;
|
||||
}
|
||||
} // namespace evo::server
|
||||
@@ -0,0 +1,200 @@
|
||||
#include "evo/server/lifecycle/primitive_lives.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <limits>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
using namespace evo::server;
|
||||
using evo::accounting::Inventory;
|
||||
void check(bool value, std::source_location at = std::source_location::current()) {
|
||||
if (!value)
|
||||
throw std::runtime_error("primitive lives line " + std::to_string(at.line()));
|
||||
}
|
||||
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
|
||||
|
||||
LifeRequest request(std::uint8_t account, std::uint64_t action = 1) {
|
||||
LifeRequest r{};
|
||||
r.account.back() = account;
|
||||
r.action = action;
|
||||
return r;
|
||||
}
|
||||
LifeAllocation allocation(std::uint64_t id) {
|
||||
return {id, id + 100, id + 200, id + 300, {10}};
|
||||
}
|
||||
Inventory price(std::uint64_t count) {
|
||||
const auto endowment = evo::biology::primitive_endowment();
|
||||
CHECK(endowment);
|
||||
auto cost = endowment->body;
|
||||
cost.energy.value = endowment->reserve.energy.value + endowment->construction.value;
|
||||
cost.energy.value *= count;
|
||||
for (auto& channel : cost.matter)
|
||||
channel.value *= count;
|
||||
return cost;
|
||||
}
|
||||
NurseryConfig config(std::uint64_t funded = 2) {
|
||||
return {90, 1, 7, 17, price(funded), {{0, 0}, {20, 0}}};
|
||||
}
|
||||
Inventory summed(std::span<const Inventory> balances) {
|
||||
Inventory sum{};
|
||||
for (const auto& b : balances) {
|
||||
sum.energy.value += b.energy.value;
|
||||
for (std::size_t c = 0; c < 4; ++c)
|
||||
sum.matter[c].value += b.matter[c].value;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
struct Cut {
|
||||
std::vector<Inventory> balances;
|
||||
std::vector<PrimitiveLife> lives;
|
||||
std::vector<std::uint8_t> archive;
|
||||
auto operator<=>(const Cut&) const = default;
|
||||
};
|
||||
Cut cut(const PrimitiveLives& nursery) {
|
||||
return {{nursery.balances().begin(), nursery.balances().end()},
|
||||
{nursery.lives().begin(), nursery.lives().end()},
|
||||
nursery.archive().encode()};
|
||||
}
|
||||
|
||||
void funded_bodies_and_equal_starts() {
|
||||
auto created = PrimitiveLives::create(config());
|
||||
CHECK(created);
|
||||
auto& nursery = **created;
|
||||
const auto opening = nursery.totals();
|
||||
CHECK(nursery.archive().recorded() == 0 && nursery.lives().empty());
|
||||
const auto first = nursery.spawn(request(1), allocation(1));
|
||||
// A large action number represents a returning account; it grants no power.
|
||||
const auto second = nursery.spawn(request(2, 999'999), allocation(2));
|
||||
CHECK(first && second && first->site == (SpawnSite{0, 0}) &&
|
||||
second->site == (SpawnSite{20, 0}));
|
||||
CHECK(first->growth == (evo::biology::GrowthState{1000, 0}));
|
||||
CHECK(first->growth == second->growth && first->source == 17 && second->source == 17);
|
||||
CHECK(nursery.balances()[first->body.value - 1] == nursery.balances()[second->body.value - 1]);
|
||||
CHECK(nursery.balances()[first->reserve.value - 1] ==
|
||||
nursery.balances()[second->reserve.value - 1]);
|
||||
const auto a = nursery.archive().find(first->identity.genome);
|
||||
const auto b = nursery.archive().find(second->identity.genome);
|
||||
CHECK(a && b);
|
||||
CHECK(evo::biology::metabolic_budget(*a, first->growth, {}) ==
|
||||
evo::biology::metabolic_budget(*b, second->growth, {}));
|
||||
CHECK(nursery.archive().organism(first->identity.organism)->born == evo::Tick{10});
|
||||
CHECK(nursery.balances()[0] == Inventory{});
|
||||
// Independently calculated body: structure 8e6 fg, membrane 2.88e6 fg.
|
||||
const auto& body = nursery.balances()[first->body.value - 1];
|
||||
CHECK(body.energy.value == 0 && body.matter[0].value == 6'016'000);
|
||||
CHECK(body.matter[1].value == 1'344'000 && body.matter[2].value == 688'000);
|
||||
CHECK(body.matter[3].value == 2'832'000);
|
||||
CHECK(nursery.balances()[first->reserve.value - 1].energy.value == 7'824'000);
|
||||
CHECK(nursery.balances()[1].energy.value == 2ULL * 435'200);
|
||||
CHECK(summed(nursery.balances()) == opening && nursery.totals() == opening);
|
||||
// Initial reserve is energy-only; phosphorus still binds the first bud.
|
||||
const auto budget = evo::biology::metabolic_budget(*a, first->growth, {});
|
||||
CHECK(budget);
|
||||
CHECK(nursery.balances()[first->reserve.value - 1].matter == Inventory{}.matter);
|
||||
for (const std::uint64_t share : {1000ULL, 500ULL, 333ULL}) {
|
||||
const auto needed = budget->reproduction_investment.matter[2].value;
|
||||
const auto rate = budget->intake_limit.matter[2].value * share / 1000;
|
||||
const auto seconds = needed / rate + (needed % rate != 0 ? 1 : 0);
|
||||
CHECK(seconds >= 300 && seconds <= 901);
|
||||
}
|
||||
}
|
||||
|
||||
void failures_and_retries_spend_nothing() {
|
||||
auto made = PrimitiveLives::create(config());
|
||||
CHECK(made);
|
||||
auto& nursery = **made;
|
||||
const auto first = nursery.spawn(request(1), allocation(1));
|
||||
CHECK(first);
|
||||
const auto before = cut(nursery);
|
||||
CHECK(nursery.spawn(request(1), {}) == first); // Retry needs no fresh allocation.
|
||||
CHECK(!nursery.spawn(request(1, 2), allocation(2)));
|
||||
CHECK(!nursery.spawn(request(0), allocation(2)));
|
||||
CHECK(!nursery.spawn(request(2, 0), allocation(2)));
|
||||
CHECK(!nursery.spawn(request(2), {}));
|
||||
for (int field = 0; field < 4; ++field) {
|
||||
auto duplicate = allocation(2);
|
||||
if (field == 0)
|
||||
duplicate.life = 1;
|
||||
if (field == 1)
|
||||
duplicate.organism = 101;
|
||||
if (field == 2)
|
||||
duplicate.genome = 201;
|
||||
if (field == 3)
|
||||
duplicate.event = 301;
|
||||
const auto result = nursery.spawn(request(2), duplicate);
|
||||
CHECK(!result && result.error() == LifeError::identity_conflict);
|
||||
}
|
||||
CHECK(cut(nursery) == before);
|
||||
CHECK(nursery.spawn(request(2), allocation(2)));
|
||||
const auto full = cut(nursery);
|
||||
const auto refused = nursery.spawn(request(3), allocation(3));
|
||||
CHECK(!refused && refused.error() == LifeError::capacity && cut(nursery) == full);
|
||||
CHECK(nursery.spawn(request(1), {}) == first); // Even when full and source empty.
|
||||
CHECK(cut(nursery) == full);
|
||||
}
|
||||
|
||||
void every_channel_must_be_funded() {
|
||||
for (std::size_t channel = 0; channel < 5; ++channel) {
|
||||
auto c = config(1);
|
||||
if (channel == 0)
|
||||
--c.funding.energy.value;
|
||||
else
|
||||
--c.funding.matter[channel - 1].value;
|
||||
auto made = PrimitiveLives::create(c);
|
||||
CHECK(made);
|
||||
const auto before = cut(**made);
|
||||
const auto result = (*made)->spawn(request(1), allocation(1));
|
||||
CHECK(!result && result.error() == LifeError::insufficient_funding);
|
||||
CHECK(cut(**made) == before);
|
||||
}
|
||||
auto made = PrimitiveLives::create(config(1));
|
||||
CHECK(made && (*made)->spawn(request(1), allocation(1)));
|
||||
const auto before = cut(**made);
|
||||
CHECK(!(*made)->spawn(request(2), allocation(2)) && cut(**made) == before);
|
||||
}
|
||||
|
||||
void invalid_sites_and_bounds() {
|
||||
auto c = config();
|
||||
c.sites[1] = {19, 19}; // 20 um square founder bodies overlap on both axes.
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c.sites[1] = {0, 0};
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c.sites = {{20, 0}, {0, 0}};
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c.sites = {{std::numeric_limits<std::int32_t>::min(), 0}};
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c.sites.clear();
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c = config();
|
||||
c.world = 0;
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c = config();
|
||||
c.sites.resize(max_primitive_lives + 1);
|
||||
CHECK(!PrimitiveLives::create(c));
|
||||
c = config();
|
||||
c.funding = {};
|
||||
auto empty = PrimitiveLives::create(c);
|
||||
CHECK(empty && !(*empty)->spawn(request(1), allocation(1)));
|
||||
// Huge valid opening stays exactly conserved, without summing channels into one mass.
|
||||
c.funding.energy.value = std::numeric_limits<std::uint64_t>::max();
|
||||
for (auto& m : c.funding.matter)
|
||||
m.value = std::numeric_limits<std::uint64_t>::max();
|
||||
auto huge = PrimitiveLives::create(c);
|
||||
CHECK(huge && (*huge)->spawn(request(1), allocation(1)));
|
||||
CHECK(summed((*huge)->balances()) == c.funding);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() try {
|
||||
funded_bodies_and_equal_starts();
|
||||
failures_and_retries_spend_nothing();
|
||||
every_channel_must_be_funded();
|
||||
invalid_sites_and_bounds();
|
||||
std::puts("PASS primitive lives: funded bodies, equal starts, atomic refusals and retries");
|
||||
return 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "%s\n", e.what());
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user