Round shares down and ages up, so a round trip never pays
M4.4 turns whole members of a cohort back into identified individuals, and does nothing else: no habitat transfer, no persistence, no resolution-equivalence claim. Materialization is instantaneous at the cohort's current tick, because advancing time is M4.3's interval. The named risk is that re-materialization becomes free healing, and it has two separable sources. The arithmetic one is closed outright. A drawn member gets its class share by integer division rounded down, because rounding up would create biomass, and a class drawn empty hands over everything it held because a class with no members may keep no reserve. A residual is never drawable, so an expected density cannot become an individual. Age is taken as the oldest the class admits. The exact age is unrecoverable, so the question is only which direction to be wrong in, and every other answer makes oscillation profitable: a member re-materialized at the bottom of its class is younger than it was, and repeating that is immortality. Taking the top means a round trip can only age someone. Both of these are the risk rather than ordinary validation, and both mutations are detected: rounding the share up, and drawing the age from the class floor. The second source is the declared resolution itself and is stated rather than mitigated. Members inside a class are indistinguishable by construction, so collapsing a starving member with a well-provisioned one and materializing both returns two average members, healing the first at the second's expense. The tests demonstrate both halves instead of only the flattering one: a round trip is exact when each class holds one member, and a coarse class conserves the total while averaging the individuals. Conservation of the total is not evidence that any individual is right, and the mitigation is the caller's choice of classes when it collapses, not anything this code can recover. Materialization produces exactly the record a collapse consumes, so the two compose and are tested against each other rather than described as inverses. The oscillation test runs twelve cycles and asserts every cycle that the conserved total never moves, nobody holds more than the richest starting member held, and nobody is younger than last cycle; it ends by asserting everyone has been pushed to a class ceiling, which records the cost of the age rule rather than claiming it away. Release 37/37, analysis, ASan 37/37 and clang-format all ran and passed here. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
+6
-1
@@ -47,7 +47,7 @@ target_link_libraries(evo_biology PUBLIC evo::accounting)
|
||||
target_compile_features(evo_biology PUBLIC cxx_std_23)
|
||||
evo_owned_target(evo_biology)
|
||||
|
||||
add_library(evo_ecology STATIC src/ecology/cohort.cpp src/ecology/collapse.cpp src/ecology/population.cpp)
|
||||
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")
|
||||
target_link_libraries(evo_ecology PUBLIC evo::accounting evo::biology)
|
||||
@@ -125,6 +125,11 @@ if(BUILD_TESTING)
|
||||
evo_owned_target(evo-population-tests)
|
||||
add_test(NAME population-contracts COMMAND evo-population-tests)
|
||||
set_tests_properties(population-contracts PROPERTIES TIMEOUT 120)
|
||||
add_executable(evo-materialize-tests tests/materialize_tests.cpp)
|
||||
target_link_libraries(evo-materialize-tests PRIVATE evo::ecology)
|
||||
evo_owned_target(evo-materialize-tests)
|
||||
add_test(NAME materialize-contracts COMMAND evo-materialize-tests)
|
||||
set_tests_properties(materialize-contracts PROPERTIES TIMEOUT 120)
|
||||
add_executable(evo-ledger-tests tests/ledger_tests.cpp)
|
||||
target_link_libraries(evo-ledger-tests PRIVATE evo::accounting)
|
||||
evo_owned_target(evo-ledger-tests)
|
||||
|
||||
@@ -131,6 +131,16 @@ cohort already holds. It amends ADR-0036 twice: a cohort records the reservoir
|
||||
backing it, and may be vacant, because a decline to exactly zero had to be
|
||||
representable.
|
||||
|
||||
M4.4 turns whole members back into individuals (ADR-0039). A drawn member gets its
|
||||
class share by integer division rounded down, because rounding up would create
|
||||
biomass, and a class drawn empty hands over everything it held rather than leaving
|
||||
a reserve nobody owns. A residual is never drawable: an expected density is not an
|
||||
available individual. Age is taken as the oldest the class admits, so a round trip
|
||||
can only age someone and oscillation is strictly lossy rather than a way to reset
|
||||
age. The smoothing the declared resolution causes is demonstrated rather than
|
||||
hidden: a round trip is exact when each class holds one member and averages within
|
||||
a coarse class, and the mitigation is the caller's choice of classes.
|
||||
|
||||
M3.6 closes M3 by making the pieces meet (ADR-0035): `strategy_for` turns a genome
|
||||
into the `StrategyConfig` the M2.6 driver already takes, founders are pre-diverged
|
||||
variants of one ancestor admitted to the archive, and `evo-sim --ensemble` runs
|
||||
|
||||
+34
-2
@@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged.
|
||||
## Completed implementation
|
||||
|
||||
- Vision, architectural pillars, risks, open-question register, architecture
|
||||
diagrams, biological contracts, engineering constitution and 38 ADRs.
|
||||
diagrams, biological contracts, engineering constitution and 39 ADRs.
|
||||
Proposed/deferred choices remain distinct from accepted proof decisions.
|
||||
- M0–M4 task breakdowns with dependencies, acceptance evidence and risks,
|
||||
plus M5–M14 gates in [ROADMAP.md](ROADMAP.md).
|
||||
@@ -61,7 +61,7 @@ for the bounded proof; the general production ECS remains a later measured choic
|
||||
|
||||
| Priority | Work | Completion evidence |
|
||||
|---|---|---|
|
||||
| 1 | M4.4 materialize representatives | Withdraw exact shares and residuals while preserving genome identity |
|
||||
| 1 | M4.5 validate resolution equivalence | Collapse 100, advance 10,000 ticks, materialize; conservation exact and distributions within a documented tolerance |
|
||||
| 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 |
|
||||
|
||||
@@ -416,3 +416,35 @@ with, since `TransferPopulation` does not exist. All fourteen guards, including
|
||||
both clamp mutations, were confirmed load-bearing by removing each and observing a
|
||||
failing run. Native Release, analysis, ASan and formatting passed 36/36; Linux CI
|
||||
has not run yet.
|
||||
|
||||
M4.4 turns whole members of a cohort back into identified individuals (ADR-0039),
|
||||
and does nothing else: no transfer between habitats, no persistence and no
|
||||
resolution-equivalence claim, which is M4.5. Materialization is instantaneous, at
|
||||
the cohort's current tick, because advancing time is M4.3's interval.
|
||||
|
||||
The named risk is that re-materialization becomes free healing, and it has two
|
||||
separable sources. The arithmetic one is closed outright: a drawn member receives
|
||||
its class share by integer division rounded down, because rounding up would create
|
||||
biomass, and a class drawn empty hands over everything it held because a class with
|
||||
no members may keep no reserve. A residual is never drawable, so an expected
|
||||
fractional density cannot become an individual. Age is taken as the oldest the
|
||||
class admits rather than the youngest or a seeded choice within it: the exact age
|
||||
is unrecoverable, so the question is which direction to be wrong in, and every
|
||||
other answer lets an adversary who picks when to convert roll back towards youth.
|
||||
A round trip can therefore only age someone, and oscillation is strictly lossy.
|
||||
|
||||
The second source is the declared resolution itself and is stated rather than
|
||||
mitigated. Members inside one class are indistinguishable by construction, so
|
||||
collapsing a starving member with a well-provisioned one and materializing both
|
||||
returns two average members; the starving one has been healed at the other's
|
||||
expense. The tests demonstrate both halves of this rather than only the flattering
|
||||
one: a round trip is exact when each class holds one member, and a coarse class
|
||||
conserves the total while averaging the individuals. The mitigation is the
|
||||
caller's choice of classes when it collapses, not anything this code can recover.
|
||||
|
||||
Materialization produces exactly the record a collapse consumes, so the two
|
||||
compose and are tested against each other instead of being described as inverses.
|
||||
Eleven guards were confirmed load-bearing by removing each and observing a failing
|
||||
run, including the two that are the risk itself: rounding shares up, and drawing
|
||||
ages from the bottom of a class. Native Release, analysis, ASan and formatting
|
||||
passed 37/37; Linux CI has not run yet.
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# ADR-0039: Materializing representatives without making a round trip profitable
|
||||
|
||||
## Status
|
||||
|
||||
Adopted for M4.4. It turns whole members of a cohort back into identified
|
||||
individuals and does nothing else: no transfer between habitats, no persistence,
|
||||
and no resolution-equivalence claim, which is M4.5. No M1 to M3 contract changes,
|
||||
and ADR-0036, ADR-0037 and ADR-0038 are unchanged.
|
||||
|
||||
## Context
|
||||
|
||||
M4.2 goes one way. Without the other, a collapsed cohort is a dead end and nothing
|
||||
can check that collapsing was faithful. The risk named for this step is that
|
||||
re-materialization becomes free healing, and ECOLOGY_MODEL adds the related
|
||||
prohibitions: a conversion may not reset age, injury, fertility or incubation, an
|
||||
expected fractional density is not an available individual, and materialization
|
||||
stays bounded by funded biomass.
|
||||
|
||||
Free healing has two quite different sources and they need separating. One is
|
||||
arithmetic: handing out more than is debited, or rounding a share upward. That is
|
||||
preventable outright. The other is the declared resolution itself: members inside
|
||||
one class are indistinguishable by construction, so collapsing a starving member
|
||||
together with a well-provisioned one and materializing both returns two average
|
||||
members. The starving one has been healed at the other's expense. No accounting
|
||||
can recover what the resolution discarded, and pretending otherwise would be worse
|
||||
than saying so.
|
||||
|
||||
## Decision
|
||||
|
||||
Materialization is instantaneous. It happens at the cohort's current tick and
|
||||
never advances it, because advancing time is ADR-0038's interval and this is not
|
||||
one. The revision still advances, so the registry's ordering rules apply
|
||||
unchanged.
|
||||
|
||||
Only whole members materialize. A residual is a fraction that is owed and not
|
||||
present, so it can never become an individual; it stays with the cohort. This is
|
||||
ECOLOGY_MODEL's rule that an expected fractional density differs from an available
|
||||
individual, enforced rather than described.
|
||||
|
||||
A drawn member receives its class's share, computed as integer division of the
|
||||
class reserve by the class count, per channel, rounded down. Rounding down is the
|
||||
whole point: rounding up would create biomass, and a share is never more than the
|
||||
class held. The remainder stays with the class, except where a class is drawn
|
||||
empty, in which case it hands over everything it held, one extra unit each to the
|
||||
first members, because a class with no members may not keep a reserve and leaving
|
||||
it would be biomass owned by nobody. A full draw therefore yields at most one unit
|
||||
per member more than a partial one; that is an ordering artifact, it is bounded by
|
||||
the class count, and it can never exceed what the class held.
|
||||
|
||||
Age is taken as the oldest the class admits, not the youngest and not a seeded
|
||||
choice within it. The exact age is not recoverable, so the question is which
|
||||
direction to be wrong in, and every other answer makes oscillation profitable: a
|
||||
member re-materialized at the bottom of its class is younger than it was, and
|
||||
repeating that is immortality. Taking the top means a round trip can only age
|
||||
someone. Oscillation is then strictly lossy in age rather than free, which is the
|
||||
behaviour to want from an exploit.
|
||||
|
||||
Conservation runs through the ledger, as in ADR-0037 and ADR-0038. One atomic
|
||||
transaction debits the cohort's reservoir and credits each member's, and each
|
||||
member's reservoir must be empty first, so a member's reserve is the whole of what
|
||||
backs it rather than a part sharing a store with inventory nobody counted. That is
|
||||
the same rule the destination of a collapse has.
|
||||
|
||||
What the resolution discards is stated, not mitigated. A round trip is exact when
|
||||
each class holds one member and smooths within a class otherwise, and the tests
|
||||
demonstrate both rather than only the flattering one. The available mitigation is
|
||||
the declared resolution itself: a caller that needs a member's own reserve
|
||||
preserved declares narrower classes when it collapses.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
Choosing an age with a seeded draw inside the class is what ECOLOGY_MODEL's
|
||||
"seeded rule" suggests for counts, and it is average-neutral, but it lets an
|
||||
adversary who controls when to convert re-roll towards youth; the conservative
|
||||
bound does not. Rounding shares to nearest would sometimes hand out more than was
|
||||
debited. Handing the remainder to the last drawn member rather than spreading it
|
||||
concentrates an arbitrary advantage. Refusing to draw a class empty unless its
|
||||
reserve divides exactly would make ordinary states unconvertible. Letting a
|
||||
fraction materialize as a member with a proportional share would turn an expected
|
||||
density into an individual, which the model forbids. Reconstructing a member's
|
||||
original reserve from provenance would require keeping per-member records, which
|
||||
is the individual representation a cohort exists to replace.
|
||||
|
||||
## Benefits
|
||||
|
||||
A round trip can never return more than was debited, in any channel, and never
|
||||
returns anyone younger. Materialization produces exactly the record a collapse
|
||||
consumes, so the two compose and can be tested against each other directly. The
|
||||
smoothing that the declared resolution causes is measurable and named rather than
|
||||
hidden, and a caller can eliminate it by choosing its classes.
|
||||
|
||||
## Costs
|
||||
|
||||
Round-tripping ages members by up to the width of their class, which is a real
|
||||
distortion in the conservative direction. A full draw yields slightly more per
|
||||
member than a partial one. Ages are drawn from class bounds, so repeated
|
||||
conversion pushes a population towards class ceilings. The caller supplies one
|
||||
empty reservoir per materialized member, which is bookkeeping it has to do. Nothing
|
||||
reconstructs injury, fertility or incubation, because a cohort never carried them.
|
||||
|
||||
## Risks
|
||||
|
||||
Materialization is not the inverse of collapse and this ADR does not claim it is.
|
||||
Within a class the two are lossy in both directions, and conservation of the total
|
||||
is not evidence that any individual is right; M4.5 is where matched ensembles are
|
||||
compared. The conservative age rule is a defence against oscillation, not a model
|
||||
of ageing, and it will make a population look older than it is under repeated
|
||||
conversion. A materialized member carries the cohort's genome and its provenance
|
||||
and nothing else, so it has no parentage, no history and no condition, and none of
|
||||
that may be invented later from a statistical membership. Ownership remains a
|
||||
single-process invariant and nothing is serialized.
|
||||
|
||||
## Consequences
|
||||
|
||||
Test that a drawn member receives the floor share and that the remainder stays
|
||||
with the class, that a class drawn empty hands over everything it held, and that
|
||||
neither a residual nor a fraction of a member can be drawn. Test that ages come
|
||||
from the top of the class and that a round trip never returns anyone younger. Test
|
||||
that a round trip is exact when each class holds one member, and that with a
|
||||
coarse class the total is conserved while individual reserves are smoothed, so the
|
||||
loss is demonstrated rather than implied absent. Test repeated oscillation over
|
||||
many cycles: the conserved total never moves, no member ever holds more than the
|
||||
largest starting member held, and ages never decrease. Test scarcity, where a
|
||||
class holding nothing materializes members holding nothing rather than refusing or
|
||||
inventing. Test that drawing more than a class holds, an unknown or repeated class,
|
||||
a reservoir that is not empty, a repeated reservoir, a stale view and a wrong owner
|
||||
are each refused, and that every rejection leaves the ledger and the registry
|
||||
unchanged. No genome schema, mutation catalog, archive, ledger, episode driver,
|
||||
ensemble, cohort record, collapse, interval accounting, renderer or deployment
|
||||
changes.
|
||||
@@ -31,6 +31,7 @@ Each record has the eight required sections.
|
||||
0036 defines the tier 2 cohort, its declared resolution and exclusive ownership.
|
||||
0037 collapses individuals into a cohort as one sampled, ledger-exact transaction.
|
||||
0038 accounts a proposed interval, refusing rather than clamping, without picking a model.
|
||||
0039 materializes representatives on shares that round down and ages that never fall.
|
||||
|
||||
Every dependency adoption records exact version/commit and integrity hash,
|
||||
transitive license obligations, maintenance/security review, owner and removal
|
||||
|
||||
@@ -227,3 +227,38 @@ structure is supplied by the caller and is not verified to be what ageing would
|
||||
produce, because ageing across a class boundary needs the within-class
|
||||
distribution the declared resolution discards. And emigration escrows into a
|
||||
reservoir nothing settles with, because `TransferPopulation` does not exist.
|
||||
|
||||
## Implemented M4.4 materialization
|
||||
|
||||
[ADR-0039](../adr/0039-materialize-representatives.md) implements
|
||||
`PlanMaterialize` and `CommitMaterialize` for one cohort in one process.
|
||||
`TransferPopulation` remains a contract nothing implements, and no
|
||||
resolution-equivalence claim is made here.
|
||||
|
||||
Representatives are debited cohort shares, as this document requires, and never
|
||||
anything else. A drawn member receives its class share by integer division rounded
|
||||
down; rounding up would create biomass. A class drawn empty hands over everything
|
||||
it held, because a class with no members may keep no reserve. A residual is never
|
||||
drawable, so an expected fractional density stays distinct from an available
|
||||
individual.
|
||||
|
||||
Age is carried, not reset, in the only direction that is safe when the exact value
|
||||
is unrecoverable: a member materializes at the oldest age its class admits. Every
|
||||
other rule lets an adversary who chooses when to convert roll back towards youth,
|
||||
and repeating that is immortality. A round trip can therefore only age someone, so
|
||||
oscillation is strictly lossy rather than free. This is a defence, not a model of
|
||||
ageing, and under repeated conversion it will make a population look older than it
|
||||
is.
|
||||
|
||||
What the declared resolution discards is stated rather than mitigated. Within one
|
||||
class members are indistinguishable, so collapsing a starving member together with
|
||||
a well-provisioned one and materializing both returns two average members, healing
|
||||
the first at the second's expense. Conservation of the total is not evidence that
|
||||
any individual is right. A round trip is exact when each class holds one member,
|
||||
and the mitigation available to a caller is to declare narrower classes when it
|
||||
collapses; nothing here can recover what a coarse class threw away.
|
||||
|
||||
A materialized member carries the cohort's genome, its habitat and a fresh
|
||||
identity, and nothing else. It has no parentage, no history and no condition,
|
||||
because a cohort never carried them, and none of that may later be invented from a
|
||||
statistical membership.
|
||||
|
||||
@@ -1134,3 +1134,61 @@ The proof golden `d61ad5bf0c928c76`, the ecosystem fingerprint
|
||||
genome fixture are unchanged, and the other 33 tests pass untouched. No deployment
|
||||
manifest or image pin changed. Linux validation is pending; no Gitea result is
|
||||
claimed since `b01a824`.
|
||||
|
||||
## M4.4 materialization
|
||||
|
||||
Executed on this Windows host (2026-09-24): Release configure, build and `ctest`
|
||||
37/37; the analysis preset (clang-tidy 19, warnings as errors) built clean; the
|
||||
ASan preset configured, built and ran 37/37; `clang-format` 19.1.5 reported no
|
||||
violations. All four checks ran and passed on the committed tree. No Clang or GCC
|
||||
compile happens on this host, so Linux CI remains the first such result.
|
||||
|
||||
`evo-materialize-tests` covers ten properties: that a drawn member receives the
|
||||
floor share while the rounding remainder stays with the class, that a class drawn
|
||||
empty hands over everything it held, that neither a residual nor a member that is
|
||||
not there can be drawn, that taking everyone leaves a vacant record rather than an
|
||||
extinction, that ages come from the top of a class and are stable when regathered,
|
||||
that a round trip is exact at one member per class, that a coarse class conserves
|
||||
the total while smoothing individuals, that repeated oscillation never pays, that
|
||||
malformed draws and stale views are refused without changing anything, and that a
|
||||
moved-from plan is whole.
|
||||
|
||||
The oscillation test runs twelve collapse and materialize cycles over three
|
||||
members of unequal reserve and asserts three things every cycle: the ledger's
|
||||
conserved total never moves, no member ever holds more than the largest starting
|
||||
member held, and no member is younger than the corresponding member of the
|
||||
previous cycle. Those three together are what stops a round trip being a way to
|
||||
heal or to reset age. It also ends by asserting every member has been pushed to a
|
||||
class ceiling, which records the cost of the conservative age rule rather than
|
||||
leaving it as a claim.
|
||||
|
||||
Eleven guards were confirmed load-bearing by removing each in turn and rerunning.
|
||||
Two of them are the named risk rather than ordinary validation, and both are
|
||||
detected: rounding the share up instead of down, which creates biomass, and
|
||||
drawing ages from the bottom of the class instead of the top, which returns
|
||||
members younger than they were and makes oscillation profitable.
|
||||
|
||||
The free-healing risk has two sources and only one is closed. The arithmetic
|
||||
source is prevented outright and tested. The other is the declared resolution
|
||||
itself: within a class members are indistinguishable, so a coarse class heals a
|
||||
starving member at a well-provisioned member's expense while conserving the total
|
||||
exactly. That is not fixable by accounting and is asserted rather than avoided,
|
||||
with a companion test showing a round trip is exact when each class holds one
|
||||
member. Reading conservation of the total as evidence that any individual is right
|
||||
would be a mistake this pair of tests exists to prevent.
|
||||
|
||||
Coverage limits. Materialization is not claimed to be the inverse of collapse and
|
||||
no test asserts that it is beyond the one-member-per-class case. Nothing checks
|
||||
that a proposed draw is ecologically sensible. A full draw yields at most one unit
|
||||
per member more than a partial one, which is an ordering artifact bounded by the
|
||||
class count and is not separately tested at every count. Injury, fertility and
|
||||
incubation are not reconstructed because a cohort never carried them. Ownership
|
||||
remains a single-process invariant, emigration escrow is still unsettled, and
|
||||
nothing is serialized. The overflow and ledger-failure branches are reachable only
|
||||
past bounds the tests do not build.
|
||||
|
||||
No existing behaviour changed. The proof golden `d61ad5bf0c928c76`, the ecosystem
|
||||
fingerprint `2cd4a15f9fbe9949`, the ensemble fingerprint `5ec59d390909b526` and
|
||||
the frozen genome fixture are unchanged, and the other 36 tests pass untouched. No
|
||||
deployment manifest or image pin changed. Linux validation is pending; no Gitea
|
||||
result is claimed since `b01a824`.
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/ecology/collapse.hpp"
|
||||
|
||||
namespace evo::ecology {
|
||||
// How many whole members to draw from one class. A residual is a fraction that is
|
||||
// owed and not present, so it is never drawable: an expected density is not an
|
||||
// available individual.
|
||||
struct ClassDraw {
|
||||
std::size_t age_class{};
|
||||
std::uint64_t count{};
|
||||
auto operator<=>(const ClassDraw&) const = default;
|
||||
};
|
||||
|
||||
struct MaterializeRequest {
|
||||
Owner owner{};
|
||||
std::uint64_t revision{};
|
||||
std::vector<ClassDraw> draws;
|
||||
// Identities are assigned in draw order from here. Materialization invents
|
||||
// identity and nothing else: no parentage, no history, no condition.
|
||||
std::uint64_t first_identity{};
|
||||
// One per member to be drawn, in draw order. Each must be empty when the plan
|
||||
// is committed, so a member's reserve is the whole of what backs it rather
|
||||
// than a part sharing a store with inventory nobody counted.
|
||||
std::vector<accounting::ReservoirId> reservoirs;
|
||||
ApproximationBound bound{};
|
||||
};
|
||||
|
||||
enum class MaterializeError : std::uint8_t {
|
||||
invalid_request,
|
||||
nothing_drawn,
|
||||
unknown_age_class,
|
||||
duplicate_age_class,
|
||||
insufficient_members,
|
||||
reservoir_mismatch,
|
||||
duplicate_reservoir,
|
||||
wrong_owner,
|
||||
stale_revision,
|
||||
overflow,
|
||||
invalid_cohort,
|
||||
not_installed,
|
||||
stale_plan,
|
||||
reservoir_not_empty,
|
||||
ledger_failure
|
||||
};
|
||||
|
||||
// The draw, decided once. Copy-only for the reason a cohort is: a moved-from plan
|
||||
// would keep its identities while losing its legs and its members.
|
||||
class MaterializePlan {
|
||||
public:
|
||||
MaterializePlan(const MaterializePlan&) = default;
|
||||
MaterializePlan& operator=(const MaterializePlan&) = default;
|
||||
|
||||
[[nodiscard]] const Cohort& before() const noexcept {
|
||||
return before_;
|
||||
}
|
||||
// The cohort after the draw is debited. Vacant if every member was taken and
|
||||
// nothing is owed: vacancy is not extinction, and the record stays.
|
||||
[[nodiscard]] const Cohort& after() const noexcept {
|
||||
return after_;
|
||||
}
|
||||
// Exactly what a collapse consumes, so the two compose and can be checked
|
||||
// against each other rather than only described as inverses.
|
||||
[[nodiscard]] std::span<const ActiveMember> members() const noexcept {
|
||||
return members_;
|
||||
}
|
||||
[[nodiscard]] std::span<const accounting::Transfer> legs() const noexcept {
|
||||
return legs_;
|
||||
}
|
||||
[[nodiscard]] accounting::Inventory withdrawn() const noexcept {
|
||||
return withdrawn_;
|
||||
}
|
||||
|
||||
auto operator<=>(const MaterializePlan&) const = default;
|
||||
|
||||
private:
|
||||
friend std::expected<MaterializePlan, MaterializeError>
|
||||
plan_materialize(const Cohort&, const MaterializeRequest&);
|
||||
MaterializePlan(const Cohort& before, const Cohort& after) : before_{before}, after_{after} {}
|
||||
Cohort before_;
|
||||
Cohort after_;
|
||||
std::vector<ActiveMember> members_;
|
||||
std::vector<accounting::Transfer> legs_;
|
||||
accounting::Inventory withdrawn_{};
|
||||
};
|
||||
|
||||
// Decides the whole draw without touching any ledger or registry. Instantaneous:
|
||||
// it happens at the cohort's current tick and never advances it, because
|
||||
// advancing time is ADR-0038's interval and this is not one.
|
||||
[[nodiscard]] std::expected<MaterializePlan, MaterializeError>
|
||||
plan_materialize(const Cohort& before, const MaterializeRequest& request);
|
||||
|
||||
// Applies exactly that plan. The installed record must still be the one the plan
|
||||
// started from and every destination reservoir must be empty, so no rejection can
|
||||
// leave the cohort debited with nobody holding what it gave up.
|
||||
[[nodiscard]] std::expected<std::vector<ActiveMember>, MaterializeError>
|
||||
commit_materialize(accounting::Ledger& ledger, CohortRegistry& registry,
|
||||
const MaterializePlan& plan);
|
||||
} // namespace evo::ecology
|
||||
@@ -0,0 +1,235 @@
|
||||
#include "evo/ecology/materialize.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
|
||||
namespace evo::ecology {
|
||||
namespace {
|
||||
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
||||
|
||||
[[nodiscard]] bool add(std::uint64_t& total, std::uint64_t amount) noexcept {
|
||||
if (amount > maximum - total) {
|
||||
return false;
|
||||
}
|
||||
total += amount;
|
||||
return true;
|
||||
}
|
||||
[[nodiscard]] bool add(accounting::Inventory& total, const accounting::Inventory& amount) noexcept {
|
||||
if (!add(total.energy.value, amount.energy.value)) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t channel = 0; channel < total.matter.size(); ++channel) {
|
||||
if (!add(total.matter[channel].value, amount.matter[channel].value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
[[nodiscard]] bool empty(const accounting::Inventory& inventory) noexcept {
|
||||
return inventory == accounting::Inventory{};
|
||||
}
|
||||
// What one member of a class is entitled to: the class reserve divided by the
|
||||
// class count, per channel, rounded down. Rounding up would create biomass.
|
||||
[[nodiscard]] accounting::Inventory share_of(const AgeClass& age) noexcept {
|
||||
accounting::Inventory share{};
|
||||
share.energy.value = age.reserve.energy.value / age.count;
|
||||
for (std::size_t channel = 0; channel < share.matter.size(); ++channel) {
|
||||
share.matter[channel].value = age.reserve.matter[channel].value / age.count;
|
||||
}
|
||||
return share;
|
||||
}
|
||||
// What rounding down left behind, per channel, strictly less than the count.
|
||||
[[nodiscard]] accounting::Inventory remainder_of(const AgeClass& age) noexcept {
|
||||
accounting::Inventory left{};
|
||||
left.energy.value = age.reserve.energy.value % age.count;
|
||||
for (std::size_t channel = 0; channel < left.matter.size(); ++channel) {
|
||||
left.matter[channel].value = age.reserve.matter[channel].value % age.count;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::expected<MaterializePlan, MaterializeError>
|
||||
plan_materialize(const Cohort& before, const MaterializeRequest& request) {
|
||||
if (request.owner.worker == 0 || request.owner.epoch == 0 || request.revision == 0 ||
|
||||
request.first_identity == 0) {
|
||||
return std::unexpected{MaterializeError::invalid_request};
|
||||
}
|
||||
if (request.owner.worker != before.owner().worker) {
|
||||
return std::unexpected{MaterializeError::wrong_owner};
|
||||
}
|
||||
if (request.owner.epoch < before.owner().epoch) {
|
||||
return std::unexpected{MaterializeError::stale_revision};
|
||||
}
|
||||
if (request.owner.epoch == before.owner().epoch && request.revision <= before.revision()) {
|
||||
return std::unexpected{MaterializeError::stale_revision};
|
||||
}
|
||||
if (request.draws.empty()) {
|
||||
return std::unexpected{MaterializeError::nothing_drawn};
|
||||
}
|
||||
|
||||
auto classes = std::vector<AgeClass>{before.classes().begin(), before.classes().end()};
|
||||
std::vector<std::size_t> seen;
|
||||
std::uint64_t drawn = 0;
|
||||
for (const auto& draw : request.draws) {
|
||||
if (draw.age_class >= classes.size()) {
|
||||
return std::unexpected{MaterializeError::unknown_age_class};
|
||||
}
|
||||
if (std::ranges::find(seen, draw.age_class) != seen.end()) {
|
||||
return std::unexpected{MaterializeError::duplicate_age_class};
|
||||
}
|
||||
seen.push_back(draw.age_class);
|
||||
if (draw.count == 0) {
|
||||
return std::unexpected{MaterializeError::nothing_drawn};
|
||||
}
|
||||
// Only whole members present in the class. A residual is owed and not
|
||||
// there, so it can never become an individual.
|
||||
if (draw.count > classes[draw.age_class].count) {
|
||||
return std::unexpected{MaterializeError::insufficient_members};
|
||||
}
|
||||
if (!add(drawn, draw.count)) {
|
||||
return std::unexpected{MaterializeError::overflow};
|
||||
}
|
||||
}
|
||||
if (request.reservoirs.size() != drawn) {
|
||||
return std::unexpected{MaterializeError::reservoir_mismatch};
|
||||
}
|
||||
if (drawn > accounting::max_transfers) {
|
||||
return std::unexpected{MaterializeError::overflow};
|
||||
}
|
||||
for (std::size_t index = 0; index < request.reservoirs.size(); ++index) {
|
||||
const auto where = request.reservoirs[index];
|
||||
if (where.value == 0 || where == before.reservoir()) {
|
||||
return std::unexpected{MaterializeError::invalid_request};
|
||||
}
|
||||
if (std::ranges::find(request.reservoirs.begin() + static_cast<std::ptrdiff_t>(index) + 1,
|
||||
request.reservoirs.end(), where) != request.reservoirs.end()) {
|
||||
return std::unexpected{MaterializeError::duplicate_reservoir};
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ActiveMember> members;
|
||||
std::vector<accounting::Transfer> legs;
|
||||
members.reserve(drawn);
|
||||
legs.reserve(drawn);
|
||||
accounting::Inventory withdrawn{};
|
||||
std::uint64_t identity = request.first_identity;
|
||||
std::size_t next_reservoir = 0;
|
||||
for (const auto& draw : request.draws) {
|
||||
auto& age = classes[draw.age_class];
|
||||
const auto share = share_of(age);
|
||||
// A class drawn empty hands over everything it held: a class with no
|
||||
// members may keep no reserve, and leaving it would be biomass nobody
|
||||
// owns. The rounding remainder goes one unit each to the first members.
|
||||
const auto emptied = draw.count == age.count;
|
||||
const auto left = emptied ? remainder_of(age) : accounting::Inventory{};
|
||||
for (std::uint64_t index = 0; index < draw.count; ++index) {
|
||||
auto reserve = share;
|
||||
if (emptied) {
|
||||
if (index < left.energy.value) {
|
||||
++reserve.energy.value;
|
||||
}
|
||||
for (std::size_t channel = 0; channel < reserve.matter.size(); ++channel) {
|
||||
if (index < left.matter[channel].value) {
|
||||
++reserve.matter[channel].value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (identity == 0 || !add(withdrawn, reserve)) {
|
||||
return std::unexpected{MaterializeError::overflow};
|
||||
}
|
||||
members.push_back({identity, before.genome(), before.habitat(),
|
||||
// The oldest the class admits. The exact age is not
|
||||
// recoverable, and every other choice lets a round
|
||||
// trip return someone younger than they were.
|
||||
age.age_high - 1, request.reservoirs[next_reservoir], reserve,
|
||||
MemberState::active});
|
||||
legs.push_back({before.reservoir(), request.reservoirs[next_reservoir], reserve});
|
||||
++next_reservoir;
|
||||
if (identity == maximum) {
|
||||
return std::unexpected{MaterializeError::overflow};
|
||||
}
|
||||
++identity;
|
||||
}
|
||||
age.count -= draw.count;
|
||||
if (emptied) {
|
||||
age.reserve = {};
|
||||
} else {
|
||||
age.reserve.energy.value -= share.energy.value * draw.count;
|
||||
for (std::size_t channel = 0; channel < age.reserve.matter.size(); ++channel) {
|
||||
age.reserve.matter[channel].value -= share.matter[channel].value * draw.count;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A class with neither members nor an owed fraction is not a class any more.
|
||||
std::erase_if(classes, [](const AgeClass& age) { return age.count == 0 && age.residual == 0; });
|
||||
|
||||
CohortDraft draft;
|
||||
draft.representation_version = before.representation_version();
|
||||
draft.habitat = before.habitat();
|
||||
draft.genome = before.genome();
|
||||
draft.owner = request.owner;
|
||||
// Instantaneous: the clock is ADR-0038's business and this is not an interval.
|
||||
draft.last_tick = before.last_tick();
|
||||
draft.revision = request.revision;
|
||||
draft.conversion = before.conversion();
|
||||
draft.reservoir = before.reservoir();
|
||||
draft.classes = classes;
|
||||
draft.bound = request.bound;
|
||||
const auto built = classes.empty() ? Cohort::vacant(draft) : Cohort::create(std::move(draft));
|
||||
if (!built) {
|
||||
return std::unexpected{MaterializeError::invalid_cohort};
|
||||
}
|
||||
MaterializePlan plan{before, *built};
|
||||
plan.members_ = std::move(members);
|
||||
plan.legs_ = std::move(legs);
|
||||
plan.withdrawn_ = withdrawn;
|
||||
return plan;
|
||||
}
|
||||
|
||||
std::expected<std::vector<ActiveMember>, MaterializeError>
|
||||
commit_materialize(accounting::Ledger& ledger, CohortRegistry& registry,
|
||||
const MaterializePlan& plan) {
|
||||
const auto& before = plan.before();
|
||||
const auto installed = registry.find(before.habitat(), before.genome());
|
||||
if (!installed) {
|
||||
return std::unexpected{MaterializeError::not_installed};
|
||||
}
|
||||
if (*installed != before) {
|
||||
return std::unexpected{MaterializeError::stale_plan};
|
||||
}
|
||||
const auto balances = ledger.balances();
|
||||
if (before.reservoir().value > balances.size()) {
|
||||
return std::unexpected{MaterializeError::stale_plan};
|
||||
}
|
||||
if (balances[before.reservoir().value - 1] != before.reserve()) {
|
||||
return std::unexpected{MaterializeError::stale_plan};
|
||||
}
|
||||
// Each member's store must be empty first, so its reserve is the whole of
|
||||
// what backs it rather than a part sharing a reservoir with inventory nobody
|
||||
// counted. This is the rule a collapse destination has, from the other side.
|
||||
for (const auto& member : plan.members()) {
|
||||
if (member.reservoir.value > balances.size()) {
|
||||
return std::unexpected{MaterializeError::stale_plan};
|
||||
}
|
||||
if (!empty(balances[member.reservoir.value - 1])) {
|
||||
return std::unexpected{MaterializeError::reservoir_not_empty};
|
||||
}
|
||||
}
|
||||
if (!plan.legs().empty()) {
|
||||
if (ledger.last_action() == maximum) {
|
||||
return std::unexpected{MaterializeError::ledger_failure};
|
||||
}
|
||||
if (!ledger.transfer(ledger.last_action() + 1, plan.legs())) {
|
||||
return std::unexpected{MaterializeError::ledger_failure};
|
||||
}
|
||||
}
|
||||
// Proved above to be a strictly later view of the installed record, so this
|
||||
// cannot fail and nothing can be stranded between the two steps.
|
||||
if (!registry.replace(plan.after())) {
|
||||
return std::unexpected{MaterializeError::stale_plan};
|
||||
}
|
||||
return std::vector<ActiveMember>{plan.members().begin(), plan.members().end()};
|
||||
}
|
||||
} // namespace evo::ecology
|
||||
@@ -0,0 +1,487 @@
|
||||
#include "evo/ecology/materialize.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <expected>
|
||||
#include <iostream>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace evo::ecology;
|
||||
using namespace evo::accounting;
|
||||
using evo::Tick;
|
||||
void check(bool condition, std::source_location location = std::source_location::current()) {
|
||||
if (!condition) {
|
||||
throw std::runtime_error("materialize line " + std::to_string(location.line()));
|
||||
}
|
||||
}
|
||||
// Variadic so a braced initializer containing a comma stays one argument.
|
||||
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
|
||||
|
||||
// Asserting on .error() alone is undefined when the call unexpectedly succeeded,
|
||||
// which would let a broken guard pass quietly. This checks the failure first.
|
||||
template <typename T>
|
||||
[[nodiscard]] bool refused(const std::expected<T, MaterializeError>& result,
|
||||
MaterializeError expected) {
|
||||
return !result.has_value() && result.error() == expected;
|
||||
}
|
||||
|
||||
Inventory held(std::uint64_t energy, std::uint64_t matter) {
|
||||
return {{energy},
|
||||
{Femtograms{matter}, Femtograms{matter}, Femtograms{matter}, Femtograms{matter}}};
|
||||
}
|
||||
// Reservoir 1 backs the cohort; 2 onwards are free stores for members.
|
||||
constexpr ReservoirId backing{1};
|
||||
constexpr std::size_t reservoir_count = 12;
|
||||
|
||||
CohortDraft draft() {
|
||||
CohortDraft source;
|
||||
source.representation_version = cohort_representation_version;
|
||||
source.habitat = {7};
|
||||
source.genome = 3;
|
||||
source.owner = {11, 2};
|
||||
source.last_tick = Tick{900};
|
||||
source.revision = 4;
|
||||
source.conversion = 5;
|
||||
source.reservoir = backing;
|
||||
// Ten energy over four members divides exactly; the matter does not, so the
|
||||
// rounding remainder is exercised by the same fixture.
|
||||
source.classes = {{0, 100, 4, held(40, 10), 0}, {100, 200, 2, held(60, 600), 250'000}};
|
||||
source.bound = {2, held(1, 1)};
|
||||
return source;
|
||||
}
|
||||
Cohort built(const CohortDraft& source) {
|
||||
const auto cohort = Cohort::create(source);
|
||||
check(cohort.has_value());
|
||||
return *cohort;
|
||||
}
|
||||
Cohort standing() {
|
||||
return built(draft());
|
||||
}
|
||||
MaterializeRequest request(std::vector<ClassDraw> draws) {
|
||||
MaterializeRequest source;
|
||||
source.owner = {11, 2};
|
||||
source.revision = 5;
|
||||
source.draws = std::move(draws);
|
||||
source.first_identity = 500;
|
||||
std::uint64_t total = 0;
|
||||
for (const auto& draw : source.draws) {
|
||||
total += draw.count;
|
||||
}
|
||||
for (std::uint64_t index = 0; index < total; ++index) {
|
||||
source.reservoirs.push_back({static_cast<std::uint32_t>(index + 2)});
|
||||
}
|
||||
source.bound = {2, held(1, 1)};
|
||||
return source;
|
||||
}
|
||||
Ledger world(const Cohort& cohort) {
|
||||
std::array<Inventory, reservoir_count> opening{};
|
||||
opening[cohort.reservoir().value - 1] = cohort.reserve();
|
||||
auto ledger = Ledger::create(opening);
|
||||
check(ledger.has_value());
|
||||
return std::move(*ledger);
|
||||
}
|
||||
CohortRegistry registry_holding(const Cohort& cohort) {
|
||||
CohortRegistry registry;
|
||||
check(registry.install(cohort).has_value());
|
||||
return registry;
|
||||
}
|
||||
Inventory sum_of(std::span<const ActiveMember> members) {
|
||||
Inventory total{};
|
||||
for (const auto& member : members) {
|
||||
total.energy.value += member.reserve.energy.value;
|
||||
for (std::size_t channel = 0; channel < total.matter.size(); ++channel) {
|
||||
total.matter[channel].value += member.reserve.matter[channel].value;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
void a_drawn_member_gets_the_floor_share_and_the_rest_stays() {
|
||||
// Two of four from a class holding forty energy and ten matter: each member
|
||||
// is entitled to ten and two, and the two matter the division could not split
|
||||
// stay with the class rather than being rounded up into existence.
|
||||
const auto before = standing();
|
||||
const auto plan = plan_materialize(before, request({{0, 2}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->members().size() == 2);
|
||||
for (const auto& member : plan->members()) {
|
||||
CHECK(member.reserve == held(10, 2));
|
||||
CHECK(member.genome == 3);
|
||||
CHECK(member.habitat == HabitatId{7});
|
||||
CHECK(member.state == MemberState::active);
|
||||
}
|
||||
CHECK(plan->members()[0].identity == 500);
|
||||
CHECK(plan->members()[1].identity == 501);
|
||||
CHECK(plan->withdrawn() == held(20, 4));
|
||||
// The class keeps two members and what the rounding left behind.
|
||||
const auto after = plan->after();
|
||||
CHECK(after.classes()[0].count == 2);
|
||||
CHECK(after.classes()[0].reserve == held(20, 6));
|
||||
// Nothing was created: what left plus what stayed is what there was.
|
||||
Inventory recombined = after.reserve();
|
||||
recombined.energy.value += plan->withdrawn().energy.value;
|
||||
for (std::size_t channel = 0; channel < recombined.matter.size(); ++channel) {
|
||||
recombined.matter[channel].value += plan->withdrawn().matter[channel].value;
|
||||
}
|
||||
CHECK(recombined == before.reserve());
|
||||
// Materialization is instantaneous: the clock does not move.
|
||||
CHECK(after.last_tick() == before.last_tick());
|
||||
CHECK(after.revision() == 5);
|
||||
}
|
||||
|
||||
void a_class_drawn_empty_hands_over_everything_it_held() {
|
||||
// Four of four from a class holding ten matter: the two the division could
|
||||
// not split go one each to the first members, because a class with nobody
|
||||
// left may keep no reserve and leaving it would be biomass nobody owns.
|
||||
const auto before = standing();
|
||||
const auto plan = plan_materialize(before, request({{0, 4}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->members().size() == 4);
|
||||
CHECK(plan->members()[0].reserve == held(10, 3));
|
||||
CHECK(plan->members()[1].reserve == held(10, 3));
|
||||
CHECK(plan->members()[2].reserve == held(10, 2));
|
||||
CHECK(plan->members()[3].reserve == held(10, 2));
|
||||
CHECK(plan->withdrawn() == held(40, 10)); // Exactly what the class held.
|
||||
// The emptied class is gone, and the other one is untouched.
|
||||
CHECK(plan->after().classes().size() == 1);
|
||||
CHECK(plan->after().classes()[0].age_low == 100);
|
||||
CHECK(plan->after().reserve() == held(60, 600));
|
||||
// A member never receives more than the class held, in any channel.
|
||||
CHECK(sum_of(plan->members()) == held(40, 10));
|
||||
}
|
||||
|
||||
void neither_a_residual_nor_a_missing_member_can_be_drawn() {
|
||||
const auto before = standing();
|
||||
// The second class holds two members and a quarter of one owed. Three is
|
||||
// more than is there: an expected density is not an available individual.
|
||||
CHECK(refused(plan_materialize(before, request({{1, 3}})),
|
||||
MaterializeError::insufficient_members));
|
||||
// Drawing both leaves the owed quarter behind, with no reserve to hold.
|
||||
const auto plan = plan_materialize(before, request({{1, 2}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->after().classes().size() == 2);
|
||||
CHECK(plan->after().classes()[1].count == 0);
|
||||
CHECK(plan->after().classes()[1].residual == 250'000);
|
||||
CHECK(plan->after().classes()[1].reserve == Inventory{});
|
||||
CHECK(plan->after().population() == 4 * residual_scale + 250'000);
|
||||
CHECK(!plan->after().is_vacant()); // A quarter of a member is not vacancy.
|
||||
}
|
||||
|
||||
void taking_everyone_leaves_a_vacant_record_and_not_an_extinction() {
|
||||
auto whole = draft();
|
||||
whole.classes = {{0, 100, 3, held(30, 33), 0}};
|
||||
const auto before = built(whole);
|
||||
const auto plan = plan_materialize(before, request({{0, 3}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->after().is_vacant());
|
||||
CHECK(plan->after().population() == 0);
|
||||
CHECK(plan->after().reserve() == Inventory{});
|
||||
// The record, its genome and its habitat all remain.
|
||||
CHECK(plan->after().genome() == 3);
|
||||
CHECK(plan->after().habitat() == HabitatId{7});
|
||||
CHECK(plan->after().conversion() == 5);
|
||||
auto ledger = world(before);
|
||||
auto registry = registry_holding(before);
|
||||
const auto total = ledger.conserved_totals();
|
||||
const auto members = commit_materialize(ledger, registry, *plan);
|
||||
CHECK(members.has_value());
|
||||
CHECK(ledger.conserved_totals() == total);
|
||||
CHECK(ledger.balances()[backing.value - 1] == Inventory{});
|
||||
CHECK(registry.size() == 1); // Nothing was removed for being empty.
|
||||
CHECK(registry.find(HabitatId{7}, 3)->is_vacant());
|
||||
}
|
||||
|
||||
void a_member_is_as_old_as_its_class_allows() {
|
||||
// The exact age is not recoverable, so the conservative bound is taken: a
|
||||
// round trip can only age someone. Any other choice lets an adversary who
|
||||
// picks when to convert roll back towards youth.
|
||||
const auto before = standing();
|
||||
const auto plan = plan_materialize(before, request({{0, 1}, {1, 1}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->members()[0].age == 99); // Top of [0, 100).
|
||||
CHECK(plan->members()[1].age == 199); // Top of [100, 200).
|
||||
// Collapsing them back puts each in the class it came from, so the choice is
|
||||
// stable under repetition rather than drifting upward through the classes.
|
||||
CollapseRequest regather;
|
||||
regather.conversion = 9;
|
||||
regather.owner = {11, 2};
|
||||
regather.habitat = {7};
|
||||
regather.genome = 3;
|
||||
regather.tick = Tick{900};
|
||||
regather.revision = 1;
|
||||
regather.destination = {9};
|
||||
regather.bounds = {{0, 100}, {100, 200}};
|
||||
const auto regathered = plan_collapse(plan->members(), regather);
|
||||
CHECK(regathered.has_value());
|
||||
CHECK(regathered->cohort().classes().size() == 2);
|
||||
CHECK(regathered->cohort().classes()[0].count == 1);
|
||||
CHECK(regathered->cohort().classes()[1].count == 1);
|
||||
}
|
||||
|
||||
void a_round_trip_is_exact_when_a_class_holds_one_member() {
|
||||
// At full resolution nothing is averaged, so collapse and materialize return
|
||||
// exactly what they were given. This is the mitigation for the smoothing the
|
||||
// next test demonstrates, and it is the caller's choice of classes.
|
||||
auto fine = draft();
|
||||
fine.classes = {
|
||||
{0, 10, 1, held(7, 70), 0}, {10, 20, 1, held(19, 3), 0}, {20, 30, 1, held(0, 0), 0}};
|
||||
const auto before = built(fine);
|
||||
const auto plan = plan_materialize(before, request({{0, 1}, {1, 1}, {2, 1}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->members()[0].reserve == held(7, 70));
|
||||
CHECK(plan->members()[1].reserve == held(19, 3));
|
||||
// Scarcity: a class holding nothing yields a member holding nothing, rather
|
||||
// than refusing or inventing a share.
|
||||
CHECK(plan->members()[2].reserve == Inventory{});
|
||||
CHECK(plan->after().is_vacant());
|
||||
CHECK(sum_of(plan->members()) == before.reserve());
|
||||
// And regathering reproduces the classes exactly.
|
||||
CollapseRequest regather;
|
||||
regather.conversion = 9;
|
||||
regather.owner = {11, 2};
|
||||
regather.habitat = {7};
|
||||
regather.genome = 3;
|
||||
regather.tick = Tick{900};
|
||||
regather.revision = 1;
|
||||
regather.destination = {9};
|
||||
regather.bounds = {{0, 10}, {10, 20}, {20, 30}};
|
||||
const auto regathered = plan_collapse(plan->members(), regather);
|
||||
CHECK(regathered.has_value());
|
||||
CHECK(regathered->cohort().reserve() == before.reserve());
|
||||
CHECK(regathered->cohort().classes()[0].reserve == held(7, 70));
|
||||
CHECK(regathered->cohort().classes()[1].reserve == held(19, 3));
|
||||
CHECK(regathered->cohort().classes()[2].reserve == Inventory{});
|
||||
}
|
||||
|
||||
void a_coarse_class_smooths_and_the_loss_is_not_hidden() {
|
||||
// One rich member and one destitute one in a single class. The total is
|
||||
// conserved and the individuals are averaged: the destitute one has been
|
||||
// healed at the rich one's expense. No accounting recovers what the declared
|
||||
// resolution discarded, and this test exists to say so rather than to pass.
|
||||
auto coarse = draft();
|
||||
coarse.classes = {{0, 100, 2, held(100, 1'000), 0}};
|
||||
const auto before = built(coarse);
|
||||
const auto plan = plan_materialize(before, request({{0, 2}}));
|
||||
CHECK(plan.has_value());
|
||||
CHECK(sum_of(plan->members()) == before.reserve()); // Conserved exactly.
|
||||
CHECK(plan->members()[0].reserve == held(50, 500)); // And averaged.
|
||||
CHECK(plan->members()[1].reserve == held(50, 500));
|
||||
// Neither member holds more than the pair held, which is what conservation
|
||||
// buys; it does not buy either of them being right.
|
||||
for (const auto& member : plan->members()) {
|
||||
CHECK(member.reserve.energy.value <= before.reserve().energy.value);
|
||||
}
|
||||
}
|
||||
|
||||
void repeated_oscillation_never_pays() {
|
||||
// Collapse and materialize over and over. The conserved total must not move,
|
||||
// no member may ever hold more than the largest starting member held, and
|
||||
// nobody may get younger. Those three together are what stops a round trip
|
||||
// being a way to heal or to reset age.
|
||||
std::array<Inventory, reservoir_count> opening{};
|
||||
std::vector<ActiveMember> members{{1, 3, {7}, 10, {2}, held(90, 900), MemberState::active},
|
||||
{2, 3, {7}, 40, {3}, held(10, 100), MemberState::active},
|
||||
{3, 3, {7}, 150, {4}, held(50, 500), MemberState::active}};
|
||||
for (const auto& member : members) {
|
||||
opening[member.reservoir.value - 1] = member.reserve;
|
||||
}
|
||||
auto ledger = Ledger::create(opening);
|
||||
CHECK(ledger.has_value());
|
||||
const auto total = ledger->conserved_totals();
|
||||
const auto ceiling = held(90, 900);
|
||||
std::uint64_t identity = 100;
|
||||
std::uint64_t revision = 1;
|
||||
std::vector<std::uint64_t> ages{10, 40, 150};
|
||||
for (std::uint64_t cycle = 0; cycle < 12; ++cycle) {
|
||||
CohortRegistry registry;
|
||||
CollapseRequest gather;
|
||||
gather.conversion = 5;
|
||||
gather.owner = {11, 2};
|
||||
gather.habitat = {7};
|
||||
gather.genome = 3;
|
||||
gather.tick = Tick{900};
|
||||
gather.revision = ++revision;
|
||||
gather.destination = backing;
|
||||
gather.bounds = {{0, 100}, {100, 200}};
|
||||
gather.bound = {0, {}};
|
||||
const auto folded = plan_collapse(members, gather);
|
||||
CHECK(folded.has_value());
|
||||
CHECK(commit_collapse(*ledger, registry, *folded).has_value());
|
||||
CHECK(ledger->conserved_totals() == total);
|
||||
const auto cohort = registry.find(HabitatId{7}, 3);
|
||||
CHECK(cohort.has_value());
|
||||
CHECK(ledger->balances()[backing.value - 1] == cohort->reserve());
|
||||
|
||||
std::vector<ClassDraw> draws;
|
||||
for (std::size_t index = 0; index < cohort->classes().size(); ++index) {
|
||||
draws.push_back({index, cohort->classes()[index].count});
|
||||
}
|
||||
auto unfold = request(draws);
|
||||
unfold.revision = ++revision;
|
||||
unfold.first_identity = identity;
|
||||
identity += members.size();
|
||||
const auto spread = plan_materialize(*cohort, unfold);
|
||||
CHECK(spread.has_value());
|
||||
const auto drawn = commit_materialize(*ledger, registry, *spread);
|
||||
CHECK(drawn.has_value());
|
||||
CHECK(ledger->conserved_totals() == total);
|
||||
CHECK(drawn->size() == members.size());
|
||||
std::vector<std::uint64_t> next;
|
||||
for (std::size_t index = 0; index < drawn->size(); ++index) {
|
||||
const auto& member = (*drawn)[index];
|
||||
// Nobody ever ends up richer than the richest we started with.
|
||||
CHECK(member.reserve.energy.value <= ceiling.energy.value);
|
||||
CHECK(member.reserve.matter[0].value <= ceiling.matter[0].value);
|
||||
next.push_back(member.age);
|
||||
}
|
||||
std::ranges::sort(next);
|
||||
auto sorted = ages;
|
||||
std::ranges::sort(sorted);
|
||||
for (std::size_t index = 0; index < next.size(); ++index) {
|
||||
CHECK(next[index] >= sorted[index]); // Nobody got younger.
|
||||
}
|
||||
ages = next;
|
||||
// Give each member back an empty store for the next cycle.
|
||||
members = *drawn;
|
||||
std::vector<Transfer> drain;
|
||||
for (std::size_t index = 0; index < members.size(); ++index) {
|
||||
const ReservoirId fresh{static_cast<std::uint32_t>(index + 2)};
|
||||
if (members[index].reservoir != fresh && !(members[index].reserve == Inventory{})) {
|
||||
drain.push_back({members[index].reservoir, fresh, members[index].reserve});
|
||||
}
|
||||
members[index].reservoir = fresh;
|
||||
}
|
||||
if (!drain.empty()) {
|
||||
CHECK(ledger->transfer(ledger->last_action() + 1, drain).has_value());
|
||||
}
|
||||
CHECK(ledger->conserved_totals() == total);
|
||||
}
|
||||
// Everyone has been pushed to a class ceiling, which is the cost of the
|
||||
// conservative age rule and is a distortion, not a model of ageing.
|
||||
for (const auto age : ages) {
|
||||
CHECK(age == 99 || age == 199);
|
||||
}
|
||||
}
|
||||
|
||||
void malformed_draws_and_stale_views_are_refused() {
|
||||
const auto before = standing();
|
||||
CHECK(refused(plan_materialize(before, request({})), MaterializeError::nothing_drawn));
|
||||
CHECK(refused(plan_materialize(before, request({{0, 0}})), MaterializeError::nothing_drawn));
|
||||
CHECK(
|
||||
refused(plan_materialize(before, request({{9, 1}})), MaterializeError::unknown_age_class));
|
||||
CHECK(refused(plan_materialize(before, request({{0, 1}, {0, 1}})),
|
||||
MaterializeError::duplicate_age_class));
|
||||
auto short_list = request({{0, 2}});
|
||||
short_list.reservoirs.pop_back();
|
||||
CHECK(refused(plan_materialize(before, short_list), MaterializeError::reservoir_mismatch));
|
||||
auto repeated = request({{0, 2}});
|
||||
repeated.reservoirs[1] = repeated.reservoirs[0];
|
||||
CHECK(refused(plan_materialize(before, repeated), MaterializeError::duplicate_reservoir));
|
||||
auto into_the_cohort = request({{0, 1}});
|
||||
into_the_cohort.reservoirs[0] = backing;
|
||||
CHECK(refused(plan_materialize(before, into_the_cohort), MaterializeError::invalid_request));
|
||||
auto nameless = request({{0, 1}});
|
||||
nameless.first_identity = 0;
|
||||
CHECK(refused(plan_materialize(before, nameless), MaterializeError::invalid_request));
|
||||
auto intruder = request({{0, 1}});
|
||||
intruder.owner = {12, 2};
|
||||
CHECK(refused(plan_materialize(before, intruder), MaterializeError::wrong_owner));
|
||||
auto replayed = request({{0, 1}});
|
||||
replayed.revision = before.revision();
|
||||
CHECK(refused(plan_materialize(before, replayed), MaterializeError::stale_revision));
|
||||
|
||||
const auto plan = plan_materialize(before, request({{0, 2}}));
|
||||
CHECK(plan.has_value());
|
||||
// Nothing installed.
|
||||
auto bare = world(before);
|
||||
CohortRegistry nothing;
|
||||
const auto opening = std::vector<Inventory>{bare.balances().begin(), bare.balances().end()};
|
||||
CHECK(refused(commit_materialize(bare, nothing, *plan), MaterializeError::not_installed));
|
||||
CHECK(std::vector<Inventory>(bare.balances().begin(), bare.balances().end()) == opening);
|
||||
// Installed but already moved on.
|
||||
auto moved = world(before);
|
||||
auto registry = registry_holding(before);
|
||||
auto newer = draft();
|
||||
newer.revision = 9;
|
||||
CHECK(registry.replace(built(newer)).has_value());
|
||||
const auto action = moved.last_action();
|
||||
CHECK(refused(commit_materialize(moved, registry, *plan), MaterializeError::stale_plan));
|
||||
CHECK(std::vector<Inventory>(moved.balances().begin(), moved.balances().end()) == opening);
|
||||
CHECK(moved.last_action() == action);
|
||||
// A destination that already holds something would leave the member's reserve
|
||||
// understating what backs it, exactly as a collapse destination would.
|
||||
auto occupied = world(before);
|
||||
auto current = registry_holding(before);
|
||||
const std::array seed{Transfer{backing, {2}, held(1, 1)}};
|
||||
CHECK(occupied.transfer(occupied.last_action() + 1, seed).has_value());
|
||||
CHECK(refused(commit_materialize(occupied, current, *plan),
|
||||
MaterializeError::stale_plan)); // The cohort balance moved too.
|
||||
auto holding = registry_holding(before);
|
||||
// Something in a member's store, with the cohort's left exactly as sampled,
|
||||
// so this reaches the destination check rather than the staleness one.
|
||||
auto seeded = std::array<Inventory, reservoir_count>{};
|
||||
seeded[backing.value - 1] = before.reserve();
|
||||
seeded[1] = held(1, 1);
|
||||
auto other = Ledger::create(seeded);
|
||||
CHECK(other.has_value());
|
||||
CHECK(
|
||||
refused(commit_materialize(*other, holding, *plan), MaterializeError::reservoir_not_empty));
|
||||
CHECK(other->balances()[backing.value - 1] == before.reserve());
|
||||
CHECK(holding.find(HabitatId{7}, 3)->revision() == 4);
|
||||
// Committing one plan twice: the second finds a record it does not match.
|
||||
auto once = world(before);
|
||||
auto held_once = registry_holding(before);
|
||||
CHECK(commit_materialize(once, held_once, *plan).has_value());
|
||||
const auto settled = std::vector<Inventory>{once.balances().begin(), once.balances().end()};
|
||||
CHECK(refused(commit_materialize(once, held_once, *plan), MaterializeError::stale_plan));
|
||||
CHECK(std::vector<Inventory>(once.balances().begin(), once.balances().end()) == settled);
|
||||
}
|
||||
|
||||
void a_moved_from_plan_is_still_a_whole_plan() {
|
||||
static_assert(std::is_copy_constructible_v<MaterializePlan>);
|
||||
static_assert(!std::is_nothrow_move_constructible_v<MaterializePlan>);
|
||||
const auto before = standing();
|
||||
auto source = plan_materialize(before, request({{0, 2}}));
|
||||
CHECK(source.has_value());
|
||||
const auto original = *source;
|
||||
// Both diagnostics are the point of the check: clang-tidy is right that no
|
||||
// move happens here and wrong that it is a mistake.
|
||||
// NOLINTNEXTLINE(performance-move-const-arg)
|
||||
const auto moved = std::move(*source);
|
||||
// NOLINTNEXTLINE(bugprone-use-after-move): the point of the check.
|
||||
CHECK(*source == original);
|
||||
// NOLINTNEXTLINE(bugprone-use-after-move)
|
||||
CHECK(source->members().size() == 2);
|
||||
// NOLINTNEXTLINE(bugprone-use-after-move)
|
||||
CHECK(source->legs().size() == 2);
|
||||
CHECK(moved == original);
|
||||
auto ledger = world(before);
|
||||
auto registry = registry_holding(before);
|
||||
// NOLINTNEXTLINE(bugprone-use-after-move)
|
||||
const auto drawn = commit_materialize(ledger, registry, *source);
|
||||
CHECK(drawn.has_value());
|
||||
CHECK(drawn->size() == 2);
|
||||
}
|
||||
} // namespace
|
||||
int main() try {
|
||||
a_drawn_member_gets_the_floor_share_and_the_rest_stays();
|
||||
a_class_drawn_empty_hands_over_everything_it_held();
|
||||
neither_a_residual_nor_a_missing_member_can_be_drawn();
|
||||
taking_everyone_leaves_a_vacant_record_and_not_an_extinction();
|
||||
a_member_is_as_old_as_its_class_allows();
|
||||
a_round_trip_is_exact_when_a_class_holds_one_member();
|
||||
a_coarse_class_smooths_and_the_loss_is_not_hidden();
|
||||
repeated_oscillation_never_pays();
|
||||
malformed_draws_and_stale_views_are_refused();
|
||||
a_moved_from_plan_is_still_a_whole_plan();
|
||||
std::cout << "PASS materialization shares, conservative ages and unprofitable round trips\n";
|
||||
return 0;
|
||||
} catch (...) {
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user