Repository navigation
Evict unreachable nodes from SharedNodeStore after tabs close - #2571
Conversation
SharedNodeStore is a single global singleton holding every node ever loaded by any tab/pane, with no eviction path: once loaded, a node stayed cached for the life of the app session even after every tab showing it closed. Track which cached nodes are still reachable from an open tab/pane by walking each node's structureTree ancestor chain up to its root and checking membership in SharedNodeStore.openDocumentRootIds — the set of open tabs' document root ids, replaced wholesale on every tab-state mutation via the new updateOpenDocumentRoots(). A node whose root drops out of that set becomes an eviction candidate after a 30s inactivity window (skipped/rescheduled while it has a pending persistence operation or an active atomic batch), clearing it from `nodes`, `versions`, `pendingUpdates`, `persistedNodeIds`, `taskFieldWriteSeq`, and the other per-node bookkeeping maps. Reachability starts dormant (nothing evicts) until the first report, so callers that never touch navigation state are unaffected. Wire navigation.svelte.ts's NavigationStore to report the current open tab set on every mutation (open, close, content change, session restore) via a new #syncNodeReachability(), called unconditionally from #persist() plus the two paths that bypass it (loadPersistedState, resetTabState) — this is what makes closeTab() actually drive eviction end-to-end rather than only being reachable via a direct API call. Add a real (process.memoryUsage()-based) multi-tab memory test to architecture-benchmarks.test.ts that opens N simulated tabs on distinct documents through the real addTab()/closeTab() path, measures SharedNodeStore's node count and heap before/after, and confirms both go back down once tabs close and the inactivity threshold elapses, plus a same-file test locking in the two-panes-share-a-node case. Expose global.gc() to the vitest fork pool (execArgv: --expose-gc) so that measurement can force a real GC pass instead of reading whatever V8 hasn't collected yet. A dedicated shared-node-store-eviction.test.ts unit-tests the mechanism directly: dormancy, threshold timing, pending-write and active-batch guards, and cancellation on reopen before the threshold elapses. Co-Authored-By: Claude Sonnet 5 <[email protected]>
… walk The structureTree-walk reachability check treats any cached node with no structureTree parent, and not itself an open tab's root, as unreachable — correct for a normal document's children, wrong for a node a component displays WITHOUT it being a structural descendant of any open tab's root: a query/Kanban/table view's matched rows (they live under whatever unrelated parent document they were created in, not as children of the query node), an inline [[wikilink]]/node-card reference resolved via setNode()/ensureNode() (never touches structureTree). Under eviction, such a node could be dropped from the cache after the inactivity threshold while still the only thing a still-open view/reference displays it — indistinguishable, from the component's point of view, from the node having been deleted. Add SharedNodeStore.pinNodes(ownerId, nodeIds)/unpinAll(ownerId): a second, additive reachability channel alongside the structureTree walk. A node pinned by any owner is reachable regardless of its structural position, for as long as that owner keeps pinning it. Owner sets replace wholesale per call (mirrors updateOpenDocumentRoots), so a changing result set or a released owner correctly drops out via the same reconcileEvictionCandidates sweep already used for tab close/reopen. Add pinReachableNodes(ownerId, nodeIds) in pin-node-reachability.ts — a thin $effect-friendly wrapper (pin now, unpin via the returned cleanup, which $effect calls automatically on id-change/unmount) — and wire it into every consumer found by an audit of every sharedNodeStore.getNode/ ensureNode call site outside reactive-node-service.svelte.ts: TableRow (query-view row), NodeRefInline (wikilink), QueryNodeViewer (the whole loadedNodeIds result set, covering ListView/KanbanView transitively via the same ids), and NodeCardInline (AI-chat inline node reference). node-ref-preview.svelte.ts's hover/focus controller isn't a Svelte component (a plain singleton class) and its card content is a one-time snapshot rather than a live binding, so it can't reproduce the same-render "looks deleted" failure — pinned anyway via the raw API for consistency and to avoid a spurious re-fetch on re-hover of an evicted id. Every other sharedNodeStore consumer audited (person-node, checkbox-node, the schema/property forms, relationship-viewer-modal, backlinks-panel, search-pane, tab-system, pane-content, the ai-chat viewers) operates on a node that either is the open tab's own root or a structureTree descendant of it, so the existing walk already covers it. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Addressed: adversarial review finding (structureTree-only reachability gap)Fixed the real finding: Fix: added a second, additive reachability channel —
Everything else audited ( New tests ( Verification: |
DATABASE_SETTINGS_NODE_ID (ui-extensions.ts) is a global per-database singleton, loaded once at startup and refreshed only on discrete edges (sync-status change, consent decision, database switch) via database.svelte.ts's refreshDatabaseSettings(). It's read continuously by always-mounted, non-tab-scoped Pro-sync chrome (pro-sync-pill.svelte, app-shell.svelte, membership.svelte.ts, collaboration-locked.svelte) — none of it tied to which tab/pane happens to be open. Neither of SharedNodeStore's reachability channels covered it: it has no structureTree relationship to any open tab, isn't itself a tab root, and this PR never pinned it. So it was evicted ~30s after the app's first navigation report, regardless of how often it was refreshed (setNode doesn't cancel a pending eviction timer). Net effect: isProSyncActive() would silently return false for a genuinely signed-in, sync-enabled Pro user. refreshDatabaseSettings() now pins the singleton on every call, unconditionally and before the async refetch — not only re-pinning after a real change, but also re-establishing the pin a database switch's clearAll() (which wipes every pin along with every cached node) would otherwise strip. New tests: database.test.ts asserts the pin call happens (fails without it, verified locally by temporarily reverting the change); a dedicated describe block in shared-node-store-eviction.test.ts reproduces the reviewer's exact repro shape against the real production node id — survives the inactivity threshold while pinned with an unrelated tab open, and a paired test without the pin shows the same sequence still evicts it (the bug this closes). Co-Authored-By: Claude Sonnet 5 <[email protected]>
Addressed: second review finding (global singleton chrome node, never pinned)Fixed: Fix: Broader audit (per the review's ask — always-mounted chrome outside the original cross-reference-display scope): grepped Tests — both fail pre-fix, pass post-fix (verified locally by temporarily reverting the pin call and re-running):
Gate (foreground, confirmed complete before push): (Note: hit the same pre-existing wall-clock flakiness in |
Summary
SharedNodeStoreis a single global singleton holding every node ever loaded by any tab/pane, with no eviction path — once loaded, a node stayed cached for the life of the app session even after every tab showing it closed. Addresses #2568.SharedNodeStore: a cached node is reachable when walking itsstructureTreeancestor chain reaches a node id present inopenDocumentRootIds— the set of currently-open tabs' document roots, replaced wholesale via the newupdateOpenDocumentRoots().nodes,versions,pendingUpdates,persistedNodeIds,taskFieldWriteSeq, and the other per-node bookkeeping maps. Eviction is skipped/rescheduled while the node has a pending/in-flight/queued persistence operation or an active atomic batch.navigation.svelte.ts'sNavigationStoreto report the current open-tab set on every tab-state mutation (open, close, content change, session restore) via a new#syncNodeReachability(), called unconditionally and synchronously (not debounced) from#persist()plus the two paths that bypass it (loadPersistedState,resetTabState). This is what makescloseTab()actually drive eviction end-to-end.process.memoryUsage()-based, not estimated) multi-tab memory test toarchitecture-benchmarks.test.tsthat opens N simulated tabs on distinct documents through the realaddTab()/closeTab()path, measuresSharedNodeStorenode count and heap before/after, and confirms both go back down once tabs close and the threshold elapses — plus a same-file test locking in the two-panes-share-a-node case through the real navigation store (createPane, two tabs on the same node id, close one, confirm still cached, close the other, confirm evicted).global.gc()to the vitest fork pool (execArgv: ['--expose-gc']) so that measurement can force a real GC pass before readingprocess.memoryUsage(), instead of reading whatever V8 hasn't gotten around to collecting yet.shared-node-store-eviction.test.ts, unit-testing the mechanism directly: dormancy before any report, threshold timing (not immediate), the pending-write guard, the active-batch guard, and timer cancellation when a node becomes reachable again before the threshold elapses (quick tab reopen).Design notes
Reachability model — computed, not separately bookkept per node. Rather than a second membership map that walker code paths would need to keep in sync with
structureTree, a node's reachability is derived by walking the existing parent index every viewer's data-loading path (loadChildrenForParent/loadChildrenTree) already populates. This also means the two-panes-showing-the-same-node case is handled "for free" — the same node id or its shared ancestor stays inopenDocumentRootIdsas long as any open tab reports it, with no refcounting.Inactivity threshold: 30 seconds — long enough that ordinary quick tab-switching or an accidental close-and-reopen never trips it, short enough to reclaim memory well within a single working session. Overridable per-instance via
__setEvictionInactivityMsForTesting(test-only) so tests don't wait out the real default.Why
navigation.svelte.tspushes rather thanSharedNodeStorepulling —SharedNodeStorenever importsnavigation.svelte.ts(avoids a circular import, sincereactive-node-service.svelte.tsalready imports a constant fromnavigation.svelte.ts, which importsSharedNodeStore). InsteadNavigationStorereports its own tab state outward on every mutation. The report is idempotent and cheap to skip when unchanged (most nav interactions — resizing a pane, switching the active tab — don't change which documents are open), so it doesn't sweep the whole cache on every trivial interaction.Correctness constraints verified:
Real memory measurement (not estimated)
New
test:perfrun (TEST_FULL_PERFORMANCE=1, 10 tabs × 300 nodes = 3,000 nodes, matching the scale of the issue's own headless probe):Node count is the deterministic signal (every node from every closed tab is gone). Heap fully recovered — the final reading (46.12MB) came in below the pre-test baseline (49.01MB), i.e. more than 100% of the peak-over-baseline growth (2.22MB) was reclaimed.
Fast-mode run (default
bun run test, 6 tabs × 120 nodes = 720 nodes):Test plan
bun run test(fast mode, full suite): 240 files / 4941 tests pass, including the new eviction unit test file and the two new perf-file tests.bun run test:coverage: passes (global thresholds met); the new code in bothshared-node-store.svelte.tsandnavigation.svelte.tsis fully exercised by the new tests (spot-checked the reported uncovered-line ranges in both files — all pre-existing, unrelated to this change).bun run quality:fix(desktop-app): 0 errors, 0 warnings across 2333 files (eslint + svelte-check).TEST_FULL_PERFORMANCE=1 bun run test:perf: passes at the issue's own probe scale (10 tabs × 300 nodes).architecture-benchmarks.test.ts's existing single-viewer benchmarks — all pass in fast mode. One full-performance-mode-only test (bulk structural operations ... <100ms, wall-clock threshold) is flaky under machine load; confirmed by running the identical test against an unmodifiedorigin/maincheckout, where it fails identically (171ms vs 100ms) — pre-existing, unrelated to this PR.🤖 Generated with Claude Code