Status: done
Priority: 1
Size: M
Arch: yardstick
Phase: implement
Design ref: none (code structure). docs/roadmap.md, sections 5.3 (rule 1) and 5.4 (indexes of the living); docs/architecture/target-v2.md, principle 2 (one writer per cache, checked against its source).
Goal: The 6-minute step walks every agent ever made, the dead included (advance in sim/clock). In src/sim, 19 loops walk every pawn record, 26 every household, 7 every agent and 5 every union; Culture.dailyStep walks every person. At year 40 of populous small, 1,274 pawn records stand behind 725 living (0.76 dead per living pawn, perhaps 4 to 5 by year 150), so the dead cost almost as much as the living, and the share grows every generation. The owners keep indexes of the live ones, and the loops in a step or a day walk them. Blocked until VB-088 is done (its history check measures this task).
Acceptance criteria:
st.living: the ids of living pawns, in id order, kept by the functions that add a pawn (births and the seeding modules) and the one that kills it (killPawn), and by nothing else. st.liveHouseholds: the ids of households not dissolved, in id order, kept by the functions that found a household and the one that dissolves it (sim/heirs; if VB-175 is done, its one founding act; if not, the three founding sites in sim/cottage, sim/farmclaims and sim/settle). Agents are walked through st.living, since an agent’s id is its pawn’s id.tools/writes.js) and what it now walks.checkState (tests/lib/invariants.js) asserts each equals a scan, every day in tests/invariants.js; tests/golden.js leaves them out of the fingerprint (DERIVED, beside jobsBy); a save and load keeps or rebuilds them (tests/saves.js passes). If VB-173 is done, its owners table lists them in its cache category.tests/golden.json unchanged: the order of every walk is kept, so behaviour is the same. npm run verify passes.walkStep and walkDaily per living pawn-day at year 40 against year 5 (VB-088’s history check) at 1.05 or below, and their entries leave tests/cost-baseline.json.small-y40 and small-y5, 30 game days each: ms per game day, ms per living pawn-day, and their ratio.ready if VB-127 is done too.
Cost: two arrays of about 1,000 ids at the late reference. A death or a dissolution costs one splice of at most 1,000 entries, about 30 a year. A step then walks about 1,000 agents instead of 1,000 plus the dead.
Notes:3 Nov 2026 (VB-181, the plan of slice 0): written. It edits many files of the simulation, so it does not run beside an ownership refactor (VB-174 to VB-179). Counted on 3 November in src/sim: 19 loops over st.pawns, 26 over st.households, 7 over st.agents, 5 over st.unions, 1 over st.record, plus Culture.dailyStep over env.people.
walkStep) and 1.495102 (walkDaily).Impact: sim/records owns two derived arrays, st.living and st.liveHouseholds. Seed/load builds them from source records; creation appends through person and makeHousehold; killPawn and extinct remove through the record owner’s operations. Existing non-enumerable record indexes also answer current-union and widow-history queries. No gameplay rules, random streams, public Sim/ArchGen/Culture APIs or design decisions changed. The Culture adapter supplies live ids without adding state to cenv.
Changed walks (all retain record-id order):
| Module | Walks and queries now using live indexes |
|---|---|
sim/clock |
Dawn positioning, end-of-work release, end-of-day household food/wood, every six-minute agent step. |
sim/lifecycle |
Moving-round candidates and handovers; daily ages, tie decay, kin floors and deaths. Death uses the current-union index; the round’s new marriages and widow status no longer scan all unions. |
sim/births |
Daily conception/pregnancy/birth checks. |
sim/jobs |
Hourly work interrupts (lookUp). |
sim/relations |
Seasonal relationship cleanup, hourly talk and hourly idle-company lists. Talk keeps its historical random starting id and lower-bounds into the live ids, preserving random draws and cyclic order. |
sim/society |
Settlement tie preparation, prestige, indoor household contacts and outdoor agent contacts. |
culture |
Daily drift and annual entrepreneurs through the adapter’s live ids; standalone calibration remains supported. |
sim/heirs |
First-heir rankings, service homes, living kin homes, coming of age, guardian queries, role refresh, first heirs, wants-out and demand. |
sim/help |
Daily help requests and annual village-store gifts. |
sim/byre, sim/meadows |
Daily barn/husbandry and meadow planning. |
sim/cottage |
Payments of shares still owed. |
sim/farmclaims, sim/settle |
Guardian queries; settlement crowding/land-wait updates. |
sim/service |
Guardian queries, orphan care and lone-household selection. |
sim/records |
Settlement members through live households; active-union and widow queries through incremental record indexes. |
Births, mortality and orphan care snapshot live ids when their own walk can splice an index. The newborn has no spouse to consider that day, so leaving it out of that day’s birth-check snapshot changes no random draws. All three founding paths pass the state’s cache to makeHousehold.
Retained full-record walks: scenario and culture seeding (including dead ancestors’ initialized fields), fixture/save history and migration, incremental record-index catch-up, family/kinship and historical spouse queries, and page/family-tree lists. Three annual historical cleanups retain their full records deliberately: clearing deceased pawns’ saved kinPush and interest, and expiring dissolved households’ ledgers. Skipping those historical writes would change golden state. They are documented at their call sites. Herd seeding/start-hay also stays a seeding-only scan.
Checks: daily invariants independently compare both live arrays against scans, including order, duplicates and missing ids. tests/living.js covers corruption, missing/incorrect indexes in format-1 saves, two childbirth deaths in one walk, every pawn dying in a daily walk, adjacent households dissolving, and counting only living agents in a step. tests/indexes.js compares the union indexes with the records. The constructed hay test supplies the new live-household index. tests/golden.json and tests/counters.json are unchanged; the tiny counter fixture contains no historical dead to exclude. Only the two fixed history exceptions (walkStep, walkDaily) leave tests/cost-baseline.json.
Measurements use the existing compatible fixtures at 4df5766 (stale golden hashes after VB-159), not remade populations. Both old and new source use those same saves and the same six-minute calls. The deterministic 30-day history check, including one explicit moving round, changes only walkStep and walkDaily: year-40/year-5 work per living pawn-day goes from 1.583676 to 0.999998 and from 1.495102 to 1.000128, respectively. Both meet 1.05. Every other work counter remains identical.
Performance correction (5 November): reducing scanned records initially exposed a V8 optimization regression in the changed Culture.dailyStep. On Node v24.22.1, the large nested traversal repeatedly entered optimized OSR code and bailed out at settlement-kind table accesses. A diagnostic run with --trace-opt --trace-deopt, including ten warm-up days and a thirty-day window on small-y40, reported 469 culture deoptimizations (468 with reason unexpected name in keyed access), versus 16 in the original source. These compiler costs are outside the deterministic work counters. The final source reports 25, including 22 of that keyed-access reason; optimization counts depend on the engine and compilation schedule and are diagnostic only.
The fix separates one person’s drift math into the private driftPerson function and resolves each settlement’s anchor and rate factors once per daily pass. The numerical operations, random draws and traversal order stay the same. This follows the roadmap’s compile-at-cadence rule without adding persistent state or changing the save codec. Profiling also tested loaded-object layout and per-agent state lookups; neither was sufficient to address the regression, so no decoder or agent-loop changes were added for this correction.
For final wall-clock measurements, original 81766f8 and corrected source ran paired thirty-day windows in the same Node process, with ten warm-up days before resetting to each fixture. Day order alternated between versions; process load order was reversed for the middle trial. All three trials used the same V8 hash seed (--hash-seed=42) and one pinned CPU (taskset -c 0) to reduce scheduling, property-hash and compilation variability. No verification jobs ran alongside them. Platform: Node v24.22.1, AMD EPYC 9V74. The windows exclude the explicit moving round. Both versions use the same compatible 4df5766 fixtures, whose golden stamps remain stale after VB-159.
| Fixture | Original median ms/day | Corrected median ms/day | Reduction |
|---|---|---|---|
small-y5 |
128.714 | 110.125 | 14.4% |
small-y40 |
229.554 | 211.598 | 7.8% |
The corrected source is faster in every pair. Raw wall-clock samples, in original/corrected ms per game day:
small-y5: 155.686/153.091, 126.419/110.125, 128.714/108.500.small-y40: 228.003/211.598, 231.856/195.448, 229.554/214.224.A separate-process cross-check with the same hash seed, CPU affinity, warm-up and fixture reset also improved: 135.186 to 128.366 ms/day at year 5 and 342.369 to 210.650 at year 40, with matching state fingerprints. The larger spread between independent processes is why the paired three-trial medians are the main result.
CPU-time results agree in direction with the wall clocks. Timing remains a report, not a flaky CI assertion. The earlier independent-process medians were a regression signal, not a completed performance result; these paired measurements supersede them.
The complete post-window canonical state fingerprint (excluding the world and the new derived arrays) matches old and new source in every sample: 412cb3cf51744533 at year 5 and d41f7872de7994e5 at year 40. Living pawn-days are identical, 11,704.500 and 21,781.000.
VB-201 stays blocked because VB-127 is still ready, not done.
Source-map review: ordered VB simulation modules and the shared page closure build to index.html; Node loads the same modules directly. Deterministic streams, exact saves, golden fingerprints and the ownership checker provide strong change protection. The five-layer target is still being adopted; existing ownership allowances, later-module dependencies, player-control/opportunity plans, bounded routes and bounded history remain their own roadmap work. The design’s family-saga premise is supported by inheritance and customs, while its direct player role is a later slice. Its proposed systems appendix retains old implementation-status descriptions of commands and saves; current code and backlog are more current on those points.
Validation after the performance correction: VB_TEST_JOBS=2 VB_CHROMIUM=/usr/bin/chromium VB_SOFTWARE_RENDER=1 npm run verify passed all 81 scripts in 264.2 s. This includes desktop and mobile Chromium checks, golden state, five long invariant runs, all four late saves, save/load continuation, history and scaling. Rebuilt index.html. Desktop and mobile functional screenshots were captured. Source changes remain local.