Keep a distribution, because a mean cannot say who survives
M4.1 defines the tier 2 record and who may act on it, and nothing else: no collapse transaction, no population advance, no materialization, no habitat geometry. Those are M4.2 to M4.4 and each needs its own decision. The named risk for this step is that population averages hide viable outliers, which is a property of the record rather than of the maths applied to it later, so it is answered here. Age classes each carry their own count and their own reserve. A count with a mean reserve cannot tell a provisioned cohort from one where half the members hold nothing, and nothing downstream can recover what that discarded. Within a class members are indistinguishable; that is the declared resolution and a stated loss. No accessor returns a mean, because an average that is easy to reach becomes the authority. Totals are summed from the classes rather than stored beside them, following the archive's rule that a second tally is a thing that can disagree. Lineage is not a field at all: ancestry is resolved from the genome through the archive, so a cohort cannot contradict it or invent parentage from membership. Residuals are integer numerators strictly below one member and are never added to a count. Ownership is enforced rather than described. One record per habitat and genome makes no-inventory-spendable-in-two-tiers unrepresentable instead of forbidden, and replacement is refused under a different worker or an older epoch. That is a single-process invariant; fencing between workers is M7 and M10. The approximation bound is carried and never computed, since carrying a bound is not meeting one. All nine guards were confirmed load-bearing by removing each and rerunning. An earlier sweep reporting none of them load-bearing was wrong and discarded: it wrote to /tmp, which Git Bash and PowerShell resolve differently, so nothing was ever mutated. Release 34/34, analysis, ASan 34/34 and clang-format all ran and passed here. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -47,6 +47,13 @@ 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)
|
||||
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)
|
||||
target_compile_features(evo_ecology PUBLIC cxx_std_23)
|
||||
evo_owned_target(evo_ecology)
|
||||
|
||||
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp src/processes/genome_strategy.cpp src/processes/ensemble.cpp)
|
||||
add_library(evo::processes ALIAS evo_processes)
|
||||
target_link_libraries(evo_processes PUBLIC evo::accounting evo::biology)
|
||||
@@ -103,6 +110,11 @@ if(BUILD_TESTING)
|
||||
evo_owned_target(evo-producer-tests)
|
||||
add_test(NAME producer-contracts COMMAND evo-producer-tests)
|
||||
set_tests_properties(producer-contracts PROPERTIES TIMEOUT 60)
|
||||
add_executable(evo-cohort-tests tests/cohort_tests.cpp)
|
||||
target_link_libraries(evo-cohort-tests PRIVATE evo::ecology)
|
||||
evo_owned_target(evo-cohort-tests)
|
||||
add_test(NAME cohort-contracts COMMAND evo-cohort-tests)
|
||||
set_tests_properties(cohort-contracts PROPERTIES TIMEOUT 60)
|
||||
add_executable(evo-ledger-tests tests/ledger_tests.cpp)
|
||||
target_link_libraries(evo-ledger-tests PRIVATE evo::accounting)
|
||||
evo_owned_target(evo-ledger-tests)
|
||||
|
||||
@@ -96,6 +96,16 @@ that carried it, ancestry and descendants resolve through dead links, and a
|
||||
lineage with no living carrier is reported absent and never extinct, because
|
||||
terminal extinction needs a reconciled watermark this type cannot see. NPC
|
||||
mutation stays undecided: the archive records an origin event and never an actor.
|
||||
M4.1 opens M4 (ADR-0036): a validated `Cohort` holding age classes that each carry
|
||||
their own count and reserve, so the record stores a distribution rather than the
|
||||
mean the named risk warns about, with totals derived from those classes and no
|
||||
stored tally that could disagree. Lineage is absent by design, because ancestry is
|
||||
the archive's answer resolved from the genome. Residuals are integer fractions
|
||||
strictly below one member. `CohortRegistry` admits one record per habitat and
|
||||
genome and refuses replacement under a wrong worker or an older epoch, so
|
||||
ECOLOGY_MODEL's "no inventory spendable in two tiers" is enforced rather than
|
||||
described. No collapse, advance or materialization exists yet.
|
||||
|
||||
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
|
||||
|
||||
+29
-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 35 ADRs.
|
||||
diagrams, biological contracts, engineering constitution and 36 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.1 cohort state and ownership | Genome, lineage, counts, age, reserves, residuals and ownership made explicit |
|
||||
| 1 | M4.2 collapse active individuals | Transfer IDs and reserves into one cohort atomically, with exact ledger conservation |
|
||||
| 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 |
|
||||
|
||||
@@ -292,3 +292,30 @@ logout treatment, species/extinction rules and multicellular transition remain
|
||||
open decisions. Renderer/networking remain later milestones. Deployment
|
||||
availability does not complete M7/M8: fenced ownership, durable outcomes, backup
|
||||
restore and world-version migration require their own implementation/fault tests.
|
||||
|
||||
M4.1 opens M4 (ADR-0036) by defining 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. A `Cohort` is validated on construction
|
||||
and never mutated afterwards. Age classes each carry their own count and their own
|
||||
reserve, so the record holds a distribution rather than the mean the milestone's
|
||||
named risk warns about; within a class members are indistinguishable, which is the
|
||||
record's declared resolution and a stated loss rather than a hidden one. No
|
||||
accessor returns a mean. Totals are summed from the classes instead of stored
|
||||
beside them, following the lineage archive's rule that a second tally is a thing
|
||||
that can disagree. Lineage is deliberately not a field: ancestry is resolved from
|
||||
the genome through the archive, so a cohort cannot contradict it or invent
|
||||
parentage from membership. Residuals are integer numerators over a declared scale,
|
||||
strictly below one member, and are never added to a count.
|
||||
|
||||
Ownership is enforced rather than described. `CohortRegistry` admits at most one
|
||||
record per habitat and genome, so ECOLOGY_MODEL's "no inventory is spendable in
|
||||
two tiers" is unrepresentable rather than forbidden, and replacement is refused
|
||||
under a different worker, an older epoch, or a changed habitat or genome. Epochs
|
||||
make a stale writer fail locally and say nothing about fencing between workers,
|
||||
which stays M7 and M10. The approximation bound is carried and never computed:
|
||||
M4.5 measures resolution equivalence, and carrying a bound is not meeting one.
|
||||
Nothing is serialized, so `schemas/population-v1.md` pins field meaning and
|
||||
invariants rather than a byte layout. All nine construction and registry guards
|
||||
were confirmed load-bearing by removing each one and observing the suite fail.
|
||||
Native Release, analysis, ASan and formatting passed 34/34; Linux CI has not run
|
||||
yet.
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# ADR-0036: Cohort state, declared resolution and exclusive ownership
|
||||
|
||||
## Status
|
||||
|
||||
Adopted for M4.1. 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.
|
||||
|
||||
## Context
|
||||
|
||||
ECOLOGY_MODEL locks two things about tier 2 and leaves the rest recommended: no
|
||||
inventory is spendable in two tiers, and distinct genomes are never averaged into
|
||||
one genome. Everything M4 does afterwards moves inventory between a cohort and
|
||||
individuals, so the record has to exist and has to be checkable before any of that
|
||||
is written. M3 supplies what a cohort is about: a genome that validates, a
|
||||
phenotype that derives from it and an archive that retains its ancestry.
|
||||
|
||||
The named risk for this step is that population averages hide viable outliers. A
|
||||
record holding a count and a mean reserve cannot answer whether anyone in it would
|
||||
survive, because a well-provisioned member and a starving one reduce to the same
|
||||
average. That is a property of the record, not of the maths applied to it later,
|
||||
so it has to be answered here or not at all.
|
||||
|
||||
## Decision
|
||||
|
||||
A `Cohort` is a validated value. `Cohort::create` takes a draft and either returns
|
||||
a cohort meeting every invariant below or an error naming the one it broke; there
|
||||
is no way to assemble one field by field and no way to mutate a field afterwards.
|
||||
|
||||
Age structure is a sequence of classes, each carrying its own count and its own
|
||||
reserve. A cohort therefore stores a distribution and never a mean. Within one
|
||||
class members are indistinguishable, which is a real loss and is the record's
|
||||
declared resolution: the class bounds state it, and a reader that needs finer
|
||||
structure declares narrower classes rather than dividing a total. No accessor
|
||||
returns a mean, because an average that is easy to reach is an average that will
|
||||
be used as the authority.
|
||||
|
||||
Totals are derived by summing the classes, never stored beside them. The lineage
|
||||
archive already establishes this: a second tally is a thing that can disagree.
|
||||
Summation rejects overflow rather than wrapping.
|
||||
|
||||
A cohort names the genome it carries and does not store its lineage. Ancestry is
|
||||
the archive's answer, resolved from the genome, so a cohort cannot claim a
|
||||
parentage the archive would contradict and cannot invent precise parentage from a
|
||||
statistical membership, which ECOLOGY_MODEL forbids.
|
||||
|
||||
Fractional members are carried per class as a residual: an integer numerator over
|
||||
a declared scale, strictly less than one member. Integer arithmetic only, as
|
||||
everywhere else in this project. A residual is owed and not yet present, so it is
|
||||
not a count and is never added to one. Funding it is M4.3's problem.
|
||||
|
||||
Ownership is exclusive and enforced rather than described. A `CohortRegistry`
|
||||
admits at most one cohort per habitat and genome, because two records of the same
|
||||
genome in one habitat would be two places the same biomass could be spent, which
|
||||
is exactly what ECOLOGY_MODEL locks against. Every cohort names an owner and an
|
||||
epoch, and a registry replacement is refused unless it comes from the recorded
|
||||
owner under the recorded epoch and leaves the habitat and genome unchanged. A late
|
||||
writer holding an old view cannot install it.
|
||||
|
||||
Approximation error is a declared field, carried and never computed here. M4.5
|
||||
measures resolution equivalence; a bound this type calculated for itself would be
|
||||
a claim it has no basis for.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
Storing a count with mean age and mean reserve is smaller and is what the risk
|
||||
warns about: it cannot distinguish a cohort that is fine from one where half the
|
||||
members are about to starve, and no later stage can recover what it discarded.
|
||||
Storing lineage on the cohort would make membership self-describing at the cost of
|
||||
a second ancestry that can drift from the archive's and of inviting invented
|
||||
parentage. Storing totals beside the classes would save a summation and introduce
|
||||
a field that can disagree with the classes it summarises. Floating point would
|
||||
make residuals natural and determinism impossible. Leaving ownership as a
|
||||
documented rule with a field to check would repeat the mistake ADR-0034 corrected:
|
||||
an invariant nothing enforces is an invariant a later change removes quietly.
|
||||
Making the registry own conversion as well would settle M4.2 by implication.
|
||||
|
||||
## Benefits
|
||||
|
||||
The record can answer who is viable, because it never averaged that away. Double
|
||||
ownership of one genome's biomass in one habitat is unrepresentable rather than
|
||||
forbidden. Every total is derived, so no two fields of a cohort can disagree.
|
||||
Ancestry has exactly one authority. Residuals are explicit, bounded and integer,
|
||||
so a fractional member can never be mistaken for an available one.
|
||||
|
||||
## Costs
|
||||
|
||||
A cohort is larger than a count and a mean, and every class costs an inventory.
|
||||
Declaring classes is a modelling decision a caller has to make, and a caller that
|
||||
declares one wide class gets the average it was trying to avoid. Totals cost a
|
||||
summation on every query. The registry is a bounded in-memory container with no
|
||||
persistence, no sharding and no cross-worker protocol; nothing here is serialized.
|
||||
|
||||
## Risks
|
||||
|
||||
A cohort is not evidence that aggregation is ecologically faithful. It holds a
|
||||
declared approximation bound that nothing yet computes or checks, and carrying a
|
||||
bound is not meeting one. The class boundaries are a chosen resolution, and
|
||||
structure finer than one class is genuinely gone. Conservation between a cohort
|
||||
and the rest of the world is the ledger's property and is not asserted by this
|
||||
type, which holds an inventory without participating in any transfer. Ownership
|
||||
here is a single-process invariant: epochs make a stale writer fail locally and
|
||||
say nothing about fencing across workers, which is M7 and M10. Nothing in this
|
||||
ADR says a population may advance, collapse or materialize.
|
||||
|
||||
## Consequences
|
||||
|
||||
Test that a valid cohort round-trips its declared fields, that totals equal the
|
||||
summed classes, and that every invariant is rejected by name: an unsupported
|
||||
representation version, a zero identity, no classes, classes that are unordered,
|
||||
overlapping or empty, a class holding reserve with nothing to hold it, a residual
|
||||
of one member or more, and a summation that would overflow. Test that a registry
|
||||
refuses a second cohort for one habitat and genome, that replacement is refused
|
||||
under a wrong owner, a stale epoch or a changed habitat or genome, and that it
|
||||
succeeds under the recorded owner. Test that a cohort names a genome the archive
|
||||
can resolve ancestry for without storing that ancestry. Negative reserves are not
|
||||
representable, since every quantity here is unsigned; what is rejected instead is
|
||||
a declared state that would require one. No genome schema, mutation catalog,
|
||||
archive, ledger, episode driver, ensemble, renderer or deployment changes.
|
||||
@@ -28,6 +28,7 @@ Each record has the eight required sections.
|
||||
0033 adopts the bounded mutation catalog and uniform seeded candidate draws.
|
||||
0034 adopts the permanent lineage archive and absence that is never extinction.
|
||||
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.
|
||||
|
||||
Every dependency adoption records exact version/commit and integrity hash,
|
||||
transitive license obligations, maintenance/security review, owner and removal
|
||||
|
||||
@@ -115,3 +115,42 @@ The shared bounded controller proposal is exercised only as a measurement driver
|
||||
It has no perception, no learning and no evolving behavior, and its constants are
|
||||
inputs rather than results. Population math, cohort collapse and resolution
|
||||
equivalence remain M4 work.
|
||||
|
||||
## Implemented M4.1 cohort record
|
||||
|
||||
[ADR-0036](../adr/0036-cohort-state-and-ownership.md) defines the tier 2 record
|
||||
and who may act on it. It settles nothing else above: there is no conversion
|
||||
transaction, no population advance, no representative materialization and no
|
||||
habitat geometry. `PlanCollapse`, `CommitCollapse`, `AdvancePopulation`,
|
||||
`PlanMaterialize`, `CommitMaterialize` and `TransferPopulation` remain contracts
|
||||
nothing implements.
|
||||
|
||||
A cohort is per genome, so distinct genomes are never averaged into one. Its age
|
||||
classes each carry their own count and their own reserve, which is how the record
|
||||
answers the risk that population averages hide viable outliers: a count with a
|
||||
mean reserve cannot distinguish a provisioned cohort from one where half the
|
||||
members hold nothing, and nothing later can recover that. Within one class members
|
||||
are indistinguishable, and that is the declared resolution rather than an
|
||||
oversight. No accessor returns a mean.
|
||||
|
||||
Lineage is not stored. It is resolved from the genome through the archive, so a
|
||||
cohort cannot claim a parentage the archive would contradict and cannot invent
|
||||
precise parentage from statistical membership. Totals are derived from the classes
|
||||
rather than stored beside them.
|
||||
|
||||
Fractional members are carried per class as integer numerators over a declared
|
||||
scale, strictly below one member. An expected fractional density is therefore
|
||||
never mistaken for an available individual. Funding a residual against biomass,
|
||||
and the seeded rule that turns one into a member, are M4.3 and M4.4.
|
||||
|
||||
`CohortRegistry` enforces that no inventory is spendable in two tiers by admitting
|
||||
at most one record per habitat and genome, and by refusing a replacement from a
|
||||
different worker or an older epoch. This is a single-process invariant: epochs
|
||||
make a stale writer fail locally and are not cross-worker fencing, which is M7 and
|
||||
M10. The registry holds no lock, lease or quorum, and nothing is serialized.
|
||||
|
||||
Approximation error is a declared field that nothing computes or checks yet.
|
||||
Carrying a bound is not meeting one; M4.5 is where resolution equivalence is
|
||||
measured. Conservation between a cohort and the rest of the world is the ledger's
|
||||
property and is not asserted by this type, which holds an inventory without
|
||||
participating in any transfer.
|
||||
|
||||
@@ -860,3 +860,61 @@ lifetimes mean a run's mean lifetime is not computable from `lived_ticks` alone
|
||||
and no test asserts one. Across a run the archive now ends holding living
|
||||
carriers, which is accurate about what was observed and is not a claim that
|
||||
anything persists; nothing is serialized.
|
||||
|
||||
## M4.1 cohort state and ownership
|
||||
|
||||
Executed on this Windows host (2026-09-24): Release configure, build and `ctest`
|
||||
34/34; the analysis preset (clang-tidy 19, warnings as errors) built clean; the
|
||||
ASan preset configured, built and ran 34/34; `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 result for the new
|
||||
`evo::ecology` library.
|
||||
|
||||
`evo-cohort-tests` covers six properties: that a cohort keeps exactly the fields
|
||||
it was given, that totals equal the summed classes, that two cohorts with
|
||||
identical totals but different structure are distinguishable, that every
|
||||
construction invariant is rejected by its own named error, that one habitat and
|
||||
genome holds one record, and that only the recorded owner under a current epoch
|
||||
may replace it. A sixth checks that a cohort names a genome the archive resolves
|
||||
ancestry for without storing that ancestry.
|
||||
|
||||
Every guard was confirmed load-bearing rather than assumed. Each of the nine was
|
||||
removed in turn and the suite rebuilt and rerun: the duplicate, stale epoch, wrong
|
||||
owner, unowned reserve, residual bound, class ordering, empty class and class
|
||||
range guards each produced a failing run, and removing the overflow guard fails to
|
||||
compile, because the running totals then have no reader and the Release build
|
||||
treats that warning as an error. An earlier attempt at this sweep reported all
|
||||
nine as not load-bearing; that result was false and was discarded. The harness
|
||||
wrote to `/tmp`, which Git Bash and PowerShell resolve to different directories,
|
||||
so the mutation script was never found and the source was never modified. The
|
||||
sweep was rerun against an absolute path.
|
||||
|
||||
Two defects in my own test code were found and fixed before the suite was trusted.
|
||||
The single-argument `CHECK` macro split on the comma inside a braced initializer
|
||||
such as `Owner{11, 2}`, which is a compile error rather than a silent one, and the
|
||||
macro is now variadic. More seriously, the rejection tests originally asserted on
|
||||
`.error()` alone, which is undefined when the call unexpectedly succeeded and would
|
||||
have let a removed guard pass quietly; they now check the failure first through a
|
||||
`refused` helper. A regex rewrite applied to make that change spanned lines and
|
||||
corrupted several positive assertions, so the test file was rewritten rather than
|
||||
patched.
|
||||
|
||||
Coverage limits. Nothing here is serialized, so `schemas/population-v1.md` pins
|
||||
field meaning and invariants and there is no encoder, no round trip and no
|
||||
migration to test. The approximation bound is carried and never computed or
|
||||
checked, so no test asserts that aggregation is faithful; that is M4.5.
|
||||
Conservation between a cohort and the rest of the world is not asserted, because
|
||||
this type holds an inventory without participating in any transfer. Ownership is
|
||||
tested as a single-process invariant only: epochs make a stale writer fail locally
|
||||
and nothing here exercises fencing between workers, which is M7 and M10. Negative
|
||||
reserves are not representable at all, since every quantity is unsigned, so what
|
||||
the suite rejects instead is a declared state that would require one, and two
|
||||
static assertions record that the underlying types are unsigned. `max_cohorts` is
|
||||
enforced but not exercised at its limit, since installing 4,096 records would add
|
||||
nothing to what the duplicate and lookup tests already establish.
|
||||
|
||||
No existing contract changed. The proof golden `d61ad5bf0c928c76`, the ecosystem
|
||||
fingerprint `2cd4a15f9fbe9949`, the ensemble fingerprint `5ec59d390909b526` and
|
||||
the frozen genome fixture are all 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`.
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/accounting/ledger.hpp"
|
||||
#include "evo/core/types.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace evo::ecology {
|
||||
// Where a cohort lives. M4.1 defines no geometry, extent or neighbourhood: this
|
||||
// is an identity a later milestone gives dimensions to.
|
||||
struct HabitatId {
|
||||
std::uint64_t value{};
|
||||
auto operator<=>(const HabitatId&) const = default;
|
||||
};
|
||||
// Who integrates this cohort, and for which epoch. ECOLOGY_MODEL locks that no
|
||||
// inventory is spendable in two tiers, so a cohort has exactly one owner and a
|
||||
// writer holding an older epoch is refused rather than merged.
|
||||
struct Owner {
|
||||
std::uint64_t worker{};
|
||||
std::uint64_t epoch{};
|
||||
auto operator<=>(const Owner&) const = default;
|
||||
};
|
||||
|
||||
// Fractional members are carried as a numerator over this scale. Integer only:
|
||||
// no quantity in this project is a float. A residual is strictly less than one
|
||||
// member, because at one member it is a member.
|
||||
inline constexpr std::uint64_t residual_scale = 1'000'000;
|
||||
|
||||
// One age class, holding its own count and its own reserve. The record keeps a
|
||||
// distribution rather than a mean, because a mean cannot say whether anyone in
|
||||
// the class would survive. Within a class members are indistinguishable; that is
|
||||
// the declared resolution, and a caller needing finer structure declares
|
||||
// narrower classes rather than dividing a total afterwards.
|
||||
struct AgeClass {
|
||||
std::uint64_t age_low{}; // ticks, inclusive
|
||||
std::uint64_t age_high{}; // ticks, exclusive; must exceed age_low
|
||||
std::uint64_t count{};
|
||||
// Held by this class in total, not per member. Dividing it would produce the
|
||||
// average this record exists to avoid.
|
||||
accounting::Inventory reserve{};
|
||||
// Owed to this class and not yet present, in units of residual_scale. It is
|
||||
// not a count and is never added to one.
|
||||
std::uint64_t residual{};
|
||||
auto operator<=>(const AgeClass&) const = default;
|
||||
};
|
||||
|
||||
// How far this representation may differ from simulating the same members
|
||||
// individually. Declared by whoever built the cohort and never computed here:
|
||||
// M4.5 measures resolution equivalence, and a bound this type derived for itself
|
||||
// would be a claim it has no basis for. Carrying a bound is not meeting one.
|
||||
struct ApproximationBound {
|
||||
std::uint64_t count{};
|
||||
accounting::Inventory inventory{};
|
||||
auto operator<=>(const ApproximationBound&) const = default;
|
||||
};
|
||||
|
||||
struct CohortDraft {
|
||||
std::uint32_t representation_version{};
|
||||
HabitatId habitat{};
|
||||
// The genome every member carries. Distinct genomes are never averaged into
|
||||
// one, so a cohort is per genome. Lineage is deliberately absent: it is the
|
||||
// archive's answer, resolved from this identity.
|
||||
std::uint64_t genome{};
|
||||
Owner owner{};
|
||||
// The last interval boundary this cohort was integrated to.
|
||||
Tick last_tick{};
|
||||
// The conversion that produced this record, kept as provenance.
|
||||
std::uint64_t conversion{};
|
||||
std::vector<AgeClass> classes;
|
||||
ApproximationBound bound{};
|
||||
};
|
||||
|
||||
enum class CohortError : std::uint8_t {
|
||||
unsupported_version,
|
||||
invalid_identity,
|
||||
no_age_classes,
|
||||
unordered_age_classes,
|
||||
empty_age_class,
|
||||
unowned_reserve,
|
||||
residual_out_of_range,
|
||||
overflow,
|
||||
duplicate_cohort,
|
||||
unknown_cohort,
|
||||
wrong_owner,
|
||||
stale_epoch,
|
||||
registry_full
|
||||
};
|
||||
|
||||
inline constexpr std::uint32_t cohort_representation_version = 1;
|
||||
inline constexpr std::size_t max_age_classes = 64;
|
||||
inline constexpr std::size_t max_cohorts = 4'096;
|
||||
|
||||
// A validated tier 2 record. Every invariant holds for as long as the value does:
|
||||
// there is no field-by-field assembly and no mutation after construction.
|
||||
class Cohort {
|
||||
public:
|
||||
[[nodiscard]] static std::expected<Cohort, CohortError> create(CohortDraft draft);
|
||||
|
||||
[[nodiscard]] std::uint32_t representation_version() const noexcept {
|
||||
return version_;
|
||||
}
|
||||
[[nodiscard]] HabitatId habitat() const noexcept {
|
||||
return habitat_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t genome() const noexcept {
|
||||
return genome_;
|
||||
}
|
||||
[[nodiscard]] Owner owner() const noexcept {
|
||||
return owner_;
|
||||
}
|
||||
[[nodiscard]] Tick last_tick() const noexcept {
|
||||
return last_tick_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t conversion() const noexcept {
|
||||
return conversion_;
|
||||
}
|
||||
[[nodiscard]] std::span<const AgeClass> classes() const noexcept {
|
||||
return classes_;
|
||||
}
|
||||
[[nodiscard]] ApproximationBound bound() const noexcept {
|
||||
return bound_;
|
||||
}
|
||||
|
||||
// Derived by summing the classes rather than stored beside them, so no two
|
||||
// fields of a cohort can disagree. Both reject overflow at construction, so
|
||||
// these cannot fail afterwards.
|
||||
[[nodiscard]] std::uint64_t count() const noexcept;
|
||||
[[nodiscard]] accounting::Inventory reserve() const noexcept;
|
||||
// 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;
|
||||
// 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.
|
||||
|
||||
auto operator<=>(const Cohort&) const = default;
|
||||
|
||||
private:
|
||||
Cohort() = default;
|
||||
std::uint32_t version_{};
|
||||
HabitatId habitat_{};
|
||||
std::uint64_t genome_{};
|
||||
Owner owner_{};
|
||||
Tick last_tick_{};
|
||||
std::uint64_t conversion_{};
|
||||
std::vector<AgeClass> classes_;
|
||||
ApproximationBound bound_{};
|
||||
};
|
||||
|
||||
// Holds at most one cohort per habitat and genome. Two records of one genome in
|
||||
// one habitat would be two places the same biomass could be spent, which is the
|
||||
// invariant ECOLOGY_MODEL locks; here it is unrepresentable rather than
|
||||
// forbidden. Nothing is serialized and no cross-worker protocol is implied.
|
||||
class CohortRegistry {
|
||||
public:
|
||||
[[nodiscard]] std::expected<void, CohortError> install(const Cohort& cohort);
|
||||
// Refused unless it comes from the recorded owner under the recorded epoch and
|
||||
// leaves habitat and genome unchanged, so a writer holding an older view fails
|
||||
// rather than overwriting a newer one.
|
||||
[[nodiscard]] std::expected<void, CohortError> replace(const Cohort& cohort);
|
||||
[[nodiscard]] std::expected<Cohort, CohortError> find(HabitatId habitat,
|
||||
std::uint64_t genome) const;
|
||||
[[nodiscard]] std::size_t size() const noexcept {
|
||||
return cohorts_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
// Sorted by habitat then genome, so a lookup is a binary search and there is
|
||||
// one record of each thing with no index that could disagree with it.
|
||||
std::vector<Cohort> cohorts_;
|
||||
};
|
||||
} // namespace evo::ecology
|
||||
@@ -0,0 +1,107 @@
|
||||
# Cohort record, representation version 1
|
||||
|
||||
Scope: the tier 2 record defined by
|
||||
[ADR-0036](../docs/adr/0036-cohort-state-and-ownership.md) and shaped by
|
||||
[ECOLOGY_MODEL.md](../docs/biology/ECOLOGY_MODEL.md). Its validator is
|
||||
`src/ecology/cohort.cpp`.
|
||||
|
||||
There is no byte layout here and no encoder. Unlike the genome record, a cohort
|
||||
is not hashed, not a mutation context and not exchanged between processes yet, so
|
||||
a wire format would be a format nothing writes or reads. Durable storage and
|
||||
cross-version migration are M7 and M8, and the version field exists so a later
|
||||
schema can fail closed on records it does not understand rather than guess. What
|
||||
this document pins is the meaning of each field and the invariants a record must
|
||||
satisfy to exist at all.
|
||||
|
||||
Not a network protocol, a durable format, a habitat geometry, a conversion
|
||||
transaction or a population model. Nothing here advances, collapses or
|
||||
materializes anything.
|
||||
|
||||
## Record
|
||||
|
||||
| Field | Type | Meaning |
|
||||
|---|---|---|
|
||||
| representation version | u32 | 1. Unknown versions fail closed |
|
||||
| habitat | u64 | Where the cohort is. Nonzero. Carries no geometry in version 1 |
|
||||
| genome | u64 | The genome every member carries. Nonzero |
|
||||
| owner worker | u64 | Who integrates this cohort. Nonzero |
|
||||
| owner epoch | u64 | Which epoch that ownership is held under. Nonzero |
|
||||
| last tick | u64 | The last interval boundary this record was integrated to |
|
||||
| conversion | u64 | The conversion that produced this record. Nonzero provenance |
|
||||
| age classes | 1 to 64 | Ordered, disjoint, each non-empty. See below |
|
||||
| approximation bound | count + inventory | Declared, never computed here |
|
||||
|
||||
Lineage is deliberately absent. Ancestry is resolved from the genome through
|
||||
`LineageArchive`, so a cohort cannot hold a parentage that contradicts the
|
||||
archive's and cannot invent precise parentage from a statistical membership,
|
||||
which ECOLOGY_MODEL forbids.
|
||||
|
||||
Totals are absent for the same reason. Count, reserve and residual are summed
|
||||
from the classes on demand; a stored total is a second tally that can disagree
|
||||
with what it summarises.
|
||||
|
||||
## Age classes
|
||||
|
||||
| Field | Type | Meaning |
|
||||
|---|---|---|
|
||||
| age low | u64 | Ticks, inclusive |
|
||||
| age high | u64 | Ticks, exclusive. Must exceed age low |
|
||||
| count | u64 | Whole members in this class |
|
||||
| reserve | inventory | Energy and four matter channels held by the class in total |
|
||||
| residual | u64 | Fraction of a member owed, over `residual_scale` (1,000,000) |
|
||||
|
||||
Each class holds its own count and its own reserve, so the record stores a
|
||||
distribution and not a mean. This is the point of the record: a count with a mean
|
||||
reserve cannot distinguish a cohort where every member is provisioned from one
|
||||
where half hold nothing, and no later stage can recover what that discards.
|
||||
|
||||
Within one class members are indistinguishable. That is the record's declared
|
||||
resolution and a real loss. A caller needing finer structure declares narrower
|
||||
classes; it does not divide a total afterwards. No accessor returns a mean,
|
||||
because an average that is easy to reach becomes the authority.
|
||||
|
||||
A residual is owed and not yet present. It is not a count, is never added to one,
|
||||
and is strictly less than one member, because at one member it is a member.
|
||||
Funding a residual against biomass is M4.3.
|
||||
|
||||
## Invariants
|
||||
|
||||
A record that breaks any of these does not exist; construction returns the named
|
||||
error instead.
|
||||
|
||||
| Rejected | Error |
|
||||
|---|---|
|
||||
| Representation version other than 1 | `unsupported_version` |
|
||||
| Zero habitat, genome, owner worker, owner epoch or conversion | `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` |
|
||||
| A class with no members and nothing owed | `empty_age_class` |
|
||||
| A class holding reserve with no members to own it | `unowned_reserve` |
|
||||
| A residual of one member or more | `residual_out_of_range` |
|
||||
| Counts, residuals or any inventory channel that would overflow when summed | `overflow` |
|
||||
|
||||
Every quantity is unsigned, so a negative reserve is not representable. What is
|
||||
rejected is a declared state that would require one: reserve held by a class with
|
||||
no members. Arithmetic that could produce one does not exist in this version,
|
||||
because this version performs none.
|
||||
|
||||
## Ownership
|
||||
|
||||
`CohortRegistry` holds at most one record per habitat and genome. Two records of
|
||||
one genome in one habitat would be two places the same biomass could be spent,
|
||||
which is what ECOLOGY_MODEL locks against; here it is unrepresentable rather than
|
||||
forbidden by convention.
|
||||
|
||||
| Rejected | Error |
|
||||
|---|---|
|
||||
| Installing a second record for one habitat and genome | `duplicate_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` |
|
||||
| Installing beyond `max_cohorts` (4,096) | `registry_full` |
|
||||
|
||||
An owner replacing under its own current epoch is the ordinary case and is
|
||||
accepted. Epochs make a stale writer fail locally; they say nothing about fencing
|
||||
between workers, which is M7 and M10. The registry is in-memory, single-process
|
||||
and holds no lock, lease or quorum.
|
||||
@@ -0,0 +1,175 @@
|
||||
#include "evo/ecology/cohort.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;
|
||||
}
|
||||
// Summed per channel: a total mass is not an additional inventory, so the
|
||||
// channels are added separately and any one of them may be what overflows.
|
||||
[[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 the registry is keyed by, which is also the uniqueness it enforces: one
|
||||
// record per habitat and genome.
|
||||
struct Key {
|
||||
HabitatId habitat;
|
||||
std::uint64_t genome;
|
||||
auto operator<=>(const Key&) const = default;
|
||||
};
|
||||
[[nodiscard]] Key key_of(const Cohort& cohort) noexcept {
|
||||
return {cohort.habitat(), cohort.genome()};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::expected<Cohort, CohortError> Cohort::create(CohortDraft draft) {
|
||||
if (draft.representation_version != cohort_representation_version) {
|
||||
return std::unexpected{CohortError::unsupported_version};
|
||||
}
|
||||
// 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.conversion == 0) {
|
||||
return std::unexpected{CohortError::invalid_identity};
|
||||
}
|
||||
if (draft.classes.empty()) {
|
||||
return std::unexpected{CohortError::no_age_classes};
|
||||
}
|
||||
if (draft.classes.size() > max_age_classes) {
|
||||
return std::unexpected{CohortError::overflow};
|
||||
}
|
||||
std::uint64_t count = 0;
|
||||
accounting::Inventory reserve{};
|
||||
std::uint64_t residual = 0;
|
||||
for (std::size_t index = 0; index < draft.classes.size(); ++index) {
|
||||
const auto& age = draft.classes[index];
|
||||
// Ascending, non-overlapping and non-empty. An empty or overlapping range
|
||||
// would make a member's class ambiguous or impossible.
|
||||
if (age.age_high <= age.age_low) {
|
||||
return std::unexpected{CohortError::unordered_age_classes};
|
||||
}
|
||||
if (index > 0 && age.age_low < draft.classes[index - 1].age_high) {
|
||||
return std::unexpected{CohortError::unordered_age_classes};
|
||||
}
|
||||
// A residual is a fraction of one member. At a whole member it is one.
|
||||
if (age.residual >= residual_scale) {
|
||||
return std::unexpected{CohortError::residual_out_of_range};
|
||||
}
|
||||
// A class with neither members nor a fraction owed is not a class; it is
|
||||
// a boundary someone declared and left empty.
|
||||
if (age.count == 0 && age.residual == 0) {
|
||||
return std::unexpected{CohortError::empty_age_class};
|
||||
}
|
||||
// Reserve belongs to members. A class with no members holding inventory
|
||||
// would be biomass owned by nobody, which no later transfer could settle.
|
||||
if (age.count == 0 && !empty(age.reserve)) {
|
||||
return std::unexpected{CohortError::unowned_reserve};
|
||||
}
|
||||
if (!add(count, age.count) || !add(reserve, age.reserve) || !add(residual, age.residual)) {
|
||||
return std::unexpected{CohortError::overflow};
|
||||
}
|
||||
}
|
||||
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.conversion_ = draft.conversion;
|
||||
cohort.classes_ = std::move(draft.classes);
|
||||
cohort.bound_ = draft.bound;
|
||||
return cohort;
|
||||
}
|
||||
|
||||
std::uint64_t Cohort::count() const noexcept {
|
||||
std::uint64_t total = 0;
|
||||
for (const auto& age : classes_) {
|
||||
// Construction proved this cannot overflow, so the sum is exact here.
|
||||
total += age.count;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
accounting::Inventory Cohort::reserve() const noexcept {
|
||||
accounting::Inventory total{};
|
||||
for (const auto& age : classes_) {
|
||||
total.energy.value += age.reserve.energy.value;
|
||||
for (std::size_t channel = 0; channel < total.matter.size(); ++channel) {
|
||||
total.matter[channel].value += age.reserve.matter[channel].value;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
std::uint64_t Cohort::residual() const noexcept {
|
||||
std::uint64_t total = 0;
|
||||
for (const auto& age : classes_) {
|
||||
total += age.residual;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
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};
|
||||
}
|
||||
if (cohorts_.size() >= max_cohorts) {
|
||||
return std::unexpected{CohortError::registry_full};
|
||||
}
|
||||
cohorts_.insert(at, cohort);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<void, CohortError> CohortRegistry::replace(const Cohort& cohort) {
|
||||
const auto wanted = key_of(cohort);
|
||||
const auto at = std::ranges::lower_bound(cohorts_, wanted, {}, key_of);
|
||||
// Habitat and genome are the record's membership, so a replacement changing
|
||||
// either is not a newer view of this cohort; it names one that is not here.
|
||||
if (at == cohorts_.end() || key_of(*at) != wanted) {
|
||||
return std::unexpected{CohortError::unknown_cohort};
|
||||
}
|
||||
if (cohort.owner().worker != at->owner().worker) {
|
||||
return std::unexpected{CohortError::wrong_owner};
|
||||
}
|
||||
// Equal is accepted: an owner rewriting its own epoch is the ordinary case.
|
||||
// Older is refused, so a writer holding a stale view cannot install it.
|
||||
if (cohort.owner().epoch < at->owner().epoch) {
|
||||
return std::unexpected{CohortError::stale_epoch};
|
||||
}
|
||||
*at = cohort;
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<Cohort, CohortError> CohortRegistry::find(HabitatId habitat,
|
||||
std::uint64_t genome) const {
|
||||
const Key wanted{habitat, genome};
|
||||
const auto at = std::ranges::lower_bound(cohorts_, wanted, {}, key_of);
|
||||
if (at == cohorts_.end() || key_of(*at) != wanted) {
|
||||
return std::unexpected{CohortError::unknown_cohort};
|
||||
}
|
||||
return *at;
|
||||
}
|
||||
} // namespace evo::ecology
|
||||
@@ -0,0 +1,321 @@
|
||||
#include "evo/biology/lineage.hpp"
|
||||
#include "evo/ecology/cohort.hpp"
|
||||
|
||||
#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::Tick;
|
||||
void check(bool condition, std::source_location location = std::source_location::current()) {
|
||||
if (!condition) {
|
||||
throw std::runtime_error("cohort 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, CohortError>& result, CohortError expected) {
|
||||
return !result.has_value() && result.error() == expected;
|
||||
}
|
||||
|
||||
Inventory held(std::uint64_t value) {
|
||||
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
|
||||
}
|
||||
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.conversion = 5;
|
||||
source.classes = {{0, 100, 40, held(400), 0},
|
||||
{100, 200, 25, held(900), 250'000},
|
||||
{200, 300, 10, held(1'000), 999'999}};
|
||||
source.bound = {2, held(30)};
|
||||
return source;
|
||||
}
|
||||
Cohort valid() {
|
||||
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;
|
||||
}
|
||||
|
||||
void a_cohort_keeps_exactly_what_it_was_given() {
|
||||
const auto cohort = valid();
|
||||
CHECK(cohort.representation_version() == cohort_representation_version);
|
||||
CHECK(cohort.habitat() == HabitatId{7});
|
||||
CHECK(cohort.genome() == 3);
|
||||
CHECK(cohort.owner() == Owner{11, 2});
|
||||
CHECK(cohort.last_tick() == Tick{900});
|
||||
CHECK(cohort.conversion() == 5);
|
||||
CHECK(cohort.bound().count == 2);
|
||||
CHECK(cohort.bound().inventory == held(30));
|
||||
CHECK(cohort.classes().size() == 3);
|
||||
// Totals are derived from the classes, so they cannot disagree with them.
|
||||
CHECK(cohort.count() == 75);
|
||||
CHECK(cohort.reserve() == held(2'300));
|
||||
CHECK(cohort.residual() == 1'249'999);
|
||||
std::uint64_t counted = 0;
|
||||
Inventory reserved{};
|
||||
for (const auto& age : cohort.classes()) {
|
||||
counted += age.count;
|
||||
reserved.energy.value += age.reserve.energy.value;
|
||||
for (std::size_t channel = 0; channel < reserved.matter.size(); ++channel) {
|
||||
reserved.matter[channel].value += age.reserve.matter[channel].value;
|
||||
}
|
||||
}
|
||||
CHECK(counted == cohort.count());
|
||||
CHECK(reserved == cohort.reserve());
|
||||
// Summed across classes the residual may exceed a member; the per-class bound
|
||||
// is what is invariant, and a fraction is never counted as a member.
|
||||
CHECK(cohort.residual() > residual_scale);
|
||||
CHECK(cohort.count() == 75);
|
||||
}
|
||||
|
||||
void the_record_keeps_a_distribution_and_not_an_average() {
|
||||
// Two cohorts with identical totals but different structure: one where every
|
||||
// member is provisioned and one where a young class holds nothing at all. A
|
||||
// record storing a count and a mean reserve could not tell these apart, which
|
||||
// is exactly how an average hides whether anyone would survive.
|
||||
auto spread = draft();
|
||||
spread.classes = {{0, 100, 50, held(500), 0}, {100, 200, 50, held(500), 0}};
|
||||
auto skewed = draft();
|
||||
skewed.classes = {{0, 100, 50, held(0), 0}, {100, 200, 50, held(1'000), 0}};
|
||||
const auto even = built(spread);
|
||||
const auto uneven = built(skewed);
|
||||
CHECK(even.count() == uneven.count());
|
||||
CHECK(even.reserve() == uneven.reserve());
|
||||
CHECK(even != uneven); // The totals agree; the records do not.
|
||||
CHECK(even.classes()[0].reserve != uneven.classes()[0].reserve);
|
||||
// A class with members but no reserve is a legitimate state, not an error:
|
||||
// it is precisely the outlier an average would have dissolved.
|
||||
CHECK(uneven.classes()[0].count == 50);
|
||||
CHECK(uneven.classes()[0].reserve == Inventory{});
|
||||
}
|
||||
|
||||
void every_invariant_is_rejected_by_name() {
|
||||
auto wrong_version = draft();
|
||||
wrong_version.representation_version = cohort_representation_version + 1;
|
||||
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}) {
|
||||
auto blank = draft();
|
||||
if (missing == 0) {
|
||||
blank.habitat = {};
|
||||
} else if (missing == 1) {
|
||||
blank.genome = 0;
|
||||
} else if (missing == 2) {
|
||||
blank.owner.worker = 0;
|
||||
} else if (missing == 3) {
|
||||
blank.owner.epoch = 0;
|
||||
} else {
|
||||
blank.conversion = 0;
|
||||
}
|
||||
CHECK(refused(Cohort::create(blank), CohortError::invalid_identity));
|
||||
}
|
||||
auto none = draft();
|
||||
none.classes.clear();
|
||||
CHECK(refused(Cohort::create(none), CohortError::no_age_classes));
|
||||
auto too_many = draft();
|
||||
too_many.classes.clear();
|
||||
for (std::uint64_t index = 0; index <= max_age_classes; ++index) {
|
||||
too_many.classes.push_back({index * 10, index * 10 + 10, 1, held(1), 0});
|
||||
}
|
||||
CHECK(refused(Cohort::create(too_many), CohortError::overflow));
|
||||
// An empty range makes a member's class impossible, an inverted one likewise,
|
||||
// and an overlap or a descending order makes it ambiguous.
|
||||
auto empty_range = draft();
|
||||
empty_range.classes[1].age_high = empty_range.classes[1].age_low;
|
||||
CHECK(refused(Cohort::create(empty_range), CohortError::unordered_age_classes));
|
||||
auto inverted = draft();
|
||||
inverted.classes[1].age_high = inverted.classes[1].age_low - 1;
|
||||
CHECK(refused(Cohort::create(inverted), CohortError::unordered_age_classes));
|
||||
auto overlapping = draft();
|
||||
overlapping.classes[1].age_low = overlapping.classes[0].age_high - 1;
|
||||
CHECK(refused(Cohort::create(overlapping), CohortError::unordered_age_classes));
|
||||
auto descending = draft();
|
||||
std::swap(descending.classes[0], descending.classes[2]);
|
||||
CHECK(refused(Cohort::create(descending), CohortError::unordered_age_classes));
|
||||
// A class with neither members nor a fraction owed is a boundary, not a class.
|
||||
auto hollow = draft();
|
||||
hollow.classes[1].count = 0;
|
||||
hollow.classes[1].residual = 0;
|
||||
hollow.classes[1].reserve = {};
|
||||
CHECK(refused(Cohort::create(hollow), CohortError::empty_age_class));
|
||||
// Reserve belongs to members; with none it would be biomass owned by nobody.
|
||||
auto orphaned = draft();
|
||||
orphaned.classes[1].count = 0;
|
||||
orphaned.classes[1].residual = 1;
|
||||
CHECK(refused(Cohort::create(orphaned), CohortError::unowned_reserve));
|
||||
// A class owed a fraction and holding nothing is valid: nothing is unowned.
|
||||
auto owed = draft();
|
||||
owed.classes[1].count = 0;
|
||||
owed.classes[1].residual = 1;
|
||||
owed.classes[1].reserve = {};
|
||||
CHECK(Cohort::create(owed).has_value());
|
||||
// At a whole member a fraction is a member, so the bound is strict.
|
||||
auto whole = draft();
|
||||
whole.classes[1].residual = residual_scale;
|
||||
CHECK(refused(Cohort::create(whole), CohortError::residual_out_of_range));
|
||||
auto just_under = draft();
|
||||
just_under.classes[1].residual = residual_scale - 1;
|
||||
CHECK(Cohort::create(just_under).has_value());
|
||||
// Summation rejects rather than wrapping, on counts and on every channel.
|
||||
constexpr auto most = std::numeric_limits<std::uint64_t>::max();
|
||||
auto counts = draft();
|
||||
counts.classes[0].count = most;
|
||||
counts.classes[1].count = 1;
|
||||
CHECK(refused(Cohort::create(counts), CohortError::overflow));
|
||||
auto energy = draft();
|
||||
energy.classes[0].reserve.energy.value = most;
|
||||
energy.classes[1].reserve.energy.value = 1;
|
||||
CHECK(refused(Cohort::create(energy), CohortError::overflow));
|
||||
for (std::size_t channel = 0; channel < 4; ++channel) {
|
||||
auto matter = draft();
|
||||
matter.classes[0].reserve.matter[channel].value = most;
|
||||
matter.classes[1].reserve.matter[channel].value = 1;
|
||||
CHECK(refused(Cohort::create(matter), CohortError::overflow));
|
||||
}
|
||||
// No negative reserve is representable, because every quantity here is
|
||||
// unsigned. What is rejected is a declared state that would require one.
|
||||
static_assert(!std::is_signed_v<decltype(Femtograms{}.value)>);
|
||||
static_assert(!std::is_signed_v<decltype(Picojoules{}.value)>);
|
||||
static_assert(!std::is_signed_v<decltype(AgeClass{}.count)>);
|
||||
}
|
||||
|
||||
void one_habitat_and_genome_holds_one_cohort() {
|
||||
CohortRegistry registry;
|
||||
CHECK(registry.install(valid()).has_value());
|
||||
CHECK(registry.size() == 1);
|
||||
// A second record of the same genome in the same habitat would be a second
|
||||
// place the same biomass could be spent, whoever claims to own it.
|
||||
CHECK(refused(registry.install(valid()), CohortError::duplicate_cohort));
|
||||
auto differing_owner = draft();
|
||||
differing_owner.owner = {99, 4};
|
||||
CHECK(refused(registry.install(built(differing_owner)), CohortError::duplicate_cohort));
|
||||
CHECK(registry.size() == 1);
|
||||
// Another genome, or the same genome elsewhere, is a different record.
|
||||
auto other_genome = draft();
|
||||
other_genome.genome = 4;
|
||||
auto other_habitat = draft();
|
||||
other_habitat.habitat = {8};
|
||||
CHECK(registry.install(built(other_genome)).has_value());
|
||||
CHECK(registry.install(built(other_habitat)).has_value());
|
||||
CHECK(registry.size() == 3);
|
||||
// Every record stays findable whatever order they arrived in.
|
||||
CHECK(registry.find(HabitatId{7}, 3)->owner() == Owner{11, 2});
|
||||
CHECK(registry.find(HabitatId{7}, 4)->genome() == 4);
|
||||
CHECK(registry.find(HabitatId{8}, 3)->habitat() == HabitatId{8});
|
||||
CHECK(refused(registry.find(HabitatId{7}, 5), CohortError::unknown_cohort));
|
||||
CHECK(refused(registry.find(HabitatId{9}, 3), CohortError::unknown_cohort));
|
||||
}
|
||||
|
||||
void only_the_recorded_owner_may_replace_a_cohort() {
|
||||
CohortRegistry registry;
|
||||
CHECK(registry.install(valid()).has_value());
|
||||
// A different worker is refused however current its epoch.
|
||||
auto intruder = draft();
|
||||
intruder.owner = {12, 99};
|
||||
CHECK(refused(registry.replace(built(intruder)), CohortError::wrong_owner));
|
||||
// A writer holding an older view of its own cohort is refused too.
|
||||
auto stale = draft();
|
||||
stale.owner = {11, 1};
|
||||
CHECK(refused(registry.replace(built(stale)), CohortError::stale_epoch));
|
||||
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{900});
|
||||
// The owner rewriting its own epoch, or advancing it, succeeds.
|
||||
auto same = draft();
|
||||
same.last_tick = Tick{1'000};
|
||||
CHECK(registry.replace(built(same)).has_value());
|
||||
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'000});
|
||||
auto advanced = draft();
|
||||
advanced.owner = {11, 3};
|
||||
advanced.last_tick = Tick{1'100};
|
||||
CHECK(registry.replace(built(advanced)).has_value());
|
||||
CHECK(registry.find(HabitatId{7}, 3)->owner() == Owner{11, 3});
|
||||
// Having advanced, the previously current epoch is now the stale one.
|
||||
CHECK(refused(registry.replace(built(same)), CohortError::stale_epoch));
|
||||
CHECK(registry.find(HabitatId{7}, 3)->last_tick() == Tick{1'100});
|
||||
// A record naming a different habitat or genome is not a newer view of this
|
||||
// one, and replacing a cohort never installed is refused outright.
|
||||
auto elsewhere = draft();
|
||||
elsewhere.habitat = {8};
|
||||
CHECK(refused(registry.replace(built(elsewhere)), CohortError::unknown_cohort));
|
||||
auto another = draft();
|
||||
another.genome = 4;
|
||||
CHECK(refused(registry.replace(built(another)), CohortError::unknown_cohort));
|
||||
CHECK(registry.size() == 1); // A refused replacement installs nothing.
|
||||
}
|
||||
|
||||
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.
|
||||
using namespace evo::biology;
|
||||
GenomeDraft founder;
|
||||
founder.id = 3;
|
||||
founder.origin_event = 1;
|
||||
founder.development_version = 1;
|
||||
founder.capabilities = {{Capability::energy_conversion, 400, 0},
|
||||
{Capability::membrane, 120, 0},
|
||||
{Capability::target_size, 2'000, 0}};
|
||||
const auto ancestor = Genome::create(founder);
|
||||
CHECK(ancestor.has_value());
|
||||
auto descended = founder;
|
||||
descended.id = 9;
|
||||
descended.origin_event = 2;
|
||||
descended.parents = {3};
|
||||
const auto child = Genome::create(descended);
|
||||
CHECK(child.has_value());
|
||||
LineageArchive archive;
|
||||
CHECK(archive.admit(*ancestor).has_value());
|
||||
CHECK(archive.admit(*child).has_value());
|
||||
auto carrying = draft();
|
||||
carrying.genome = 9;
|
||||
const auto cohort = built(carrying);
|
||||
// The cohort contributes the identity; the archive contributes the ancestry.
|
||||
const auto line = archive.ancestry(cohort.genome());
|
||||
CHECK(line.has_value());
|
||||
CHECK(line->size() == 2);
|
||||
CHECK(line->front() == 3);
|
||||
CHECK(line->back() == 9);
|
||||
CHECK(archive.find(cohort.genome()).has_value());
|
||||
// Distinct genomes are never averaged into one, so each keeps its own record.
|
||||
CohortRegistry registry;
|
||||
CHECK(registry.install(cohort).has_value());
|
||||
auto sibling = draft();
|
||||
sibling.genome = 3;
|
||||
CHECK(registry.install(built(sibling)).has_value());
|
||||
CHECK(registry.size() == 2);
|
||||
CHECK(registry.find(HabitatId{7}, 3)->genome() != registry.find(HabitatId{7}, 9)->genome());
|
||||
}
|
||||
} // namespace
|
||||
int main() try {
|
||||
a_cohort_keeps_exactly_what_it_was_given();
|
||||
the_record_keeps_a_distribution_and_not_an_average();
|
||||
every_invariant_is_rejected_by_name();
|
||||
one_habitat_and_genome_holds_one_cohort();
|
||||
only_the_recorded_owner_may_replace_a_cohort();
|
||||
lineage_stays_the_archives_answer();
|
||||
std::cout << "PASS cohort state, declared resolution and exclusive ownership\n";
|
||||
return 0;
|
||||
} catch (...) {
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user