Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(navigation): stop scenePanelElement selector cache pinning departed scene trees (#69250)

Paul D'Ambrae0e648431f8e
diff --git a/frontend/src/@types/memlab-lens.d.ts b/frontend/src/@types/memlab-lens.d.ts
index 2eefe6ff260e..41ce4ec9c551 100644
--- a/frontend/src/@types/memlab-lens.d.ts
+++ b/frontend/src/@types/memlab-lens.d.ts
@@ -1,5 +1,5 @@
declare module '@memlab/lens/dist/memlens.lib.bundle.js' {
- interface MemLensScanResult {
+ export interface MemLensScanResult {
totalElements: number
totalDetachedElements: number
detachedComponentToFiberNodeCount: Map<string, number>
@@ -8,14 +8,21 @@ declare module '@memlab/lens/dist/memlens.lib.bundle.js' {
end: number
}
- interface MemLensScanner {
+ export interface MemLensDOMElementInfo {
+ element: WeakRef<Element>
+ componentStack: string[] | null | undefined
+ }
+
+ export interface MemLensScanner {
subscribe: (callback: (result: MemLensScanResult) => void) => () => void
start: () => void
stop: () => void
dispose: () => void
+ scan: () => Omit<MemLensScanResult, 'start' | 'end'>
+ getDetachedDOMInfo: () => MemLensDOMElementInfo[]
}
- interface MemLensScanOptions {
+ export interface MemLensScanOptions {
scanIntervalMs?: number
trackEventListenerLeaks?: boolean
}
diff --git a/frontend/src/detachedElementTracker.ts b/frontend/src/detachedElementTracker.ts
index 1525954dd07e..d11c1a98004b 100644
--- a/frontend/src/detachedElementTracker.ts
+++ b/frontend/src/detachedElementTracker.ts
@@ -1,3 +1,7 @@
+import type { MemLensScanner } from '@memlab/lens/dist/memlens.lib.bundle.js'
+
+import { getAppContext } from 'lib/utils/getAppContext'
+
const SCAN_INTERVAL_MS = 30_000
const TOP_N = 10
const IDLE_TIMEOUT_MS = 5_000
@@ -6,22 +10,6 @@ interface Capturable {
capture: (event: string, properties?: Record<string, unknown>) => void
}
-interface MemLensScanResult {
- totalElements: number
- totalDetachedElements: number
- detachedComponentToFiberNodeCount: Map<string, number>
- componentToFiberNodeCount: Map<string, number>
- start: number
- end: number
-}
-
-interface MemLensScanner {
- subscribe: (callback: (result: MemLensScanResult) => void) => () => void
- start: () => void
- stop: () => void
- dispose: () => void
-}
-
export function shouldCaptureDetachedElements(currentCount: number, previousCount: number | null): boolean {
if (currentCount === 0) {
return false
@@ -70,7 +58,7 @@ export function startDetachedElementTracking(posthog: Capturable): void {
state = 'ready'
- const scan: MemLensScanner = createReactMemoryScan({
+ const scan = createReactMemoryScan({
scanIntervalMs: SCAN_INTERVAL_MS,
trackEventListenerLeaks: false,
})
@@ -105,6 +93,10 @@ export function startDetachedElementTracking(posthog: Capturable): void {
document.addEventListener('visibilitychange', onVisibilityChange)
+ if (getAppContext()?.preflight?.is_debug) {
+ exposeLeakHunterDevHelpers(scan)
+ }
+
if (!document.hidden) {
scan.start()
}
@@ -112,6 +104,7 @@ export function startDetachedElementTracking(posthog: Capturable): void {
window.addEventListener('beforeunload', () => {
scan.stop()
scan.dispose()
+ delete (window as unknown as { __leakHunter?: unknown }).__leakHunter
document.removeEventListener('visibilitychange', onVisibilityChange)
})
} catch {
@@ -120,3 +113,51 @@ export function startDetachedElementTracking(posthog: Capturable): void {
}
}, IDLE_TIMEOUT_MS)
}
+
+interface LeakHunterScanSummary {
+ totalElements: number
+ totalDetachedElements: number
+ detachedComponents: Record<string, number>
+}
+
+interface LeakHunterDetachedElementSummary {
+ i: number
+ tag?: string
+ id?: string
+ classes?: string | null
+ components?: string[]
+}
+
+// Dev-only console helpers for hunting detached-DOM retainers. The convenience
+// accessors (`el(i)`, `detached()`) deref WeakRefs on demand rather than holding
+// elements; `scanner` is the raw MemLens instance and keeps its own tracking state.
+function exposeLeakHunterDevHelpers(scan: MemLensScanner): void {
+ const leakHunter = {
+ scanner: scan,
+ scan: (): LeakHunterScanSummary => {
+ const result = scan.scan()
+ return {
+ totalElements: result.totalElements,
+ totalDetachedElements: result.totalDetachedElements,
+ detachedComponents: mapToTopN(result.detachedComponentToFiberNodeCount, 50),
+ }
+ },
+ detached: (limit: number = 50): LeakHunterDetachedElementSummary[] =>
+ scan
+ .getDetachedDOMInfo()
+ .slice(0, limit)
+ .map((info, i) => {
+ const el = info.element.deref()
+ return {
+ i,
+ tag: el?.tagName,
+ id: el?.id,
+ classes: el?.getAttribute('class'),
+ components: info.componentStack?.slice(0, 10) ?? undefined,
+ }
+ }),
+ el: (i: number): Element | undefined => scan.getDetachedDOMInfo()[i]?.element.deref(),
+ }
+ ;(window as unknown as { __leakHunter?: typeof leakHunter }).__leakHunter = leakHunter
+ console.info('[leak-hunter] window.__leakHunter ready')
+}
diff --git a/frontend/src/layout/scenes/sceneLayoutLogic.test.ts b/frontend/src/layout/scenes/sceneLayoutLogic.test.ts
new file mode 100644
index 000000000000..a6731265ade3
--- /dev/null
+++ b/frontend/src/layout/scenes/sceneLayoutLogic.test.ts
@@ -0,0 +1,32 @@
+import { initKeaTests } from '~/test/init'
+
+import { sceneLayoutLogic } from './sceneLayoutLogic'
+
+describe('sceneLayoutLogic', () => {
+ let logic: ReturnType<typeof sceneLayoutLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = sceneLayoutLogic()
+ logic.mount()
+ })
+
+ it('releases the previous panel element from the memoized selector cache', () => {
+ // Regression guard for detached-DOM retention: with no ScenePanel
+ // subscribed, the reselect cache is only refreshed by the
+ // registerScenePanelElement listener. If that listener is removed, the
+ // stale cached element pins the departed scene's whole fiber/DOM tree.
+ const element = document.createElement('div')
+ logic.actions.registerScenePanelElement(element)
+ expect(logic.values.scenePanelElement).toBe(element)
+
+ logic.actions.registerScenePanelElement(null)
+
+ // `lastResult` is a reselect 5 internal, not a public API — if a future
+ // kea/reselect upgrade renames it, this cast fails mechanically (TypeError),
+ // it isn't a behavioural regression in the fix itself.
+ const lastResult = (logic.selectors.scenePanelElement as unknown as { lastResult: () => HTMLElement | null })
+ .lastResult
+ expect(lastResult()).toBe(null)
+ })
+})
diff --git a/frontend/src/layout/scenes/sceneLayoutLogic.tsx b/frontend/src/layout/scenes/sceneLayoutLogic.tsx
index a52345c8281e..63b059388739 100644
--- a/frontend/src/layout/scenes/sceneLayoutLogic.tsx
+++ b/frontend/src/layout/scenes/sceneLayoutLogic.tsx
@@ -1,4 +1,4 @@
-import { actions, connect, kea, path, reducers } from 'kea'
+import { actions, connect, kea, listeners, path, reducers } from 'kea'
import React from 'react'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -54,4 +54,17 @@ export const sceneLayoutLogic = kea<sceneLayoutLogicType>([
},
],
}),
+ listeners(({ values }) => ({
+ registerScenePanelElement: () => {
+ refreshScenePanelElementSelectorCache(values)
+ },
+ })),
])
+
+// The memoized `scenePanelElement` selector only recomputes when evaluated, and once
+// the last ScenePanel unmounts nothing subscribes to it — so without this read its
+// cached result keeps the previous (now detached) panel container alive, which pins
+// the departed scene's entire fiber and DOM tree via the element's React fiber expandos.
+function refreshScenePanelElementSelectorCache(values: sceneLayoutLogicType['values']): void {
+ void values.scenePanelElement
+}