From 59b11eba924a70b2181265e58672de67863a6c5c Mon Sep 17 00:00:00 2001 From: NeoLorenzo Date: Sun, 1 Nov 2026 20:50:17 +0000 Subject: [PATCH] fix(life16): free walking routes no walk can read again [LIFE16-Routes-075] --- CHANGELOG.md | 5 +++++ LAB_NOTES.md | 10 ++++++++++ docs/ARCHITECTURE.md | 2 +- src/valley/engine.test.ts | 17 ++++++++++++++++- src/valley/engine.ts | 12 ++++++++++++ 5 files changed, 44 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5965dde..b505ece 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ All notable changes to Econ-Engine are documented here. The changelog records what changed in each update. Design rationale, experiments, observations, and lessons are documented separately in [Lab Notes](LAB_NOTES.md). +## [LIFE16-Routes-075] - (2026-10-30) + +- Fixes a memory leak on long runs: the state kept every route ever walked, about 45,000 route segments a day, so the heap grew about 12 MB a day and a year's run ran out of memory, in Node and in the page's worker alike. Each step now frees the routes below the lowest one still being walked; route ids keep counting. +- Trajectories are unchanged, and so are the fingerprints. + ## [LIFE16-PeopleCharts-073] - (2026-10-29) - The history panel has three views: Skills, Relationships and Over time. The charts over time move to their own view. diff --git a/LAB_NOTES.md b/LAB_NOTES.md index 3dc178c..68d593e 100644 --- a/LAB_NOTES.md +++ b/LAB_NOTES.md @@ -6,6 +6,16 @@ Every meaningful model, architecture, experimental, or design update should receive a newest-first entry. Use at most one base update number per Git commit. Refinements completed before that commit keep the same base number with a decimal suffix—for example, `003` and `003.1` belong to the same commit family. Allocate the next base number only for a later commit. Preserve the context, observed problem or research question, rationale, important implementation decisions, trade-offs, findings, and unresolved questions. Distinguish verified observations from hypotheses. If the original rationale is unknown, say so rather than inferring intent from the finished code. +## [LIFE16-Routes-075] - (2026-10-30) + +While measuring Life 17, a one-year run ran out of memory, and `main` grew at the same rate: running the canonical configuration day by day with `advanceValley` and collecting garbage every 25 days, the heap grew about 12 MB a day, to 2.4 GB by day 150. Node's default heap and the page's worker both fail before a year. + +**Cause.** The module-level caches suspected first grow only slowly. Counted directly, the views remembered per person, nearest-frontier answers, place vicinities and ground lookups gained some tens of entries a day each. The earlier check that the state does not grow had compared JSON sizes of a few fields, and `state.routes` was not among them. A census of the state's arrays and maps between days 20 and 40 found it: 15,618 routes with 1.83 million segments at day 20 and 23,423 with 2.73 million at day 40. Every route ever planned stayed in the state, since a route's id is its index in that array. + +**Fix.** A route is read only while its walk lasts. Within a step, the checker and replay also read routes of walks under way when the step began, and of walks started and ended in it. Each step therefore begins by deleting every route below the lowest one still walked; the lowest only rises, so the loop stops at the first slot already freed and costs nothing on most steps. Ids keep counting, so wake-up order, which breaks ties by route id, is unchanged, and so are all fingerprints. A day run in one step and the same day run minute by minute now free routes at different moments, so the test comparing them frees both before comparing. + +**Result.** The same run after the fix: 421 MB at day 25, 453 MB at day 150, 508 MB at day 350. The slow remaining growth, about 0.3 MB a day, is the caches above and people's growing memories of banks and ways; it was not pursued. + ## [LIFE16-PeopleCharts-073] - (2026-10-29) The owner found the line charts of little use and asked for a macro view of everyone's skills, to see who specialises in wood or axes, and for a graph of all relationships. The line charts move to their own view. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cb7919b..58149e9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -92,7 +92,7 @@ The 3D world draws each firm and Government across its plot: `buildingScale` str - **Knowledge and routes.** `perception.ts` records what a person sees at a wake-up: mesh triangles, places with their stock, bank points and other people. Triangle knowledge is a bitset shared between a state and its copy until its holder learns something. `routes.ts` runs A\* over known ground triangles, pulls the path straight through the corridor with the funnel algorithm, and cuts it at triangle edges into segments with their slope and walking time. Bank points sit on the ground side of each shore edge. A new route is planned the way people find their way: first the straight line, kept when every triangle it crosses is known walkable ground (`lineCorridor`, exact side tests; a line through a vertex counts as blocked); otherwise it is steered. Steering takes an A* over the person's pieces, the joined-up patches of known ground within each chunk, linked across chunk borders only where the person knows ground on both sides (`ChunkLinks`, precomputed per mesh), and then crosses each piece toward the crossing into the next whose midpoint is nearest the line on to the target: straight where the line stays in the piece, otherwise by A* confined to that piece. A chain of pieces is joined-up known ground, so a steered plan always arrives; there is no search over the whole known ground. Pieces are derived from knowledge, cached per knowledge and carried forward at each survey by dropping only the chunks where triangles were learnt. The still landscape is surveyed again only after moving `resurveyCm` (100 m) from the last survey point; stock at the person's place, people and fires are seen at every wake-up. - **Ways.** `ways.ts` keeps each person's remembered ways: immutable corridors of triangles between two ends (the hearth, a place, a known bank point), at most `waysRemembered` (64), the least recently used forgotten first. A walk to such an end takes a way that holds the walker's triangle, whole or joined part-way, in either direction; the route is pulled straight along the way's corridor at the walker's current load. A way is planned again once a day has passed and the person has seen new ground since, or at once if it crosses ground no longer known. Walk events record whether the walk used a way, joined one or planned a new one. An idle person with nothing to explore takes one leisure walk a day along the way from home used longest ago (`leisureMinute`), goes home when away, and otherwise rests. - **Ties.** `ties.ts` keeps each person's ties: an immutable record per person known, at most `tiesRemembered` (150), the least familiar forgotten first. A tie holds familiarity (minutes spent standing within talking distance, counted once at the end of a task in both ties), credit (minutes of work given less received) and grievance (minutes, from refusals), each fading by `tieFadePerMillion` a day with its own remainder. After an exchange, a person who needs food or wood asks the people met, closest tie first and each at most once a day; the one asked gives up to what they can spare and the asker lacks when their goodwill covers what the asker already owes, and otherwise refuses. Gifts move food lots or wood and are recorded as `gift` events; refusals as `refusal` events; time together as `together` events. -- **Tasks and lazy bodies.** `tasks.ts` builds a `TaskRecord` (kind, start and end minute, place, route, reason, starting body and load). `body.ts` gives energy and water at any minute of a task in closed form (`energyAt`, `waterAt`), and `positionAt` gives the position along its route. Nobody is advanced minute by minute. Food, wood, fire, huts, axes, trade and practice (`food.ts`, `work.ts`, `fire.ts`, `huts.ts`, `axes.ts`, `trade.ts`, `practice.ts`, `social.ts`) apply their rules when a task settles or two people meet. +- **Tasks and lazy bodies.** `tasks.ts` builds a `TaskRecord` (kind, start and end minute, place, route, reason, starting body and load). `body.ts` gives energy and water at any minute of a task in closed form (`energyAt`, `waterAt`), and `positionAt` gives the position along its route. A route is stored in `state.routes` under its id while a walk can read it; each step first frees every route below the lowest still walked (`releaseRoutes`), and ids keep counting. Nobody is advanced minute by minute. Food, wood, fire, huts, axes, trade and practice (`food.ts`, `work.ts`, `fire.ts`, `huts.ts`, `axes.ts`, `trade.ts`, `practice.ts`, `social.ts`) apply their rules when a task settles or two people meet. - **Checker.** `invariants.ts` checks each interval against the preceding immutable state. `replay.ts` keeps separate stock, fish, body, tool, hut and water ledgers, replays recorded transfers and regrowth, and compares them with the returned state. `replayTies` replays time together, gifts, refusals and the midnight fade, and checks each gift against the giving rule. Geography is checked once. `ruleFixtures.ts` is imported only by tests: surveyed ground and small explicit lakes isolate rules without changing production starts. diff --git a/src/valley/engine.test.ts b/src/valley/engine.test.ts index 872d0b4..c4d1cc8 100644 --- a/src/valley/engine.test.ts +++ b/src/valley/engine.test.ts @@ -1,6 +1,6 @@ import { addTestLake } from './ruleFixtures' import { describe, expect, it } from 'vitest' -import { advanceValley, createValley, stepValley, cloneValley } from './engine' +import { advanceValley, createValley, stepValley, cloneValley, releaseRoutes } from './engine' import { FLAT_LAND } from './config' import { WakeQueue } from './clock' @@ -27,6 +27,9 @@ describe('wake-up engine', () => { for (let minute = 1; minute <= 1_440; minute += 1) single = stepValley(single, minute) batch.lastInterval = [] single.lastInterval = [] + // Single steps free finished routes sooner; both hold the same ones once freed up to the same lowest walk. + releaseRoutes(batch) + releaseRoutes(single) expect(batch).toEqual(single) expect(state).toEqual(before) }) @@ -64,6 +67,9 @@ describe('wake-up engine', () => { for (let minute = 1; minute <= 1_440; minute += 1) single = stepValley(single, minute) batch.lastInterval = [] single.lastInterval = [] + // Single steps free finished routes sooner; both hold the same ones once freed up to the same lowest walk. + releaseRoutes(batch) + releaseRoutes(single) expect(batch).toEqual(single) expect(state).toEqual(before) }) @@ -76,6 +82,15 @@ describe('wake-up engine', () => { expect(owned).toEqual(stepped) } }) + it('frees the routes below the lowest still walked and keeps counting ids', () => { + // Routes are freed as a step begins, so the step with no minutes frees those of the walks ended before it. + const state = advanceValley(advanceValley(createValley(FLAT_LAND), 2_880), 2_880) + const walked = state.foragers.flatMap((p) => (p.task?.kind === 'walk' ? [p.task.routeId] : [])) + const lowest = Math.min(state.routes.length, ...walked) + expect(lowest).toBeGreaterThan(0) + for (let id = 0; id < state.routes.length; id += 1) expect(id in state.routes).toBe(id >= lowest) + for (const id of walked) expect(state.routes[id]).toBeDefined() + }) }) describe('food, water and wood tasks', () => { diff --git a/src/valley/engine.ts b/src/valley/engine.ts index d60fd4c..386897c 100644 --- a/src/valley/engine.ts +++ b/src/valley/engine.ts @@ -519,6 +519,17 @@ export function stepValley(previous: ValleyState, toMinute = previous.minute + 1 throw new Error('Target minute must be a safe integer at or after the current minute') return advanceValley(cloneValley(previous), toMinute, stop) } +/** + * Frees the routes no walk can read again. A route is read only while its walk lasts, and by the step's checks and + * replay for walks under way when the step began, so every route below the lowest one still walked is dropped. Ids + * keep counting, so nothing else changes; without this a year's routes outgrow the heap. + */ +export function releaseRoutes(state: ValleyState) { + let lowest = state.routes.length + for (const person of state.foragers) if (person.task?.kind === 'walk') lowest = Math.min(lowest, person.task.routeId) + // Routes below an earlier lowest were freed then, and the lowest only rises, so this stops at the last one freed. + for (let id = lowest - 1; id >= 0 && state.routes[id] !== undefined; id -= 1) delete state.routes[id] +} /** * Runs `state` itself on to `toMinute`, exactly as `stepValley` runs a copy of it, and returns it. Only for a caller * that owns the state and never reads it again as it was, such as the engine's worker: the copy each step makes, and @@ -529,6 +540,7 @@ export function advanceValley(state: ValleyState, toMinute = state.minute + 1, s throw new Error('Target minute must be a safe integer at or after the current minute') const start = state.minute state.lastInterval = [] + releaseRoutes(state) if (toMinute === start) return state while (state.queue.peek() && state.queue.peek()!.minute <= toMinute) { if (stop && state.queue.peek()!.minute > state.minute && state.minute > start && stop()) {