Implement M6.5a coupled resource snapshots and restore
This commit is contained in:
+1
-1
@@ -34,7 +34,7 @@ target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in
|
|||||||
target_compile_features(evo_simulation PUBLIC cxx_std_23)
|
target_compile_features(evo_simulation PUBLIC cxx_std_23)
|
||||||
evo_owned_target(evo_simulation)
|
evo_owned_target(evo_simulation)
|
||||||
|
|
||||||
set(evo_world_sources src/world/coordinates.cpp src/world/generation.cpp src/world/chunks.cpp src/world/edits.cpp src/world/codec.cpp src/world/local_files.cpp src/world/environment_units.cpp src/world/fields.cpp src/world/environment.cpp src/world/transfers.cpp)
|
set(evo_world_sources src/world/coordinates.cpp src/world/generation.cpp src/world/chunks.cpp src/world/edits.cpp src/world/codec.cpp src/world/local_files.cpp src/world/environment_units.cpp src/world/fields.cpp src/world/environment.cpp src/world/transfers.cpp src/world/transfer_codec.cpp)
|
||||||
add_library(evo_world STATIC ${evo_world_sources})
|
add_library(evo_world STATIC ${evo_world_sources})
|
||||||
add_library(evo::world ALIAS evo_world)
|
add_library(evo::world ALIAS evo_world)
|
||||||
target_include_directories(evo_world PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
target_include_directories(evo_world PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||||
|
|||||||
@@ -440,3 +440,8 @@ M6.5 sequencing review: [ADR-0054](adr/0054-m65-source-persistence-prerequisite.
|
|||||||
is proposed because ADR-0051 requires persistence before rates while ADR-0053 defers
|
is proposed because ADR-0051 requires persistence before rates while ADR-0053 defers
|
||||||
coupled persistence to M6.8. Its recommended prerequisite and task breakdown are
|
coupled persistence to M6.8. Its recommended prerequisite and task breakdown are
|
||||||
pending scope confirmation; the M6.5 completion criteria above remain unchanged.
|
pending scope confirmation; the M6.5 completion criteria above remain unchanged.
|
||||||
|
|
||||||
|
Accepted 2026-09-27: ADR-0054 brings coupled snapshot/restore into M6.5. M6.5a's
|
||||||
|
resource codec is implemented; the earlier pending-scope statement is superseded.
|
||||||
|
Next are 6.5b conversions, 6.5c complete rate/biology persistence and fixture, and
|
||||||
|
6.5d qualification. M6.8 retains the full decomposition/regrowth ecology gate.
|
||||||
|
|||||||
@@ -663,3 +663,17 @@ minimal coupled buffer codec forward, preserving the earlier guarantee. The prop
|
|||||||
breaks M6.5 into codec, explicit biological conversion contract, rate-driven fixture,
|
breaks M6.5 into codec, explicit biological conversion contract, rate-driven fixture,
|
||||||
and qualification segments. No source-rate code or public interface changed in this
|
and qualification segments. No source-rate code or public interface changed in this
|
||||||
review; M6.5 remains incomplete. M6.4's validated behavior is unchanged.
|
review; M6.5 remains incomplete. M6.4's validated behavior is unchanged.
|
||||||
|
|
||||||
|
## Accepted M6.5 sequencing and M6.5a codec (2026-09-27)
|
||||||
|
|
||||||
|
The maintainer accepted ADR-0054: bring coupled snapshot/restore forward. This
|
||||||
|
supersedes the pending-decision status above. M6.5a now implements
|
||||||
|
[resource snapshot v1](../schemas/coupled-resources.md): terrain, finite fields,
|
||||||
|
organism accounts/capacities, adoption watermark and chronological full retry history
|
||||||
|
restore as one validated owner. Restore audits retained transfers backwards against
|
||||||
|
current balances and validates nested codecs and aggregate ownership/budgets.
|
||||||
|
|
||||||
|
Next: M6.5b explicit capture/growth/feeding conversion contract, followed by M6.5c's
|
||||||
|
complete source-rate/biology envelope and M6.5d qualification. No rates are enabled
|
||||||
|
by the resource codec; no source progress is invented during restore. M6.5 as a
|
||||||
|
whole remains incomplete. Durable publication and region recovery remain M7.
|
||||||
|
|||||||
@@ -75,3 +75,7 @@ Test last-nutrient contention, exact/changed/expired retries, stale/foreign view
|
|||||||
uncovered endpoints, capacity, overflow, peak budgets, late-leg rollback and independent
|
uncovered endpoints, capacity, overflow, peak budgets, late-leg rollback and independent
|
||||||
per-channel conservation. No account may progress offline via this primitive: biology
|
per-channel conservation. No account may progress offline via this primitive: biology
|
||||||
adapters must validate active lifecycle and permitted actions before submission.
|
adapters must validate active lifecycle and permitted actions before submission.
|
||||||
|
|
||||||
|
M6.5 amendment (2026-09-27): accepted ADR-0054 brings the coupled buffer codec
|
||||||
|
forward to M6.5a. This supersedes the deferral above; rate/biology progress must
|
||||||
|
join the aggregate before rate-driven execution in M6.5c. Durable publication stays M7.
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
# ADR-0054: M6.5 source persistence prerequisite
|
# ADR-0054: M6.5 source persistence prerequisite
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
Proposed, 2026-09-27. No rate-driven implementation is authorized by this proposal.
|
Accepted by the maintainer, 2026-09-27. Bring coupled snapshot/restore into M6.5.
|
||||||
M6.4 remains complete as a scoped in-memory transfer primitive. M6.5 is pending
|
M6.4 remains complete as a scoped in-memory transfer primitive. M6.5 follows the segments below and is not yet complete.
|
||||||
resolution of the prerequisite below, not complete.
|
|
||||||
|
|
||||||
## Context
|
## Context
|
||||||
The accepted contracts disagree about when coupled persistence is required:
|
The accepted contracts disagree about when coupled persistence is required:
|
||||||
@@ -29,7 +28,7 @@ The repository working agreement requires stopping affected implementation and
|
|||||||
proposing a resolution when architecture conflicts. This record exposes the mismatch
|
proposing a resolution when architecture conflicts. This record exposes the mismatch
|
||||||
rather than silently interpreting the later scope statement as superseding ADR-0051.
|
rather than silently interpreting the later scope statement as superseding ADR-0051.
|
||||||
|
|
||||||
## Decision (recommended, pending scope confirmation)
|
## Decision
|
||||||
Bring the minimal coupled binary-buffer snapshot/restore contract forward into the
|
Bring the minimal coupled binary-buffer snapshot/restore contract forward into the
|
||||||
M6.5 prerequisite. Keep durable filesystem publication and region crash recovery in
|
M6.5 prerequisite. Keep durable filesystem publication and region crash recovery in
|
||||||
M7; a canonical buffer codec is not a durable acknowledgment or fencing mechanism.
|
M7; a canonical buffer codec is not a durable acknowledgment or fencing mechanism.
|
||||||
@@ -99,6 +98,6 @@ Buffer round trips do not prove disk crash consistency, host-loss safety or regi
|
|||||||
ownership. Keep those delivery gates separate and unclaimed.
|
ownership. Keep those delivery gates separate and unclaimed.
|
||||||
|
|
||||||
## Consequences
|
## Consequences
|
||||||
After acceptance, revise the scoped ADR and roadmap references together before code.
|
Acceptance brings the minimal coupled codec forward; revise scoped references together.
|
||||||
Until then, do not enable rate integration, weaken persistence requirements, or report
|
Until complete rate/biology state is serialized, do not enable rate integration or report
|
||||||
M6.5 as implemented. Existing tests and deployed behavior remain unchanged.
|
M6.5 as implemented. Existing tests and deployed behavior remain unchanged.
|
||||||
|
|||||||
+1
-1
@@ -60,4 +60,4 @@ design. No unadopted candidate is a link dependency of the proof.
|
|||||||
- [ADR-0051: Optional environmental fields](0051-optional-environmental-fields.md) - accepted for M6.2 finite sparse pages, local transfers and field snapshot v1.
|
- [ADR-0051: Optional environmental fields](0051-optional-environmental-fields.md) - accepted for M6.2 finite sparse pages, local transfers and field snapshot v1.
|
||||||
- [ADR-0052: Environment views](0052-read-only-environment-views.md) - accepted for M6.3 bounded read-only footprint queries and freshness validation.
|
- [ADR-0052: Environment views](0052-read-only-environment-views.md) - accepted for M6.3 bounded read-only footprint queries and freshness validation.
|
||||||
- [ADR-0053: Atomic environmental transfers](0053-atomic-environmental-transfers.md) - accepted for M6.4 tagged resource ownership, atomic local batches and bounded exact retries.
|
- [ADR-0053: Atomic environmental transfers](0053-atomic-environmental-transfers.md) - accepted for M6.4 tagged resource ownership, atomic local batches and bounded exact retries.
|
||||||
- [ADR-0054: M6.5 source persistence prerequisite](0054-m65-source-persistence-prerequisite.md) - proposed resolution of rate-persistence versus M6.8 sequencing; not implemented.
|
- [ADR-0054: M6.5 source persistence prerequisite](0054-m65-source-persistence-prerequisite.md) - accepted: coupled codec brought forward into M6.5; M6.5a implemented, rate/biology envelope follows.
|
||||||
|
|||||||
@@ -192,3 +192,8 @@ stocks, terrain binding and tagged organism resource accounts. Fresh views autho
|
|||||||
only staged transfers; both endpoints and the retry receipt publish together after
|
only staged transfers; both endpoints and the retry receipt publish together after
|
||||||
validation and allocation. Accounts are resource endpoints; biological lifecycle
|
validation and allocation. Accounts are resource endpoints; biological lifecycle
|
||||||
integration follows in M6.5. Field-only snapshots cannot recover a coupled owner.
|
integration follows in M6.5. Field-only snapshots cannot recover a coupled owner.
|
||||||
|
|
||||||
|
M6.5a now provides [coupled resource snapshots](../../schemas/coupled-resources.md)
|
||||||
|
under accepted ADR-0054. This is a detached, bounded buffer codec; M7 still owns
|
||||||
|
file publication and durable acknowledgment. M6.5c must extend persistence to
|
||||||
|
source-rate and biological progress before enabling the corresponding simulation.
|
||||||
|
|||||||
@@ -1800,3 +1800,28 @@ ADRs 0050/0051 and 0053. ADR-0054 proposes a resolution; it is not accepted or
|
|||||||
implemented. `git diff --check` passed. No source, public API, test, schema or build
|
implemented. `git diff --check` passed. No source, public API, test, schema or build
|
||||||
configuration changed, so builds/sanitizers were not rerun for this proposal. The
|
configuration changed, so builds/sanitizers were not rerun for this proposal. The
|
||||||
M6.4 validation above remains historical evidence, not M6.5 completion evidence.
|
M6.4 validation above remains historical evidence, not M6.5 completion evidence.
|
||||||
|
|
||||||
|
## M6.5a coupled resource codec - 2026-09-27
|
||||||
|
|
||||||
|
ADR-0054 accepted by the maintainer. Added resource envelope v1 without changing
|
||||||
|
nested terrain/field formats or existing simulation goldens. Rates are still disabled;
|
||||||
|
source configuration/residuals and biology join the later M6.5c fixture envelope.
|
||||||
|
|
||||||
|
Executed Windows checks:
|
||||||
|
|
||||||
|
- Release check: 52/52 CTests passed with NDEBUG.
|
||||||
|
- Analysis check: clang-tidy/warnings-as-errors build and 52/52 CTests passed.
|
||||||
|
- ASan check: 52/52 CTests passed.
|
||||||
|
- After tightening restore to require all mapped chunks already in the snapshot,
|
||||||
|
Release and analysis rebuilt and environment-transfers-contracts passed again;
|
||||||
|
the ASan full run includes this final adjustment.
|
||||||
|
- Release format target passed.
|
||||||
|
|
||||||
|
Codec tests cover empty history, 66 transfers crossing the retry-ring boundary,
|
||||||
|
canonical restored bytes, exact/conflicting/expired retries, equivalent continuation,
|
||||||
|
all truncation lengths, checksum errors, recomputed-checksum invalid version/counts/
|
||||||
|
amounts, identity mismatch and each budget. Initial compilation caught missing codec
|
||||||
|
error enum entries; corrected before the passing runs above.
|
||||||
|
|
||||||
|
No Linux/UBSan/TSan, disk crash, allocation-failure injection or cluster validation
|
||||||
|
was performed locally. Buffer round trips are not durable publication. M6.5b-d remain.
|
||||||
|
|||||||
@@ -83,3 +83,8 @@ coupled world state. Tests exercise in-memory atomicity, not crash recovery.
|
|||||||
M6.5 biology adapters must validate active/alive status, capabilities, source budgets
|
M6.5 biology adapters must validate active/alive status, capabilities, source budgets
|
||||||
and biological costs. This resource endpoint abstraction neither implements metabolism
|
and biological costs. This resource endpoint abstraction neither implements metabolism
|
||||||
nor allows offline progression. Next: one producer/consumer fixture using this owner.
|
nor allows offline progression. Next: one producer/consumer fixture using this owner.
|
||||||
|
|
||||||
|
M6.5a amendment: accepted ADR-0054 brings a [coupled buffer codec](../../schemas/coupled-resources.md)
|
||||||
|
forward. `snapshot`/`restore` now save terrain, fields, accounts and full retry history
|
||||||
|
together. This supersedes the M6.8 resource-codec deferral above. No rate/biology
|
||||||
|
state exists yet; the later fixture must include it before enabling source integration.
|
||||||
|
|||||||
@@ -52,7 +52,10 @@ enum class TransferError : std::uint8_t {
|
|||||||
unknown_organism,
|
unknown_organism,
|
||||||
insufficient,
|
insufficient,
|
||||||
conflict,
|
conflict,
|
||||||
stale_command
|
stale_command,
|
||||||
|
format,
|
||||||
|
version,
|
||||||
|
checksum
|
||||||
};
|
};
|
||||||
class EnvironmentalTransfers {
|
class EnvironmentalTransfers {
|
||||||
public:
|
public:
|
||||||
@@ -76,6 +79,11 @@ class EnvironmentalTransfers {
|
|||||||
[[nodiscard]] std::span<const OrganismResources> organisms() const noexcept {
|
[[nodiscard]] std::span<const OrganismResources> organisms() const noexcept {
|
||||||
return std::span{organisms_}.first(count_);
|
return std::span{organisms_}.first(count_);
|
||||||
}
|
}
|
||||||
|
static constexpr std::size_t max_snapshot_bytes = std::size_t{72} * 1024 * 1024;
|
||||||
|
[[nodiscard]] std::expected<WorldBytes, TransferError> snapshot() const;
|
||||||
|
[[nodiscard]] static std::expected<std::unique_ptr<EnvironmentalTransfers>, TransferError>
|
||||||
|
restore(std::span<const std::uint8_t> bytes, WorldIdentity identity, std::size_t byte_budget,
|
||||||
|
std::size_t field_budget, std::size_t terrain_budget);
|
||||||
[[nodiscard]] accounting::Inventory totals() const noexcept;
|
[[nodiscard]] accounting::Inventory totals() const noexcept;
|
||||||
[[nodiscard]] std::size_t accounted_bytes() const noexcept;
|
[[nodiscard]] std::size_t accounted_bytes() const noexcept;
|
||||||
[[nodiscard]] std::expected<EnvironmentalReceipt, TransferError>
|
[[nodiscard]] std::expected<EnvironmentalReceipt, TransferError>
|
||||||
@@ -93,5 +101,6 @@ class EnvironmentalTransfers {
|
|||||||
std::array<OrganismResources, max_organisms> organisms_{};
|
std::array<OrganismResources, max_organisms> organisms_{};
|
||||||
std::array<History, retained_commands> history_{};
|
std::array<History, retained_commands> history_{};
|
||||||
std::size_t count_{}, budget_{}, next_history_{};
|
std::size_t count_{}, budget_{}, next_history_{};
|
||||||
|
std::uint64_t adoption_command_{};
|
||||||
};
|
};
|
||||||
} // namespace evo::world
|
} // namespace evo::world
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Coupled resource snapshot v1 (M6.5a)
|
||||||
|
|
||||||
|
Little endian, bounded to 72 MiB, corruption checksum FNV-1a-64 (not authentication).
|
||||||
|
No native layouts or pointers. Nested terrain and field codecs retain their versions.
|
||||||
|
This format has no source rates or biological process state: it must not be used to
|
||||||
|
resume a rate-enabled fixture. M6.5c requires a new complete fixture envelope.
|
||||||
|
|
||||||
|
Header: magic u64 0x31504c43564f4541, format u32=1, total length u32,
|
||||||
|
world u64, frame u64, adoption command watermark u64, account count u32,
|
||||||
|
history count u32, terrain payload length u32, field payload length u32.
|
||||||
|
Then terrain bytes, field bytes, accounts and chronological retained history;
|
||||||
|
finally checksum u64 over all preceding bytes.
|
||||||
|
Account: ID u64, ten u64 balances, ten u64 capacities (Field order).
|
||||||
|
History: command u64, tick u64, leg count u32; each leg is voxel x/y/z i64
|
||||||
|
(two's complement), organism ID u64, field u8, direction u8, amount u64.
|
||||||
|
No ring position or unused entries are serialized. Restore packs history in order.
|
||||||
|
|
||||||
|
Require 1..64 sorted unique accounts, 0..64 histories, 1..32 legs per history.
|
||||||
|
Commands strictly increase above adoption watermark; last equals the field command
|
||||||
|
(or adoption equals field command if empty). Validate every endpoint/tag/amount.
|
||||||
|
Reverse the retained legs from current stocks to verify supplies and capacities of
|
||||||
|
each prior state. This establishes plausible retained transfers, not authentic history.
|
||||||
|
Revalidate field/terrain identity and mapped substrate; all mapped chunks must be
|
||||||
|
present in the nested terrain snapshot. Query tokens never survive restore.
|
||||||
|
|
||||||
|
Restore receives total-owner, field and terrain budgets. Charge owner/scratch first,
|
||||||
|
then fields, then terrain under remaining total allowance. Input/output buffers and nested codec decode scratch
|
||||||
|
follow the existing codec exclusions; fixed reverse-audit scratch is bounded to 32KiB
|
||||||
|
and runs separately from transfer staging. Allocation failures propagate before any
|
||||||
|
returned owner. Failure leaves the caller's existing owner untouched.
|
||||||
|
|
||||||
|
Snapshot/restore are pure buffer operations with exclusive host access. They do not
|
||||||
|
publish files, fence duplicate processes or acknowledge durability. Tests must cover
|
||||||
|
canonical bytes, exact/changed retries after restore, continuation, ring wrap,
|
||||||
|
truncation/corruption, recomputed-checksum malformed state, identity and budgets.
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
#include "evo/world/transfers.hpp"
|
||||||
|
#include <algorithm>
|
||||||
|
#include <bit>
|
||||||
|
#include <limits>
|
||||||
|
namespace evo::world {
|
||||||
|
namespace {
|
||||||
|
constexpr std::uint64_t magic = 0x31504c43564f4541ULL;
|
||||||
|
void put(WorldBytes& b, std::uint64_t v, unsigned n) {
|
||||||
|
for (unsigned i = 0; i < n; ++i) {
|
||||||
|
b.push_back(static_cast<std::uint8_t>(v & 255U));
|
||||||
|
v >>= 8U;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::uint64_t hash(std::span<const std::uint8_t> b) {
|
||||||
|
std::uint64_t h = 14695981039346656037ULL;
|
||||||
|
for (auto v : b)
|
||||||
|
h = (h ^ v) * 1099511628211ULL;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
struct Reader {
|
||||||
|
std::span<const std::uint8_t> bytes;
|
||||||
|
std::size_t at{};
|
||||||
|
bool ok{true};
|
||||||
|
std::uint64_t get(unsigned n) {
|
||||||
|
if (n > bytes.size() - at) {
|
||||||
|
ok = false;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
std::uint64_t v{};
|
||||||
|
for (unsigned i = 0; i < n; ++i)
|
||||||
|
v |= std::uint64_t{bytes[at++]} << (8U * i);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
auto take(std::size_t n) {
|
||||||
|
if (n > bytes.size() - at) {
|
||||||
|
ok = false;
|
||||||
|
return std::span<const std::uint8_t>{};
|
||||||
|
}
|
||||||
|
auto s = bytes.subspan(at, n);
|
||||||
|
at += n;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
std::expected<WorldBytes, TransferError> EnvironmentalTransfers::snapshot() const {
|
||||||
|
auto terrain = terrain_->snapshot(fields_->identity());
|
||||||
|
if (!terrain)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
const auto fields = fields_->snapshot();
|
||||||
|
std::array<const History*, retained_commands> ordered{};
|
||||||
|
std::size_t count{};
|
||||||
|
for (const auto& h : history_)
|
||||||
|
if (h.receipt.command != 0)
|
||||||
|
ordered[count++] = &h;
|
||||||
|
std::sort(ordered.begin(), ordered.begin() + static_cast<std::ptrdiff_t>(count),
|
||||||
|
[](const auto* a, const auto* b) { return a->receipt.command < b->receipt.command; });
|
||||||
|
std::size_t length = 64 + terrain->size() + fields.size() + count_ * 168;
|
||||||
|
for (std::size_t i = 0; i < count; ++i)
|
||||||
|
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());
|
||||||
|
for (const auto& a : organisms()) {
|
||||||
|
put(out, a.id.value, 8);
|
||||||
|
for (auto v : a.balances)
|
||||||
|
put(out, v, 8);
|
||||||
|
for (auto v : a.capacities)
|
||||||
|
put(out, 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);
|
||||||
|
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, hash(out), 8);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
std::expected<std::unique_ptr<EnvironmentalTransfers>, TransferError>
|
||||||
|
EnvironmentalTransfers::restore(std::span<const std::uint8_t> bytes, WorldIdentity identity,
|
||||||
|
std::size_t budget, std::size_t field_budget,
|
||||||
|
std::size_t terrain_budget) {
|
||||||
|
if (bytes.size() < 64 || bytes.size() > max_snapshot_bytes)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
Reader r{bytes.first(bytes.size() - 8)}, tail{bytes.last(8)};
|
||||||
|
if (r.get(8) != magic)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
if (r.get(4) != 1)
|
||||||
|
return std::unexpected{TransferError::version};
|
||||||
|
if (r.get(4) != bytes.size())
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
if (hash(r.bytes) != tail.get(8))
|
||||||
|
return std::unexpected{TransferError::checksum};
|
||||||
|
if (WorldIdentity{r.get(8), r.get(8)} != identity || identity.world == 0 || identity.frame == 0)
|
||||||
|
return std::unexpected{TransferError::identity};
|
||||||
|
const auto adoption = r.get(8), count = r.get(4), records = r.get(4), terrain_length = r.get(4),
|
||||||
|
field_length = r.get(4);
|
||||||
|
if (count == 0 || count > max_organisms || records > retained_commands ||
|
||||||
|
terrain_length > max_world_snapshot_bytes || field_length > FieldStore::max_snapshot_bytes)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
const auto terrain_bytes = r.take(static_cast<std::size_t>(terrain_length));
|
||||||
|
const auto field_bytes = r.take(static_cast<std::size_t>(field_length));
|
||||||
|
if (!r.ok || count * 168 + records * 62 > r.bytes.size() - r.at)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
if (budget < sizeof(EnvironmentalTransfers) + scratch_bytes)
|
||||||
|
return std::unexpected{TransferError::budget};
|
||||||
|
const auto available = budget - sizeof(EnvironmentalTransfers) - scratch_bytes;
|
||||||
|
auto fields = FieldStore::restore(field_bytes, identity, std::min(field_budget, available));
|
||||||
|
if (!fields)
|
||||||
|
return std::unexpected{fields.error() == FieldError::budget ? TransferError::budget
|
||||||
|
: TransferError::format};
|
||||||
|
if ((*fields)->sites().size() > max_sites)
|
||||||
|
return std::unexpected{TransferError::config};
|
||||||
|
auto terrain =
|
||||||
|
ChunkStore::restore(terrain_bytes, identity,
|
||||||
|
std::min(terrain_budget, available - (*fields)->accounted_bytes()));
|
||||||
|
if (!terrain)
|
||||||
|
return std::unexpected{terrain.error() == WorldCodecError::budget ? TransferError::budget
|
||||||
|
: TransferError::format};
|
||||||
|
|
||||||
|
std::array<OrganismResources, max_organisms> accounts{};
|
||||||
|
for (auto& a : std::span{accounts}.first(static_cast<std::size_t>(count))) {
|
||||||
|
a.id = {r.get(8)};
|
||||||
|
for (auto& v : a.balances)
|
||||||
|
v = r.get(8);
|
||||||
|
for (auto& v : a.capacities)
|
||||||
|
v = r.get(8);
|
||||||
|
}
|
||||||
|
auto out = create(identity, std::move(*fields), std::move(*terrain),
|
||||||
|
std::span{accounts}.first(static_cast<std::size_t>(count)), budget);
|
||||||
|
if (!out)
|
||||||
|
return out;
|
||||||
|
auto& o = **out;
|
||||||
|
o.adoption_command_ = adoption;
|
||||||
|
std::uint64_t previous = adoption;
|
||||||
|
for (std::size_t i = 0; i < records; ++i) {
|
||||||
|
auto& h = o.history_[i];
|
||||||
|
h.receipt = {r.get(8), r.get(8), static_cast<std::size_t>(r.get(4))};
|
||||||
|
if (!r.ok || h.receipt.command <= previous || h.receipt.legs == 0 ||
|
||||||
|
h.receipt.legs > max_legs)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
previous = h.receipt.command;
|
||||||
|
for (auto& l : std::span{h.legs}.first(h.receipt.legs)) {
|
||||||
|
l.voxel = {std::bit_cast<std::int64_t>(r.get(8)), std::bit_cast<std::int64_t>(r.get(8)),
|
||||||
|
std::bit_cast<std::int64_t>(r.get(8))};
|
||||||
|
l.organism = {r.get(8)};
|
||||||
|
const auto field = r.get(1), direction = r.get(1);
|
||||||
|
l.amount = r.get(8);
|
||||||
|
if (!r.ok || field >= field_count || direction > 1 || l.amount == 0)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
l.field = static_cast<Field>(field);
|
||||||
|
l.direction = static_cast<ResourceDirection>(direction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!r.ok || r.at != r.bytes.size() || previous != o.fields_->last_command())
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
// Reverse retained history against current state: every predecessor must be possible.
|
||||||
|
std::array<std::array<std::uint64_t, max_sites>, field_count> values{};
|
||||||
|
const auto sites = o.fields_->sites();
|
||||||
|
for (std::size_t k = 0; k < field_count; ++k)
|
||||||
|
for (std::size_t j = 0; j < sites.size(); ++j) {
|
||||||
|
auto v = o.fields_->read(j, static_cast<Field>(k));
|
||||||
|
if (v)
|
||||||
|
values[k][j] = *v;
|
||||||
|
}
|
||||||
|
for (std::size_t n = static_cast<std::size_t>(records); n > 0; --n) {
|
||||||
|
const auto& h = o.history_[n - 1];
|
||||||
|
for (std::size_t m = h.receipt.legs; m > 0; --m) {
|
||||||
|
const auto& l = h.legs[m - 1];
|
||||||
|
const auto site =
|
||||||
|
std::lower_bound(sites.begin(), sites.end(), l.voxel,
|
||||||
|
[](const FieldSite& s, VoxelAddress v) { return s.voxel < v; });
|
||||||
|
const auto end = accounts.begin() + static_cast<std::ptrdiff_t>(count);
|
||||||
|
const auto a = std::lower_bound(
|
||||||
|
accounts.begin(), end, l.organism,
|
||||||
|
[](const OrganismResources& x, OrganismResourceId v) { return x.id < v; });
|
||||||
|
if (site == sites.end() || site->voxel != l.voxel || a == end || a->id != l.organism)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
const auto j = static_cast<std::size_t>(site - sites.begin()),
|
||||||
|
k = static_cast<std::size_t>(l.field);
|
||||||
|
if (!o.fields_->read(j, l.field))
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
const bool uptake = l.direction == ResourceDirection::to_organism;
|
||||||
|
auto& source = uptake ? a->balances[k] : values[k][j];
|
||||||
|
auto& destination = uptake ? values[k][j] : a->balances[k];
|
||||||
|
const auto cap =
|
||||||
|
uptake ? (l.field == Field::water ? o.fields_->water_capacity(j)->value
|
||||||
|
: std::numeric_limits<std::uint64_t>::max())
|
||||||
|
: a->capacities[k];
|
||||||
|
if (source < l.amount || l.amount > cap - destination)
|
||||||
|
return std::unexpected{TransferError::format};
|
||||||
|
source -= l.amount;
|
||||||
|
destination += l.amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.next_history_ = static_cast<std::size_t>(records) % retained_commands;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
} // namespace evo::world
|
||||||
@@ -58,6 +58,7 @@ EnvironmentalTransfers::create(WorldIdentity identity, std::unique_ptr<FieldStor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
auto owner = std::unique_ptr<EnvironmentalTransfers>(new EnvironmentalTransfers);
|
auto owner = std::unique_ptr<EnvironmentalTransfers>(new EnvironmentalTransfers);
|
||||||
|
owner->adoption_command_ = fields->last_command();
|
||||||
owner->fields_ = std::move(fields);
|
owner->fields_ = std::move(fields);
|
||||||
owner->terrain_ = std::move(terrain);
|
owner->terrain_ = std::move(terrain);
|
||||||
std::copy(organisms.begin(), organisms.end(), owner->organisms_.begin());
|
std::copy(organisms.begin(), organisms.end(), owner->organisms_.begin());
|
||||||
|
|||||||
@@ -183,6 +183,69 @@ void admission_budget() {
|
|||||||
v = view(**bounded);
|
v = view(**bounded);
|
||||||
CHECK(refused((*bounded)->commit({1, 1, {&a, 1}}, v, 1), TransferError::budget));
|
CHECK(refused((*bounded)->commit({1, 1, {&a, 1}}, v, 1), TransferError::budget));
|
||||||
}
|
}
|
||||||
|
void codec() {
|
||||||
|
auto o = owner();
|
||||||
|
for (std::uint64_t c = 1; c <= 66; ++c) {
|
||||||
|
auto v = view(*o, c);
|
||||||
|
auto a = leg(Field::water, 1);
|
||||||
|
if (c % 2 == 0)
|
||||||
|
a.direction = ResourceDirection::to_environment;
|
||||||
|
CHECK(o->commit({c, c, {&a, 1}}, v, c));
|
||||||
|
}
|
||||||
|
auto saved = o->snapshot();
|
||||||
|
CHECK(saved);
|
||||||
|
auto restored = EnvironmentalTransfers::restore(*saved, id, 4000000, 2000000, 2000000);
|
||||||
|
CHECK(restored);
|
||||||
|
CHECK((*restored)->snapshot() == saved);
|
||||||
|
CHECK(state(**restored) == state(*o));
|
||||||
|
auto v = view(**restored, 67);
|
||||||
|
auto a = leg(Field::water, 1);
|
||||||
|
a.direction = ResourceDirection::to_environment;
|
||||||
|
CHECK((*restored)->commit({66, 66, {&a, 1}}, v, 67));
|
||||||
|
a.amount = 2;
|
||||||
|
CHECK(refused((*restored)->commit({66, 66, {&a, 1}}, v, 67), TransferError::conflict));
|
||||||
|
CHECK(refused((*restored)->commit({1, 1, {&a, 1}}, v, 67), TransferError::stale_command));
|
||||||
|
a = leg(Field::nitrogen, 2);
|
||||||
|
auto original_view = view(*o, 67);
|
||||||
|
CHECK(o->commit({67, 67, {&a, 1}}, original_view, 67));
|
||||||
|
CHECK((*restored)->commit({67, 67, {&a, 1}}, v, 67));
|
||||||
|
CHECK(o->snapshot() == (*restored)->snapshot());
|
||||||
|
CHECK(refused(EnvironmentalTransfers::restore(*saved, {8, 9}, 4000000, 2000000, 2000000),
|
||||||
|
TransferError::identity));
|
||||||
|
CHECK(refused(EnvironmentalTransfers::restore(*saved, id, 1, 2000000, 2000000),
|
||||||
|
TransferError::budget));
|
||||||
|
CHECK(refused(EnvironmentalTransfers::restore(*saved, id, 4000000, 1, 2000000),
|
||||||
|
TransferError::budget));
|
||||||
|
CHECK(refused(EnvironmentalTransfers::restore(*saved, id, 4000000, 2000000, 1),
|
||||||
|
TransferError::budget));
|
||||||
|
auto empty = owner();
|
||||||
|
auto initial = empty->snapshot();
|
||||||
|
CHECK(initial);
|
||||||
|
auto fresh = EnvironmentalTransfers::restore(*initial, id, 4000000, 2000000, 2000000);
|
||||||
|
CHECK(fresh);
|
||||||
|
CHECK((*fresh)->snapshot() == initial);
|
||||||
|
for (std::size_t n = 0; n < saved->size(); ++n)
|
||||||
|
CHECK(!EnvironmentalTransfers::restore(std::span{*saved}.first(n), id, 4000000, 2000000,
|
||||||
|
2000000));
|
||||||
|
auto bad = *saved;
|
||||||
|
bad[60] ^= 1;
|
||||||
|
CHECK(refused(EnvironmentalTransfers::restore(bad, id, 4000000, 2000000, 2000000),
|
||||||
|
TransferError::checksum));
|
||||||
|
auto fix_hash = [](WorldBytes& bytes) {
|
||||||
|
std::uint64_t h = 14695981039346656037ULL;
|
||||||
|
for (auto b : std::span{bytes}.first(bytes.size() - 8))
|
||||||
|
h = (h ^ b) * 1099511628211ULL;
|
||||||
|
for (unsigned i = 0; i < 8; ++i)
|
||||||
|
bytes[bytes.size() - 8 + i] = static_cast<std::uint8_t>((h >> (8U * i)) & 255U);
|
||||||
|
};
|
||||||
|
for (auto offset : {std::size_t{8}, std::size_t{40}, std::size_t{44}, saved->size() - 9}) {
|
||||||
|
bad = *saved;
|
||||||
|
bad[offset] = 255;
|
||||||
|
fix_hash(bad);
|
||||||
|
CHECK(!EnvironmentalTransfers::restore(bad, id, 4000000, 2000000, 2000000));
|
||||||
|
}
|
||||||
|
CHECK((*restored)->snapshot() == o->snapshot());
|
||||||
|
}
|
||||||
void conservation_history() {
|
void conservation_history() {
|
||||||
auto o = owner();
|
auto o = owner();
|
||||||
const auto total = o->totals();
|
const auto total = o->totals();
|
||||||
@@ -214,6 +277,7 @@ void conservation_history() {
|
|||||||
} // namespace
|
} // namespace
|
||||||
int main() {
|
int main() {
|
||||||
try {
|
try {
|
||||||
|
codec();
|
||||||
atomicity();
|
atomicity();
|
||||||
rejection();
|
rejection();
|
||||||
admission_budget();
|
admission_budget();
|
||||||
|
|||||||
Reference in New Issue
Block a user