Account for the interval a model proposes; never clamp it
M4.3 advances a cohort over one declared interval and deliberately does not model one. ECOLOGY_MODEL keeps population maths an experiment and asks for several candidates to be compared, so choosing one here would turn a recommendation into a locked rule. A model proposes fluxes; this checks the declared result is exactly what they imply, for counts and for every inventory channel. Nothing is clamped. A loss larger than what is there refuses the interval and says whether it was the population or the biomass, so a caller can subdivide; subtraction is checked against what is present rather than performed and repaired, so a negative population is never constructed. That is the answer to the named risk: a clamp is how an interval a model could not integrate becomes a plausible result, and how a false extinction arrives. Both clamp mutations are detected by the tests. Counts carry whole members and owed fractions as one quantity, so a population below one member is a number rather than a rounding decision. Biomass has no birth term at all, so a birth cannot bring inventory in and newborns are necessarily funded from what the cohort holds. Immigration draws from a reservoir that already held it, so a late transfer is not new production. Conservation runs through the ledger as one atomic transaction; an interval where nothing moves submits none. Two amendments to M4.1 were forced, not chosen. A cohort records the reservoir backing it, because an advance cannot otherwise know where the inventory is and passing it alongside would let a caller advance one cohort against another's store, which comparing balances cannot detect between equal reserves; the registry now refuses two cohorts sharing one. And a cohort may be vacant, through a separate factory so vacancy stays deliberate, because a decline to exactly zero was otherwise unrepresentable and the only way through would have been the clamp this milestone exists to refuse. A vacant cohort is not an extinction: the record, its genome, its habitat and its provenance remain and it stays installed. Fourteen guards confirmed load-bearing by removing each and rerunning. Two of my own expectations were wrong rather than the code: escrow arithmetic in the migration test, and a dwindling case that shed all but one femtogram while declaring a result holding none. The second surfaced a real tension now recorded in ADR-0038 rather than worked around: a class reduced to a fraction of a member may hold no reserve, because reserve belongs to members and a fraction is not one yet, so that biomass has to go somewhere the same interval. Closure is checked and stability is not, so an interval whose arithmetic balances and whose ecology is nonsense is accepted. The declared age structure is not verified to be what ageing would produce, because that needs the within-class distribution the record discards. Release 36/36, analysis, ASan 36/36 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)
|
||||
add_library(evo_ecology STATIC src/ecology/cohort.cpp src/ecology/collapse.cpp src/ecology/population.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)
|
||||
@@ -120,6 +120,11 @@ if(BUILD_TESTING)
|
||||
evo_owned_target(evo-collapse-tests)
|
||||
add_test(NAME collapse-contracts COMMAND evo-collapse-tests)
|
||||
set_tests_properties(collapse-contracts PROPERTIES TIMEOUT 60)
|
||||
add_executable(evo-population-tests tests/population_tests.cpp)
|
||||
target_link_libraries(evo-population-tests PRIVATE evo::ecology)
|
||||
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-ledger-tests tests/ledger_tests.cpp)
|
||||
target_link_libraries(evo-ledger-tests PRIVATE evo::accounting)
|
||||
evo_owned_target(evo-ledger-tests)
|
||||
|
||||
@@ -119,6 +119,18 @@ reserve, and the destination is proved available before anything moves, so every
|
||||
rejection leaves both the ledger and the registry exactly as they were. What this
|
||||
cannot check is that the caller offered every member it had.
|
||||
|
||||
M4.3 advances a cohort over one declared interval (ADR-0038) without choosing an
|
||||
ecology: a model proposes fluxes and this accounts for them, checking that the
|
||||
declared result is exactly what they imply. Nothing is clamped, because a clamp is
|
||||
how an interval a model could not integrate becomes a plausible result and how a
|
||||
false extinction arrives; a loss larger than what is there refuses the interval and
|
||||
says whether it was the population or the biomass. Counts carry whole members and
|
||||
owed fractions together, so a population below one member is still a number.
|
||||
Biomass has no birth term at all, so newborns are necessarily funded from what the
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
+42
-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 37 ADRs.
|
||||
diagrams, biological contracts, engineering constitution and 38 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.3 advance local cohorts | Conservative birth, death, predation and migration accounting per interval |
|
||||
| 1 | M4.4 materialize representatives | Withdraw exact shares and residuals while preserving genome identity |
|
||||
| 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 |
|
||||
|
||||
@@ -376,3 +376,43 @@ picojoules against a cohort recording 60, so the cohort's reserve understated wh
|
||||
backed it and the surplus belonged to nobody. A destination holding anything is
|
||||
now refused, a cohort's reserve is the whole of its reservoir rather than a part
|
||||
of it, and the success test asserts that equality directly.
|
||||
|
||||
M4.3 advances a cohort over one declared interval (ADR-0038) and deliberately does
|
||||
not model one. ECOLOGY_MODEL keeps population maths an experiment and asks for
|
||||
several candidates to be compared, so choosing one here would turn a
|
||||
recommendation into a locked rule. A model proposes fluxes; this checks that the
|
||||
declared result is exactly what they imply, for counts and for every inventory
|
||||
channel.
|
||||
|
||||
Nothing is clamped. A loss larger than what is there refuses the interval and
|
||||
names whether it was the population or the biomass, so a caller can subdivide and
|
||||
retry, and subtraction is checked against what is present rather than performed
|
||||
and repaired. That is the answer to the milestone's named risk: a clamp is how an
|
||||
interval a model could not integrate becomes a plausible looking result, and how a
|
||||
false extinction arrives. Counts carry whole members and owed fractions together,
|
||||
so a population below one member is a number rather than a rounding decision.
|
||||
Biomass has no birth term at all, so a birth cannot bring inventory in and
|
||||
newborns are necessarily funded from what the cohort already holds; immigration
|
||||
draws from a reservoir that already held it, so a late transfer is not new
|
||||
production either. Conservation runs through the ledger as one atomic transaction,
|
||||
and an interval in which nothing moves submits none.
|
||||
|
||||
Two amendments to M4.1's record were forced rather than chosen. A cohort now
|
||||
records the reservoir backing it, because an advance cannot otherwise know where
|
||||
the inventory is and passing it alongside would let a caller advance one cohort
|
||||
against another's store, which comparing balances cannot detect between equal
|
||||
reserves; the registry refuses two cohorts sharing a reservoir. And a cohort may
|
||||
be vacant, through a separate factory so vacancy stays deliberate, because a
|
||||
population declining to exactly zero would otherwise be unrepresentable and the
|
||||
caller would have to clamp. A vacant cohort is not an extinction: the record, its
|
||||
genome, its habitat and its provenance all remain and it stays installed.
|
||||
|
||||
Limits are stated rather than implied covered. Accounting is not fidelity: closure
|
||||
is checked, stability is not, so a long interval whose arithmetic closes and whose
|
||||
ecology is nonsense is accepted. The declared age structure is not verified to be
|
||||
what ageing would produce, because that needs the within-class distribution the
|
||||
record deliberately discards. Emigration escrows into a reservoir nothing settles
|
||||
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.
|
||||
|
||||
@@ -2,7 +2,14 @@
|
||||
|
||||
## Status
|
||||
|
||||
Adopted for M4.1. It defines the tier 2 record and who may act on it, and nothing
|
||||
Adopted for M4.1, and amended twice by ADR-0038 when M4.3 needed what this record
|
||||
did not carry. A cohort now records the reservoir backing it, and the registry
|
||||
refuses two cohorts sharing one. A cohort may also be vacant, holding no classes,
|
||||
no members and no reserve, through a separate factory so vacancy stays deliberate
|
||||
and `create` goes on refusing a draft that merely has no classes; without it a
|
||||
population declining to exactly zero would be unrepresentable and a caller would
|
||||
have to clamp. Both amendments are described in ADR-0038 and in
|
||||
`schemas/population-v1.md`. It defines the tier 2 record and who may act on it, and nothing
|
||||
else: there is no collapse transaction, no population advance, no materialization
|
||||
and no habitat geometry. Those are M4.2 to M4.4 and each needs its own decision.
|
||||
No M1 to M3 contract changes. ECOLOGY_MODEL's population math stays an experiment.
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# ADR-0038: Accounting a proposed interval without choosing an ecology
|
||||
|
||||
## Status
|
||||
|
||||
Adopted for M4.3. It accounts for one declared interval on one cohort and does
|
||||
not model one: no birth rate, no mortality curve, no functional response and no
|
||||
carrying capacity is chosen here. Materialization back into individuals is M4.4
|
||||
and resolution equivalence is M4.5. It amends ADR-0036 in two ways, both forced
|
||||
by this milestone and described below. No M1 to M3 contract changes.
|
||||
|
||||
## Context
|
||||
|
||||
ECOLOGY_MODEL is explicit that the population maths is an experiment: it lists
|
||||
`N_next = N + births - deaths + immigration - emigration`, the matching biomass
|
||||
identity, and then says to compare bounded flux, seeded stochastic and
|
||||
deterministic expected-density models. Picking one of those here would turn a
|
||||
recommendation into a locked game rule, which the working agreement forbids.
|
||||
|
||||
What the same document does lock is the arithmetic around whichever model runs:
|
||||
never hide negative populations with clamps, reject or subdivide unstable
|
||||
intervals, births redistribute funded investment rather than creating biomass,
|
||||
predation transfers biomass once and death returns detritus, one owner integrates
|
||||
each interval, late transfers are not new production, and rounding a density to
|
||||
zero cannot declare extinction. Those are the contract. The named risk is
|
||||
numerical instability and false extinctions, and a clamp is exactly how both
|
||||
arrive: it turns an interval the model could not integrate into a plausible
|
||||
looking result, and it manufactures an extinction nobody proposed.
|
||||
|
||||
## Decision
|
||||
|
||||
A model proposes fluxes and this library accounts for them. `plan_advance` takes
|
||||
the cohort, the interval end, the declared fluxes and the declared resulting age
|
||||
structure, and checks that the result is exactly what the fluxes imply. It never
|
||||
computes the result itself, because computing it would mean choosing the model.
|
||||
|
||||
Nothing is clamped. A loss larger than what is there refuses the interval and
|
||||
names whether it was the population or the biomass, so a caller can subdivide and
|
||||
retry. Subtraction is checked against what is present rather than performed and
|
||||
repaired afterwards, so a negative value is never constructed in the first place.
|
||||
|
||||
Counts are carried in units of `residual_scale`, whole members and owed fractions
|
||||
together. A population below one member is then a number, not a rounding
|
||||
decision, and a density falling towards zero stays a density.
|
||||
|
||||
Biomass has no birth term at all. A birth cannot bring inventory in because there
|
||||
is no field by which it could, so newborns are necessarily funded from what the
|
||||
cohort already holds. This is ECOLOGY_MODEL's rule made structural rather than
|
||||
documented. Immigration does have a term, and it draws from a reservoir that
|
||||
already held the inventory, so a late transfer is not new production either.
|
||||
|
||||
Conservation runs through the ledger, as in ADR-0037. Each non-empty outflow and
|
||||
inflow becomes one leg of a single atomic transaction against the cohort's
|
||||
reservoir, so the conserved total is unchanged by construction. An interval in
|
||||
which nothing moves submits no transaction at all rather than an empty one.
|
||||
|
||||
Commit refuses a proposal computed against a stale view. The installed record
|
||||
must still be exactly the one the plan started from, down to the revision, and
|
||||
the reservoir must still hold what the plan counted. Ownership and ordering are
|
||||
then the registry's existing rules, so one owner integrates each interval and a
|
||||
late writer cannot install an older view.
|
||||
|
||||
This milestone amends ADR-0036 twice, and both amendments are corrections rather
|
||||
than additions. A cohort now records the reservoir backing it, because an advance
|
||||
cannot otherwise know where the inventory is, and passing it alongside would let
|
||||
a caller advance one cohort against another's store while a balance comparison
|
||||
could not tell two equal reserves apart. The registry accordingly refuses two
|
||||
cohorts sharing a reservoir. A cohort may also now be vacant, holding no classes,
|
||||
no members and no reserve, through a separate factory so vacancy is always
|
||||
deliberate and `create` goes on refusing a draft that merely has no classes.
|
||||
Without that, a population declining to exactly zero would be unrepresentable and
|
||||
a caller would be forced to clamp, which is the thing this ADR exists to prevent.
|
||||
A vacant cohort is not an extinction: the record, its genome, its habitat and its
|
||||
provenance all remain.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
Computing the fluxes here from rates would be a model, and would make one of the
|
||||
candidates ECOLOGY_MODEL wants compared into the only one that exists. Clamping
|
||||
at zero and reporting a warning was rejected because a warning is not a refusal
|
||||
and the result would still propagate. Deriving the resulting age structure by
|
||||
ageing the classes is impossible without the within-class distribution ADR-0036
|
||||
deliberately discards; asking the caller for it is honest about what the record
|
||||
knows. Keeping counts in whole members would make a population below one member
|
||||
round to zero, which the model forbids being read as extinction. Deleting a
|
||||
cohort that reaches zero would destroy the genome and habitat association that
|
||||
makes absence recoverable, and is the false extinction named in the risk column.
|
||||
Threading the reservoir through each request instead of binding it to the record
|
||||
was rejected above. Letting the advance perform several ledger transactions would
|
||||
give up atomicity for no gain, since one transaction holds all four legs.
|
||||
|
||||
## Benefits
|
||||
|
||||
Whatever model runs above this, its arithmetic has to close, and an interval it
|
||||
cannot integrate fails loudly with enough information to subdivide. Conservation
|
||||
is the ledger's property rather than a claim. Births cannot create biomass
|
||||
because there is no way to express it. A population can shrink below one member,
|
||||
and reach zero, without anything being deleted or declared extinct.
|
||||
|
||||
## Costs
|
||||
|
||||
The caller supplies the resulting age structure, which is more work than being
|
||||
handed one and is a modelling decision it must make. Four fluxes plus a structure
|
||||
is a wide request. A plan holds copies of both cohorts. An interval is accounted
|
||||
for as a whole, so a caller that needs finer granularity subdivides and pays for
|
||||
several plans. The residual carried by a class that has fallen below one member
|
||||
cannot hold reserve, because ADR-0036 gives reserve to members and a fraction is
|
||||
not one yet; that biomass has to go somewhere the same interval.
|
||||
|
||||
## Risks
|
||||
|
||||
Accounting is not fidelity. Nothing here says the proposed fluxes are
|
||||
ecologically reasonable, and a model that conserves exactly can still be wrong in
|
||||
every other way; M4.5 is where resolution equivalence is measured. The interval
|
||||
is not checked for stability, only for closure, so a caller can propose a long
|
||||
interval whose arithmetic closes and whose ecology is nonsense. The declared age
|
||||
structure is not verified to be what ageing would produce, because that cannot be
|
||||
checked without the distribution the record does not keep. Emigration escrows
|
||||
into a reservoir this milestone does not settle with, so a destination cohort
|
||||
receiving it is `TransferPopulation` and does not exist. Ownership remains a
|
||||
single-process invariant. Nothing is serialized.
|
||||
|
||||
## Consequences
|
||||
|
||||
Test that an interval with no flux still advances the clock and submits no ledger
|
||||
transaction, that births change the population and leave the reserve untouched,
|
||||
and that death, predation, immigration and emigration each move biomass once to
|
||||
the right counterparty with the conserved total unchanged. Test that a loss
|
||||
exceeding the population or any one inventory channel is refused rather than
|
||||
clamped, at the boundary of a single millionth of a member, and that taking
|
||||
exactly everything is vacancy rather than refusal. Test that a population below
|
||||
one member is still a population and that its record stays installed. Test that a
|
||||
declared result which does not match the fluxes is refused, in both directions,
|
||||
for counts and for biomass. Test that an empty or backward interval, a foreign
|
||||
owner and a repeated revision are refused. Test that a commit against a record
|
||||
that has moved on, or a reservoir that no longer holds what was counted, changes
|
||||
nothing in either the ledger or the registry, and that one plan cannot be
|
||||
committed twice. Test over many seeded interval sequences that the conserved
|
||||
total never moves, that the cohort's reservoir always equals its recorded reserve,
|
||||
and that both the accepted and the refused paths actually occur. No genome schema,
|
||||
mutation catalog, archive, ledger, episode driver, ensemble, renderer or
|
||||
deployment changes.
|
||||
@@ -30,6 +30,7 @@ Each record has the eight required sections.
|
||||
0035 derives strategies from genomes and measures them over a split-half gradient.
|
||||
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.
|
||||
|
||||
Every dependency adoption records exact version/commit and integrity hash,
|
||||
transitive license obligations, maintenance/security review, owner and removal
|
||||
|
||||
@@ -193,3 +193,37 @@ only the registry's single-ownership rule bounds what that would mean. Durable
|
||||
conversion sequence numbers, escrow and crash recovery across a process boundary
|
||||
are M7 and M8; the before-and-after property proved here holds across a rejection
|
||||
inside one process.
|
||||
|
||||
## Implemented M4.3 interval accounting
|
||||
|
||||
[ADR-0038](../adr/0038-interval-accounting.md) implements `AdvancePopulation` as
|
||||
accounting rather than as a model. The population maths above stays an experiment:
|
||||
no birth rate, mortality curve, functional response or carrying capacity is chosen
|
||||
here, so none of the candidate models listed above has been made the only one.
|
||||
What is enforced is the arithmetic around whichever model runs.
|
||||
|
||||
Nothing is clamped. A loss larger than what is present refuses the interval and
|
||||
names whether it was the population or the biomass, so an unstable interval is
|
||||
rejected and can be subdivided. Subtraction is checked against what is there
|
||||
rather than performed and repaired, so a negative population is never constructed.
|
||||
|
||||
Counts carry whole members and owed fractions as one scaled quantity, so a density
|
||||
below one member is still a number and rounding it to zero is not available as a
|
||||
decision. A population that reaches exactly zero becomes a vacant record, which is
|
||||
neither absence nor extinction: the genome, the habitat, the owner and the
|
||||
provenance all remain and the record stays installed. Deleting it would have been
|
||||
the false extinction this milestone is named against.
|
||||
|
||||
Births redistribute funded investment because there is no term by which a birth
|
||||
could bring biomass in. Immigration draws from a reservoir that already held the
|
||||
inventory, so a late transfer is not new production. Death returns detritus and
|
||||
predation transfers once, each to a named counterparty, as one atomic ledger
|
||||
transaction against the cohort's reservoir.
|
||||
|
||||
Three gaps are explicit. Closure is checked and stability is not, so an interval
|
||||
whose arithmetic balances and whose ecology is nonsense is accepted; comparing
|
||||
matched ensembles and publishing error envelopes is M4.5. The resulting age
|
||||
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.
|
||||
|
||||
@@ -1061,3 +1061,76 @@ mangled the escaped newlines in the mutation script and the script failed to
|
||||
parse, so nothing was ever mutated. It is the second time this environment quirk
|
||||
has produced a false negative in a mutation sweep, and both times the printed
|
||||
output rather than the exit status is what revealed it.
|
||||
|
||||
## M4.3 interval accounting
|
||||
|
||||
Executed on this Windows host (2026-09-24): Release configure, build and `ctest`
|
||||
36/36; the analysis preset (clang-tidy 19, warnings as errors) built clean; the
|
||||
ASan preset configured, built and ran 36/36; `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-population-tests` covers ten properties, and `evo-cohort-tests` gained two
|
||||
for the amendments. An interval with no flux advances the clock and submits no
|
||||
ledger transaction. Births change the population and leave the reserve untouched.
|
||||
Death, predation, immigration and emigration each move biomass once to the named
|
||||
counterparty with the conserved total unchanged. A loss exceeding the population
|
||||
or any one inventory channel is refused rather than clamped, including at the
|
||||
boundary of a single millionth of a member, while taking exactly everything is
|
||||
vacancy rather than refusal. A population below one member stays a population and
|
||||
its record stays installed. A declared result that does not match the fluxes is
|
||||
refused in both directions, for counts and for biomass. Empty and backward
|
||||
intervals, a foreign owner and a repeated revision are refused. A commit against a
|
||||
record that has moved on, or a reservoir that no longer holds what was counted,
|
||||
changes nothing in either the ledger or the registry, and one plan cannot be
|
||||
committed twice.
|
||||
|
||||
The seeded ensemble runs twenty-four seeds of forty proposed intervals each,
|
||||
deliberately proposing losses unbounded relative to the cohort so that some must
|
||||
be refused. Every accepted interval is checked for the conserved total being
|
||||
unchanged and for the cohort's reservoir equalling its recorded reserve. The test
|
||||
asserts that both the accepted and the refused path actually occurred, so a change
|
||||
that made everything refuse, or everything pass, fails rather than looking clean.
|
||||
|
||||
All fourteen guards were confirmed load-bearing by removing each in turn and
|
||||
rerunning: the two no-clamp guards, the two mismatch guards, the interval, owner,
|
||||
revision and counterparty guards, the three commit staleness guards, and the three
|
||||
amendments to the cohort record. The two clamp mutations are the ones worth
|
||||
naming, because they are the defect rather than a missing check: replacing the
|
||||
refusals with saturating subtraction, which is what a clamp is, is detected.
|
||||
|
||||
Two of my own expectations were wrong rather than the code. The escrow arithmetic
|
||||
in the migration test was miscalculated: the reservoir receives two hundred matter
|
||||
and returns one hundred, so from seven it stands at a hundred and seven, not a
|
||||
hundred and ninety-seven. And the dwindling-population test shed all but one
|
||||
femtogram of the reserve while declaring a result that held none, which is a real
|
||||
`biomass_mismatch`; the test now sheds the whole reserve. That second one surfaced
|
||||
a genuine tension worth recording: a class reduced to a fraction of a member may
|
||||
hold no reserve, because ADR-0036 gives reserve to members and a fraction is not
|
||||
one yet, so that biomass has to go somewhere in the same interval. It is recorded
|
||||
in ADR-0038's costs rather than worked around.
|
||||
|
||||
ADR-0036 was amended twice, and both were forced by this milestone rather than
|
||||
chosen. Threading the reservoir through each request instead of binding it to the
|
||||
record would have let a caller advance one cohort against another's store, and a
|
||||
balance comparison cannot distinguish two equal reserves, so the binding is a
|
||||
correctness fix and not tidiness. Vacancy is required because a decline to exactly
|
||||
zero was otherwise unrepresentable and the only way through would have been the
|
||||
clamp this milestone exists to refuse. `Cohort::vacant` is a separate factory
|
||||
precisely so that an empty class list in a draft stays an error.
|
||||
|
||||
Coverage limits. Closure is checked and stability is not: an interval whose
|
||||
arithmetic balances and whose ecology is nonsense is accepted, and no test asserts
|
||||
otherwise, because comparing matched ensembles is M4.5. The declared age structure
|
||||
is not verified to be what ageing would produce, since that needs the within-class
|
||||
distribution the record discards; nothing here checks that members did not get
|
||||
younger. Emigration escrows into a reservoir nothing settles with. Ownership
|
||||
remains a single-process invariant. The overflow and ledger-failure branches are
|
||||
reachable only past bounds the tests do not build, so they are refused by
|
||||
construction rather than exercised. Nothing is serialized.
|
||||
|
||||
The proof golden `d61ad5bf0c928c76`, the ecosystem fingerprint
|
||||
`2cd4a15f9fbe9949`, the ensemble fingerprint `5ec59d390909b526` and the frozen
|
||||
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`.
|
||||
|
||||
@@ -73,6 +73,11 @@ struct CohortDraft {
|
||||
std::uint64_t revision{};
|
||||
// The conversion that produced this record, kept as provenance.
|
||||
std::uint64_t conversion{};
|
||||
// Where this cohort's reserve actually is. Bound to the record rather than
|
||||
// passed alongside it: a caller could otherwise advance one cohort against
|
||||
// another's reservoir, and comparing balances cannot tell two equal reserves
|
||||
// apart. Amended in M4.2/M4.3; see ADR-0036.
|
||||
accounting::ReservoirId reservoir{};
|
||||
std::vector<AgeClass> classes;
|
||||
ApproximationBound bound{};
|
||||
};
|
||||
@@ -86,6 +91,7 @@ enum class CohortError : std::uint8_t {
|
||||
unowned_reserve,
|
||||
residual_out_of_range,
|
||||
overflow,
|
||||
not_vacant,
|
||||
duplicate_cohort,
|
||||
unknown_cohort,
|
||||
wrong_owner,
|
||||
@@ -104,6 +110,13 @@ inline constexpr std::size_t max_cohorts = 4'096;
|
||||
class Cohort {
|
||||
public:
|
||||
[[nodiscard]] static std::expected<Cohort, CohortError> create(CohortDraft draft);
|
||||
// A cohort whose population reached exactly zero. It is a separate factory so
|
||||
// vacancy is always deliberate: `create` goes on refusing a draft that simply
|
||||
// has no classes, which would otherwise become a vacant record by accident.
|
||||
// Without this a decline to zero would be unrepresentable and a caller would
|
||||
// have to clamp, which ECOLOGY_MODEL forbids. A vacant cohort is not
|
||||
// extinction: the record, its genome and its habitat are all still here.
|
||||
[[nodiscard]] static std::expected<Cohort, CohortError> vacant(const CohortDraft& draft);
|
||||
// Copy-only on purpose. A moved-from record would keep its habitat, genome,
|
||||
// owner and totals while losing its age classes, which is precisely the
|
||||
// invalid cohort `create` refuses to build; the registry would then accept
|
||||
@@ -134,6 +147,12 @@ class Cohort {
|
||||
[[nodiscard]] std::uint64_t conversion() const noexcept {
|
||||
return conversion_;
|
||||
}
|
||||
[[nodiscard]] accounting::ReservoirId reservoir() const noexcept {
|
||||
return reservoir_;
|
||||
}
|
||||
[[nodiscard]] bool is_vacant() const noexcept {
|
||||
return classes_.empty();
|
||||
}
|
||||
[[nodiscard]] std::span<const AgeClass> classes() const noexcept {
|
||||
return classes_;
|
||||
}
|
||||
@@ -149,6 +168,10 @@ class Cohort {
|
||||
// Total owed fraction, in units of residual_scale. May exceed one member once
|
||||
// summed across classes; the per-class bound is what is invariant.
|
||||
[[nodiscard]] std::uint64_t residual() const noexcept;
|
||||
// Whole members and owed fractions as one quantity, in units of
|
||||
// residual_scale, so a population that has fallen below one member is still a
|
||||
// number and not a rounding decision. Bounded at construction.
|
||||
[[nodiscard]] std::uint64_t population() const noexcept;
|
||||
// Deliberately no mean age and no per-member reserve. An average that is easy
|
||||
// to reach is an average that gets used as the authority.
|
||||
|
||||
@@ -163,6 +186,7 @@ class Cohort {
|
||||
Tick last_tick_{};
|
||||
std::uint64_t revision_{};
|
||||
std::uint64_t conversion_{};
|
||||
accounting::ReservoirId reservoir_{};
|
||||
std::vector<AgeClass> classes_;
|
||||
ApproximationBound bound_{};
|
||||
};
|
||||
@@ -173,6 +197,9 @@ class Cohort {
|
||||
// forbidden. Nothing is serialized and no cross-worker protocol is implied.
|
||||
class CohortRegistry {
|
||||
public:
|
||||
// Also refuses a cohort whose reservoir another cohort already uses: one
|
||||
// reservoir backing two records is the same inventory in two places, which is
|
||||
// the invariant this registry exists for.
|
||||
[[nodiscard]] std::expected<void, CohortError> install(const Cohort& cohort);
|
||||
// Refused unless it is a strictly later view of the same record by the same
|
||||
// owner: the habitat and genome must match, the epoch must not be older, the
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/ecology/cohort.hpp"
|
||||
|
||||
namespace evo::ecology {
|
||||
// What a model proposes happened to a cohort over one declared interval. This
|
||||
// library does not decide any of it. ECOLOGY_MODEL keeps population maths an
|
||||
// experiment and lists several candidate models, so choosing one here would turn
|
||||
// a recommendation into a locked rule. What is a contract is that a proposal
|
||||
// balances: these are fluxes to be accounted for, not a model to be believed.
|
||||
//
|
||||
// Counts are in units of `residual_scale`, so a fraction of a member is a number
|
||||
// rather than a rounding decision, and a population below one member is still a
|
||||
// population. Births carry no biomass term on purpose: ECOLOGY_MODEL requires
|
||||
// that births redistribute funded investment rather than create biomass, so
|
||||
// there is nowhere for a birth to bring any in.
|
||||
struct IntervalFlux {
|
||||
std::uint64_t births{};
|
||||
std::uint64_t immigration{};
|
||||
std::uint64_t deaths{};
|
||||
std::uint64_t predation{};
|
||||
std::uint64_t emigration{};
|
||||
// Biomass leaving the cohort, by where it goes. Death returns detritus,
|
||||
// predation transfers once, emigration is escrowed for a destination this
|
||||
// milestone does not settle with.
|
||||
accounting::Inventory to_detritus{};
|
||||
accounting::Inventory to_predators{};
|
||||
accounting::Inventory to_elsewhere{};
|
||||
// Biomass arriving with immigrants. A late transfer is not new production:
|
||||
// it comes out of a reservoir that already held it.
|
||||
accounting::Inventory from_elsewhere{};
|
||||
auto operator<=>(const IntervalFlux&) const = default;
|
||||
};
|
||||
|
||||
struct AdvanceRequest {
|
||||
// The end of the interval. The start is the cohort's own last tick, so
|
||||
// intervals cannot overlap or leave a gap.
|
||||
Tick to{};
|
||||
Owner owner{};
|
||||
std::uint64_t revision{};
|
||||
// The age structure the model says results. This library cannot derive it:
|
||||
// ageing across a class boundary needs the within-class distribution that
|
||||
// ADR-0036's declared resolution deliberately does not keep.
|
||||
std::vector<AgeClass> after;
|
||||
IntervalFlux flux;
|
||||
accounting::ReservoirId detritus{};
|
||||
accounting::ReservoirId predators{};
|
||||
accounting::ReservoirId elsewhere{};
|
||||
ApproximationBound bound{};
|
||||
};
|
||||
|
||||
enum class PopulationError : std::uint8_t {
|
||||
invalid_request,
|
||||
empty_interval,
|
||||
wrong_owner,
|
||||
stale_revision,
|
||||
// A proposal that would take the population or the reserve below zero. It is
|
||||
// refused and never clamped: ECOLOGY_MODEL requires that an interval which
|
||||
// does not balance be rejected or subdivided, because a clamp would hide a
|
||||
// model that has gone unstable and would manufacture a false extinction.
|
||||
negative_population,
|
||||
negative_biomass,
|
||||
// The declared result does not equal what the fluxes imply.
|
||||
population_mismatch,
|
||||
biomass_mismatch,
|
||||
overflow,
|
||||
invalid_cohort,
|
||||
not_installed,
|
||||
stale_plan,
|
||||
ledger_failure
|
||||
};
|
||||
|
||||
// The accounted interval, decided once. Copy-only for the reason a cohort is: a
|
||||
// moved-from plan would keep its identities while losing its legs.
|
||||
class AdvancePlan {
|
||||
public:
|
||||
AdvancePlan(const AdvancePlan&) = default;
|
||||
AdvancePlan& operator=(const AdvancePlan&) = default;
|
||||
|
||||
[[nodiscard]] const Cohort& before() const noexcept {
|
||||
return before_;
|
||||
}
|
||||
[[nodiscard]] const Cohort& after() const noexcept {
|
||||
return after_;
|
||||
}
|
||||
[[nodiscard]] std::span<const accounting::Transfer> legs() const noexcept {
|
||||
return legs_;
|
||||
}
|
||||
[[nodiscard]] const IntervalFlux& flux() const noexcept {
|
||||
return flux_;
|
||||
}
|
||||
// Ticks covered. A model that has to subdivide an interval is told how long
|
||||
// the one it proposed was.
|
||||
[[nodiscard]] std::uint64_t span() const noexcept {
|
||||
return after_.last_tick().value - before_.last_tick().value;
|
||||
}
|
||||
|
||||
auto operator<=>(const AdvancePlan&) const = default;
|
||||
|
||||
private:
|
||||
friend std::expected<AdvancePlan, PopulationError> plan_advance(const Cohort&,
|
||||
const AdvanceRequest&);
|
||||
AdvancePlan(const Cohort& before, const Cohort& after) : before_{before}, after_{after} {}
|
||||
Cohort before_;
|
||||
Cohort after_;
|
||||
std::vector<accounting::Transfer> legs_;
|
||||
IntervalFlux flux_{};
|
||||
};
|
||||
|
||||
// Accounts for one proposed interval without touching any ledger or registry.
|
||||
// It checks that the declared result is exactly what the fluxes imply, and that
|
||||
// neither the population nor any inventory channel would go below zero.
|
||||
[[nodiscard]] std::expected<AdvancePlan, PopulationError>
|
||||
plan_advance(const Cohort& before, const AdvanceRequest& request);
|
||||
|
||||
// Applies exactly that plan. The installed record must still be the one the plan
|
||||
// started from, and the cohort's reservoir must still hold what it held, so a
|
||||
// proposal computed against a stale view is refused rather than applied. Every
|
||||
// rejection leaves the ledger and the registry as they were.
|
||||
[[nodiscard]] std::expected<Cohort, PopulationError>
|
||||
commit_advance(accounting::Ledger& ledger, CohortRegistry& registry, const AdvancePlan& plan);
|
||||
} // namespace evo::ecology
|
||||
@@ -29,6 +29,7 @@ materializes anything.
|
||||
| last tick | u64 | The last interval boundary integrated to. Never runs backwards |
|
||||
| revision | u64 | Nonzero. Strictly increases with every replacement within an epoch |
|
||||
| conversion | u64 | The conversion that produced this record. Nonzero provenance |
|
||||
| reservoir | u32 | Nonzero. The ledger reservoir holding this cohort's reserve |
|
||||
| age classes | 1 to 64 | Ordered, disjoint, each non-empty. See below |
|
||||
| approximation bound | count + inventory | Declared, never computed here |
|
||||
|
||||
@@ -73,7 +74,7 @@ error instead.
|
||||
| Rejected | Error |
|
||||
|---|---|
|
||||
| Representation version other than 1 | `unsupported_version` |
|
||||
| Zero habitat, genome, owner worker, owner epoch, revision or conversion | `invalid_identity` |
|
||||
| Zero habitat, genome, owner worker, owner epoch, revision, conversion or reservoir | `invalid_identity` |
|
||||
| No age classes | `no_age_classes` |
|
||||
| More than 64 age classes | `overflow` |
|
||||
| `age_high <= age_low`, or a class overlapping or preceding the one before it | `unordered_age_classes` |
|
||||
@@ -97,6 +98,8 @@ forbidden by convention.
|
||||
| Rejected | Error |
|
||||
|---|---|
|
||||
| Installing a second record for one habitat and genome | `duplicate_cohort` |
|
||||
| Installing a record whose reservoir another record already uses | `duplicate_cohort` |
|
||||
| Replacing with a record naming a different reservoir | `unknown_cohort` |
|
||||
| Replacing a record that is not installed, or naming a different habitat or genome | `unknown_cohort` |
|
||||
| Replacing under a different worker | `wrong_owner` |
|
||||
| Replacing under an older epoch | `stale_epoch` |
|
||||
@@ -120,3 +123,31 @@ no lock, lease or quorum.
|
||||
A cohort is copy-only. A moved-from record would keep its identities and lose its
|
||||
classes, which is the invalid state construction refuses, so the implicit moves
|
||||
are suppressed and a move decays to a copy.
|
||||
|
||||
## Vacancy
|
||||
|
||||
A cohort whose population reached exactly zero has no classes, no members and no
|
||||
reserve. It is built by a separate factory, so vacancy is always deliberate: the
|
||||
ordinary constructor goes on refusing a draft that merely has no classes, which
|
||||
would otherwise become a vacant record by accident.
|
||||
|
||||
| Rejected | Error |
|
||||
|---|---|
|
||||
| Building a vacant record from a draft that has classes | `not_vacant` |
|
||||
| Building an ordinary record from a draft with no classes | `no_age_classes` |
|
||||
|
||||
Vacancy exists because a population declining to exactly zero has to be
|
||||
representable. Without it a caller would have to clamp, which ECOLOGY_MODEL
|
||||
forbids, and rounding a density to zero would become a deletion. A vacant cohort
|
||||
is not an extinction and not an absence: the record, its genome, its habitat, its
|
||||
owner and its provenance all remain, and it stays installed in the registry.
|
||||
|
||||
## Reservoir
|
||||
|
||||
A cohort records which ledger reservoir holds its reserve. The reservoir is bound
|
||||
to the record rather than supplied alongside it, because an advance would
|
||||
otherwise be able to run one cohort's fluxes against another cohort's store, and
|
||||
comparing balances cannot tell two equal reserves apart. The registry refuses two
|
||||
records sharing a reservoir, and a replacement may not move a record to a
|
||||
different one: that would be other inventory holding this cohort, not a later view
|
||||
of this one.
|
||||
|
||||
+53
-1
@@ -50,7 +50,8 @@ std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
|
||||
// Every identity a cohort names has to name something. A zero owner or epoch
|
||||
// would be a record nobody is responsible for integrating.
|
||||
if (draft.habitat.value == 0 || draft.genome == 0 || draft.owner.worker == 0 ||
|
||||
draft.owner.epoch == 0 || draft.revision == 0 || draft.conversion == 0) {
|
||||
draft.owner.epoch == 0 || draft.revision == 0 || draft.conversion == 0 ||
|
||||
draft.reservoir.value == 0) {
|
||||
return std::unexpected{CohortError::invalid_identity};
|
||||
}
|
||||
if (draft.classes.empty()) {
|
||||
@@ -90,6 +91,11 @@ std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
|
||||
return std::unexpected{CohortError::overflow};
|
||||
}
|
||||
}
|
||||
// Whole members and owed fractions are also read as one scaled quantity, so
|
||||
// the count has to stay inside what that scaling can hold.
|
||||
if (count > maximum / residual_scale || residual > maximum - count * residual_scale) {
|
||||
return std::unexpected{CohortError::overflow};
|
||||
}
|
||||
Cohort cohort;
|
||||
cohort.version_ = draft.representation_version;
|
||||
cohort.habitat_ = draft.habitat;
|
||||
@@ -98,11 +104,40 @@ std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
|
||||
cohort.last_tick_ = draft.last_tick;
|
||||
cohort.revision_ = draft.revision;
|
||||
cohort.conversion_ = draft.conversion;
|
||||
cohort.reservoir_ = draft.reservoir;
|
||||
cohort.classes_ = std::move(draft.classes);
|
||||
cohort.bound_ = draft.bound;
|
||||
return cohort;
|
||||
}
|
||||
|
||||
std::expected<Cohort, CohortError> Cohort::vacant(const CohortDraft& draft) {
|
||||
// A record with no members may hold nothing: a reserve with nobody to own it
|
||||
// is the same defect a class with no members and a reserve would be.
|
||||
if (!draft.classes.empty()) {
|
||||
return std::unexpected{CohortError::not_vacant};
|
||||
}
|
||||
// Everything else a cohort must name, it still must. The identity checks are
|
||||
// borrowed from `create` through a placeholder class that is then discarded,
|
||||
// so the two factories cannot drift apart on what an identity is.
|
||||
auto probe = draft;
|
||||
probe.classes = {{0, 1, 1, {}, 0}};
|
||||
const auto checked = create(std::move(probe));
|
||||
if (!checked) {
|
||||
return std::unexpected{checked.error()};
|
||||
}
|
||||
Cohort cohort;
|
||||
cohort.version_ = draft.representation_version;
|
||||
cohort.habitat_ = draft.habitat;
|
||||
cohort.genome_ = draft.genome;
|
||||
cohort.owner_ = draft.owner;
|
||||
cohort.last_tick_ = draft.last_tick;
|
||||
cohort.revision_ = draft.revision;
|
||||
cohort.conversion_ = draft.conversion;
|
||||
cohort.reservoir_ = draft.reservoir;
|
||||
cohort.bound_ = draft.bound;
|
||||
return cohort;
|
||||
}
|
||||
|
||||
std::uint64_t Cohort::count() const noexcept {
|
||||
std::uint64_t total = 0;
|
||||
for (const auto& age : classes_) {
|
||||
@@ -131,12 +166,24 @@ std::uint64_t Cohort::residual() const noexcept {
|
||||
return total;
|
||||
}
|
||||
|
||||
std::uint64_t Cohort::population() const noexcept {
|
||||
// Construction proved this cannot overflow.
|
||||
return count() * residual_scale + residual();
|
||||
}
|
||||
|
||||
std::expected<void, CohortError> CohortRegistry::install(const Cohort& cohort) {
|
||||
const auto wanted = key_of(cohort);
|
||||
const auto at = std::ranges::lower_bound(cohorts_, wanted, {}, key_of);
|
||||
if (at != cohorts_.end() && key_of(*at) == wanted) {
|
||||
return std::unexpected{CohortError::duplicate_cohort};
|
||||
}
|
||||
// One reservoir backing two records would be the same inventory in two
|
||||
// places, which is what this registry exists to make unrepresentable.
|
||||
if (std::ranges::any_of(cohorts_, [&](const Cohort& other) {
|
||||
return other.reservoir() == cohort.reservoir();
|
||||
})) {
|
||||
return std::unexpected{CohortError::duplicate_cohort};
|
||||
}
|
||||
if (cohorts_.size() >= max_cohorts) {
|
||||
return std::unexpected{CohortError::registry_full};
|
||||
}
|
||||
@@ -172,6 +219,11 @@ std::expected<void, CohortError> CohortRegistry::replace(const Cohort& cohort) {
|
||||
if (cohort.last_tick() < at->last_tick()) {
|
||||
return std::unexpected{CohortError::backward_tick};
|
||||
}
|
||||
// A record cannot change which reservoir backs it: that would be a different
|
||||
// store holding this cohort's inventory, not a later view of this one.
|
||||
if (cohort.reservoir() != at->reservoir()) {
|
||||
return std::unexpected{CohortError::unknown_cohort};
|
||||
}
|
||||
*at = cohort;
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -113,6 +113,9 @@ std::expected<CollapsePlan, CollapseError> plan_collapse(std::span<const ActiveM
|
||||
draft.last_tick = request.tick;
|
||||
draft.revision = request.revision;
|
||||
draft.conversion = request.conversion;
|
||||
// The gathering reservoir is where the cohort's reserve will live, so the
|
||||
// record carries it rather than leaving it to be supplied again later.
|
||||
draft.reservoir = request.destination;
|
||||
draft.classes = std::move(classes);
|
||||
draft.bound = request.bound;
|
||||
// Built and validated here, so commit cannot fail on the record's validity
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
#include "evo/ecology/population.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 take(std::uint64_t& total, std::uint64_t amount) noexcept {
|
||||
if (amount > 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;
|
||||
}
|
||||
// Every channel separately: a total mass is not an additional inventory, so any
|
||||
// one channel may be the one that would go below zero.
|
||||
[[nodiscard]] bool take(accounting::Inventory& total,
|
||||
const accounting::Inventory& amount) noexcept {
|
||||
if (!take(total.energy.value, amount.energy.value)) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t channel = 0; channel < total.matter.size(); ++channel) {
|
||||
if (!take(total.matter[channel].value, amount.matter[channel].value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
[[nodiscard]] bool empty(const accounting::Inventory& inventory) noexcept {
|
||||
return inventory == accounting::Inventory{};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::expected<AdvancePlan, PopulationError> plan_advance(const Cohort& before,
|
||||
const AdvanceRequest& request) {
|
||||
if (request.owner.worker == 0 || request.owner.epoch == 0 || request.revision == 0) {
|
||||
return std::unexpected{PopulationError::invalid_request};
|
||||
}
|
||||
// The interval starts where the record stands, so intervals cannot overlap
|
||||
// or leave a gap, and a zero-length one integrates nothing.
|
||||
if (request.to <= before.last_tick()) {
|
||||
return std::unexpected{PopulationError::empty_interval};
|
||||
}
|
||||
if (request.owner.worker != before.owner().worker) {
|
||||
return std::unexpected{PopulationError::wrong_owner};
|
||||
}
|
||||
if (request.owner.epoch < before.owner().epoch) {
|
||||
return std::unexpected{PopulationError::stale_revision};
|
||||
}
|
||||
if (request.owner.epoch == before.owner().epoch && request.revision <= before.revision()) {
|
||||
return std::unexpected{PopulationError::stale_revision};
|
||||
}
|
||||
// Biomass has to leave for somewhere that is not the cohort itself, and only
|
||||
// where an amount actually moves does a counterparty have to be named.
|
||||
const auto& flux = request.flux;
|
||||
const auto needs = [&](const accounting::Inventory& amount, accounting::ReservoirId where) {
|
||||
return empty(amount) || (where.value != 0 && where != before.reservoir());
|
||||
};
|
||||
if (!needs(flux.to_detritus, request.detritus) ||
|
||||
!needs(flux.to_predators, request.predators) ||
|
||||
!needs(flux.to_elsewhere, request.elsewhere) ||
|
||||
!needs(flux.from_elsewhere, request.elsewhere)) {
|
||||
return std::unexpected{PopulationError::invalid_request};
|
||||
}
|
||||
|
||||
// Population, in units of residual_scale. Additions first so a subtraction
|
||||
// never has to borrow against an arrival that has not been counted.
|
||||
auto population = before.population();
|
||||
if (!add(population, flux.births) || !add(population, flux.immigration)) {
|
||||
return std::unexpected{PopulationError::overflow};
|
||||
}
|
||||
if (!take(population, flux.deaths) || !take(population, flux.predation) ||
|
||||
!take(population, flux.emigration)) {
|
||||
// Refused, never clamped: a clamp would hide an unstable interval and
|
||||
// manufacture an extinction the model never proposed.
|
||||
return std::unexpected{PopulationError::negative_population};
|
||||
}
|
||||
// Biomass. There is deliberately no birth term: a birth redistributes what
|
||||
// the cohort already holds, so there is nowhere for one to bring biomass in.
|
||||
auto reserve = before.reserve();
|
||||
if (!add(reserve, flux.from_elsewhere)) {
|
||||
return std::unexpected{PopulationError::overflow};
|
||||
}
|
||||
if (!take(reserve, flux.to_detritus) || !take(reserve, flux.to_predators) ||
|
||||
!take(reserve, flux.to_elsewhere)) {
|
||||
return std::unexpected{PopulationError::negative_biomass};
|
||||
}
|
||||
|
||||
CohortDraft draft;
|
||||
draft.representation_version = before.representation_version();
|
||||
draft.habitat = before.habitat();
|
||||
draft.genome = before.genome();
|
||||
draft.owner = request.owner;
|
||||
draft.last_tick = request.to;
|
||||
draft.revision = request.revision;
|
||||
draft.conversion = before.conversion();
|
||||
draft.reservoir = before.reservoir();
|
||||
draft.classes = request.after;
|
||||
draft.bound = request.bound;
|
||||
// A population that reached exactly zero is a vacant record, not an absent
|
||||
// one and not an extinct one: the genome, the habitat and the history stay.
|
||||
const auto built =
|
||||
request.after.empty() ? Cohort::vacant(draft) : Cohort::create(std::move(draft));
|
||||
if (!built) {
|
||||
return std::unexpected{PopulationError::invalid_cohort};
|
||||
}
|
||||
// The declared result has to be exactly what the fluxes imply. Anything else
|
||||
// is a model whose own arithmetic does not close.
|
||||
if (built->population() != population) {
|
||||
return std::unexpected{PopulationError::population_mismatch};
|
||||
}
|
||||
if (built->reserve() != reserve) {
|
||||
return std::unexpected{PopulationError::biomass_mismatch};
|
||||
}
|
||||
|
||||
std::vector<accounting::Transfer> legs;
|
||||
const auto leg = [&](const accounting::Inventory& amount, accounting::ReservoirId where,
|
||||
bool inbound) {
|
||||
if (empty(amount)) {
|
||||
return;
|
||||
}
|
||||
legs.push_back(inbound ? accounting::Transfer{where, before.reservoir(), amount}
|
||||
: accounting::Transfer{before.reservoir(), where, amount});
|
||||
};
|
||||
leg(flux.to_detritus, request.detritus, false);
|
||||
leg(flux.to_predators, request.predators, false);
|
||||
leg(flux.to_elsewhere, request.elsewhere, false);
|
||||
leg(flux.from_elsewhere, request.elsewhere, true);
|
||||
if (legs.size() > accounting::max_transfers) {
|
||||
return std::unexpected{PopulationError::overflow};
|
||||
}
|
||||
|
||||
AdvancePlan plan{before, *built};
|
||||
plan.legs_ = std::move(legs);
|
||||
plan.flux_ = flux;
|
||||
return plan;
|
||||
}
|
||||
|
||||
std::expected<Cohort, PopulationError>
|
||||
commit_advance(accounting::Ledger& ledger, CohortRegistry& registry, const AdvancePlan& plan) {
|
||||
const auto& before = plan.before();
|
||||
// The record the plan was computed against must still be the installed one,
|
||||
// to the revision: a proposal built on a stale view is refused, not applied.
|
||||
const auto installed = registry.find(before.habitat(), before.genome());
|
||||
if (!installed) {
|
||||
return std::unexpected{PopulationError::not_installed};
|
||||
}
|
||||
if (*installed != before) {
|
||||
return std::unexpected{PopulationError::stale_plan};
|
||||
}
|
||||
const auto balances = ledger.balances();
|
||||
if (before.reservoir().value > balances.size()) {
|
||||
return std::unexpected{PopulationError::stale_plan};
|
||||
}
|
||||
// And the reservoir must still hold what the plan accounted for, or the
|
||||
// fluxes were measured against inventory that is no longer there.
|
||||
if (balances[before.reservoir().value - 1] != before.reserve()) {
|
||||
return std::unexpected{PopulationError::stale_plan};
|
||||
}
|
||||
for (const auto& leg : plan.legs()) {
|
||||
if (leg.from.value > balances.size() || leg.to.value > balances.size()) {
|
||||
return std::unexpected{PopulationError::stale_plan};
|
||||
}
|
||||
}
|
||||
if (!plan.legs().empty()) {
|
||||
if (ledger.last_action() == maximum) {
|
||||
return std::unexpected{PopulationError::ledger_failure};
|
||||
}
|
||||
if (!ledger.transfer(ledger.last_action() + 1, plan.legs())) {
|
||||
return std::unexpected{PopulationError::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{PopulationError::stale_plan};
|
||||
}
|
||||
return plan.after();
|
||||
}
|
||||
} // namespace evo::ecology
|
||||
+79
-2
@@ -42,6 +42,7 @@ CohortDraft draft() {
|
||||
source.last_tick = Tick{900};
|
||||
source.revision = 4;
|
||||
source.conversion = 5;
|
||||
source.reservoir = {1};
|
||||
source.classes = {{0, 100, 40, held(400), 0},
|
||||
{100, 200, 25, held(900), 250'000},
|
||||
{200, 300, 10, held(1'000), 999'999}};
|
||||
@@ -68,6 +69,9 @@ void a_cohort_keeps_exactly_what_it_was_given() {
|
||||
CHECK(cohort.last_tick() == Tick{900});
|
||||
CHECK(cohort.revision() == 4);
|
||||
CHECK(cohort.conversion() == 5);
|
||||
CHECK(cohort.reservoir() == ReservoirId{1});
|
||||
CHECK(!cohort.is_vacant());
|
||||
CHECK(cohort.population() == cohort.count() * residual_scale + cohort.residual());
|
||||
CHECK(cohort.bound().count == 2);
|
||||
CHECK(cohort.bound().inventory == held(30));
|
||||
CHECK(cohort.classes().size() == 3);
|
||||
@@ -119,7 +123,7 @@ void every_invariant_is_rejected_by_name() {
|
||||
CHECK(refused(Cohort::create(wrong_version), CohortError::unsupported_version));
|
||||
// Each identity a cohort names has to name something, including its owner:
|
||||
// a record nobody is responsible for integrating has no owner at all.
|
||||
for (auto missing : {0U, 1U, 2U, 3U, 4U, 5U}) {
|
||||
for (auto missing : {0U, 1U, 2U, 3U, 4U, 5U, 6U}) {
|
||||
auto blank = draft();
|
||||
if (missing == 0) {
|
||||
blank.habitat = {};
|
||||
@@ -131,8 +135,12 @@ void every_invariant_is_rejected_by_name() {
|
||||
blank.owner.epoch = 0;
|
||||
} else if (missing == 4) {
|
||||
blank.revision = 0;
|
||||
} else {
|
||||
} else if (missing == 5) {
|
||||
blank.conversion = 0;
|
||||
} else {
|
||||
// A cohort that does not say where its reserve is could be advanced
|
||||
// against another cohort's reservoir.
|
||||
blank.reservoir = {};
|
||||
}
|
||||
CHECK(refused(Cohort::create(blank), CohortError::invalid_identity));
|
||||
}
|
||||
@@ -220,8 +228,10 @@ void one_habitat_and_genome_holds_one_cohort() {
|
||||
// Another genome, or the same genome elsewhere, is a different record.
|
||||
auto other_genome = draft();
|
||||
other_genome.genome = 4;
|
||||
other_genome.reservoir = {2};
|
||||
auto other_habitat = draft();
|
||||
other_habitat.habitat = {8};
|
||||
other_habitat.reservoir = {3};
|
||||
CHECK(registry.install(built(other_genome)).has_value());
|
||||
CHECK(registry.install(built(other_habitat)).has_value());
|
||||
CHECK(registry.size() == 3);
|
||||
@@ -370,6 +380,70 @@ void a_moved_from_cohort_is_still_a_valid_cohort() {
|
||||
CHECK(refused(Cohort::create(hollow), CohortError::no_age_classes));
|
||||
}
|
||||
|
||||
void one_reservoir_backs_one_cohort() {
|
||||
// Two records sharing a reservoir would be the same inventory in two places,
|
||||
// which is the whole point of the registry. Habitat and genome differing does
|
||||
// not make it two stores.
|
||||
CohortRegistry registry;
|
||||
CHECK(registry.install(valid()).has_value());
|
||||
auto sharing = draft();
|
||||
sharing.genome = 4;
|
||||
CHECK(refused(registry.install(built(sharing)), CohortError::duplicate_cohort));
|
||||
auto elsewhere_sharing = draft();
|
||||
elsewhere_sharing.habitat = {8};
|
||||
CHECK(refused(registry.install(built(elsewhere_sharing)), CohortError::duplicate_cohort));
|
||||
CHECK(registry.size() == 1);
|
||||
auto separate = draft();
|
||||
separate.genome = 4;
|
||||
separate.reservoir = {2};
|
||||
CHECK(registry.install(built(separate)).has_value());
|
||||
CHECK(registry.size() == 2);
|
||||
// A replacement cannot move a record to a different store either: that would
|
||||
// be other inventory holding this cohort, not a later view of this one.
|
||||
auto rehomed = draft();
|
||||
rehomed.revision = 9;
|
||||
rehomed.reservoir = {3};
|
||||
CHECK(refused(registry.replace(built(rehomed)), CohortError::unknown_cohort));
|
||||
CHECK(registry.find(HabitatId{7}, 3)->reservoir() == ReservoirId{1});
|
||||
}
|
||||
|
||||
void vacancy_is_deliberate_and_keeps_the_record() {
|
||||
// A population that reaches exactly zero has to be representable, or a caller
|
||||
// would have to clamp, which ECOLOGY_MODEL forbids. It is a separate factory
|
||||
// so it can never happen by leaving the classes out of a draft by accident.
|
||||
auto empty_draft = draft();
|
||||
empty_draft.classes.clear();
|
||||
CHECK(refused(Cohort::create(empty_draft), CohortError::no_age_classes));
|
||||
CHECK(refused(Cohort::vacant(draft()), CohortError::not_vacant));
|
||||
const auto vacated = Cohort::vacant(empty_draft);
|
||||
CHECK(vacated.has_value());
|
||||
CHECK(vacated->is_vacant());
|
||||
CHECK(vacated->count() == 0);
|
||||
CHECK(vacated->residual() == 0);
|
||||
CHECK(vacated->population() == 0);
|
||||
CHECK(vacated->reserve() == Inventory{});
|
||||
// Everything that identifies the record survives being empty. A vacant cohort
|
||||
// is not an extinction: the genome and its habitat are both still here.
|
||||
CHECK(vacated->genome() == 3);
|
||||
CHECK(vacated->habitat() == HabitatId{7});
|
||||
CHECK(vacated->owner() == Owner{11, 2});
|
||||
CHECK(vacated->conversion() == 5);
|
||||
CHECK(vacated->reservoir() == ReservoirId{1});
|
||||
CHECK(vacated->last_tick() == Tick{900});
|
||||
// The identities are still required, borrowed from the same checks.
|
||||
auto anonymous = empty_draft;
|
||||
anonymous.genome = 0;
|
||||
CHECK(refused(Cohort::vacant(anonymous), CohortError::invalid_identity));
|
||||
auto homeless = empty_draft;
|
||||
homeless.reservoir = {};
|
||||
CHECK(refused(Cohort::vacant(homeless), CohortError::invalid_identity));
|
||||
// It installs and is kept like any other record.
|
||||
CohortRegistry registry;
|
||||
CHECK(registry.install(*vacated).has_value());
|
||||
CHECK(registry.find(HabitatId{7}, 3)->is_vacant());
|
||||
CHECK(registry.size() == 1);
|
||||
}
|
||||
|
||||
void lineage_stays_the_archives_answer() {
|
||||
// A cohort names a genome and never stores its ancestry, so it cannot claim a
|
||||
// parentage the archive would contradict, and invents none from membership.
|
||||
@@ -407,6 +481,7 @@ void lineage_stays_the_archives_answer() {
|
||||
CHECK(registry.install(cohort).has_value());
|
||||
auto sibling = draft();
|
||||
sibling.genome = 3;
|
||||
sibling.reservoir = {2};
|
||||
CHECK(registry.install(built(sibling)).has_value());
|
||||
CHECK(registry.size() == 2);
|
||||
CHECK(registry.find(HabitatId{7}, 3)->genome() != registry.find(HabitatId{7}, 9)->genome());
|
||||
@@ -418,6 +493,8 @@ int main() try {
|
||||
every_invariant_is_rejected_by_name();
|
||||
one_habitat_and_genome_holds_one_cohort();
|
||||
only_the_recorded_owner_may_replace_a_cohort();
|
||||
one_reservoir_backs_one_cohort();
|
||||
vacancy_is_deliberate_and_keeps_the_record();
|
||||
an_epoch_alone_cannot_order_two_writes();
|
||||
a_moved_from_cohort_is_still_a_valid_cohort();
|
||||
lineage_stays_the_archives_answer();
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
#include "evo/core/random.hpp"
|
||||
#include "evo/ecology/population.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <expected>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#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::Random;
|
||||
using evo::Tick;
|
||||
void check(bool condition, std::source_location location = std::source_location::current()) {
|
||||
if (!condition) {
|
||||
throw std::runtime_error("population 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, PopulationError>& result,
|
||||
PopulationError 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}}};
|
||||
}
|
||||
// 1 backs the cohort, 2 detritus, 3 predators, 4 escrow elsewhere, 5 unrelated.
|
||||
constexpr ReservoirId backing{1};
|
||||
constexpr ReservoirId detritus{2};
|
||||
constexpr ReservoirId predators{3};
|
||||
constexpr ReservoirId elsewhere{4};
|
||||
constexpr std::size_t reservoir_count = 5;
|
||||
|
||||
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;
|
||||
source.classes = {{0, 100, 40, held(400, 4'000), 0}, {100, 200, 20, held(600, 6'000), 0}};
|
||||
source.bound = {2, held(1, 1)};
|
||||
return source;
|
||||
}
|
||||
Cohort standing() {
|
||||
const auto cohort = Cohort::create(draft());
|
||||
check(cohort.has_value());
|
||||
return *cohort;
|
||||
}
|
||||
Cohort built(const CohortDraft& source) {
|
||||
const auto cohort = Cohort::create(source);
|
||||
check(cohort.has_value());
|
||||
return *cohort;
|
||||
}
|
||||
AdvanceRequest request() {
|
||||
AdvanceRequest source;
|
||||
source.to = Tick{1'000};
|
||||
source.owner = {11, 2};
|
||||
source.revision = 5;
|
||||
source.after = draft().classes;
|
||||
source.detritus = detritus;
|
||||
source.predators = predators;
|
||||
source.elsewhere = elsewhere;
|
||||
source.bound = {2, held(1, 1)};
|
||||
return source;
|
||||
}
|
||||
Ledger world() {
|
||||
std::array<Inventory, reservoir_count> opening{};
|
||||
opening[0] = standing().reserve();
|
||||
opening[4] = held(7, 7); // Unrelated, to prove nothing else moves.
|
||||
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;
|
||||
}
|
||||
|
||||
void an_interval_that_changes_nothing_still_advances_the_clock() {
|
||||
const auto before = standing();
|
||||
CHECK(before.population() == 60 * residual_scale);
|
||||
const auto plan = plan_advance(before, request());
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->span() == 100);
|
||||
CHECK(plan->after().last_tick() == Tick{1'000});
|
||||
CHECK(plan->after().revision() == 5);
|
||||
CHECK(plan->after().population() == before.population());
|
||||
CHECK(plan->after().reserve() == before.reserve());
|
||||
CHECK(plan->after().reservoir() == before.reservoir());
|
||||
CHECK(plan->legs().empty()); // Nothing moved, so nothing is transferred.
|
||||
auto ledger = world();
|
||||
auto registry = registry_holding(before);
|
||||
const auto action = ledger.last_action();
|
||||
const auto installed = commit_advance(ledger, registry, *plan);
|
||||
CHECK(installed.has_value());
|
||||
CHECK(ledger.last_action() == action); // No empty transaction was submitted.
|
||||
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'000});
|
||||
}
|
||||
|
||||
void a_birth_redistributes_and_never_creates_biomass() {
|
||||
// There is no term by which a birth could bring biomass in, so newborns are
|
||||
// funded from what the cohort already holds. The reserve is unchanged and the
|
||||
// declared structure says where inside the cohort it now sits.
|
||||
auto grown = request();
|
||||
grown.flux.births = 5 * residual_scale;
|
||||
grown.after = {{0, 100, 45, held(400, 4'000), 0}, {100, 200, 20, held(600, 6'000), 0}};
|
||||
const auto before = standing();
|
||||
const auto plan = plan_advance(before, grown);
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->after().population() == before.population() + 5 * residual_scale);
|
||||
CHECK(plan->after().reserve() == before.reserve()); // Nothing was created.
|
||||
CHECK(plan->legs().empty());
|
||||
auto ledger = world();
|
||||
auto registry = registry_holding(before);
|
||||
const auto total = ledger.conserved_totals();
|
||||
CHECK(commit_advance(ledger, registry, *plan).has_value());
|
||||
CHECK(ledger.conserved_totals() == total);
|
||||
CHECK(ledger.balances()[0] == before.reserve());
|
||||
}
|
||||
|
||||
void death_predation_and_migration_move_biomass_once() {
|
||||
auto mixed = request();
|
||||
mixed.flux.deaths = 4 * residual_scale;
|
||||
mixed.flux.predation = 3 * residual_scale;
|
||||
mixed.flux.emigration = 2 * residual_scale;
|
||||
mixed.flux.immigration = 1 * residual_scale;
|
||||
mixed.flux.to_detritus = held(40, 400);
|
||||
mixed.flux.to_predators = held(30, 300);
|
||||
mixed.flux.to_elsewhere = held(20, 200);
|
||||
mixed.flux.from_elsewhere = held(10, 100);
|
||||
// 60 - 4 - 3 - 2 + 1 = 52 members; 1000 - 40 - 30 - 20 + 10 = 920 energy.
|
||||
mixed.after = {{0, 100, 32, held(320, 3'200), 0}, {100, 200, 20, held(600, 6'000), 0}};
|
||||
const auto before = standing();
|
||||
const auto plan = plan_advance(before, mixed);
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->after().population() == 52 * residual_scale);
|
||||
CHECK(plan->after().reserve() == held(920, 9'200));
|
||||
CHECK(plan->legs().size() == 4);
|
||||
auto ledger = world();
|
||||
auto registry = registry_holding(before);
|
||||
// The escrow has to be able to fund the immigrants it sends.
|
||||
const std::array seed{Transfer{{5}, elsewhere, held(7, 7)}};
|
||||
CHECK(ledger.transfer(ledger.last_action() + 1, seed).has_value());
|
||||
const auto total = ledger.conserved_totals();
|
||||
const auto committed = commit_advance(ledger, registry, *plan);
|
||||
CHECK(committed.has_value());
|
||||
// Conservation is the ledger's property; nothing was created or destroyed.
|
||||
CHECK(ledger.conserved_totals() == total);
|
||||
CHECK(ledger.balances()[backing.value - 1] == held(920, 9'200));
|
||||
CHECK(ledger.balances()[backing.value - 1] == committed->reserve());
|
||||
CHECK(ledger.balances()[detritus.value - 1] == held(40, 400));
|
||||
CHECK(ledger.balances()[predators.value - 1] == held(30, 300));
|
||||
// The escrow received twenty energy and two hundred matter and gave back ten
|
||||
// and one hundred, so from seven it stands at seventeen and a hundred and
|
||||
// seven. The legs apply in order, so it can fund the immigrants it sends.
|
||||
CHECK(ledger.balances()[elsewhere.value - 1] == held(17, 107));
|
||||
}
|
||||
|
||||
void a_proposal_that_would_go_below_zero_is_refused_not_clamped() {
|
||||
const auto before = standing();
|
||||
// More deaths than there are members. A clamp here would hide an interval
|
||||
// the model could not integrate and would invent an extinction.
|
||||
auto overkill = request();
|
||||
overkill.flux.deaths = 61 * residual_scale;
|
||||
overkill.after.clear();
|
||||
CHECK(refused(plan_advance(before, overkill), PopulationError::negative_population));
|
||||
// By a single millionth of a member, which is the boundary that matters.
|
||||
auto barely = request();
|
||||
barely.flux.deaths = before.population() + 1;
|
||||
barely.after.clear();
|
||||
CHECK(refused(plan_advance(before, barely), PopulationError::negative_population));
|
||||
// Exactly all of them is representable, and is vacancy rather than refusal.
|
||||
auto exact = request();
|
||||
exact.flux.deaths = before.population();
|
||||
exact.flux.to_detritus = before.reserve();
|
||||
exact.after.clear();
|
||||
const auto emptied = plan_advance(before, exact);
|
||||
CHECK(emptied.has_value());
|
||||
CHECK(emptied->after().is_vacant());
|
||||
CHECK(emptied->after().population() == 0);
|
||||
CHECK(emptied->after().reserve() == Inventory{});
|
||||
// Biomass is bounded per channel, so any one channel may be the one refused.
|
||||
for (std::size_t channel = 0; channel < 4; ++channel) {
|
||||
auto greedy = request();
|
||||
greedy.flux.to_detritus = before.reserve();
|
||||
greedy.flux.to_detritus.matter[channel].value += 1;
|
||||
greedy.flux.deaths = before.population();
|
||||
greedy.after.clear();
|
||||
CHECK(refused(plan_advance(before, greedy), PopulationError::negative_biomass));
|
||||
}
|
||||
auto too_much_energy = request();
|
||||
too_much_energy.flux.to_detritus = before.reserve();
|
||||
too_much_energy.flux.to_detritus.energy.value += 1;
|
||||
too_much_energy.flux.deaths = before.population();
|
||||
too_much_energy.after.clear();
|
||||
CHECK(refused(plan_advance(before, too_much_energy), PopulationError::negative_biomass));
|
||||
}
|
||||
|
||||
void a_population_below_one_member_is_still_a_population() {
|
||||
// Rounding a density to zero cannot declare an extinction, so a fraction of
|
||||
// a member is a number the record carries rather than a decision it makes.
|
||||
const auto before = standing();
|
||||
auto dwindling = request();
|
||||
dwindling.flux.deaths = before.population() - 250'000;
|
||||
// All of the biomass leaves with them. A class that is only a fraction of a
|
||||
// member may hold no reserve, because ADR-0036 gives reserve to members and a
|
||||
// fraction is not one yet; that tension is real and is recorded, not hidden.
|
||||
dwindling.flux.to_detritus = before.reserve();
|
||||
dwindling.after = {{0, 100, 0, Inventory{}, 250'000}};
|
||||
const auto plan = plan_advance(before, dwindling);
|
||||
CHECK(plan.has_value());
|
||||
CHECK(plan->after().count() == 0);
|
||||
CHECK(plan->after().residual() == 250'000);
|
||||
CHECK(plan->after().population() == 250'000);
|
||||
CHECK(!plan->after().is_vacant()); // A quarter of a member is not vacancy.
|
||||
auto ledger = world();
|
||||
auto registry = registry_holding(before);
|
||||
CHECK(commit_advance(ledger, registry, *plan).has_value());
|
||||
// The record is still installed: nothing was removed for being small.
|
||||
const auto found = registry.find(HabitatId{7}, 3);
|
||||
CHECK(found.has_value());
|
||||
CHECK(found->population() == 250'000);
|
||||
CHECK(registry.size() == 1);
|
||||
}
|
||||
|
||||
void a_vacant_cohort_is_not_an_extinction() {
|
||||
auto empty_draft = draft();
|
||||
empty_draft.classes.clear();
|
||||
const auto vacated = Cohort::vacant(empty_draft);
|
||||
CHECK(vacated.has_value());
|
||||
CHECK(vacated->is_vacant());
|
||||
CHECK(vacated->population() == 0);
|
||||
CHECK(vacated->reserve() == Inventory{});
|
||||
// It is still a whole record: genome, habitat, owner and provenance remain.
|
||||
CHECK(vacated->genome() == 3);
|
||||
CHECK(vacated->habitat() == HabitatId{7});
|
||||
CHECK(vacated->conversion() == 5);
|
||||
CHECK(vacated->reservoir() == backing);
|
||||
// And it stays in the registry rather than being removed for being empty.
|
||||
auto registry = registry_holding(*vacated);
|
||||
CHECK(registry.size() == 1);
|
||||
CHECK(registry.find(HabitatId{7}, 3)->is_vacant());
|
||||
// Vacancy is deliberate: `create` still refuses a draft that merely has no
|
||||
// classes, and `vacant` refuses one that has some.
|
||||
CHECK(!Cohort::create(empty_draft).has_value());
|
||||
CHECK(!Cohort::vacant(draft()).has_value());
|
||||
// A vacant record holding inventory would be biomass owned by nobody.
|
||||
const auto before = standing();
|
||||
auto unfunded = request();
|
||||
unfunded.flux.deaths = before.population();
|
||||
unfunded.after.clear();
|
||||
CHECK(refused(plan_advance(before, unfunded), PopulationError::biomass_mismatch));
|
||||
}
|
||||
|
||||
void the_declared_result_must_be_what_the_fluxes_imply() {
|
||||
const auto before = standing();
|
||||
// A structure claiming more members than the fluxes produced.
|
||||
auto inflated = request();
|
||||
inflated.after[0].count += 1;
|
||||
CHECK(refused(plan_advance(before, inflated), PopulationError::population_mismatch));
|
||||
// A structure claiming biomass the fluxes did not leave behind.
|
||||
auto enriched = request();
|
||||
enriched.after[0].reserve.energy.value += 1;
|
||||
CHECK(refused(plan_advance(before, enriched), PopulationError::biomass_mismatch));
|
||||
// Biomass that left without anyone declaring where it went.
|
||||
auto vanished = request();
|
||||
vanished.after[0].reserve.energy.value -= 1;
|
||||
CHECK(refused(plan_advance(before, vanished), PopulationError::biomass_mismatch));
|
||||
// An interval must move forward, and one that ends where it began integrates
|
||||
// nothing while claiming a new revision.
|
||||
auto backwards = request();
|
||||
backwards.to = Tick{800};
|
||||
CHECK(refused(plan_advance(before, backwards), PopulationError::empty_interval));
|
||||
auto standstill = request();
|
||||
standstill.to = before.last_tick();
|
||||
CHECK(refused(plan_advance(before, standstill), PopulationError::empty_interval));
|
||||
// One owner integrates each interval, and only ever forwards.
|
||||
auto intruder = request();
|
||||
intruder.owner = {12, 2};
|
||||
CHECK(refused(plan_advance(before, intruder), PopulationError::wrong_owner));
|
||||
auto replayed = request();
|
||||
replayed.revision = before.revision();
|
||||
CHECK(refused(plan_advance(before, replayed), PopulationError::stale_revision));
|
||||
auto older = request();
|
||||
older.owner = {11, 1};
|
||||
CHECK(refused(plan_advance(before, older), PopulationError::stale_revision));
|
||||
// Biomass cannot leave for the cohort's own reservoir, which would move
|
||||
// nothing while reporting that it had.
|
||||
auto circular = request();
|
||||
circular.flux.deaths = 1 * residual_scale;
|
||||
circular.flux.to_detritus = held(10, 100);
|
||||
circular.detritus = backing;
|
||||
circular.after = {{0, 100, 39, held(390, 3'900), 0}, {100, 200, 20, held(600, 6'000), 0}};
|
||||
CHECK(refused(plan_advance(before, circular), PopulationError::invalid_request));
|
||||
auto unnamed = circular;
|
||||
unnamed.detritus = {};
|
||||
CHECK(refused(plan_advance(before, unnamed), PopulationError::invalid_request));
|
||||
}
|
||||
|
||||
void a_stale_proposal_is_refused_and_changes_nothing() {
|
||||
const auto before = standing();
|
||||
auto mover = request();
|
||||
mover.flux.deaths = 4 * residual_scale;
|
||||
mover.flux.to_detritus = held(40, 400);
|
||||
mover.after = {{0, 100, 36, held(360, 3'600), 0}, {100, 200, 20, held(600, 6'000), 0}};
|
||||
const auto plan = plan_advance(before, mover);
|
||||
CHECK(plan.has_value());
|
||||
|
||||
// Nothing installed at all.
|
||||
auto bare = world();
|
||||
CohortRegistry nothing;
|
||||
const auto opening = std::vector<Inventory>{bare.balances().begin(), bare.balances().end()};
|
||||
CHECK(refused(commit_advance(bare, nothing, *plan), PopulationError::not_installed));
|
||||
CHECK(std::vector<Inventory>(bare.balances().begin(), bare.balances().end()) == opening);
|
||||
|
||||
// Installed, but already advanced past the view the plan was built on.
|
||||
auto moved = world();
|
||||
auto registry = registry_holding(before);
|
||||
auto newer = draft();
|
||||
newer.revision = 9;
|
||||
newer.last_tick = Tick{950};
|
||||
CHECK(registry.replace(built(newer)).has_value());
|
||||
const auto action = moved.last_action();
|
||||
CHECK(refused(commit_advance(moved, registry, *plan), PopulationError::stale_plan));
|
||||
CHECK(std::vector<Inventory>(moved.balances().begin(), moved.balances().end()) == opening);
|
||||
CHECK(moved.last_action() == action);
|
||||
CHECK(registry.find(HabitatId{7}, 3)->revision() == 9);
|
||||
|
||||
// Installed and current, but the reservoir no longer holds what was counted.
|
||||
auto drifted = world();
|
||||
auto current = registry_holding(before);
|
||||
const std::array leak{Transfer{backing, {5}, held(1, 1)}};
|
||||
CHECK(drifted.transfer(drifted.last_action() + 1, leak).has_value());
|
||||
const auto after_leak =
|
||||
std::vector<Inventory>{drifted.balances().begin(), drifted.balances().end()};
|
||||
const auto leaked_action = drifted.last_action();
|
||||
CHECK(refused(commit_advance(drifted, current, *plan), PopulationError::stale_plan));
|
||||
CHECK(std::vector<Inventory>(drifted.balances().begin(), drifted.balances().end()) ==
|
||||
after_leak);
|
||||
CHECK(drifted.last_action() == leaked_action);
|
||||
CHECK(current.find(HabitatId{7}, 3)->last_tick() == Tick{900});
|
||||
|
||||
// Committing one plan twice: the second finds a record it does not match.
|
||||
auto once = world();
|
||||
auto held_once = registry_holding(before);
|
||||
CHECK(commit_advance(once, held_once, *plan).has_value());
|
||||
const auto settled = std::vector<Inventory>{once.balances().begin(), once.balances().end()};
|
||||
const auto settled_action = once.last_action();
|
||||
CHECK(refused(commit_advance(once, held_once, *plan), PopulationError::stale_plan));
|
||||
CHECK(std::vector<Inventory>(once.balances().begin(), once.balances().end()) == settled);
|
||||
CHECK(once.last_action() == settled_action);
|
||||
}
|
||||
|
||||
void seeded_intervals_conserve_over_and_over() {
|
||||
// Many intervals of pseudo-random bounded flux. Nothing here is an ecology:
|
||||
// the point is that whatever a model proposes, the accounting either closes
|
||||
// or refuses, and the world total never moves.
|
||||
for (std::uint64_t seed = 1; seed <= 24; ++seed) {
|
||||
Random random{seed};
|
||||
auto ledger = world();
|
||||
const std::array seed_escrow{Transfer{{5}, elsewhere, held(7, 7)}};
|
||||
CHECK(ledger.transfer(ledger.last_action() + 1, seed_escrow).has_value());
|
||||
const auto total = ledger.conserved_totals();
|
||||
auto cohort = standing();
|
||||
auto registry = registry_holding(cohort);
|
||||
std::uint64_t revision = cohort.revision();
|
||||
std::uint64_t tick = cohort.last_tick().value;
|
||||
std::uint64_t advanced = 0, refusals = 0;
|
||||
for (std::uint64_t step = 0; step < 40; ++step) {
|
||||
AdvanceRequest proposal;
|
||||
tick += 1 + random.next() % 50;
|
||||
proposal.to = Tick{tick};
|
||||
proposal.owner = cohort.owner();
|
||||
proposal.revision = ++revision;
|
||||
proposal.detritus = detritus;
|
||||
proposal.predators = predators;
|
||||
proposal.elsewhere = elsewhere;
|
||||
proposal.bound = cohort.bound();
|
||||
// Deliberately unbounded relative to the cohort, so some proposals
|
||||
// ask for more than is there and must be refused rather than clamped.
|
||||
const auto deaths = (random.next() % 9) * residual_scale;
|
||||
const auto energy = random.next() % 120;
|
||||
const auto matter = random.next() % 900;
|
||||
proposal.flux.deaths = deaths;
|
||||
proposal.flux.to_detritus = held(energy, matter);
|
||||
auto remaining = cohort.population();
|
||||
const bool survives = deaths <= remaining;
|
||||
remaining = survives ? remaining - deaths : 0;
|
||||
auto reserve = cohort.reserve();
|
||||
const bool affordable =
|
||||
reserve.energy.value >= energy && reserve.matter[0].value >= matter;
|
||||
if (survives && affordable) {
|
||||
reserve.energy.value -= energy;
|
||||
for (auto& channel : reserve.matter) {
|
||||
channel.value -= matter;
|
||||
}
|
||||
if (remaining == 0) {
|
||||
proposal.flux.to_detritus = reserve;
|
||||
proposal.flux.to_detritus.energy.value = reserve.energy.value + energy;
|
||||
proposal.after.clear();
|
||||
} else {
|
||||
proposal.after = {
|
||||
{0, 100, remaining / residual_scale, reserve, remaining % residual_scale}};
|
||||
}
|
||||
} else {
|
||||
proposal.after = {{0, 100, 1, Inventory{}, 0}};
|
||||
}
|
||||
const auto plan = plan_advance(cohort, proposal);
|
||||
if (!plan) {
|
||||
++refusals;
|
||||
--revision;
|
||||
tick = cohort.last_tick().value;
|
||||
continue;
|
||||
}
|
||||
const auto committed = commit_advance(ledger, registry, *plan);
|
||||
CHECK(committed.has_value());
|
||||
cohort = *committed;
|
||||
++advanced;
|
||||
// Every invariant, every interval.
|
||||
CHECK(ledger.conserved_totals() == total);
|
||||
CHECK(ledger.balances()[backing.value - 1] == cohort.reserve());
|
||||
CHECK(cohort.last_tick().value == tick);
|
||||
CHECK(registry.size() == 1);
|
||||
if (cohort.is_vacant()) {
|
||||
CHECK(cohort.population() == 0);
|
||||
CHECK(cohort.reserve() == Inventory{});
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Both paths must actually occur, or this would prove nothing.
|
||||
CHECK(advanced > 0);
|
||||
CHECK(refusals > 0);
|
||||
}
|
||||
}
|
||||
|
||||
void a_moved_from_plan_is_still_a_whole_plan() {
|
||||
static_assert(std::is_copy_constructible_v<AdvancePlan>);
|
||||
static_assert(!std::is_nothrow_move_constructible_v<AdvancePlan>);
|
||||
const auto before = standing();
|
||||
auto mover = request();
|
||||
mover.flux.deaths = 4 * residual_scale;
|
||||
mover.flux.to_detritus = held(40, 400);
|
||||
mover.after = {{0, 100, 36, held(360, 3'600), 0}, {100, 200, 20, held(600, 6'000), 0}};
|
||||
auto source = plan_advance(before, mover);
|
||||
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->legs().size() == 1);
|
||||
CHECK(moved == original);
|
||||
auto ledger = world();
|
||||
auto registry = registry_holding(before);
|
||||
// NOLINTNEXTLINE(bugprone-use-after-move)
|
||||
const auto committed = commit_advance(ledger, registry, *source);
|
||||
CHECK(committed.has_value());
|
||||
CHECK(ledger.balances()[detritus.value - 1] == held(40, 400));
|
||||
}
|
||||
} // namespace
|
||||
int main() try {
|
||||
an_interval_that_changes_nothing_still_advances_the_clock();
|
||||
a_birth_redistributes_and_never_creates_biomass();
|
||||
death_predation_and_migration_move_biomass_once();
|
||||
a_proposal_that_would_go_below_zero_is_refused_not_clamped();
|
||||
a_population_below_one_member_is_still_a_population();
|
||||
a_vacant_cohort_is_not_an_extinction();
|
||||
the_declared_result_must_be_what_the_fluxes_imply();
|
||||
a_stale_proposal_is_refused_and_changes_nothing();
|
||||
seeded_intervals_conserve_over_and_over();
|
||||
a_moved_from_plan_is_still_a_whole_plan();
|
||||
std::cout << "PASS interval accounting, refusal without clamping and seeded conservation\n";
|
||||
return 0;
|
||||
} catch (...) {
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user