Skip to content

Evict unreachable nodes from SharedNodeStore after tabs close - #2571

Merged
mstomar125 merged 3 commits into
mainfrom
issue-2568-shared-node-store-eviction
Sep 11, 2026
Merged

mstomar125 merged 3 commits into
mainfrom
issue-2568-shared-node-store-eviction

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

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. Addresses #2568.

  • Adds reachability tracking to SharedNodeStore: a cached node is reachable when walking its structureTree ancestor chain reaches a node id present in openDocumentRootIds — the set of currently-open tabs' document roots, replaced wholesale via the new updateOpenDocumentRoots().
  • A node whose root drops out of that set becomes an eviction candidate after a 30s inactivity window (not immediate — avoids thrashing on quick tab switches), clearing it from 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.
  • Reachability starts fully dormant (nothing ever evicts) until the first report — every existing caller/test that never touches navigation state is unaffected.
  • Wires navigation.svelte.ts's NavigationStore to 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 makes closeTab() actually drive eviction end-to-end.
  • Adds a real (process.memoryUsage()-based, not estimated) 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 node 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).
  • Exposes global.gc() to the vitest fork pool (execArgv: ['--expose-gc']) so that measurement can force a real GC pass before reading process.memoryUsage(), instead of reading whatever V8 hasn't gotten around to collecting yet.
  • Adds 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 in openDocumentRootIds as 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.ts pushes rather than SharedNodeStore pulling — SharedNodeStore never imports navigation.svelte.ts (avoids a circular import, since reactive-node-service.svelte.ts already imports a constant from navigation.svelte.ts, which imports SharedNodeStore). Instead NavigationStore reports 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:

  • A node open in two panes simultaneously is never evicted while either still shows it — both a direct unit test and an end-to-end test through the real navigation store.
  • A node with a pending/unflushed write (debounced, in-flight, or queued behind one) or an active atomic batch is never evicted mid-write — re-verified at the moment the timer fires, not just at scheduling time, and rescheduled rather than dropped if still dirty.

Real memory measurement (not estimated)

New test:perf run (TEST_FULL_PERFORMANCE=1, 10 tabs × 300 nodes = 3,000 nodes, matching the scale of the issue's own headless probe):

Node count: 3000 while open -> 0 after close + eviction (baseline 0)
Heap used (process.memoryUsage, GC forced via --expose-gc):
  baseline 49.01MB, peak 51.23MB, final 46.12MB

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):

Node count: 720 while open -> 0 after close + eviction (baseline 0)
Heap used: baseline 46.24MB, peak 46.79MB, final 46.47MB

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 both shared-node-store.svelte.ts and navigation.svelte.ts is 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).
  • No regression to 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 unmodified origin/main checkout, where it fails identically (171ms vs 100ms) — pre-existing, unrelated to this PR.

🤖 Generated with Claude Code

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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Addressed: adversarial review finding (structureTree-only reachability gap)

Fixed the real finding: isReachable() only walked structureTree, so any node displayed WITHOUT being a structural descendant of an open tab's root (a query-view result row, a [[wikilink]]/node-card reference) was judged unreachable the instant it was cached — even while a still-open consumer was the only thing showing it.

Fix: added a second, additive reachability channel — SharedNodeStore.pinNodes(ownerId, nodeIds) / unpinAll(ownerId). A node pinned by any owner is reachable regardless of structural position. Wired via a new pinReachableNodes(ownerId, nodeIds) $effect-friendly helper (pin-node-reachability.ts) into every consumer found by a full audit of sharedNodeStore.getNode/ensureNode call sites:

  • TableRow (query-view row)
  • NodeRefInline (wikilink)
  • QueryNodeViewer (the whole loadedNodeIds result set — covers ListView/KanbanView transitively, since they read the same ids from the same parent)
  • NodeCardInline (AI-chat inline node reference — same bug shape as the wikilink case, confirmed by the audit)
  • node-ref-preview.svelte.ts (hover/focus controller) — pinned via the raw API for consistency, though this one doesn't actually reproduce the failure mode (its card content is a one-time snapshot, not a live store read)

Everything else 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 the open tab's own root node or a real structureTree descendant of it — already covered by the existing walk, confirmed by direct code reading, not assumption.

New tests (shared-node-store-eviction.test.ts, pinNodes describe block) reproduce the exact bug shape and fail against the pre-fix code: a node with no structureTree parent, not itself an open root, pinned by a simulated "query view" or "reference" owner — never evicted while pinned; evicted once unpinned + threshold elapses; stays reachable via a second owner after the first releases it (mirrors the two-panes guarantee, for pins); a changing pin set only keeps the current rows reachable.

Verification: bun run test:all (frontend+coverage, skill, full Rust workspace) and bun run quality:fix both pass clean, confirmed in the foreground. Full desktop-app suite: 240 files / 4947 tests (up from 4941 — 6 new pin tests).

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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Addressed: second review finding (global singleton chrome node, never pinned)

Fixed: 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). It has no structureTree relationship to any open tab, isn't itself a tab root, and wasn't pinned — so it was evicted ~30s after the app's first navigation report, regardless of refresh frequency (setNode alone doesn't cancel a pending eviction timer).

Fix: refreshDatabaseSettings() now pins the singleton on every call — unconditionally, before the async refetch (no window where it's cached-but-unpinned regardless of fetch timing), which also re-establishes the pin after a database switch's clearAll() wipes every pin along with every cached node.

Broader audit (per the review's ask — always-mounted chrome outside the original cross-reference-display scope): grepped packages/desktop-app/src/lib/plugins/, all top-level layout components, and every _NODE_ID/_SINGLETON-style constant in the codebase. DATABASE_SETTINGS_NODE_ID is the only global singleton node id in the tree, and ui-extensions.svelte.ts is the only plugins/ file reading sharedNodeStore directly. app-shell.svelte only writes (setNode/deleteNode for MCP-driven changes); tab-system.svelte/pane-content.svelte operate on tab.content.nodeId, which is an open document root by construction. No other gap found.

Tests — both fail pre-fix, pass post-fix (verified locally by temporarily reverting the pin call and re-running):

  • database.test.ts: asserts refreshDatabaseSettings() calls pinNodes with DATABASE_SETTINGS_NODE_ID, and that a second refresh re-pins it (simulating the post-switch-clearAll case).
  • shared-node-store-eviction.test.ts: a new describe block reproduces the reviewer's exact repro against the real production node id — setNode the singleton, pin it (mirroring what refreshDatabaseSettings() does), open an unrelated tab, wait past the inactivity threshold, assert it survives — paired with a second test showing the same sequence without the pin still evicts it.

Gate (foreground, confirmed complete before push): bun run test:all (frontend+coverage, skill, full Rust workspace) green — 240 files / 4951 tests, 5 skill files / 91 tests, full Rust workspace all ok. bun run quality:fix green, 0 diffs. Pushed and confirmed via gh pr view: head 46556bc7, OPEN/MERGEABLE.

(Note: hit the same pre-existing wall-clock flakiness in architecture-benchmarks.test.ts under coverage instrumentation on this machine during earlier gate runs today — already independently confirmed unrelated to this PR by diffing against unmodified origin/main; a clean retry passed fully before this push.)

@mstomar125
mstomar125 merged commit 5fd7955 into main Sep 11, 2026
@mstomar125
mstomar125 deleted the issue-2568-shared-node-store-eviction branch September 11, 2026 10:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant