ReviewOS

stacks/stx

SPA nav: window.stx._scopes leaks ~4 entries per round-trip (disposeSubtreeScopes only cleans inside the swap container)

#1775
Closed glennmichael123 opened this 22 days ago · 0 comments
22 days ago

Concrete, clean-stack reproducible

Navigating Dashboard ⇄ other tabs in the ts-analytics dashboard grows window.stx._scopes monotonically and never shrinks:

after hard load: {total:18, liveInDom:18, orphaned:0}
after 8 hops:    {total:34, liveInDom:18, orphaned:16}
orphanByPrefix: { stx_scope_StatsRow:4, stx_scope_NoDataMessage:4, stx_site_selector_*:8 }

(liveInDom = registry ids that still match a [data-stx-scope] element in the DOM; orphaned = registry entries whose element is gone.) Measured via a WebView driving real SPA navigation; ~4 orphans accumulate per Dashboard round-trip, unbounded.

Root cause

cleanupContainer(container) → disposeSubtreeScopes(container) (signals.ts). disposeSubtreeScopes only inspects root.querySelectorAll('[data-stx-scope]') and delete window.stx._scopes[scopeId] for those. So a scope entry is reclaimed only if its element is a descendant of the cleanup container at cleanup time. Two ways to leak:

  1. Rendered outside the swap container. ts-analytics' NoDataMessage is @included in the layout outside <main id="main-content">; its scope element is never under the container passed to cleanup → never deleted. (StatsRow/site_selector leak similarly depending on swap boundary.)
  2. Detached before cleanup walks. If the swap replaces container content before cleanupContainer runs its querySelectorAll, the old scope elements are already gone → their ids are never matched → never deleted.

Why it matters

  • Unbounded memory growth on long SPA sessions (each entry retains scope vars, signals, closures).
  • Strongly suspected contributor to the intermittent hydration failures we've been chasing (#1769/#1772/#1773 family): the failures only appear after accumulated session state, never on a clean boot — a registry bloated with hundreds of orphaned scopes is exactly that accumulated state. Our field forensics on a stalled component showed totalScopes: 19 with the current component registered:true, mounted:false.

Suggested fixes

  • In cleanupContainer, also sweep scopes whose elements are no longer connected: after the container walk, iterate Object.keys(window.stx._scopes) and delete any whose [data-stx-scope=id] element is absent from document (or whose stored $el is !isConnected). A periodic/again-on-load GC pass bounds the registry regardless of swap-boundary quirks.
  • Or capture the set of scope ids present in the outgoing fragment before the swap and delete exactly those after.

Happy to share the instrumented repro script (WebView + auth + nav loop).

Sign in to comment on this issue.