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(notebooks): stop the kernel poll when its kea store is replaced (#88952)

Julian Bezdca9d9197c91
diff --git a/.agents/skills/using-kea-disposables/SKILL.md b/.agents/skills/using-kea-disposables/SKILL.md
index 4fa11db4456d..8d3d4d03f048 100644
--- a/.agents/skills/using-kea-disposables/SKILL.md
+++ b/.agents/skills/using-kea-disposables/SKILL.md
@@ -82,6 +82,15 @@ actions.connectionErrored(reason)
This matters most in a `finally`.
A request the unmount aborted rejects, and the `finally` then runs against a logic that no longer exists.
+One caveat on a logic that mounts again.
+The next mount puts a fresh manager on the cache, so a continuation left over from the previous life can reach `cache.disposables` and find a live one.
+`isDisposed` reads `false` there, and disposing a shared key tears down the new life's resource.
+Capture what the continuation needs while the logic is alive when that matters.
+
+Do not guard a timer callback with `isDisposed` alone if it reads `values`.
+The flag only moves on unmount, and replacing the kea context (which storybook does on every story mount) drops the logic from the store without unmounting it, so the cleanup never runs.
+Compare `getContext()` against the context the resource was set up in — see `frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts`.
+
## Examples in the codebase
**Unnamed `setInterval` poller** — see the canonical example in [The pattern](#the-pattern) (`frontend/src/layout/navigation/noEventsBannerLogic.ts:14-21`).
diff --git a/frontend/src/kea-disposables.test.ts b/frontend/src/kea-disposables.test.ts
index a20b5d6ac46c..a5784ada57be 100644
--- a/frontend/src/kea-disposables.test.ts
+++ b/frontend/src/kea-disposables.test.ts
@@ -229,4 +229,23 @@ describe('disposablesPlugin', () => {
expect(setupCalls).toBe(1)
expect(cache.disposables.registry.has('k2')).toBe(false)
})
+
+ it('mounting a built logic again replaces its disposed manager', () => {
+ // Remounting a retained built logic keeps its cache, the lifecycle
+ // scratchpadLogic.test.ts exercises. A manager left disposed there makes every add() in
+ // the next afterMount a no-op, so the logic loses its timers and listeners for good.
+ setHidden(false)
+ const remounted = kea<logicType>([path(['test', 'disposablesRemountTest'])]).build()
+ remounted.mount()
+ ;(remounted as any).cache.disposables.add(makeSetup(), 'k1')
+ remounted.unmount()
+ expect(cleanupCalls).toBe(1)
+ expect((remounted as any).cache.disposables.isDisposed).toBe(true)
+
+ remounted.mount()
+ ;(remounted as any).cache.disposables.add(makeSetup(), 'k1')
+ expect(setupCalls).toBe(2)
+ expect((remounted as any).cache.disposables.registry.has('k1')).toBe(true)
+ remounted.unmount()
+ })
})
diff --git a/frontend/src/kea-disposables.ts b/frontend/src/kea-disposables.ts
index 349e72e4d202..d8ca3e72fc51 100644
--- a/frontend/src/kea-disposables.ts
+++ b/frontend/src/kea-disposables.ts
@@ -25,6 +25,12 @@ export type DisposablesManager = {
* `dispose` do nothing from that point on, which is what lets async work that outlives the
* unmount call them unconditionally. Read it when the continuation itself must stop early,
* for instance before reading `values` on a logic whose reducers are already detached.
+ *
+ * A disposed manager stays inert for the rest of its own life, but the next mount of the same
+ * logic puts a fresh manager on the cache. So a continuation that reaches `cache.disposables`
+ * late can find a live manager belonging to the logic's next life, and disposing a shared key
+ * from there tears down the new life's resource. Capture what the continuation needs while the
+ * logic is alive when that matters.
*/
isDisposed: boolean
}
@@ -114,7 +120,10 @@ const detachGlobalVisibilityListener = (): void => {
}
const initializeDisposablesManager = (logic: LogicWithCache): void => {
- if (logic.cache.disposables) {
+ // A logic that mounts again keeps the same cache, so the disposed manager from its previous
+ // life is still attached. Replace it, or every `add` in the new `afterMount` is a no-op and
+ // the logic silently loses its timers and listeners for the rest of the session.
+ if (logic.cache.disposables && !logic.cache.disposables.isDisposed) {
return
}
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts
index 89c4b0ce280a..71b4803002f4 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.test.ts
@@ -5,6 +5,11 @@ import { initKeaTests } from '~/test/init'
import { notebookKernelInfoLogic } from './notebookKernelInfoLogic'
import type { NotebookLogicMode } from './notebookLogic'
+const setHidden = (hidden: boolean): void => {
+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
+ document.dispatchEvent(new Event('visibilitychange'))
+}
+
describe('notebookKernelInfoLogic', () => {
let kernelStatusSpy: jest.SpyInstance
let logic: ReturnType<typeof notebookKernelInfoLogic.build> | undefined
@@ -20,6 +25,7 @@ describe('notebookKernelInfoLogic', () => {
afterEach(() => {
logic?.unmount()
logic = undefined
+ setHidden(false)
jest.useRealTimers()
kernelStatusSpy.mockRestore()
})
@@ -49,4 +55,93 @@ describe('notebookKernelInfoLogic', () => {
expect(kernelStatusSpy).not.toHaveBeenCalled()
}
})
+
+ test('stops the refresh loop when the kea store is replaced under it', async () => {
+ logic = notebookKernelInfoLogic({ shortId: 'store-reset-01890abc', mode: 'notebook' })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ const callsBeforeReset = kernelStatusSpy.mock.calls.length
+ expect(callsBeforeReset).toBeGreaterThan(1)
+
+ // Storybook resets the kea context on every story mount, which drops this logic's path
+ // from the store without unmounting it. A tick that reads `values` after that throws
+ // "[KEA] Can not find path", and in a story that surfaces as an unhandled error.
+ initKeaTests()
+ // The reset already dropped the logic, so the afterEach unmount has nothing to do.
+ logic = undefined
+
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ expect(kernelStatusSpy).toHaveBeenCalledTimes(callsBeforeReset)
+ })
+
+ test('a logic replaced at the same path keeps its own refresh loop', async () => {
+ const shortId = 'remount-01890abc'
+ logic = notebookKernelInfoLogic({ shortId, mode: 'notebook' })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ const callsPerMount = kernelStatusSpy.mock.calls.length
+ expect(callsPerMount).toBeGreaterThan(1)
+
+ // A storybook remount resets the context and then mounts the same notebook again, so the
+ // replaced logic's loop finds a live logic sitting at its own path. Checking the path
+ // alone lets it keep polling, which doubles the request rate for the new logic.
+ initKeaTests()
+ kernelStatusSpy.mockClear()
+ logic = notebookKernelInfoLogic({ shortId, mode: 'notebook' })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ expect(kernelStatusSpy).toHaveBeenCalledTimes(callsPerMount)
+ })
+
+ test('re-arms the refresh loop when a remounted logic reuses its cache', async () => {
+ logic = notebookKernelInfoLogic({ shortId: 'reused-cache-01890abc', mode: 'notebook' })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ const callsPerMount = kernelStatusSpy.mock.calls.length
+ expect(callsPerMount).toBeGreaterThan(1)
+
+ // Remounting a retained built logic keeps its cache and its kea context, the lifecycle
+ // scratchpadLogic.test.ts exercises. The loop has to arm again instead of reading the
+ // reused cache as a sign that the logic went away.
+ logic.unmount()
+ logic.mount()
+ kernelStatusSpy.mockClear()
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ // One fewer than a full window, because the mount request itself is already counted out.
+ expect(kernelStatusSpy).toHaveBeenCalledTimes(callsPerMount - 1)
+ })
+
+ test('stays stopped when the tab returns after the kea store was replaced', async () => {
+ logic = notebookKernelInfoLogic({ shortId: 'hidden-tab-01890abc', mode: 'notebook' })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(30_000)
+ expect(kernelStatusSpy.mock.calls.length).toBeGreaterThan(1)
+
+ initKeaTests()
+ // The reset already dropped the logic, so the afterEach unmount has nothing to do.
+ logic = undefined
+ kernelStatusSpy.mockClear()
+
+ // The plugin keeps every manager in a module-level set, so the reset leaves this one
+ // registered. Going hidden and back reruns its setup, which has to stay inert instead of
+ // reading `values` from a store without this logic's path. The plugin catches a throwing
+ // setup and logs it, so the log is what separates an inert rerun from a reading one.
+ const consoleErrorSpy = jest.spyOn(console, 'error')
+ try {
+ setHidden(true)
+ setHidden(false)
+ await jest.advanceTimersByTimeAsync(30_000)
+
+ expect(kernelStatusSpy).not.toHaveBeenCalled()
+ expect(consoleErrorSpy.mock.calls.flat().join(' ')).not.toContain('Disposable setup failed')
+ } finally {
+ consoleErrorSpy.mockRestore()
+ }
+ })
})
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts
index 2eb24c197442..b88b305bb3f3 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookKernelInfoLogic.ts
@@ -2,7 +2,7 @@ import {
MakeLogicType,
actions,
afterMount,
- beforeUnmount,
+ getContext,
kea,
key,
listeners,
@@ -558,21 +558,40 @@ export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([
if (props.mode && props.mode !== 'notebook') {
return
}
- const scheduleRefresh = (): void => {
- const delayMs = values.isStarting ? 2000 : 10000
- cache.kernelInfoRefresh = window.setTimeout(() => {
- if (!values.actionInFlight.refresh) {
- actions.loadKernelInfo()
- }
- scheduleRefresh()
- }, delayMs)
- }
+ // Replacing the kea context drops this logic's path from the store without unmounting it,
+ // so the disposable never runs its cleanup and the timer survives. Storybook does that on
+ // every story mount. Reading `values` after it either throws "Can not find path" or, once
+ // something else mounts at the same path, reads a store this loop no longer belongs to.
+ // Captured out here rather than inside the setup, because the plugin holds every manager
+ // in a module-level set and reruns setup when the tab becomes visible. A context read
+ // inside the setup would be the context of that rerun, which compares equal to itself and
+ // guards nothing.
+ const mountedIn = getContext()
+ const isLive = (): boolean => getContext() === mountedIn
actions.loadKernelInfo()
- scheduleRefresh()
- }),
- beforeUnmount(({ cache }) => {
- if (cache.kernelInfoRefresh) {
- clearTimeout(cache.kernelInfoRefresh)
- }
+ cache.disposables.add(() => {
+ // Reschedules itself rather than using setInterval, because a starting kernel is
+ // polled five times more often than a settled one.
+ let timeoutId = 0
+ const scheduleRefresh = (): void => {
+ if (!isLive()) {
+ return
+ }
+ timeoutId = window.setTimeout(
+ () => {
+ if (!isLive()) {
+ return
+ }
+ if (!values.actionInFlight.refresh) {
+ actions.loadKernelInfo()
+ }
+ scheduleRefresh()
+ },
+ values.isStarting ? 2000 : 10000
+ )
+ }
+ scheduleRefresh()
+ return () => clearTimeout(timeoutId)
+ }, 'kernelInfoRefresh')
}),
])