diff --git a/CMakeLists.txt b/CMakeLists.txt index 4422bd9..cdc775b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -130,6 +130,11 @@ if(BUILD_TESTING) evo_owned_target(evo-materialize-tests) add_test(NAME materialize-contracts COMMAND evo-materialize-tests) set_tests_properties(materialize-contracts PROPERTIES TIMEOUT 120) + add_executable(evo-equivalence-tests tests/equivalence_tests.cpp) + target_link_libraries(evo-equivalence-tests PRIVATE evo::ecology) + evo_owned_target(evo-equivalence-tests) + add_test(NAME resolution-equivalence COMMAND evo-equivalence-tests) + set_tests_properties(resolution-equivalence PROPERTIES TIMEOUT 600) add_executable(evo-ledger-tests tests/ledger_tests.cpp) target_link_libraries(evo-ledger-tests PRIVATE evo::accounting) evo_owned_target(evo-ledger-tests) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b596fbd..3791ef8 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -141,6 +141,20 @@ age. The smoothing the declared resolution causes is demonstrated rather than hidden: a round trip is exact when each class holds one member and averages within a coarse class, and the mitigation is the caller's choice of classes. +M4.5 closes M4 by measuring what the aggregation costs (ADR-0040), and adds no +library code: one rule is written once and applied at both resolutions, with a +one-member-per-class control proving the two runs are the same rule before any +divergence is attributed to resolution. The measurement is reported, not smoothed. +At class widths of ten and fifty the aggregate population survives ten thousand +ticks within 375 parts per thousand on population; at twenty-five, one hundred and +two hundred it dies out entirely while the individual run sustains seventy-five +members, which is a false extinction caused by resolution alone. The collapse is +not monotone in width, so a resolution cannot be chosen by assuming degradation +worsens smoothly. Conservation was exact at every tick in every run, including the +ones that died out, which is precisely why conservation is not sufficient evidence. +The comparison also found a real defect in M4.3: arrivals are now the first ledger +leg, because an interval affordable as a whole was being refused leg by leg. + 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 diff --git a/docs/STATUS.md b/docs/STATUS.md index 109f6ff..de8c973 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -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 39 ADRs. + diagrams, biological contracts, engineering constitution and 40 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.5 validate resolution equivalence | Collapse 100, advance 10,000 ticks, materialize; conservation exact and distributions within a documented tolerance | +| 1 | M4.6 budget and review the aggregate model | CPU and memory against the measured error regimes; the tier policy has to survive a resolution boundary that is not monotone | | 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 | @@ -468,3 +468,41 @@ Collapse now repopulates a vacant record in place, continuing its ownership and revision series rather than restarting them, and refuses a record that still holds a population. The test keeps one registry throughout and asserts the revision continues. + +M4.5 closes M4 by measuring what aggregation costs (ADR-0040). It adds no library +code: one rule is written once and applied at both resolutions, and a +one-member-per-class control proves the two runs are the same rule before any +divergence is attributed to resolution. Without that control a measured gap could +equally be a transcription mistake, and nothing afterwards would separate them; a +deliberate one-unit drift in the aggregate rule is caught by it. + +The result is reported rather than smoothed into a tolerance. At class widths of ten +and fifty the aggregate population survives ten thousand ticks and tracks the +individual run within 375 parts per thousand on population and 43 on energy. At +widths of twenty-five, one hundred and two hundred it dies out entirely while the +individual run sustains seventy-five members: a false extinction caused by +resolution alone, because a whole class starves the moment its average cannot pay +upkeep where individuals would have starved a few at a time and the survivors would +have kept the shared per-capita share up. + +The collapse is not monotone in class width. Twenty-five destroys the population +while fifty sustains it, so a resolution cannot be chosen by assuming degradation +worsens smoothly as classes widen, and a width that works is no evidence that every +narrower width works. The tests assert that non-monotonicity, because it is +surprising and because the warning written around it would otherwise be able to +become wrong silently. They also assert the runs disagree, so equivalence can never +be read as identity, and the word is not used for what was measured. + +Conservation was exact at every tick on both sides of every run, including the three +whose populations died out. Four of five runs conserve perfectly and three are +ecologically worthless, which is exactly ECOLOGY_MODEL's point that conservation is +insufficient evidence. + +The comparison also found a real defect in M4.3, which is what a validation +milestone is for. `plan_advance` checked affordability with arrivals added before +losses were taken, but emitted the ledger legs with the outflows first, so an +interval that was affordable as a whole underflowed leg by leg and was refused at +commit. A fifty-tick interval shedding 10,480 against 6,950 held while drawing +13,080 in reproduced it. Arrivals are now the first leg, matching the order the +arithmetic was checked in, with a regression covering it. Native Release, analysis, +ASan and formatting passed 38/38; Linux CI has not run yet. diff --git a/docs/adr/0040-resolution-equivalence.md b/docs/adr/0040-resolution-equivalence.md new file mode 100644 index 0000000..3eb8361 --- /dev/null +++ b/docs/adr/0040-resolution-equivalence.md @@ -0,0 +1,162 @@ +# ADR-0040: Measuring what aggregation costs, and refusing to call it equivalence + +## Status + +Adopted for M4.5, which closes M4. It adds no library code: the whole increment is +a measurement, and needing to change a contract in order to measure it would have +been a finding rather than a step. No M1 to M4.4 contract changes, and ADR-0038's +refusal to choose an ecology is unchanged: the model compared here lives in the +test fixture as a declared measurement input. + +## Context + +Everything M4 built proves its arithmetic closes. None of it says whether a cohort +behaves like the individuals it replaced, and ECOLOGY_MODEL is blunt about the +difference: passing conservation alone is insufficient ecological evidence, exact +seeded repeatability does not imply exact fidelity to individual ecology, and what +is wanted is matched ensembles with published error envelopes. + +The named risk is claiming identical trajectories at different resolution. It is a +risk precisely because the tempting experiment supports the claim: pick a fixture +where averaging happens not to bite, observe agreement, and report equivalence. +The honest experiment has to be built so that it can fail, and has to report the +size of the disagreement rather than its absence. + +There is a second, quieter problem. Comparing two implementations of "the same" +model measures the difference between the implementations as well as the difference +between the resolutions, and those are not separable after the fact. A divergence +of five per cent could be aggregation error or could be a transcription mistake in +one of the two runs, and no amount of staring at the number distinguishes them. + +## Decision + +The rule is written once and applied at both resolutions. The individual run +applies it to one member at a time; the aggregate run applies it to a class average +and multiplies by the count. Nothing else differs, and in particular the aggregate +run sub-steps internally at one tick so that interval length is not a second source +of error confounded with the first. + +A control run establishes that the two are the same rule before any divergence is +attributed to resolution. When every class holds exactly one member, a class +average is that member, so the aggregate run must reproduce the individual run +exactly, tick by tick, in population and in every inventory channel. That control +is the experiment's instrument check: without it a measured divergence means +nothing, and if it ever fails, every other number in this ADR is void. + +Divergence is then produced deliberately by coarsening the classes, which is the +resolution axis. Width is varied and the envelope is reported per width, so the +relationship between declared resolution and error is visible rather than a single +number standing in for it. + +The scarce quantity is a single axis. A shared environment supplies a fixed amount +of energy per tick divided equally among the living, and everything else is +abundant, so a member that cannot pay its upkeep starves. That makes the mechanism +attributable: at individual resolution the weakest starve first, and at class +resolution the average pays for everyone until it cannot, at which point the class +goes together. This is the "population averages hide viable outliers" risk of +ADR-0036 arriving as a measurable quantity rather than as a warning. + +The tests assert an envelope, and they also assert that the trajectories differ. +Asserting the difference is the part that protects the claim: a later change that +quietly made the runs agree would mean either that the fixture stopped exercising +aggregation or that the comparison stopped comparing, and both should fail loudly +rather than look like progress. Nothing in this ADR asserts equality outside the +one-member-per-class control, and the word equivalence is not used for what is +measured. + +The envelope is published as a results file alongside the existing benchmark +series, so the numbers are reviewable and comparable across platforms rather than +living only in a commit message. + +## What the measurement found + +The control holds: with one member per class the two runs agree exactly, tick by +tick, in population and in every channel. A deliberate one-unit drift introduced +into the aggregate rule is caught by it, so the instrument works. + +Coarsening then produces two regimes rather than a gradient. At class widths of ten +and fifty the aggregate population survives ten thousand ticks and tracks the +individual run within 375 parts per thousand on population and 43 on energy. At +widths of twenty-five, one hundred and two hundred the aggregate population dies +out entirely while the individual run sustains seventy-five members. That is a +false extinction produced by resolution alone: a whole class starves the moment its +average cannot pay upkeep, where individuals would have starved a few at a time and +the survivors would have kept the shared per-capita share up. + +The collapse is not monotone in class width. Width twenty-five destroys the +population while width fifty sustains it. Whether a class dips below upkeep +together depends on how its width lands against the population cycle that the +shared intake drives, and this fixture does not characterise that further. The +consequence for a tier policy is the useful part: a resolution cannot be chosen by +assuming that degradation worsens smoothly as classes widen, and a width that works +is not evidence that every narrower width works. M4.6 inherits that. + +Conservation was exact at every tick on both sides in every run, including the ones +whose populations died out, which is the point ECOLOGY_MODEL makes about +conservation being insufficient evidence. Four of these five runs conserve +perfectly and three of them are ecologically worthless. + +## Alternatives Considered + +Asserting the aggregate run matches the individual run within a tolerance and +leaving it there is the shape this milestone is named against: it reads as +equivalence, it says nothing about where the error comes from, and it passes just +as well when the fixture has been chosen so that nothing is averaged. Deriving the +aggregate fluxes from a separately written population model would be a more +realistic aggregate, and would make every divergence uninterpretable, because the +two models would differ in ways nobody could enumerate. Varying the interval length +as the resolution axis was considered and rejected for this increment: it measures +a real error but confounds it with the averaging error, and the averaging error is +the one M4 is built on. Using a fitted tolerance derived from the observed numbers +would make the test unfalsifiable; the asserted bounds are round numbers chosen +above the measurement with room for platform variation, and the measurement itself +is what is published. + +## Benefits + +The cost of aggregation in this fixture is a number rather than an assurance, and +it is attributable to averaging because the control rules out an implementation +difference. The relationship between class width and error is visible, so a caller +choosing a resolution has something to choose against. A change that made the +comparison stop comparing fails the suite. + +## Costs + +The fixture is one model, one scarce axis and one seed regime, so its numbers +describe itself and nothing wider. The control is limited to a short horizon, +because one class per age exhausts the sixty-four-class bound within a few tens of +ticks; the instrument is therefore checked over tens of ticks and used over ten +thousand. The aggregate run sub-steps at one tick, which is not how a cheap +aggregate would be run in production, so this measures the averaging cost alone and +not the cost of a long interval. + +## Risks + +This is not a fidelity claim and does not become one by being repeated. The +measured envelope belongs to this fixture: another model, another scarcity regime +or another initial distribution would give other numbers, and nothing here bounds +them. Agreement inside the control proves the two runs implement one rule, not that +the rule resembles biology. The asserted bounds are chosen, not derived, so they +are a regression guard and not a theoretical limit. Interval-length error is +unmeasured. Diversity is compared as counts per genome, which is not a species +concept and settles nothing about speciation, and this fixture runs one genome, so +the mixed-genome case ECOLOGY_MODEL also asks for is not covered here. The +non-monotonicity is reported from five widths, which locates it but does not map +it; the boundary between the regimes is not characterised and no mechanism beyond +whole-class starvation is claimed. Nothing here is persistent, no +population is distributed across owners, and crash behaviour at conversion +boundaries remains what ADR-0037 and ADR-0039 already scoped in one process. + +## Consequences + +Test the control first, so a failing instrument fails before any envelope is +reported: with one member per class the aggregate run must equal the individual run +exactly, every tick, in population and every channel. Then run the scenario +ECOLOGY_MODEL asks for, a hundred funded individuals collapsed, advanced over ten +thousand ticks and materialized, asserting that conservation is exact at every step +on both sides, that genome identity is preserved and no genome is invented or lost, +and that population, biomass and diversity divergence stay inside the published +envelope. Assert that the two runs do not agree, so equivalence cannot be read as +identity. Report the envelope per class width to a results file. No genome schema, +mutation catalog, archive, ledger, episode driver, ensemble, cohort record, +collapse, interval accounting, materialization, renderer or deployment changes. diff --git a/docs/adr/README.md b/docs/adr/README.md index 3a944a7..e46874f 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -32,6 +32,7 @@ Each record has the eight required sections. 0037 collapses individuals into a cohort as one sampled, ledger-exact transaction. 0038 accounts a proposed interval, refusing rather than clamping, without picking a model. 0039 materializes representatives on shares that round down and ages that never fall. +0040 measures what aggregation costs and refuses to call the result equivalence. Every dependency adoption records exact version/commit and integrity hash, transitive license obligations, maintenance/security review, owner and removal diff --git a/docs/biology/ECOLOGY_MODEL.md b/docs/biology/ECOLOGY_MODEL.md index d3a44d2..97c5cac 100644 --- a/docs/biology/ECOLOGY_MODEL.md +++ b/docs/biology/ECOLOGY_MODEL.md @@ -274,3 +274,44 @@ A materialized member carries the cohort's genome, its habitat and a fresh identity, and nothing else. It has no parentage, no history and no condition, because a cohort never carried them, and none of that may later be invented from a statistical membership. + +## Implemented M4.5 resolution comparison + +[ADR-0040](../adr/0040-resolution-equivalence.md) carries out the comparison this +document asks for: a hundred funded individuals collapsed, advanced over ten +thousand ticks and materialized, against the same hundred simulated explicitly. The +numbers are in +[resolution-equivalence-msvc1944.jsonl](../engineering/results/resolution-equivalence-msvc1944.jsonl). + +One rule is written once and applied at both resolutions, and a control with one +member per class establishes that the two runs are the same rule before any gap is +blamed on resolution. Every state the aggregate run passes through is checked to be +a representable cohort, so the envelope describes this library rather than a model +it could not hold. + +The claim this document warns against is not made. Nothing asserts the trajectories +agree; the tests assert that they differ, so equivalence cannot be read as identity, +and the word is not used for what was measured. + +What was measured is two regimes rather than a gradient. At some class widths the +aggregate tracks the individuals within a few hundred parts per thousand. At others +it dies out entirely while the individuals persist, which is a false extinction +caused by resolution alone: a whole class starves the moment its average cannot pay +upkeep, where individuals starve a few at a time and the survivors keep the shared +per-capita share up. This is the "population averages hide viable outliers" risk +arriving as a measurable quantity. + +The collapse is not monotone in class width: a narrower class is not reliably safer. +A tier policy therefore cannot be derived by assuming degradation worsens smoothly +as resolution coarsens, and the boundary between the regimes is not characterised +here. + +Conservation held exactly at every tick of every run, including the ones whose +populations died out. That is this document's point about conservation being +insufficient ecological evidence, demonstrated rather than restated. + +Not covered: one genome only, so the mixed-genome diversity case remains open; one +model, one scarce axis and one initial distribution, so the numbers describe this +fixture; interval-length error is unmeasured, because the aggregate run sub-steps at +one tick to keep the averaging error attributable; and nothing here is distributed +or persistent. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index a3f1bc9..45896a4 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1242,3 +1242,83 @@ parse, so the larger test edits in this increment were written to a scratchpad f and run from there. That is the third distinct way heredocs have mangled content in this project, after backslash escapes and `/tmp` resolving differently between shells. + +## M4.5 resolution comparison + +Executed on this Windows host (2026-09-24): Release configure, build and `ctest` +38/38; the analysis preset (clang-tidy 19, warnings as errors) built clean; the ASan +preset configured, built and ran 38/38; `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. + +The increment adds no library code apart from one defect fix described below. One +rule is written once and applied at both resolutions; the individual run gives it a +member at a time and the aggregate run gives it a class average and multiplies by +the count. The aggregate run sub-steps at one tick, so interval-length error is not +confounded with averaging error, and interval-length error is therefore unmeasured. + +The control is the part that makes the rest mean anything. With one member per class +a class average is that member, so the two runs must agree exactly; the test checks +population and every channel at every tick over forty ticks, and checks the class +count stays inside the sixty-four-class bound. Introducing a one-unit drift into the +aggregate upkeep is caught by it, so the instrument was verified rather than assumed. +Without this control a measured divergence would be indistinguishable from a +transcription mistake in one of the two runs. + +Measured, and reported rather than smoothed into a tolerance. Class widths ten and +fifty: the aggregate population survives ten thousand ticks, with population gaps of +250 and 375 parts per thousand and energy gaps of 24 and 43. Class widths +twenty-five, one hundred and two hundred: the aggregate population reaches zero while +the individual run sustains seventy-five members. That is a false extinction caused +by resolution alone. The numbers are in +`docs/engineering/results/resolution-equivalence-msvc1944.jsonl`. + +The collapse is not monotone in class width: twenty-five destroys the population and +fifty sustains it. An earlier version of the test asserted that coarser is never +better, and the measurement refuted it; the assertion was removed rather than the +widths being chosen to make it hold, and the non-monotonicity is now asserted +instead, because it is surprising and because the warning written around it could +otherwise become wrong without failing. Five widths locate the effect and do not map +it; no mechanism beyond whole-class starvation is claimed. + +Conservation was exact at every tick on both sides of all five runs, including the +three whose populations died out. Four of five conserve perfectly and three are +ecologically worthless, which is the clearest available demonstration of +ECOLOGY_MODEL's point that conservation is insufficient ecological evidence. + +Two flaws in my own experiment were found and fixed before any number was believed. +The aggregate model originally shifted class bounds every tick and opened newborn +classes at the full declared width, which produced overlapping classes: the model +being measured was not one a cohort record could represent, and the first numbers +measured were therefore of a model the library could not hold. Newborns now extend +the youngest class down while it is narrower than the width, keeping the structure +contiguous and ascending, and every step of the aggregate run is now checked to +construct a valid `Cohort`. The earlier figures were discarded. + +The comparison also found a real defect in M4.3. `plan_advance` checked affordability +with arrivals added before losses were taken, but emitted the ledger legs with the +outflows first. The ledger applies legs in sequence, so an interval affordable as a +whole underflowed leg by leg and was refused at commit with `ledger_failure`: a +fifty-tick interval shedding 10,480 energy against 6,950 held while drawing 13,080 +in reproduced it exactly. Arrivals are now the first leg, matching the order the +arithmetic was validated in. The fix was confirmed load-bearing by restoring the old +order, which fails both suites, and a dedicated regression in `evo-population-tests` +covers an interval affordable only with its arrivals. One existing test had seeded +its escrow assuming the old order and was corrected, with its comment; that comment +had asserted the old ordering was what made the interval fundable, which was true +and is now true of the opposite order. + +Coverage limits. One genome, so the mixed-genome diversity case ECOLOGY_MODEL also +asks for is untested. One model, one scarce axis, one initial distribution and one +capacity, so every number describes this fixture. The control runs over tens of +ticks because one class per age exhausts the class bound, while the measurement runs +over ten thousand: the instrument is checked at a shorter horizon than it is used at. +The asserted envelope bounds are round numbers above the measurement with room for +platform variation, so they are a regression guard and not a theoretical limit. +Interval-length error, crash behaviour at conversion boundaries beyond one process, +distribution across owners and persistence are all out of scope here. + +The proof golden `d61ad5bf0c928c76`, the ecosystem fingerprint `2cd4a15f9fbe9949`, +the ensemble fingerprint `5ec59d390909b526` and the frozen genome fixture are +unchanged. No deployment manifest or image pin changed. Linux validation is pending; +no Gitea result is claimed since `b01a824`. diff --git a/docs/engineering/results/resolution-equivalence-msvc1944.jsonl b/docs/engineering/results/resolution-equivalence-msvc1944.jsonl new file mode 100644 index 0000000..cb1ccdc --- /dev/null +++ b/docs/engineering/results/resolution-equivalence-msvc1944.jsonl @@ -0,0 +1,6 @@ +{"experiment":"resolution-equivalence-v1","model":"fixture-v1","compiler":"MSVC 1944","build":"release","commit":"m4.5","founders":100,"ticks":10000,"scarce_axis":"energy","lifespan":400,"capacity":200,"note":"Aggregate and individual runs apply one rule at two resolutions. The width-1 control matches exactly; these are the coarse measurements. Not an equivalence claim. See docs/adr/0040-resolution-equivalence.md"} +{"class_width":10,"individual_living":75,"aggregate_living":100,"individual_energy":6275,"aggregate_energy":6120,"living_gap_per_thousand":250,"energy_gap_per_thousand":24,"aggregate_survived":true} +{"class_width":25,"individual_living":75,"aggregate_living":0,"individual_energy":6275,"aggregate_energy":0,"living_gap_per_thousand":1000,"energy_gap_per_thousand":1000,"aggregate_survived":false} +{"class_width":50,"individual_living":75,"aggregate_living":120,"individual_energy":6275,"aggregate_energy":6000,"living_gap_per_thousand":375,"energy_gap_per_thousand":43,"aggregate_survived":true} +{"class_width":100,"individual_living":75,"aggregate_living":0,"individual_energy":6275,"aggregate_energy":0,"living_gap_per_thousand":1000,"energy_gap_per_thousand":1000,"aggregate_survived":false} +{"class_width":200,"individual_living":75,"aggregate_living":0,"individual_energy":6275,"aggregate_energy":0,"living_gap_per_thousand":1000,"energy_gap_per_thousand":1000,"aggregate_survived":false} diff --git a/src/ecology/population.cpp b/src/ecology/population.cpp index 147e153..28a660e 100644 --- a/src/ecology/population.cpp +++ b/src/ecology/population.cpp @@ -143,10 +143,15 @@ std::expected plan_advance(const Cohort& before, legs.push_back(inbound ? accounting::Transfer{where, before.reservoir(), amount} : accounting::Transfer{before.reservoir(), where, amount}); }; + // Arrivals first, in the same order the arithmetic above was checked: the + // ledger applies legs in sequence, so an outflow placed before an inflow could + // underflow a reservoir that the interval as a whole affords. Without this a + // cohort shedding more than it currently holds, while receiving enough to cover + // it, would pass planning and then be refused at commit. + leg(flux.from_elsewhere, request.elsewhere, true); 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}; } diff --git a/tests/equivalence_tests.cpp b/tests/equivalence_tests.cpp new file mode 100644 index 0000000..ca22931 --- /dev/null +++ b/tests/equivalence_tests.cpp @@ -0,0 +1,749 @@ +#include "evo/ecology/materialize.hpp" +#include "evo/ecology/population.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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("equivalence line " + std::to_string(location.line())); + } +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) + +// --------------------------------------------------------------------------- +// The rule. Written once, applied at both resolutions: the individual run gives +// it one member at a time and the aggregate run gives it a class average and +// multiplies by the count. It is a fixture constant, not a simulation contract: +// ADR-0038 deliberately declines to choose an ecology, and this does not choose +// one for it. Energy is the only scarce axis so that divergence is attributable. +// --------------------------------------------------------------------------- +namespace rule { +constexpr std::uint64_t environment_energy = 300; // per tick, shared by the living +constexpr std::uint64_t matter_intake = 4; // per member per tick, abundant +constexpr std::uint64_t upkeep_energy = 2; +constexpr std::uint64_t upkeep_matter = 1; +constexpr std::uint64_t lifespan = 400; +constexpr std::uint64_t maturity = 50; +constexpr std::uint64_t threshold_energy = 100; +constexpr std::uint64_t investment_energy = 40; +constexpr std::uint64_t investment_matter = 40; +constexpr std::uint64_t capacity = 200; + +// A member that cannot pay its upkeep starves. At class resolution the average +// member is asked the same question, which is exactly where the resolution bites. +[[nodiscard]] constexpr bool starves(std::uint64_t energy) noexcept { + return energy < upkeep_energy; +} +[[nodiscard]] constexpr bool breeds(std::uint64_t age, std::uint64_t energy) noexcept { + return age >= maturity && energy >= threshold_energy; +} +[[nodiscard]] constexpr std::uint64_t per_capita(std::uint64_t living) noexcept { + return living == 0 ? 0 : environment_energy / living; +} +} // namespace rule + +// Matter behaves identically in all four channels here, so one number is tracked +// and mirrored into the four. Stated rather than left for a reader to infer. +Inventory spread(std::uint64_t energy, std::uint64_t matter) { + return {{energy}, + {Femtograms{matter}, Femtograms{matter}, Femtograms{matter}, Femtograms{matter}}}; +} + +struct Census { + std::uint64_t living{}; + std::uint64_t energy{}; + std::uint64_t matter{}; + std::uint64_t births{}; + std::uint64_t deaths{}; + auto operator<=>(const Census&) const = default; +}; + +// --------------------------------------------------------------------------- +// Individual resolution. Inventory is tracked as plain values and conservation is +// asserted arithmetically: this is the reference fixture, not a contract, and a +// reservoir per member would exceed the ledger's per-transaction leg bound. +// --------------------------------------------------------------------------- +struct Member { + std::uint64_t age{}; + std::uint64_t energy{}; + std::uint64_t matter{}; + bool alive{true}; +}; + +struct IndividualRun { + std::vector members; + std::uint64_t environment{}; + std::uint64_t detritus_energy{}; + std::uint64_t detritus_matter{}; + std::uint64_t matter_store{}; + std::uint64_t births{}; + std::uint64_t deaths{}; + + [[nodiscard]] Census census() const { + Census now; + for (const auto& member : members) { + if (!member.alive) { + continue; + } + ++now.living; + now.energy += member.energy; + now.matter += member.matter; + } + now.births = births; + now.deaths = deaths; + return now; + } + [[nodiscard]] std::uint64_t total_energy() const { + std::uint64_t total = environment + detritus_energy; + for (const auto& member : members) { + if (member.alive) { + total += member.energy; + } + } + return total; + } + [[nodiscard]] std::uint64_t total_matter() const { + std::uint64_t total = matter_store + detritus_matter; + for (const auto& member : members) { + if (member.alive) { + total += member.matter; + } + } + return total; + } + + void step() { + std::uint64_t living = 0; + for (const auto& member : members) { + living += member.alive ? 1 : 0; + } + const auto share = rule::per_capita(living); + // Starvation first, then upkeep, then intake, then ageing, then breeding. + // The aggregate run applies the same five stages in the same order. + for (auto& member : members) { + if (!member.alive) { + continue; + } + if (rule::starves(member.energy)) { + member.alive = false; + detritus_energy += member.energy; + detritus_matter += member.matter; + member.energy = 0; + member.matter = 0; + ++deaths; + } + } + for (auto& member : members) { + if (!member.alive) { + continue; + } + member.energy -= rule::upkeep_energy; + detritus_energy += rule::upkeep_energy; + const auto paid = std::min(member.matter, rule::upkeep_matter); + member.matter -= paid; + detritus_matter += paid; + } + for (auto& member : members) { + if (!member.alive) { + continue; + } + const auto taken = std::min(share, environment); + environment -= taken; + member.energy += taken; + const auto gathered = std::min(rule::matter_intake, matter_store); + matter_store -= gathered; + member.matter += gathered; + } + for (auto& member : members) { + if (!member.alive) { + continue; + } + ++member.age; + if (member.age >= rule::lifespan) { + member.alive = false; + detritus_energy += member.energy; + detritus_matter += member.matter; + member.energy = 0; + member.matter = 0; + ++deaths; + } + } + std::uint64_t population = 0; + for (const auto& member : members) { + population += member.alive ? 1 : 0; + } + const auto before = members.size(); + for (std::size_t index = 0; index < before; ++index) { + auto& member = members[index]; + if (!member.alive || population >= rule::capacity) { + continue; + } + if (!rule::breeds(member.age, member.energy)) { + continue; + } + if (member.matter < rule::investment_matter) { + continue; + } + member.energy -= rule::investment_energy; + member.matter -= rule::investment_matter; + members.push_back({0, rule::investment_energy, rule::investment_matter, true}); + ++population; + ++births; + } + } +}; + +IndividualRun founding_individuals(std::uint64_t count) { + IndividualRun run; + // Deliberately spread: variation is what averaging destroys, so a fixture + // where everyone is identical would measure nothing. + for (std::uint64_t index = 0; index < count; ++index) { + run.members.push_back({index % 60, 20 + index, 50 + index, true}); + } + run.environment = 100'000'000; + run.matter_store = 100'000'000; + return run; +} + +// --------------------------------------------------------------------------- +// Aggregate resolution. Real cohort records, real ledger, real conversions. The +// class state is advanced by the same five stages applied to a class average. +// --------------------------------------------------------------------------- +struct AggregateClass { + std::uint64_t age_low{}; + std::uint64_t age_high{}; + std::uint64_t count{}; + std::uint64_t energy{}; // held by the class in total + std::uint64_t matter{}; +}; + +struct AggregateRun { + std::vector classes; + std::uint64_t width{}; + std::uint64_t environment{}; + std::uint64_t matter_store{}; + std::uint64_t detritus_energy{}; + std::uint64_t detritus_matter{}; + std::uint64_t births{}; + std::uint64_t deaths{}; + + [[nodiscard]] Census census() const { + Census now; + for (const auto& age : classes) { + now.living += age.count; + now.energy += age.energy; + now.matter += age.matter; + } + now.births = births; + now.deaths = deaths; + return now; + } + [[nodiscard]] std::uint64_t total_energy() const { + std::uint64_t total = environment + detritus_energy; + for (const auto& age : classes) { + total += age.energy; + } + return total; + } + [[nodiscard]] std::uint64_t total_matter() const { + std::uint64_t total = matter_store + detritus_matter; + for (const auto& age : classes) { + total += age.matter; + } + return total; + } + + void step() { + std::uint64_t living = 0; + for (const auto& age : classes) { + living += age.count; + } + const auto share = rule::per_capita(living); + // Starvation, judged on the class average. This is the resolution error: + // the average pays for everyone until it cannot, and then the class goes + // together, where individuals would have starved one at a time. + for (auto& age : classes) { + if (age.count == 0) { + continue; + } + if (rule::starves(age.energy / age.count)) { + detritus_energy += age.energy; + detritus_matter += age.matter; + deaths += age.count; + age.count = 0; + age.energy = 0; + age.matter = 0; + } + } + std::erase_if(classes, [](const AggregateClass& age) { return age.count == 0; }); + for (auto& age : classes) { + const auto owed = rule::upkeep_energy * age.count; + age.energy -= owed; + detritus_energy += owed; + const auto paid = std::min(age.matter, rule::upkeep_matter * age.count); + age.matter -= paid; + detritus_matter += paid; + } + for (auto& age : classes) { + const auto wanted = share * age.count; + const auto taken = std::min(wanted, environment); + environment -= taken; + age.energy += taken; + const auto gathered = std::min(rule::matter_intake * age.count, matter_store); + matter_store -= gathered; + age.matter += gathered; + } + // Ageing shifts the class bounds rather than moving members between + // classes, so no member ever has to be placed by an age the record cannot + // know. A class is a birth cohort and stays one. + for (auto& age : classes) { + ++age.age_low; + ++age.age_high; + } + for (auto& age : classes) { + if (age.age_low >= rule::lifespan) { + detritus_energy += age.energy; + detritus_matter += age.matter; + deaths += age.count; + age.count = 0; + age.energy = 0; + age.matter = 0; + } + } + std::erase_if(classes, [](const AggregateClass& age) { return age.count == 0; }); + std::uint64_t population = 0; + for (const auto& age : classes) { + population += age.count; + } + std::uint64_t newborns = 0; + std::uint64_t taken_energy = 0; + std::uint64_t taken_matter = 0; + for (auto& age : classes) { + if (age.count == 0 || population + newborns >= rule::capacity) { + continue; + } + const auto average_energy = age.energy / age.count; + const auto average_matter = age.matter / age.count; + if (!rule::breeds(age.age_low, average_energy)) { + continue; + } + if (average_matter < rule::investment_matter) { + continue; + } + auto breeding = age.count; + if (population + newborns + breeding > rule::capacity) { + breeding = rule::capacity - population - newborns; + } + const auto energy_moved = rule::investment_energy * breeding; + const auto matter_moved = rule::investment_matter * breeding; + if (energy_moved > age.energy || matter_moved > age.matter) { + continue; + } + age.energy -= energy_moved; + age.matter -= matter_moved; + taken_energy += energy_moved; + taken_matter += matter_moved; + newborns += breeding; + } + if (newborns > 0) { + // Ageing shifted every class up by one, so nothing now starts at zero. + // The youngest class is extended down to cover the newborns while it is + // still narrower than the declared width, and otherwise a new one + // opens. That keeps the classes contiguous, ascending and never wider + // than the width, which is what makes the state a representable + // cohort: bounds that merely shift would overlap the moment a class + // was opened part way through an interval. + const auto at = std::ranges::min_element( + classes, {}, [](const AggregateClass& age) { return age.age_low; }); + if (at != classes.end() && at->age_low == 1 && at->age_high - at->age_low < width) { + at->age_low = 0; + at->count += newborns; + at->energy += taken_energy; + at->matter += taken_matter; + } else { + classes.push_back({0, 1, newborns, taken_energy, taken_matter}); + } + births += newborns; + } else { + // A class that opened and then had no births still has to grow to the + // declared width rather than staying one tick wide for ever, or the + // structure would drift towards one class per tick. + const auto at = std::ranges::min_element( + classes, {}, [](const AggregateClass& age) { return age.age_low; }); + if (at != classes.end() && at->age_low == 1 && at->age_high - at->age_low < width) { + at->age_low = 0; + } + } + std::ranges::sort(classes, {}, [](const AggregateClass& age) { return age.age_low; }); + } +}; + +AggregateRun founding_classes(const IndividualRun& source, std::uint64_t width) { + AggregateRun run; + run.width = width; + run.environment = source.environment; + run.matter_store = source.matter_store; + for (const auto& member : source.members) { + if (!member.alive) { + continue; + } + const auto low = member.age / width * width; + const auto at = std::ranges::find_if( + run.classes, [&](const AggregateClass& age) { return age.age_low == low; }); + if (at == run.classes.end()) { + run.classes.push_back({low, low + width, 1, member.energy, member.matter}); + } else { + ++at->count; + at->energy += member.energy; + at->matter += member.matter; + } + } + std::ranges::sort(run.classes, {}, [](const AggregateClass& age) { return age.age_low; }); + check(run.classes.size() <= max_age_classes); + return run; +} + +// Whether the aggregate state is something a cohort record can actually hold. The +// experiment is worthless if it measures a model the library could not represent, +// so this is checked at every step rather than assumed. +[[nodiscard]] bool representable(const AggregateRun& run) { + if (run.classes.empty()) { + return true; // Vacancy is representable; ADR-0036 has a factory for it. + } + CohortDraft probe; + probe.representation_version = cohort_representation_version; + probe.habitat = {7}; + probe.genome = 3; + probe.owner = {11, 1}; + probe.last_tick = Tick{0}; + probe.revision = 1; + probe.conversion = 1; + probe.reservoir = {1}; + for (const auto& age : run.classes) { + probe.classes.push_back( + {age.age_low, age.age_high, age.count, spread(age.energy, age.matter), 0}); + } + return Cohort::create(std::move(probe)).has_value(); +} + +// --------------------------------------------------------------------------- +// The instrument check. With one member per class a class average is that member, +// so the two runs must agree exactly. Without this a measured divergence could be +// aggregation error or a transcription mistake, and nothing would tell them apart. +// --------------------------------------------------------------------------- +void one_member_per_class_agrees_exactly() { + auto individual = founding_individuals(20); + // Distinct ages so every class holds exactly one member at width one. + for (std::size_t index = 0; index < individual.members.size(); ++index) { + individual.members[index].age = index; + } + auto aggregate = founding_classes(individual, 1); + CHECK(aggregate.classes.size() == individual.members.size()); + CHECK(individual.census() == aggregate.census()); + for (std::uint64_t tick = 0; tick < 40; ++tick) { + individual.step(); + aggregate.step(); + // Every tick, not only at the end: a divergence that cancelled would + // otherwise pass. + CHECK(individual.census() == aggregate.census()); + CHECK(individual.total_energy() == aggregate.total_energy()); + CHECK(individual.total_matter() == aggregate.total_matter()); + CHECK(aggregate.classes.size() <= max_age_classes); + CHECK(representable(aggregate)); + } + // The control has to have exercised something, or it proves nothing. + CHECK(individual.census().births > 0); + CHECK(individual.census().living > 20); +} + +// --------------------------------------------------------------------------- +// The scenario ECOLOGY_MODEL asks for, through the real conversions. +// --------------------------------------------------------------------------- +struct Divergence { + std::uint64_t width{}; + std::uint64_t individual_living{}; + std::uint64_t aggregate_living{}; + std::uint64_t individual_energy{}; + std::uint64_t aggregate_energy{}; + std::uint64_t living_gap_per_thousand{}; + std::uint64_t energy_gap_per_thousand{}; +}; + +std::uint64_t gap_per_thousand(std::uint64_t left, std::uint64_t right) { + const auto high = std::max(left, right); + const auto low = std::min(left, right); + if (high == 0) { + return 0; + } + return (high - low) * 1000 / high; +} + +Divergence measure(std::uint64_t width, std::uint64_t ticks) { + auto individual = founding_individuals(100); + auto aggregate = founding_classes(individual, width); + const auto opening_energy = individual.total_energy(); + const auto opening_matter = individual.total_matter(); + CHECK(aggregate.total_energy() == opening_energy); + CHECK(aggregate.total_matter() == opening_matter); + for (std::uint64_t tick = 0; tick < ticks; ++tick) { + individual.step(); + aggregate.step(); + // Conservation is exact on both sides at every tick, whatever the two + // populations do to each other. + CHECK(individual.total_energy() == opening_energy); + CHECK(individual.total_matter() == opening_matter); + CHECK(aggregate.total_energy() == opening_energy); + CHECK(aggregate.total_matter() == opening_matter); + CHECK(aggregate.classes.size() <= max_age_classes); + // Every step of the aggregate run is a state a cohort could hold, so the + // envelope describes this library and not a model it cannot represent. + CHECK(representable(aggregate)); + } + const auto left = individual.census(); + const auto right = aggregate.census(); + return {width, + left.living, + right.living, + left.energy, + right.energy, + gap_per_thousand(left.living, right.living), + gap_per_thousand(left.energy, right.energy)}; +} + +std::vector envelope; + +void aggregation_costs_something_and_coarse_classes_destroy_the_population() { + // Ten thousand ticks, a hundred funded individuals, five declared resolutions. + // Nothing here asserts the runs agree, and nothing tunes a bound to fit. + for (const std::uint64_t width : {10U, 25U, 50U, 100U, 200U}) { + const auto measured = measure(width, 10'000); + envelope.push_back(measured); + std::cout << "{\"class_width\":" << measured.width + << ",\"individual_living\":" << measured.individual_living + << ",\"aggregate_living\":" << measured.aggregate_living + << ",\"individual_energy\":" << measured.individual_energy + << ",\"aggregate_energy\":" << measured.aggregate_energy + << ",\"living_gap_per_thousand\":" << measured.living_gap_per_thousand + << ",\"energy_gap_per_thousand\":" << measured.energy_gap_per_thousand << "}\n"; + } + // The individual run is the reference and must survive in every case, or the + // comparison is against a corpse and every gap below is meaningless. + for (const auto& measured : envelope) { + CHECK(measured.individual_living > 0); + } + // The measured result, reported rather than smoothed. Below a width the + // aggregate tracks the individuals; above it the aggregate population dies out + // entirely while the individuals persist. That is a false extinction caused by + // resolution alone: a whole class starves together the moment its average + // cannot pay upkeep, where individuals would have starved a few at a time and + // the survivors would have kept the per-capita share up. + std::uint64_t usable = 0; + std::uint64_t destroyed = 0; + for (const auto& measured : envelope) { + if (measured.aggregate_living == 0) { + ++destroyed; + // A false extinction, since the reference population is alive. + CHECK(measured.individual_living > 0); + CHECK(measured.living_gap_per_thousand == 1000); + } else { + ++usable; + // Where the aggregate survives, this is the envelope. The bounds are + // chosen above the measurement with room for platform variation; they + // are a regression guard, not a theoretical limit. See ADR-0040. + CHECK(measured.living_gap_per_thousand <= 600); + CHECK(measured.energy_gap_per_thousand <= 600); + } + } + // Both regimes have to appear, or this measured one thing and reported two. + CHECK(usable > 0); + CHECK(destroyed > 0); + // And the collapse is not monotone in class width. A narrower class is not + // reliably safer: the measurement finds a width that destroys the population + // while a coarser one sustains it. Whether a whole class dips below upkeep + // together depends on how the width lands against the population cycle that + // the shared per-capita intake drives, and this fixture does not characterise + // that further. The consequence for a tier policy is the point: a resolution + // cannot be chosen by assuming degradation worsens smoothly with coarseness. + // Asserted because it is surprising: if a change ever made it monotone, the + // warning written around this number would have become wrong. + bool out_of_order = false; + for (std::size_t index = 1; index < envelope.size(); ++index) { + if (envelope[index - 1].aggregate_living == 0 && envelope[index].aggregate_living > 0) { + out_of_order = true; + } + } + CHECK(out_of_order); + // And the runs must not agree anywhere. A change that quietly made them match + // would mean the fixture stopped exercising aggregation or the comparison + // stopped comparing, and either should fail rather than look like progress. + for (const auto& measured : envelope) { + CHECK(measured.living_gap_per_thousand > 0 || measured.energy_gap_per_thousand > 0); + } +} + +// --------------------------------------------------------------------------- +// The same hundred individuals through the real conversions, end to end. +// --------------------------------------------------------------------------- +void the_full_scenario_conserves_and_keeps_its_genome() { + constexpr ReservoirId backing{1}; + constexpr ReservoirId detritus{2}; + constexpr ReservoirId escrow{3}; + constexpr std::uint32_t first_member_store = 4; + auto individual = founding_individuals(100); + // One ledger reservoir per founder, plus the cohort, detritus and the escrow + // that stands for the environment. The escrow is seeded with what the + // environment holds, because inventory arriving with immigration has to come + // out of a store that already held it: a late transfer is not new production. + // Sized for the capacity rather than the founders: the population grows, and a + // draw of more members than there were founders would otherwise run off the + // end of the ledger and be reported as a stale plan. + std::vector opening(first_member_store + rule::capacity); + opening[escrow.value - 1] = spread(individual.environment, individual.matter_store); + std::vector members; + for (std::size_t index = 0; index < individual.members.size(); ++index) { + const auto& source = individual.members[index]; + const ReservoirId store{static_cast(first_member_store + index)}; + const auto reserve = spread(source.energy, source.matter); + opening[store.value - 1] = reserve; + members.push_back({index + 1, 3, {7}, source.age, store, reserve, MemberState::active}); + } + auto ledger = Ledger::create(opening); + CHECK(ledger.has_value()); + const auto total = ledger->conserved_totals(); + + CollapseRequest gather; + gather.conversion = 1; + gather.owner = {11, 1}; + gather.habitat = {7}; + gather.genome = 3; + gather.tick = Tick{0}; + gather.revision = 1; + gather.destination = backing; + for (std::uint64_t low = 0; low < rule::lifespan; low += 50) { + gather.bounds.push_back({low, low + 50}); + } + const auto folded = plan_collapse(members, gather); + CHECK(folded.has_value()); + CohortRegistry registry; + const auto installed = commit_collapse(*ledger, registry, *folded); + CHECK(installed.has_value()); + CHECK(ledger->conserved_totals() == total); + CHECK(installed->count() == 100); + CHECK(installed->genome() == 3); + + // Ten thousand ticks, advanced through M4.3 in intervals of fifty. The model + // sub-steps internally; the interval reports the net flux it produced. + auto aggregate = founding_classes(individual, 50); + auto cohort = *installed; + std::uint64_t revision = 1; + std::uint64_t tick = 0; + for (std::uint64_t interval = 0; interval < 200; ++interval) { + const auto before = aggregate.census(); + const auto before_detritus_energy = aggregate.detritus_energy; + const auto before_detritus_matter = aggregate.detritus_matter; + const auto before_environment = aggregate.environment; + const auto before_store = aggregate.matter_store; + for (std::uint64_t step = 0; step < 50; ++step) { + aggregate.step(); + } + tick += 50; + const auto after = aggregate.census(); + if (after.living == 0) { + break; + } + AdvanceRequest proposal; + proposal.to = Tick{tick}; + proposal.owner = cohort.owner(); + proposal.revision = ++revision + 1; + proposal.detritus = detritus; + proposal.predators = detritus; + proposal.elsewhere = escrow; + proposal.bound = cohort.bound(); + // The cohort's classes are the aggregate model's classes, and its fluxes + // are the net change the model produced over the interval. + for (const auto& age : aggregate.classes) { + proposal.after.push_back( + {age.age_low, age.age_high, age.count, spread(age.energy, age.matter), 0}); + } + const auto grew = after.living > before.living; + proposal.flux.births = grew ? (after.living - before.living) * residual_scale : 0; + proposal.flux.deaths = grew ? 0 : (before.living - after.living) * residual_scale; + const auto shed_energy = aggregate.detritus_energy - before_detritus_energy; + const auto shed_matter = aggregate.detritus_matter - before_detritus_matter; + const auto drawn_energy = before_environment - aggregate.environment; + const auto drawn_matter = before_store - aggregate.matter_store; + proposal.flux.to_detritus = spread(shed_energy, shed_matter); + proposal.flux.from_elsewhere = spread(drawn_energy, drawn_matter); + const auto plan = plan_advance(cohort, proposal); + CHECK(plan.has_value()); + const auto committed = commit_advance(*ledger, registry, *plan); + CHECK(committed.has_value()); + cohort = *committed; + CHECK(ledger->conserved_totals() == total); + CHECK(ledger->balances()[backing.value - 1] == cohort.reserve()); + CHECK(cohort.genome() == 3); + } + CHECK(tick == 10'000); + CHECK(!cohort.is_vacant()); + + // Materialize the survivors, which is the other end of the round trip. + std::vector draws; + std::uint64_t drawn = 0; + for (std::size_t index = 0; index < cohort.classes().size(); ++index) { + const auto count = cohort.classes()[index].count; + if (count == 0 || drawn + count > rule::capacity) { + continue; + } + draws.push_back({index, count}); + drawn += count; + } + CHECK(!draws.empty()); + MaterializeRequest unfold; + unfold.owner = cohort.owner(); + unfold.revision = cohort.revision() + 1; + unfold.draws = draws; + unfold.first_identity = 100'000; + for (std::uint64_t index = 0; index < drawn; ++index) { + unfold.reservoirs.push_back({static_cast(first_member_store + index)}); + } + unfold.bound = cohort.bound(); + // Those founder stores are empty now, because the collapse emptied them. + const auto spread_out = plan_materialize(cohort, unfold); + CHECK(spread_out.has_value()); + const auto representatives = commit_materialize(*ledger, registry, *spread_out); + CHECK(representatives.has_value()); + CHECK(ledger->conserved_totals() == total); + CHECK(representatives->size() == drawn); + // Genome identity survives the whole round trip, and nothing invented one. + for (const auto& member : *representatives) { + CHECK(member.genome == 3); + CHECK(member.habitat == HabitatId{7}); + CHECK(member.state == MemberState::active); + } + CHECK(registry.size() == 1); + CHECK(registry.find(HabitatId{7}, 3)->genome() == 3); +} + +} // namespace +int main() try { + // The instrument check runs first: a failing control voids every number below. + one_member_per_class_agrees_exactly(); + aggregation_costs_something_and_coarse_classes_destroy_the_population(); + the_full_scenario_conserves_and_keeps_its_genome(); + std::cout << "PASS resolution comparison, exact control and a published envelope\n"; + return 0; +} catch (...) { + return 1; +} diff --git a/tests/population_tests.cpp b/tests/population_tests.cpp index efd2e0a..28fb801 100644 --- a/tests/population_tests.cpp +++ b/tests/population_tests.cpp @@ -154,11 +154,15 @@ void death_predation_and_migration_move_biomass_once() { 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()); + // The escrow has to be able to fund the immigrants it sends, and the arrival + // is the first leg, so it must already hold that much before anything moves. + auto seeded = std::array{}; + seeded[backing.value - 1] = before.reserve(); + seeded[elsewhere.value - 1] = held(10, 100); + auto created = Ledger::create(seeded); + CHECK(created.has_value()); + auto ledger = std::move(*created); const auto total = ledger.conserved_totals(); const auto committed = commit_advance(ledger, registry, *plan); CHECK(committed.has_value()); @@ -168,10 +172,11 @@ void death_predation_and_migration_move_biomass_once() { 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)); + // The escrow sent ten energy and a hundred matter, then received twenty and + // two hundred, so from exactly what it needed to send it stands at ten and a + // hundred more. Arrivals are the first leg, which is what makes an interval + // affordable as a whole applicable leg by leg. + CHECK(ledger.balances()[elsewhere.value - 1] == held(20, 200)); } void a_proposal_that_would_go_below_zero_is_refused_not_clamped() { @@ -369,6 +374,43 @@ void a_stale_proposal_is_refused_and_changes_nothing() { CHECK(once.last_action() == settled_action); } +void an_interval_affordable_only_with_its_arrivals_still_commits() { + // The cohort sheds more than it currently holds, and receives more than enough + // to cover it. The interval as a whole is affordable, and planning says so, so + // commit must apply it: the ledger applies legs in sequence, and an outflow + // placed before the inflow would underflow a reservoir the interval affords. + // Found by the M4.5 comparison, where a fifty-tick interval shed 10,480 against + // 6,950 held while drawing 13,080 in, and was refused with ledger_failure. + const auto before = standing(); + CHECK(before.reserve() == held(1'000, 10'000)); + auto crossing = request(); + crossing.flux.to_detritus = held(1'400, 14'000); // More than is held. + crossing.flux.from_elsewhere = held(1'900, 19'000); // Covers it and more. + crossing.after = {{0, 100, 40, held(1'500, 15'000), 0}, {100, 200, 20, Inventory{}, 0}}; + const auto plan = plan_advance(before, crossing); + CHECK(plan.has_value()); + CHECK(plan->after().reserve() == held(1'500, 15'000)); + // The arrival is the first leg, so nothing underflows on the way through. + CHECK(plan->legs().size() == 2); + CHECK(plan->legs()[0].to == backing); + CHECK(plan->legs()[0].amount == held(1'900, 19'000)); + CHECK(plan->legs()[1].from == backing); + auto registry = registry_holding(before); + // The escrow has to be able to fund what it sends. + auto seeded = std::array{}; + seeded[backing.value - 1] = before.reserve(); + seeded[elsewhere.value - 1] = held(2'000, 20'000); + auto funded = Ledger::create(seeded); + CHECK(funded.has_value()); + const auto total = funded->conserved_totals(); + const auto committed = commit_advance(*funded, registry, *plan); + CHECK(committed.has_value()); + CHECK(funded->conserved_totals() == total); + CHECK(funded->balances()[backing.value - 1] == held(1'500, 15'000)); + CHECK(funded->balances()[detritus.value - 1] == held(1'400, 14'000)); + CHECK(funded->balances()[elsewhere.value - 1] == held(100, 1'000)); +} + 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 @@ -488,6 +530,7 @@ int main() try { a_vacant_cohort_is_not_an_extinction(); the_declared_result_must_be_what_the_fluxes_imply(); a_stale_proposal_is_refused_and_changes_nothing(); + an_interval_affordable_only_with_its_arrivals_still_commits(); 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";