Implement M6.5c persisted environmental community and bounded writers
This commit is contained in:
+7
-2
@@ -61,9 +61,9 @@ target_link_libraries(evo_ecology PUBLIC evo::accounting evo::biology)
|
||||
target_compile_features(evo_ecology PUBLIC cxx_std_23)
|
||||
evo_owned_target(evo_ecology)
|
||||
|
||||
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp src/processes/genome_strategy.cpp src/processes/ensemble.cpp)
|
||||
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp src/processes/genome_strategy.cpp src/processes/ensemble.cpp src/processes/environmental_community.cpp src/processes/environmental_codec.cpp)
|
||||
add_library(evo::processes ALIAS evo_processes)
|
||||
target_link_libraries(evo_processes PUBLIC evo::accounting evo::biology)
|
||||
target_link_libraries(evo_processes PUBLIC evo::accounting evo::biology evo::world)
|
||||
evo_owned_target(evo_processes)
|
||||
|
||||
add_executable(evo-sim apps/evo-sim/main.cpp)
|
||||
@@ -72,6 +72,11 @@ evo_owned_target(evo-sim)
|
||||
|
||||
include(CTest)
|
||||
if(BUILD_TESTING)
|
||||
add_executable(evo-environmental-community-tests tests/environmental_community_tests.cpp)
|
||||
target_link_libraries(evo-environmental-community-tests PRIVATE evo::processes)
|
||||
evo_owned_target(evo-environmental-community-tests)
|
||||
add_test(NAME environmental-community-contracts COMMAND evo-environmental-community-tests)
|
||||
set_tests_properties(environmental-community-contracts PROPERTIES TIMEOUT 60)
|
||||
add_executable(evo-environment-transfers-tests tests/environment_transfers_tests.cpp)
|
||||
target_link_libraries(evo-environment-transfers-tests PRIVATE evo::world)
|
||||
evo_owned_target(evo-environment-transfers-tests)
|
||||
|
||||
@@ -146,3 +146,7 @@ M5.8 process restart proof and measured costs: [world proof](docs/engineering/WO
|
||||
M6.4: [atomic environmental transfers](docs/world/ENVIRONMENTAL_TRANSFERS.md)
|
||||
own finite field and organism resource compartments together. Biology integration
|
||||
is next (M6.5); coupled snapshot/recovery remains M6.8.
|
||||
|
||||
M6.5c: [persisted producer/consumer fixture](docs/biology/ENVIRONMENTAL_PROCESS.md),
|
||||
with finite source capture, tagged growth/feeding and complete rate/lifecycle snapshots.
|
||||
It is a library/test fixture; existing CLI modes and M2/M3 rules are unchanged.
|
||||
|
||||
@@ -451,3 +451,8 @@ and the [process contract](biology/ENVIRONMENTAL_PROCESS.md) specify conversions
|
||||
source residual policy, temperature gates, synthetic depletion and private resource
|
||||
checkpoints with process retry history. Next: M6.5c implementation/persistence,
|
||||
then M6.5d qualification. No rate-enabled runtime exists yet.
|
||||
|
||||
M6.5c implemented: complete process envelope and atomic environmental fixture.
|
||||
Source rates, residuals, last funded interval, lifecycle and exact retry reports now
|
||||
restore together; retained history is replay-validated against an audit anchor.
|
||||
Next M6.5d: broader boundary/long-run qualification; M6.5 remains open until it passes.
|
||||
|
||||
+18
-1
@@ -61,7 +61,7 @@ for the bounded proof; the general production ECS remains a later measured choic
|
||||
|
||||
| Priority | Work | Completion evidence |
|
||||
|---|---|---|
|
||||
| 1 | M6.5c implement persisted producer/consumer fixture | Complete rate/biology envelope, then atomic process stepping under ADR-0055 |
|
||||
| 1 | M6.5d qualify persisted producer/consumer fixture | Broader adversarial bounds, long-run seeds, restored replay and cost evidence |
|
||||
| Research | Improve aggregate fidelity and measure Linux/target-host costs | M4.6 found no qualifying width; see the aggregate budget report |
|
||||
| 2 | Revisit the ADR-0031/0032 reproduction cost model | Reproduction is affordable only at the genome schema's floor; decide whether that is intended before M4 builds cohorts on it |
|
||||
| Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes |
|
||||
@@ -691,3 +691,20 @@ Next: M6.5c implements the fixture and complete source-rate/biology snapshot bef
|
||||
exposing advance; M6.5d qualifies it. M6.5 remains incomplete. M2/M3 maintenance,
|
||||
reproduction and mortality behavior is unchanged; resource starvation is reported
|
||||
without inventing a new death policy.
|
||||
|
||||
## M6.5c persisted environmental fixture (2026-09-27)
|
||||
|
||||
Implemented EnvironmentalCommunity: area-bounded finite capture, recipe growth,
|
||||
organic feeding/waste/heat, source exhaustion and temperature gates, plus whole-tick
|
||||
rollback and exact retained retries. Rates execute only alongside the complete
|
||||
[process envelope](../schemas/environmental-community.md), which restores primitive
|
||||
config, residuals, lifecycle, resources and history and audits retained inputs by
|
||||
replay from a historical anchor. Existing M2/M3 rules and codecs are unchanged.
|
||||
|
||||
The pasted GCC 14 CI log exposed a vector reserve/append diagnostic in the resource
|
||||
snapshot writer. Both coupled writers now fill exactly sized buffers and check their
|
||||
final cursor, retaining strict compiler warnings and unchanged resource wire bytes.
|
||||
Native validation is recorded separately from Linux CI verification.
|
||||
|
||||
Next: M6.5d broader qualification (boundary/adversarial cases, long-run seeds and
|
||||
cost evidence). M6.5 as a whole is not yet marked complete; no deployment changed.
|
||||
|
||||
@@ -71,3 +71,9 @@ M6.5c must implement and test the full envelope before exposing advance. M6.5d m
|
||||
check source-off, resource limits, temperature boundaries, retries, rollback and
|
||||
restored seeded continuation. Durable publication remains M7. No dependency or
|
||||
schema implementation is introduced merely to make the repository appear complete.
|
||||
|
||||
M6.5c implemented 2026-09-27. One-site staged scalars replace full terrain cloning;
|
||||
the private checkpoint validates accounting before nonthrowing publication. The
|
||||
complete envelope includes an audit anchor that permits deterministic replay of the
|
||||
retained process receipts on restore. See schemas/environmental-community.md and
|
||||
the process contract for bounds. M6.5d remains the broader qualification gate.
|
||||
|
||||
@@ -112,3 +112,9 @@ The process library may depend on world; world must not depend on process or gen
|
||||
code. Only constrained process operations may create private resource checkpoints.
|
||||
Complete rate/biology persistence precedes executable stepping in M6.5c. Existing
|
||||
M2 process interfaces and results remain unchanged.
|
||||
|
||||
M6.5c now implements `evo::processes::EnvironmentalCommunity` and its complete
|
||||
[rate/biology envelope](../../schemas/environmental-community.md). World only exposes
|
||||
a private conserved checkpoint to this constrained process owner; no genome or
|
||||
process-type dependency enters the world library. New public stepping lives in the
|
||||
process layer; existing M2 process interfaces remain unchanged.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# M6.5 environmental process contract v1
|
||||
|
||||
Authority: ADR-0055, ADR-0054, environmental units (ADR-0050), and the scoped
|
||||
producer/feeding rules (ADRs 0025/0026). **Specified, not implemented.** M6.5b is a
|
||||
contract segment. M6.5c must implement this contract and the complete buffer codec
|
||||
before advance is enabled. Coefficients below are fixture inputs, not game rules.
|
||||
producer/feeding rules (ADRs 0025/0026). **Implemented in M6.5c; broader qualification remains M6.5d.** M6.5b is a
|
||||
contract segment. M6.5c implements the runtime and complete buffer codec together.
|
||||
Coefficients below are fixture inputs, not game rules.
|
||||
|
||||
## Ownership and interface boundary
|
||||
|
||||
One `EnvironmentalCommunity` (working name) owns one coupled resource owner,
|
||||
One `EnvironmentalCommunity` owns one coupled resource owner,
|
||||
immutable configuration, progress and process retry receipts. Admission supports
|
||||
one habitat site and exactly two sorted nonzero actor IDs. Producer and consumer
|
||||
are configured capabilities, not inheritance classes or permanent species.
|
||||
@@ -19,13 +19,13 @@ Require all ten fields present, valid material binding and capacities, and a fre
|
||||
resource owner (command/adoption watermark zero and no history). Reject adopting a
|
||||
previously advanced independent resource owner: migration is not implied.
|
||||
|
||||
Conceptual API, to be finalized with callers/tests in M6.5c:
|
||||
Public API in `include/evo/processes/environmental_community.hpp`:
|
||||
|
||||
- create(config, exclusively owned resources, total peak byte budget) -> expected owner;
|
||||
- advance(exact next tick, immutable tick input) -> expected report;
|
||||
- snapshot() -> complete canonical process envelope;
|
||||
- restore(bytes, expected world, budgets) -> detached validated owner;
|
||||
- inspect() -> read-only values/views, invalidated at publication.
|
||||
- resources()/progress() -> read-only resource access and copied progress; views require freshness validation.
|
||||
|
||||
No mutable resource getter, user-supplied resource delta, commit callback, external
|
||||
credit/debit or independent process-state setter. Host access is single-writer.
|
||||
@@ -39,7 +39,7 @@ sequenceDiagram
|
||||
participant C as Detached candidate
|
||||
H->>P: exact tick + bounded input
|
||||
P->>P: resolve retained exact retry or reject conflict
|
||||
P->>C: clone complete owned state within peak budget
|
||||
P->>C: stage scalar balances and progress within peak budget
|
||||
C->>C: capture then growth then feeding
|
||||
C->>C: validate conservation, capacity, progress and report
|
||||
P->>P: publish resources + progress + retry history (noexcept)
|
||||
@@ -173,8 +173,7 @@ history order/count, latest tick, endpoint/rules references, residual bounds and
|
||||
resource checkpoint watermark. Reject a bare resource snapshot as a process snapshot.
|
||||
Do not synthesize absent source or lifecycle state from defaults.
|
||||
|
||||
M6.5c must define exact byte fields, bounds and malformed-input validation before
|
||||
exposing advance. Nothing here grants restart fencing, durable ACKs, disk publication
|
||||
M6.5c defines exact byte fields and validation in [the envelope schema](../../schemas/environmental-community.md). Nothing here grants restart fencing, durable ACKs, disk publication
|
||||
or host-loss recovery; those remain M7/M8.
|
||||
|
||||
## Hand-checkable acceptance vectors
|
||||
@@ -199,3 +198,19 @@ zero efficiency, all capacity/overflow bounds, exact retry after restore, more t
|
||||
64 ticks, malformed snapshots, deterministic seeded input streams and independent
|
||||
per-channel accounting. No stochastic fairness or RNG is required in the engine;
|
||||
seeded test drivers record their full input sequence.
|
||||
|
||||
|
||||
## M6.5c implementation detail
|
||||
|
||||
For one site, field channels are uniform scalars. Stage all 30 balances, progress,
|
||||
report and the historical audit anchor in bounded arrays. A private world checkpoint
|
||||
validates conserved totals and capacities then replaces baselines without allocation;
|
||||
process progress/history publish immediately afterward without throwing. Terrain is
|
||||
unchanged. There is no full terrain clone or codec round trip in advance. This refines
|
||||
the initial cloning baseline above while retaining detached candidate semantics.
|
||||
|
||||
Restore replays the 64-tick receipt window from a persisted historical anchor and
|
||||
compares all reports and final state. The anchor is not spendable. The consumer is
|
||||
always active in rules v1 (no consumer-death operation exists); producer terminal
|
||||
state is serialized explicitly. Frame/site, account IDs, source identity and primitive
|
||||
rate config come from the complete envelope, never missing-state defaults.
|
||||
|
||||
@@ -1839,3 +1839,40 @@ all passed. `git diff --check` passed. These are specification checks, not runti
|
||||
integration tests. No C++/CMake/schema change; builds, CTest and sanitizers were not
|
||||
rerun for this documentation segment. M6.5c/d must supply executable evidence for
|
||||
rollback, source exhaustion, temperature limits, lifecycle and restored replay.
|
||||
|
||||
## M6.5c persisted environmental community - 2026-09-27
|
||||
|
||||
Implemented the one-habitat/two-actor fixture and envelope v1, preserving source
|
||||
identity/rate, residuals, last funded interval, lifecycle, resources and 64 exact
|
||||
input/report receipts. Restore replays receipts from a historical anchor, validates
|
||||
reports and compares the final state. Scalar candidate staging commits without
|
||||
allocation; the world layer checks capacities and conserved totals before publication.
|
||||
|
||||
Executed Windows x64 checks:
|
||||
|
||||
- Release check: 53/53 CTests passed, NDEBUG enabled.
|
||||
- Analysis check: clang-tidy/warnings-as-errors build and 53/53 CTests passed.
|
||||
- ASan check: 53/53 CTests passed.
|
||||
- After final tight-budget and continuous/restored comparison additions, analysis
|
||||
ran all 53 tests again; Release and ASan rebuilt and the two environmental
|
||||
transfer/community tests passed again.
|
||||
- Release format check passed. No existing golden changed.
|
||||
|
||||
Coverage includes hand-calculated capture/growth/feeding, source disabled/unfunded,
|
||||
frozen residuals, inclusive temperature gates, terminal producer, whole-tick rollback,
|
||||
exact/conflicting/expired retries, eight deterministic input sequences through 90
|
||||
ticks, continuous versus restored bytes/reports, every truncation length, corruption,
|
||||
recomputed-checksum invalid config/anchor/report/count/state, identity and budgets.
|
||||
M6.5d remains the broader adversarial, long-run and cost qualification gate.
|
||||
|
||||
The supplied Gitea log shows GCC 14 Release rejecting transfer_codec.cpp with
|
||||
-Werror=free-nonheap-object in the vector reserve/push_back path. Changed that writer
|
||||
and the new process writer to exactly sized buffers, checked writes and final cursor
|
||||
validation. No warning suppression or resource format change. The next Gitea run must
|
||||
confirm Linux: Docker's Linux engine was unavailable locally; WSL Ubuntu exists but
|
||||
has no g++/g++-14, CMake or Ninja. No toolchain installation was attempted. No local
|
||||
Linux/UBSan/TSan or cluster result is claimed.
|
||||
|
||||
Initial native static analysis flagged an unspecified enum base and integer widening
|
||||
in a size constant; both corrected before the passing analysis runs. No disk/host-loss
|
||||
recovery, biological maintenance, reproduction or player/offline progression added.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
#include "evo/world/transfers.hpp"
|
||||
namespace evo::processes {
|
||||
// Explicit fixture parameters; units and array order in environmental-community.md.
|
||||
struct EnvironmentalConfig {
|
||||
std::uint64_t rules{1}, world{}, frame{}, producer{}, consumer{}, source{}, tick_microseconds{},
|
||||
area_um2{}, irradiance_numerator{}, irradiance_denominator{1}, efficiency{},
|
||||
growth_numerator{}, growth_denominator{1}, growth_cost{};
|
||||
std::array<std::uint64_t, 5> recipe{}, intake{};
|
||||
std::uint64_t assimilation{}, producer_min_mK{}, producer_max_mK{}, consumer_min_mK{},
|
||||
consumer_max_mK{};
|
||||
auto operator<=>(const EnvironmentalConfig&) const = default;
|
||||
};
|
||||
struct EnvironmentalInput {
|
||||
std::uint64_t temperature_mK{}, source_enabled{};
|
||||
std::array<std::uint64_t, 5> bite{};
|
||||
auto operator<=>(const EnvironmentalInput&) const = default;
|
||||
};
|
||||
struct EnvironmentalProgress {
|
||||
std::uint64_t tick{}, source_remainder{}, last_funded{}, efficiency_remainder{},
|
||||
growth_remainder{}, producer_terminal{};
|
||||
auto operator<=>(const EnvironmentalProgress&) const = default;
|
||||
};
|
||||
struct EnvironmentalReport {
|
||||
std::uint64_t tick{}, captured{}, retained{}, capture_heat{}, grown{}, unmet{}, source_status{};
|
||||
std::array<std::uint64_t, 5> assimilated{}, waste{};
|
||||
std::uint64_t terminal_transition{};
|
||||
auto operator<=>(const EnvironmentalReport&) const = default;
|
||||
};
|
||||
enum class CommunityError : std::uint8_t {
|
||||
config,
|
||||
input,
|
||||
tick,
|
||||
conflict,
|
||||
stale,
|
||||
capacity,
|
||||
insufficient,
|
||||
overflow,
|
||||
budget,
|
||||
format,
|
||||
version,
|
||||
checksum,
|
||||
resources
|
||||
};
|
||||
class EnvironmentalCommunity {
|
||||
public:
|
||||
static constexpr std::size_t history_limit = 64, scratch_bytes = 65536,
|
||||
max_snapshot_bytes = std::size_t{1024} * 1024;
|
||||
[[nodiscard]] static std::expected<std::unique_ptr<EnvironmentalCommunity>, CommunityError>
|
||||
create(EnvironmentalConfig config, std::unique_ptr<world::EnvironmentalTransfers> resources,
|
||||
std::size_t budget);
|
||||
[[nodiscard]] std::expected<EnvironmentalReport, CommunityError>
|
||||
advance(std::uint64_t tick, const EnvironmentalInput& input);
|
||||
[[nodiscard]] std::expected<world::WorldBytes, CommunityError> snapshot() const;
|
||||
[[nodiscard]] static std::expected<std::unique_ptr<EnvironmentalCommunity>, CommunityError>
|
||||
restore(std::span<const std::uint8_t> bytes, world::WorldIdentity identity, std::size_t budget);
|
||||
[[nodiscard]] const world::EnvironmentalTransfers& resources() const noexcept {
|
||||
return *resources_;
|
||||
}
|
||||
[[nodiscard]] EnvironmentalProgress progress() const noexcept {
|
||||
return progress_;
|
||||
}
|
||||
|
||||
private:
|
||||
struct State {
|
||||
std::array<std::uint64_t, 10> environment{}, producer{}, consumer{};
|
||||
EnvironmentalProgress progress{};
|
||||
auto operator<=>(const State&) const = default;
|
||||
};
|
||||
struct History {
|
||||
EnvironmentalInput input{};
|
||||
EnvironmentalReport report{};
|
||||
};
|
||||
EnvironmentalCommunity() = default;
|
||||
[[nodiscard]] State state() const noexcept;
|
||||
[[nodiscard]] bool valid(const State& s) const noexcept;
|
||||
[[nodiscard]] static bool configuration(const EnvironmentalConfig& c,
|
||||
const world::EnvironmentalTransfers& r) noexcept;
|
||||
[[nodiscard]] std::expected<EnvironmentalReport, CommunityError>
|
||||
step(State& candidate, std::uint64_t tick, const EnvironmentalInput& input) const noexcept;
|
||||
EnvironmentalConfig config_{};
|
||||
std::unique_ptr<world::EnvironmentalTransfers> resources_;
|
||||
EnvironmentalProgress progress_{};
|
||||
State anchor_{};
|
||||
std::array<History, history_limit> history_{};
|
||||
std::size_t count_{}, next_{}, budget_{};
|
||||
};
|
||||
} // namespace evo::processes
|
||||
@@ -8,6 +8,9 @@
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
namespace evo::processes {
|
||||
class EnvironmentalCommunity;
|
||||
}
|
||||
namespace evo::world {
|
||||
struct OrganismResourceId {
|
||||
std::uint64_t value{};
|
||||
@@ -91,6 +94,11 @@ class EnvironmentalTransfers {
|
||||
std::uint64_t current_tick);
|
||||
|
||||
private:
|
||||
friend class evo::processes::EnvironmentalCommunity;
|
||||
[[nodiscard]] bool process_checkpoint(std::uint64_t tick,
|
||||
const std::array<std::uint64_t, 10>& environment,
|
||||
const std::array<std::uint64_t, 10>& producer,
|
||||
const std::array<std::uint64_t, 10>& consumer) noexcept;
|
||||
struct History {
|
||||
EnvironmentalReceipt receipt{};
|
||||
std::array<EnvironmentalLeg, max_legs> legs{};
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# Environmental community envelope v1 (M6.5c)
|
||||
|
||||
Authority ADR-0055. All integers little-endian, no native struct serialization.
|
||||
Header u64 magic 0x3150434f564541, u64 format=1, u64 total bytes. Maximum 1 MiB.
|
||||
Then config, current progress, audit anchor, u64 receipt count, chronological
|
||||
receipts, u64 coupled resource payload length, resource v1 bytes, trailing FNV-1a64
|
||||
checksum of all previous bytes. FNV detects corruption, not hostile forgery.
|
||||
|
||||
Config fields are u64 in public declaration order: rules, world, frame, producer,
|
||||
consumer, source, tick_microseconds, area_um2, irradiance_numerator/denominator,
|
||||
efficiency, growth_numerator/denominator, growth_cost, recipe[5] (W/C/N/P/O),
|
||||
intake[5] (C/N/P/O/E), assimilation, producer_min/max_mK, consumer_min/max_mK.
|
||||
Site is the unique nested field site; it is not independently defaulted on restore.
|
||||
Progress: tick, source_remainder, last_funded, efficiency_remainder,
|
||||
growth_remainder, producer_terminal (0/1). Consumer has no terminal transition in
|
||||
v1; its sole supported state is active, encoded by rules v1 rather than an unused flag.
|
||||
Anchor: environment[10], producer[10], consumer[10], then progress.
|
||||
Each receipt: input (temperature_mK, source_enabled 0/1, bite[5]), report
|
||||
(tick,captured,retained,capture_heat,grown,unmet,source_status 0/1/2,
|
||||
assimilated[5],waste[5],terminal_transition 0/1).
|
||||
|
||||
Require receipt count=min(tick,64), ticks contiguous ending at current tick, anchor
|
||||
tick=current tick-count. Validate anchor capacities, per-element totals, source and
|
||||
growth residuals, source interval watermark, lifecycle bounds. Replay retained inputs
|
||||
from the audit anchor with immutable config and current capacities; every report
|
||||
must match and final balances/progress must equal the nested checkpoint/current
|
||||
progress. This audit copy is historical state, never another spendable inventory.
|
||||
At tick0, progress and history are empty. No missing rate data is defaulted.
|
||||
|
||||
Only a pristine resource owner with one field site, one resident terrain chunk,
|
||||
all ten fields, two ordered accounts and zero command history is admitted. Process
|
||||
restore separately requires checkpoint command/adoption=tick and empty transfer
|
||||
history. Bare resource snapshots are not process envelopes. No live migration API.
|
||||
|
||||
One-site staging uses fixed scalar arrays; replacing scalar field baselines allocates
|
||||
nothing. Charge sizeof(process owner), owned resource resident bytes and 64KiB
|
||||
process scratch plus the resource owner's separate 64KiB scratch before admission/restore. Query/snapshot caller buffers and allocator headers
|
||||
are excluded. Snapshot construction temporarily holds nested bytes plus output,
|
||||
bounded by 2MiB; host must provide that additional output allowance. No terrain clone
|
||||
or codec buffer is allocated by advance. Restore replay is bounded to 64 steps.
|
||||
|
||||
Codec and transitions are single-owner, in-memory operations. No disk publication,
|
||||
region lease, external energy import, player login or offline progression exists.
|
||||
@@ -0,0 +1,193 @@
|
||||
#include "evo/processes/environmental_community.hpp"
|
||||
#include <algorithm>
|
||||
namespace evo::processes {
|
||||
namespace {
|
||||
constexpr std::uint64_t magic = 0x3150434f564541ULL;
|
||||
std::uint64_t hash(std::span<const std::uint8_t> bytes) {
|
||||
std::uint64_t h = 14695981039346656037ULL;
|
||||
for (auto b : bytes)
|
||||
h = (h ^ b) * 1099511628211ULL;
|
||||
return h;
|
||||
}
|
||||
struct Writer {
|
||||
world::WorldBytes bytes;
|
||||
std::size_t at{};
|
||||
void operator()(std::uint64_t v) {
|
||||
for (unsigned i = 0; i < 8; ++i) {
|
||||
bytes.at(at++) = static_cast<std::uint8_t>(v & 255U);
|
||||
v >>= 8U;
|
||||
}
|
||||
}
|
||||
};
|
||||
struct Reader {
|
||||
std::span<const std::uint8_t> bytes;
|
||||
std::size_t at{};
|
||||
bool ok{true};
|
||||
void operator()(std::uint64_t& v) {
|
||||
v = 0;
|
||||
if (bytes.size() - at < 8) {
|
||||
ok = false;
|
||||
return;
|
||||
}
|
||||
for (unsigned i = 0; i < 8; ++i)
|
||||
v |= std::uint64_t{bytes[at++]} << (8U * i);
|
||||
}
|
||||
std::uint64_t get() {
|
||||
std::uint64_t v{};
|
||||
(*this)(v);
|
||||
return v;
|
||||
}
|
||||
};
|
||||
template <class T, class IO> void config_io(T& c, IO& io) {
|
||||
io(c.rules);
|
||||
io(c.world);
|
||||
io(c.frame);
|
||||
io(c.producer);
|
||||
io(c.consumer);
|
||||
io(c.source);
|
||||
io(c.tick_microseconds);
|
||||
io(c.area_um2);
|
||||
io(c.irradiance_numerator);
|
||||
io(c.irradiance_denominator);
|
||||
io(c.efficiency);
|
||||
io(c.growth_numerator);
|
||||
io(c.growth_denominator);
|
||||
io(c.growth_cost);
|
||||
for (auto& x : c.recipe)
|
||||
io(x);
|
||||
for (auto& x : c.intake)
|
||||
io(x);
|
||||
io(c.assimilation);
|
||||
io(c.producer_min_mK);
|
||||
io(c.producer_max_mK);
|
||||
io(c.consumer_min_mK);
|
||||
io(c.consumer_max_mK);
|
||||
}
|
||||
template <class T, class IO> void progress_io(T& p, IO& io) {
|
||||
io(p.tick);
|
||||
io(p.source_remainder);
|
||||
io(p.last_funded);
|
||||
io(p.efficiency_remainder);
|
||||
io(p.growth_remainder);
|
||||
io(p.producer_terminal);
|
||||
}
|
||||
template <class T, class IO> void state_io(T& s, IO& io) {
|
||||
for (auto& v : s.environment)
|
||||
io(v);
|
||||
for (auto& v : s.producer)
|
||||
io(v);
|
||||
for (auto& v : s.consumer)
|
||||
io(v);
|
||||
progress_io(s.progress, io);
|
||||
}
|
||||
template <class T, class IO> void history_io(T& h, IO& io) {
|
||||
io(h.input.temperature_mK);
|
||||
io(h.input.source_enabled);
|
||||
for (auto& v : h.input.bite)
|
||||
io(v);
|
||||
auto& r = h.report;
|
||||
io(r.tick);
|
||||
io(r.captured);
|
||||
io(r.retained);
|
||||
io(r.capture_heat);
|
||||
io(r.grown);
|
||||
io(r.unmet);
|
||||
io(r.source_status);
|
||||
for (auto& v : r.assimilated)
|
||||
io(v);
|
||||
for (auto& v : r.waste)
|
||||
io(v);
|
||||
io(r.terminal_transition);
|
||||
}
|
||||
} // namespace
|
||||
std::expected<world::WorldBytes, CommunityError> EnvironmentalCommunity::snapshot() const {
|
||||
auto resource = resources_->snapshot();
|
||||
if (!resource)
|
||||
return std::unexpected{CommunityError::resources};
|
||||
const auto length =
|
||||
24 + 29 * 8 + 6 * 8 + 36 * 8 + 8 + count_ * 25 * 8 + 8 + resource->size() + 8;
|
||||
if (length > max_snapshot_bytes)
|
||||
return std::unexpected{CommunityError::budget};
|
||||
Writer w;
|
||||
w.bytes.resize(length);
|
||||
w(magic);
|
||||
w(1);
|
||||
w(length);
|
||||
config_io(config_, w);
|
||||
progress_io(progress_, w);
|
||||
state_io(anchor_, w);
|
||||
w(count_);
|
||||
for (std::size_t i = 0; i < count_; ++i)
|
||||
history_io(history_[(next_ + history_limit - count_ + i) % history_limit], w);
|
||||
w(resource->size());
|
||||
std::copy(resource->begin(), resource->end(),
|
||||
w.bytes.begin() + static_cast<std::ptrdiff_t>(w.at));
|
||||
w.at += resource->size();
|
||||
w(hash(std::span{w.bytes}.first(length - 8)));
|
||||
if (w.at != length)
|
||||
return std::unexpected{CommunityError::format};
|
||||
return std::move(w.bytes);
|
||||
}
|
||||
std::expected<std::unique_ptr<EnvironmentalCommunity>, CommunityError>
|
||||
EnvironmentalCommunity::restore(std::span<const std::uint8_t> bytes, world::WorldIdentity identity,
|
||||
std::size_t budget) {
|
||||
if (bytes.size() < 616 || bytes.size() > max_snapshot_bytes)
|
||||
return std::unexpected{CommunityError::format};
|
||||
Reader r{bytes.first(bytes.size() - 8)}, tail{bytes.last(8)};
|
||||
if (r.get() != magic)
|
||||
return std::unexpected{CommunityError::format};
|
||||
if (r.get() != 1)
|
||||
return std::unexpected{CommunityError::version};
|
||||
if (r.get() != bytes.size())
|
||||
return std::unexpected{CommunityError::format};
|
||||
if (hash(r.bytes) != tail.get())
|
||||
return std::unexpected{CommunityError::checksum};
|
||||
if (budget < sizeof(EnvironmentalCommunity) + scratch_bytes)
|
||||
return std::unexpected{CommunityError::budget};
|
||||
auto o = std::unique_ptr<EnvironmentalCommunity>(new EnvironmentalCommunity);
|
||||
config_io(o->config_, r);
|
||||
progress_io(o->progress_, r);
|
||||
state_io(o->anchor_, r);
|
||||
const auto count = r.get();
|
||||
if (!r.ok || count != std::min(o->progress_.tick, std::uint64_t{history_limit}) ||
|
||||
o->anchor_.progress.tick != o->progress_.tick - count ||
|
||||
count * 200 > r.bytes.size() - r.at)
|
||||
return std::unexpected{CommunityError::format};
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
history_io(o->history_[i], r);
|
||||
if (o->history_[i].report.tick != o->anchor_.progress.tick + i + 1)
|
||||
return std::unexpected{CommunityError::format};
|
||||
}
|
||||
const auto length = r.get();
|
||||
if (!r.ok || length != r.bytes.size() - r.at)
|
||||
return std::unexpected{CommunityError::format};
|
||||
const auto resource_budget = budget - sizeof(EnvironmentalCommunity) - scratch_bytes;
|
||||
auto resource = world::EnvironmentalTransfers::restore(
|
||||
r.bytes.subspan(r.at), identity, resource_budget, resource_budget, resource_budget);
|
||||
if (!resource)
|
||||
return std::unexpected{resource.error() == world::TransferError::budget
|
||||
? CommunityError::budget
|
||||
: CommunityError::format};
|
||||
o->resources_ = std::move(*resource);
|
||||
o->budget_ = budget;
|
||||
o->count_ = static_cast<std::size_t>(count);
|
||||
o->next_ = o->count_ % history_limit;
|
||||
if (!configuration(o->config_, *o->resources_) ||
|
||||
o->resources_->adoption_command_ != o->progress_.tick ||
|
||||
o->resources_->fields().last_command() != o->progress_.tick ||
|
||||
std::ranges::any_of(o->resources_->history_,
|
||||
[](const auto& h) { return h.receipt.command != 0; }) ||
|
||||
!o->valid(o->state()) || !o->valid(o->anchor_))
|
||||
return std::unexpected{CommunityError::format};
|
||||
auto replay = o->anchor_;
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
const auto& h = o->history_[i];
|
||||
auto report = o->step(replay, h.report.tick, h.input);
|
||||
if (!report || *report != h.report)
|
||||
return std::unexpected{CommunityError::format};
|
||||
}
|
||||
if (replay != o->state())
|
||||
return std::unexpected{CommunityError::format};
|
||||
return o;
|
||||
}
|
||||
} // namespace evo::processes
|
||||
@@ -0,0 +1,217 @@
|
||||
#include "evo/processes/environmental_community.hpp"
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
namespace evo::processes {
|
||||
namespace {
|
||||
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
||||
constexpr std::array<std::size_t, 5> food{3, 4, 5, 6, 7}, growth_from{0, 3, 1, 2, 6},
|
||||
growth_to{0, 3, 4, 5, 6};
|
||||
bool any(const std::array<std::uint64_t, 5>& a) {
|
||||
return std::ranges::any_of(a, [](auto x) { return x != 0; });
|
||||
}
|
||||
std::uint64_t portion(std::uint64_t x, std::uint64_t a) {
|
||||
return (x / 1000) * a + (x % 1000) * a / 1000;
|
||||
}
|
||||
} // namespace
|
||||
bool EnvironmentalCommunity::configuration(const EnvironmentalConfig& c,
|
||||
const world::EnvironmentalTransfers& r) noexcept {
|
||||
if (c.rules != 1 || c.world == 0 || c.frame == 0 ||
|
||||
r.fields().identity() != world::WorldIdentity{c.world, c.frame} || c.source == 0 ||
|
||||
c.tick_microseconds == 0 || c.area_um2 == 0 || c.irradiance_denominator == 0 ||
|
||||
c.growth_denominator == 0 || c.efficiency > 1000 || c.assimilation > 1000 ||
|
||||
c.growth_cost == 0 || c.producer_min_mK == 0 || c.consumer_min_mK == 0 ||
|
||||
c.producer_min_mK > c.producer_max_mK || c.consumer_min_mK > c.consumer_max_mK)
|
||||
return false;
|
||||
if (r.fields().sites().size() != 1 || r.terrain().size() != 1 || r.organisms().size() != 2 ||
|
||||
r.organisms()[0].id.value != c.producer || r.organisms()[1].id.value != c.consumer)
|
||||
return false;
|
||||
const auto measure = world::measure_habitat(r.fields().sites()[0].box);
|
||||
if (!measure || c.area_um2 > measure->area.value ||
|
||||
c.irradiance_numerator > maximum / c.area_um2)
|
||||
return false;
|
||||
for (std::size_t k = 0; k < 10; ++k)
|
||||
if (!r.fields().read(0, static_cast<world::Field>(k)))
|
||||
return false;
|
||||
for (std::size_t k = 0; k < 4; ++k)
|
||||
if (c.recipe[k] == 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
EnvironmentalCommunity::State EnvironmentalCommunity::state() const noexcept {
|
||||
State s;
|
||||
for (std::size_t k = 0; k < 10; ++k)
|
||||
s.environment[k] = *resources_->fields().read(0, static_cast<world::Field>(k));
|
||||
s.producer = resources_->organisms()[0].balances;
|
||||
s.consumer = resources_->organisms()[1].balances;
|
||||
s.progress = progress_;
|
||||
return s;
|
||||
}
|
||||
bool EnvironmentalCommunity::valid(const State& s) const noexcept {
|
||||
const auto& p = s.progress;
|
||||
if ((p.last_funded == 0 && (p.source_remainder != 0 || p.efficiency_remainder != 0)) ||
|
||||
p.source_remainder >= config_.irradiance_denominator ||
|
||||
p.growth_remainder >= config_.growth_denominator || p.efficiency_remainder >= 1000 ||
|
||||
p.last_funded > p.tick || p.producer_terminal > 1 ||
|
||||
(p.tick == 0 && p != EnvironmentalProgress{}))
|
||||
return false;
|
||||
if (p.producer_terminal && std::ranges::any_of(s.producer, [](auto v) { return v != 0; }))
|
||||
return false;
|
||||
if (s.environment[0] > resources_->fields().water_capacity(0)->value)
|
||||
return false;
|
||||
auto remaining = resources_->totals();
|
||||
constexpr std::array<std::size_t, 7> channels{3, 1, 2, 0, 1, 2, 3};
|
||||
for (std::size_t k = 0; k < 10; ++k) {
|
||||
if (s.producer[k] > resources_->organisms()[0].capacities[k] ||
|
||||
s.consumer[k] > resources_->organisms()[1].capacities[k])
|
||||
return false;
|
||||
auto& total = k < 7 ? remaining.matter[channels[k]].value : remaining.energy.value;
|
||||
for (auto v : {s.environment[k], s.producer[k], s.consumer[k]}) {
|
||||
if (v > total)
|
||||
return false;
|
||||
total -= v;
|
||||
}
|
||||
}
|
||||
return remaining == accounting::Inventory{};
|
||||
}
|
||||
std::expected<std::unique_ptr<EnvironmentalCommunity>, CommunityError>
|
||||
EnvironmentalCommunity::create(EnvironmentalConfig c,
|
||||
std::unique_ptr<world::EnvironmentalTransfers> r,
|
||||
std::size_t budget) {
|
||||
if (!r || !configuration(c, *r) || r->fields().last_command() != 0 || r->adoption_command_ != 0)
|
||||
return std::unexpected{CommunityError::config};
|
||||
if (budget < sizeof(EnvironmentalCommunity) + 2 * scratch_bytes ||
|
||||
r->accounted_bytes() > budget - sizeof(EnvironmentalCommunity) - 2 * scratch_bytes)
|
||||
return std::unexpected{CommunityError::budget};
|
||||
auto o = std::unique_ptr<EnvironmentalCommunity>(new EnvironmentalCommunity);
|
||||
o->config_ = c;
|
||||
o->resources_ = std::move(r);
|
||||
o->budget_ = budget;
|
||||
o->anchor_ = o->state();
|
||||
return o;
|
||||
}
|
||||
std::expected<EnvironmentalReport, CommunityError>
|
||||
EnvironmentalCommunity::step(State& s, std::uint64_t tick,
|
||||
const EnvironmentalInput& input) const noexcept {
|
||||
if (input.temperature_mK == 0 || input.source_enabled > 1)
|
||||
return std::unexpected{CommunityError::input};
|
||||
auto& p = s.progress;
|
||||
const auto& c = config_;
|
||||
EnvironmentalReport report{};
|
||||
report.tick = tick;
|
||||
const bool eligible = !p.producer_terminal && input.temperature_mK >= c.producer_min_mK &&
|
||||
input.temperature_mK <= c.producer_max_mK;
|
||||
if (eligible && input.source_enabled) {
|
||||
auto quota = world::integrate_energy(
|
||||
{c.irradiance_numerator * c.area_um2, c.irradiance_denominator}, 1, p.source_remainder);
|
||||
if (!quota)
|
||||
return std::unexpected{CommunityError::overflow};
|
||||
const auto energy = quota->amount.value;
|
||||
if (energy > s.environment[8])
|
||||
report.source_status = 2;
|
||||
else {
|
||||
const auto frac = (energy % 1000) * c.efficiency + p.efficiency_remainder;
|
||||
const auto retained = (energy / 1000) * c.efficiency + frac / 1000;
|
||||
if (retained > resources_->organisms()[0].capacities[7] - s.producer[7])
|
||||
return std::unexpected{CommunityError::capacity};
|
||||
s.environment[8] -= energy;
|
||||
s.producer[7] += retained;
|
||||
s.environment[9] += energy - retained;
|
||||
p.source_remainder = quota->remainder;
|
||||
p.efficiency_remainder = frac % 1000;
|
||||
p.last_funded = tick;
|
||||
report.captured = energy;
|
||||
report.retained = retained;
|
||||
report.capture_heat = energy - retained;
|
||||
report.source_status = 1;
|
||||
}
|
||||
}
|
||||
if (eligible) {
|
||||
auto quota = world::integrate_energy({c.growth_numerator, c.growth_denominator}, 1,
|
||||
p.growth_remainder);
|
||||
if (!quota)
|
||||
return std::unexpected{CommunityError::overflow};
|
||||
auto grown = std::min(quota->amount.value, s.producer[7] / c.growth_cost);
|
||||
for (std::size_t j = 0; j < 5; ++j)
|
||||
if (c.recipe[j] != 0) {
|
||||
grown = std::min(grown, s.environment[growth_from[j]] / c.recipe[j]);
|
||||
grown = std::min(grown, (resources_->organisms()[0].capacities[growth_to[j]] -
|
||||
s.producer[growth_to[j]]) /
|
||||
c.recipe[j]);
|
||||
}
|
||||
for (std::size_t j = 0; j < 5; ++j) {
|
||||
const auto amount = grown * c.recipe[j];
|
||||
s.environment[growth_from[j]] -= amount;
|
||||
s.producer[growth_to[j]] += amount;
|
||||
}
|
||||
s.producer[7] -= grown * c.growth_cost;
|
||||
s.environment[9] += grown * c.growth_cost;
|
||||
p.growth_remainder = quota->remainder;
|
||||
report.grown = grown;
|
||||
report.unmet = quota->amount.value - grown;
|
||||
}
|
||||
if (any(input.bite)) {
|
||||
if (p.producer_terminal || input.temperature_mK < c.consumer_min_mK ||
|
||||
input.temperature_mK > c.consumer_max_mK)
|
||||
return std::unexpected{CommunityError::input};
|
||||
for (std::size_t j = 0; j < 5; ++j) {
|
||||
const auto amount = input.bite[j], k = food[j];
|
||||
if (amount > c.intake[j])
|
||||
return std::unexpected{CommunityError::input};
|
||||
if (amount > s.producer[k])
|
||||
return std::unexpected{CommunityError::insufficient};
|
||||
const auto kept = portion(amount, c.assimilation);
|
||||
if (kept > resources_->organisms()[1].capacities[k] - s.consumer[k])
|
||||
return std::unexpected{CommunityError::capacity};
|
||||
s.producer[k] -= amount;
|
||||
s.consumer[k] += kept;
|
||||
s.environment[j == 4 ? 9 : k] += amount - kept;
|
||||
report.assimilated[j] = kept;
|
||||
report.waste[j] = amount - kept;
|
||||
}
|
||||
if (std::ranges::all_of(s.producer, [](auto v) { return v == 0; })) {
|
||||
p.producer_terminal = 1;
|
||||
report.terminal_transition = 1;
|
||||
}
|
||||
}
|
||||
p.tick = tick;
|
||||
if (!valid(s))
|
||||
return std::unexpected{CommunityError::resources};
|
||||
return report;
|
||||
}
|
||||
std::expected<EnvironmentalReport, CommunityError>
|
||||
EnvironmentalCommunity::advance(std::uint64_t tick, const EnvironmentalInput& input) {
|
||||
if (tick == 0)
|
||||
return std::unexpected{CommunityError::tick};
|
||||
if (tick <= progress_.tick) {
|
||||
for (const auto& h : history_)
|
||||
if (h.report.tick == tick) {
|
||||
if (h.input != input)
|
||||
return std::unexpected{CommunityError::conflict};
|
||||
return h.report;
|
||||
}
|
||||
return std::unexpected{CommunityError::stale};
|
||||
}
|
||||
if (progress_.tick == maximum || tick != progress_.tick + 1)
|
||||
return std::unexpected{CommunityError::tick};
|
||||
auto candidate = state();
|
||||
auto report = step(candidate, tick, input);
|
||||
if (!report)
|
||||
return report;
|
||||
auto anchor = anchor_;
|
||||
if (count_ == history_limit) {
|
||||
const auto& old = history_[next_];
|
||||
auto checked = step(anchor, old.report.tick, old.input);
|
||||
if (!checked || *checked != old.report)
|
||||
return std::unexpected{CommunityError::resources};
|
||||
}
|
||||
if (!resources_->process_checkpoint(tick, candidate.environment, candidate.producer,
|
||||
candidate.consumer))
|
||||
return std::unexpected{CommunityError::resources};
|
||||
progress_ = candidate.progress;
|
||||
anchor_ = anchor;
|
||||
history_[next_] = {input, *report};
|
||||
next_ = (next_ + 1) % history_limit;
|
||||
count_ = std::min(count_ + 1, history_limit);
|
||||
return report;
|
||||
}
|
||||
} // namespace evo::processes
|
||||
@@ -5,9 +5,9 @@
|
||||
namespace evo::world {
|
||||
namespace {
|
||||
constexpr std::uint64_t magic = 0x31504c43564f4541ULL;
|
||||
void put(WorldBytes& b, std::uint64_t v, unsigned n) {
|
||||
void put(WorldBytes& b, std::size_t& at, std::uint64_t v, unsigned n) {
|
||||
for (unsigned i = 0; i < n; ++i) {
|
||||
b.push_back(static_cast<std::uint8_t>(v & 255U));
|
||||
b.at(at++) = static_cast<std::uint8_t>(v & 255U);
|
||||
v >>= 8U;
|
||||
}
|
||||
}
|
||||
@@ -59,43 +59,47 @@ std::expected<WorldBytes, TransferError> EnvironmentalTransfers::snapshot() cons
|
||||
length += 20 + 42 * ordered[i]->receipt.legs;
|
||||
if (length > max_snapshot_bytes)
|
||||
return std::unexpected{TransferError::budget};
|
||||
WorldBytes out;
|
||||
out.reserve(length);
|
||||
put(out, magic, 8);
|
||||
put(out, 1, 4);
|
||||
put(out, length, 4);
|
||||
put(out, fields_->identity().world, 8);
|
||||
put(out, fields_->identity().frame, 8);
|
||||
put(out, adoption_command_, 8);
|
||||
put(out, count_, 4);
|
||||
put(out, count, 4);
|
||||
put(out, terrain->size(), 4);
|
||||
put(out, fields.size(), 4);
|
||||
out.insert(out.end(), terrain->begin(), terrain->end());
|
||||
out.insert(out.end(), fields.begin(), fields.end());
|
||||
WorldBytes out(length);
|
||||
std::size_t at{};
|
||||
put(out, at, magic, 8);
|
||||
put(out, at, 1, 4);
|
||||
put(out, at, length, 4);
|
||||
put(out, at, fields_->identity().world, 8);
|
||||
put(out, at, fields_->identity().frame, 8);
|
||||
put(out, at, adoption_command_, 8);
|
||||
put(out, at, count_, 4);
|
||||
put(out, at, count, 4);
|
||||
put(out, at, terrain->size(), 4);
|
||||
put(out, at, fields.size(), 4);
|
||||
std::copy(terrain->begin(), terrain->end(), out.begin() + static_cast<std::ptrdiff_t>(at));
|
||||
at += terrain->size();
|
||||
std::copy(fields.begin(), fields.end(), out.begin() + static_cast<std::ptrdiff_t>(at));
|
||||
at += fields.size();
|
||||
for (const auto& a : organisms()) {
|
||||
put(out, a.id.value, 8);
|
||||
put(out, at, a.id.value, 8);
|
||||
for (auto v : a.balances)
|
||||
put(out, v, 8);
|
||||
put(out, at, v, 8);
|
||||
for (auto v : a.capacities)
|
||||
put(out, v, 8);
|
||||
put(out, at, v, 8);
|
||||
}
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
const auto& h = *ordered[i];
|
||||
put(out, h.receipt.command, 8);
|
||||
put(out, h.receipt.tick, 8);
|
||||
put(out, h.receipt.legs, 4);
|
||||
put(out, at, h.receipt.command, 8);
|
||||
put(out, at, h.receipt.tick, 8);
|
||||
put(out, at, h.receipt.legs, 4);
|
||||
for (const auto& l : std::span{h.legs}.first(h.receipt.legs)) {
|
||||
put(out, std::bit_cast<std::uint64_t>(l.voxel.x), 8);
|
||||
put(out, std::bit_cast<std::uint64_t>(l.voxel.y), 8);
|
||||
put(out, std::bit_cast<std::uint64_t>(l.voxel.z), 8);
|
||||
put(out, l.organism.value, 8);
|
||||
put(out, static_cast<std::uint8_t>(l.field), 1);
|
||||
put(out, static_cast<std::uint8_t>(l.direction), 1);
|
||||
put(out, l.amount, 8);
|
||||
put(out, at, std::bit_cast<std::uint64_t>(l.voxel.x), 8);
|
||||
put(out, at, std::bit_cast<std::uint64_t>(l.voxel.y), 8);
|
||||
put(out, at, std::bit_cast<std::uint64_t>(l.voxel.z), 8);
|
||||
put(out, at, l.organism.value, 8);
|
||||
put(out, at, static_cast<std::uint8_t>(l.field), 1);
|
||||
put(out, at, static_cast<std::uint8_t>(l.direction), 1);
|
||||
put(out, at, l.amount, 8);
|
||||
}
|
||||
}
|
||||
put(out, hash(out), 8);
|
||||
put(out, at, hash(std::span{out}.first(length - 8)), 8);
|
||||
if (at != length)
|
||||
return std::unexpected{TransferError::format};
|
||||
return out;
|
||||
}
|
||||
std::expected<std::unique_ptr<EnvironmentalTransfers>, TransferError>
|
||||
|
||||
@@ -183,3 +183,34 @@ EnvironmentalTransfers::commit(const EnvironmentalBatch& batch, const Environmen
|
||||
return history.receipt;
|
||||
}
|
||||
} // namespace evo::world
|
||||
|
||||
namespace evo::world {
|
||||
bool EnvironmentalTransfers::process_checkpoint(
|
||||
std::uint64_t tick, const std::array<std::uint64_t, 10>& environment,
|
||||
const std::array<std::uint64_t, 10>& producer,
|
||||
const std::array<std::uint64_t, 10>& consumer) noexcept {
|
||||
if (fields_->sites().size() != 1 || count_ != 2 || fields_->command_ == ceiling ||
|
||||
tick != fields_->command_ + 1)
|
||||
return false;
|
||||
accounting::Inventory sum{};
|
||||
for (std::size_t k = 0; k < 10; ++k) {
|
||||
if (!fields_->fields_[k].present || producer[k] > organisms_[0].capacities[k] ||
|
||||
consumer[k] > organisms_[1].capacities[k] || !accumulate(sum, k, environment[k]) ||
|
||||
!accumulate(sum, k, producer[k]) || !accumulate(sum, k, consumer[k]))
|
||||
return false;
|
||||
}
|
||||
if (environment[0] > fields_->water_capacity(0)->value || sum != totals())
|
||||
return false;
|
||||
for (std::size_t k = 0; k < 10; ++k) {
|
||||
fields_->fields_[k].baseline = environment[k];
|
||||
organisms_[0].balances[k] = producer[k];
|
||||
organisms_[1].balances[k] = consumer[k];
|
||||
}
|
||||
fields_->command_ = tick;
|
||||
adoption_command_ = tick;
|
||||
for (auto& entry : history_)
|
||||
entry.receipt = {};
|
||||
next_history_ = 0;
|
||||
return true;
|
||||
}
|
||||
} // namespace evo::world
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
#include "evo/processes/environmental_community.hpp"
|
||||
#include <cstdio>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
namespace {
|
||||
using namespace evo::world;
|
||||
using namespace evo::processes;
|
||||
void check(bool b, std::source_location at = std::source_location::current()) {
|
||||
if (!b)
|
||||
throw std::runtime_error("environmental community line " + std::to_string(at.line()));
|
||||
}
|
||||
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
|
||||
constexpr WorldIdentity identity{7, 9};
|
||||
EnvironmentalConfig config() {
|
||||
EnvironmentalConfig c;
|
||||
c.world = 7;
|
||||
c.frame = 9;
|
||||
c.producer = 1;
|
||||
c.consumer = 2;
|
||||
c.source = 3;
|
||||
c.tick_microseconds = 50000;
|
||||
c.area_um2 = 1;
|
||||
c.irradiance_numerator = 5;
|
||||
c.irradiance_denominator = 3;
|
||||
c.efficiency = 600;
|
||||
c.growth_cost = 3;
|
||||
c.recipe = {2, 4, 1, 1, 0};
|
||||
c.intake.fill(100);
|
||||
c.assimilation = 600;
|
||||
c.producer_min_mK = c.consumer_min_mK = 270000;
|
||||
c.producer_max_mK = c.consumer_max_mK = 310000;
|
||||
return c;
|
||||
}
|
||||
std::unique_ptr<EnvironmentalTransfers>
|
||||
resources(std::array<std::uint64_t, 10> e = {100, 100, 100, 100, 0, 0, 100, 0, 10, 0},
|
||||
std::array<std::uint64_t, 10> p = {}) {
|
||||
const FieldSite site{{0, 0, -16000}, {{0}, {0}, {0}, {10}, {20}, {3}}, {1}};
|
||||
std::array<FieldOpening, 10> opening{};
|
||||
for (std::size_t k = 0; k < 10; ++k)
|
||||
opening[k] = {static_cast<Field>(k), {&e[k], 1}};
|
||||
const FieldDefaults defaults{{evo::accounting::Femtograms{0}, evo::accounting::Femtograms{1000},
|
||||
evo::accounting::Femtograms{0}}};
|
||||
auto f = FieldStore::create(identity, 1, defaults, {&site, 1}, opening, 2000000);
|
||||
CHECK(f);
|
||||
auto t = ChunkStore::create({}, 1, 2000000, {{VolumeUnits{100}, VolumeUnits{100}}});
|
||||
CHECK(t);
|
||||
CHECK((*t)->load({0, 0, -1000}));
|
||||
std::array<OrganismResources, 2> accounts{};
|
||||
accounts[0].id = {1};
|
||||
accounts[1].id = {2};
|
||||
accounts[0].balances = p;
|
||||
for (auto& a : accounts)
|
||||
a.capacities.fill(1000);
|
||||
auto r =
|
||||
EnvironmentalTransfers::create(identity, std::move(*f), std::move(*t), accounts, 4000000);
|
||||
CHECK(r);
|
||||
return std::move(*r);
|
||||
}
|
||||
auto make(EnvironmentalConfig c = config()) {
|
||||
auto o = EnvironmentalCommunity::create(c, resources(), 8000000);
|
||||
CHECK(o);
|
||||
return std::move(*o);
|
||||
}
|
||||
|
||||
evo::accounting::Inventory audit(const EnvironmentalCommunity& o) {
|
||||
evo::accounting::Inventory sum{};
|
||||
constexpr std::array<std::size_t, 7> channel{3, 1, 2, 0, 1, 2, 3};
|
||||
for (std::size_t k = 0; k < 10; ++k) {
|
||||
auto amount = *o.resources().fields().read(0, static_cast<Field>(k));
|
||||
for (const auto& a : o.resources().organisms())
|
||||
amount += a.balances[k];
|
||||
if (k < 7)
|
||||
sum.matter[channel[k]].value += amount;
|
||||
else
|
||||
sum.energy.value += amount;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
void vectors() {
|
||||
auto o = make();
|
||||
const auto total = audit(*o);
|
||||
EnvironmentalInput in{290000, 1, {}};
|
||||
const std::array<std::uint64_t, 3> captured{1, 2, 2}, retained{0, 1, 2};
|
||||
for (std::uint64_t t = 1; t <= 3; ++t) {
|
||||
auto r = o->advance(t, in);
|
||||
CHECK(r);
|
||||
CHECK(r->captured == captured[t - 1] && r->retained == retained[t - 1]);
|
||||
CHECK(audit(*o) == total);
|
||||
}
|
||||
CHECK(o->progress().source_remainder == 0 && o->progress().efficiency_remainder == 0);
|
||||
auto c = config();
|
||||
c.growth_numerator = 2;
|
||||
std::array<std::uint64_t, 10> p{};
|
||||
p[7] = 10;
|
||||
auto growth =
|
||||
EnvironmentalCommunity::create(c, resources({4, 1, 2, 8, 0, 0, 0, 0, 0, 0}, p), 8000000);
|
||||
CHECK(growth);
|
||||
auto r = (*growth)->advance(1, {290000, 0, {}});
|
||||
CHECK(r && r->grown == 1 && r->unmet == 1);
|
||||
CHECK((*growth)->resources().organisms()[0].balances[0] == 2 &&
|
||||
(*growth)->resources().organisms()[0].balances[7] == 7);
|
||||
p = {};
|
||||
p[3] = 5;
|
||||
p[4] = 3;
|
||||
p[5] = 1;
|
||||
p[7] = 7;
|
||||
auto feed = EnvironmentalCommunity::create(config(), resources({}, p), 8000000);
|
||||
CHECK(feed);
|
||||
r = (*feed)->advance(1, {290000, 0, {5, 3, 1, 0, 7}});
|
||||
CHECK(r);
|
||||
CHECK(r->assimilated == std::array<std::uint64_t, 5>{3, 1, 0, 0, 4});
|
||||
CHECK(r->waste == std::array<std::uint64_t, 5>{2, 2, 1, 0, 3});
|
||||
CHECK(r->terminal_transition == 1);
|
||||
auto frozen = (*feed)->advance(2, in);
|
||||
CHECK(frozen && frozen->captured == 0);
|
||||
CHECK(!(*feed)->advance(3, {290000, 0, {1, 0, 0, 0, 0}}));
|
||||
}
|
||||
void rollback_limits() {
|
||||
auto c = config();
|
||||
c.growth_numerator = 1;
|
||||
auto o = make(c);
|
||||
auto before = o->snapshot();
|
||||
CHECK(before);
|
||||
CHECK(!o->advance(1, {290000, 1, {100, 0, 0, 0, 0}}));
|
||||
CHECK(o->snapshot() == before);
|
||||
CHECK(!o->advance(2, {290000, 1, {}}));
|
||||
CHECK(!o->advance(1, {0, 1, {}}));
|
||||
CHECK(!o->advance(1, {290000, 2, {}}));
|
||||
CHECK(o->snapshot() == before);
|
||||
EnvironmentalInput input{290000, 1, {}};
|
||||
auto report = o->advance(1, input);
|
||||
CHECK(report);
|
||||
auto after = o->snapshot();
|
||||
CHECK(o->advance(1, input) == report);
|
||||
input.source_enabled = 0;
|
||||
CHECK(!o->advance(1, input));
|
||||
CHECK(o->snapshot() == after);
|
||||
auto off = make();
|
||||
for (std::uint64_t t = 1; t < 5; ++t) {
|
||||
auto r = off->advance(t, {290000, 0, {}});
|
||||
CHECK(r && r->captured == 0);
|
||||
}
|
||||
CHECK(off->progress().source_remainder == 0);
|
||||
auto cold = make();
|
||||
CHECK(cold->advance(1, {269999, 1, {}})->captured == 0);
|
||||
CHECK(cold->advance(2, {270000, 1, {}})->captured == 1);
|
||||
CHECK(cold->advance(3, {310000, 1, {}})->captured == 2);
|
||||
CHECK(cold->advance(4, {310001, 1, {}})->captured == 0);
|
||||
auto exhausted = EnvironmentalCommunity::create(
|
||||
config(), resources({0, 0, 0, 0, 0, 0, 0, 0, 2, 0}), 8000000);
|
||||
CHECK(exhausted);
|
||||
CHECK((*exhausted)->advance(1, {290000, 1, {}}));
|
||||
auto progress = (*exhausted)->progress();
|
||||
auto r = (*exhausted)->advance(2, {290000, 1, {}});
|
||||
CHECK(r && r->source_status == 2);
|
||||
CHECK((*exhausted)->progress().source_remainder == progress.source_remainder &&
|
||||
(*exhausted)->progress().last_funded == 1);
|
||||
c = config();
|
||||
c.area_um2 = 201;
|
||||
CHECK(!EnvironmentalCommunity::create(c, resources(), 8000000));
|
||||
CHECK(!EnvironmentalCommunity::create(config(), resources(), 1));
|
||||
}
|
||||
void codec_replay() {
|
||||
for (std::uint64_t seed = 0; seed < 8; ++seed) {
|
||||
auto c = config();
|
||||
c.growth_numerator = 1;
|
||||
auto o = make(c);
|
||||
auto continuous = make(c);
|
||||
const auto total = audit(*o);
|
||||
for (std::uint64_t t = 1; t <= 90; ++t) {
|
||||
EnvironmentalInput input{290000, (t + seed) % 3 == 0 ? 0ULL : 1ULL, {}};
|
||||
auto r = o->advance(t, input);
|
||||
CHECK(continuous->advance(t, input) == r);
|
||||
CHECK(r);
|
||||
CHECK(audit(*o) == total);
|
||||
if (t == 17 || t == 65 || t == 90) {
|
||||
auto b = o->snapshot();
|
||||
CHECK(b);
|
||||
CHECK(continuous->snapshot() == b);
|
||||
auto restored = EnvironmentalCommunity::restore(*b, identity, 8000000);
|
||||
CHECK(restored);
|
||||
CHECK((*restored)->snapshot() == b);
|
||||
CHECK((*restored)->advance(t, input) == r);
|
||||
if (t > 64)
|
||||
CHECK(!(*restored)->advance(1, input));
|
||||
o = std::move(*restored);
|
||||
}
|
||||
}
|
||||
}
|
||||
auto tight_resources = resources();
|
||||
const auto tight_budget = sizeof(EnvironmentalCommunity) +
|
||||
2 * EnvironmentalCommunity::scratch_bytes +
|
||||
tight_resources->accounted_bytes();
|
||||
auto tight = EnvironmentalCommunity::create(config(), std::move(tight_resources), tight_budget);
|
||||
CHECK(tight);
|
||||
CHECK((*tight)->advance(1, {290000, 1, {}}));
|
||||
auto tight_bytes = (*tight)->snapshot();
|
||||
CHECK(tight_bytes);
|
||||
CHECK(EnvironmentalCommunity::restore(*tight_bytes, identity, tight_budget));
|
||||
auto o = make();
|
||||
auto initial = o->snapshot();
|
||||
CHECK(initial);
|
||||
CHECK(EnvironmentalCommunity::restore(*initial, identity, 8000000));
|
||||
CHECK(o->advance(1, {290000, 1, {}}));
|
||||
auto saved = o->snapshot();
|
||||
CHECK(saved);
|
||||
for (std::size_t n = 0; n < saved->size(); ++n)
|
||||
CHECK(!EnvironmentalCommunity::restore(std::span{*saved}.first(n), identity, 8000000));
|
||||
CHECK(!EnvironmentalCommunity::restore(*saved, {1, 2}, 8000000));
|
||||
CHECK(!EnvironmentalCommunity::restore(*saved, identity, 1));
|
||||
auto nested = o->resources().snapshot();
|
||||
CHECK(nested);
|
||||
CHECK(!EnvironmentalCommunity::restore(*nested, identity, 8000000));
|
||||
auto fix = [](WorldBytes& b) {
|
||||
std::uint64_t h = 14695981039346656037ULL;
|
||||
for (auto v : std::span{b}.first(b.size() - 8))
|
||||
h = (h ^ v) * 1099511628211ULL;
|
||||
for (unsigned i = 0; i < 8; ++i)
|
||||
b[b.size() - 8 + i] = static_cast<std::uint8_t>((h >> (8 * i)) & 255U);
|
||||
};
|
||||
for (std::size_t offset :
|
||||
{std::size_t{8}, std::size_t{24}, std::size_t{24 + 8 * 9}, std::size_t{24 + 29 * 8 + 8},
|
||||
std::size_t{24 + 29 * 8 + 6 * 8 + 36 * 8}, std::size_t{304}, std::size_t{664},
|
||||
saved->size() - 9}) {
|
||||
auto b = *saved;
|
||||
b[offset] = 255;
|
||||
fix(b);
|
||||
CHECK(!EnvironmentalCommunity::restore(b, identity, 8000000));
|
||||
}
|
||||
auto corrupted = *saved;
|
||||
corrupted[80] ^= 1;
|
||||
CHECK(!EnvironmentalCommunity::restore(corrupted, identity, 8000000));
|
||||
CHECK(o->snapshot() == saved);
|
||||
}
|
||||
} // namespace
|
||||
int main() {
|
||||
try {
|
||||
vectors();
|
||||
rollback_limits();
|
||||
codec_replay();
|
||||
return 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "%s\n", e.what());
|
||||
return 1;
|
||||
} catch (...) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user