#pragma once #include "evo/accounting/ledger.hpp" #include "evo/core/types.hpp" #include #include #include 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. It never runs // backwards: a record naming an earlier boundary is an older view. Tick last_tick{}; // Strictly increases with every replacement within one owner epoch, so two // writes that share a boundary are still ordered. An epoch that is itself // newer may restart it, because re-acquiring ownership begins a new series. 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 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, not_vacant, duplicate_cohort, unknown_cohort, wrong_owner, stale_epoch, stale_revision, backward_tick, 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 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 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 // through a move what it rejects through construction. Declaring the copy // operations suppresses the implicit moves, so a move decays to a copy and // the source stays valid. A cohort is at most 64 classes, so that is cheap. Cohort(const Cohort&) = default; Cohort& operator=(const Cohort&) = default; [[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 revision() const noexcept { return revision_; } [[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 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; // 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. 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 revision_{}; std::uint64_t conversion_{}; accounting::ReservoirId reservoir_{}; std::vector 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: // Whether installing or replacing would be accepted, without doing it. A // conversion has to know before it moves any inventory, because a registry // step that failed afterwards would leave biomass in a store nothing owns. // `install` and `replace` delegate to these, so there is one rule and not two. [[nodiscard]] std::expected may_install(const Cohort& cohort) const; [[nodiscard]] std::expected may_replace(const Cohort& cohort) const; // Whether any installed record's reserve lives in this reservoir. An empty // reservoir is not the same as an unowned one: a vacant cohort, or one holding // nothing, still owns its store, and crediting it would put inventory there // that its own record does not account for. [[nodiscard]] bool reservoir_used(accounting::ReservoirId reservoir) const noexcept; // 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 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 // revision must advance within an epoch, and the interval boundary must not // run backwards. An epoch alone is too coarse, because two writes inside one // epoch would otherwise be interchangeable and replaying the earlier one // would restore inventory the later one had already spent. [[nodiscard]] std::expected replace(const Cohort& cohort); [[nodiscard]] std::expected 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 cohorts_; }; } // namespace evo::ecology