: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(taxonomic-filter): don't crash when the list unmounts mid-fetch (#81690)
Sam Penningtone0a51a33cae6
diff --git a/.agents/skills/using-kea-disposables/SKILL.md b/.agents/skills/using-kea-disposables/SKILL.mdindex 85d7c4f45b66..4fa11db4456d 100644--- a/.agents/skills/using-kea-disposables/SKILL.md+++ b/.agents/skills/using-kea-disposables/SKILL.md@@ -63,6 +63,25 @@ Note: `popstate` cannot fire on a hidden tab (it's user-driven), so pausing on h`cache.disposables.dispose('key')` tears down one specific resource without unmounting the logic. Use it when a state transition should end the resource — pause/resume a poller, stop a hover-only ticker on mouseleave, close a modal-scoped listener.+## Calling into the manager after unmount++`add()` and `dispose()` are no-ops once the logic has unmounted, so call them plainly.+Don't write `cache.disposables?.dispose(...)` or `if (!cache.disposables) return`; the manager is never null after mount.++An async continuation usually has to skip more than the disposable, though, because dispatching an action or reading `values` on a torn-down logic is its own bug.+Branch on `isDisposed` for that:++```ts+// The stream teardown aborts this request, so the catch can resume after the unmount+if (cache.disposables.isDisposed) {+ return+}+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.+## 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/.claude/rules/kea-disposables.md b/.claude/rules/kea-disposables.mdindex eceddd6408b4..f997c25cf198 100644--- a/.claude/rules/kea-disposables.md+++ b/.claude/rules/kea-disposables.md@@ -10,3 +10,7 @@ If this kea logic adds `setInterval`, `setTimeout`, `addEventListener`, or any oresource that needs cleanup, invoke the `/using-kea-disposables` skill before makingchanges. Prefer `cache.disposables.add(() => ..., 'key')` over `cache.foo = setInterval(...)`plus `beforeUnmount` cleanup — the plugin handles teardown and auto-pauses on hidden tabs.++`add`/`dispose` are no-ops after unmount, so call them without `?.` or a null check. When an+async continuation must also skip its own work after an unmount, branch on+`cache.disposables.isDisposed`.diff --git a/frontend/src/kea-disposables.test.ts b/frontend/src/kea-disposables.test.tsindex 43c5cbaec21e..a20b5d6ac46c 100644--- a/frontend/src/kea-disposables.test.ts+++ b/frontend/src/kea-disposables.test.ts@@ -211,4 +211,22 @@ describe('disposablesPlugin', () => {logic.unmount()expect(cleanupCalls).toBe(2)})++ it('add() and dispose() are inert after unmount rather than throwing', () => {+ setHidden(false)+ ;(logic as any).cache.disposables.add(makeSetup(), 'k1')+ // A loader or listener closes over `cache`, then reaches `cache.disposables` when it+ // resumes. Read the manager the same way here, so nulling it on unmount fails this test.+ const cache = (logic as any).cache++ logic.unmount()+ expect(cleanupCalls).toBe(1)+ expect(cache.disposables.isDisposed).toBe(true)++ expect(cache.disposables.dispose('k1')).toBe(false)++ cache.disposables.add(makeSetup(), 'k2')+ expect(setupCalls).toBe(1)+ expect(cache.disposables.registry.has('k2')).toBe(false)+ })})diff --git a/frontend/src/kea-disposables.ts b/frontend/src/kea-disposables.tsindex b8b7cc3e6064..349e72e4d202 100644--- a/frontend/src/kea-disposables.ts+++ b/frontend/src/kea-disposables.ts@@ -19,11 +19,19 @@ export type DisposablesManager = {registry: Map<string, DisposableEntry>keyCounter: numberlogicPath: string+ /**+ * True once the logic has begun its final unmount. It is set before the registered cleanups+ * run, so a cleanup that wakes a continuation already sees an inert manager. `add` and+ * `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.+ */+ isDisposed: boolean}// Type for logic with disposables addedtype LogicWithCache = BuiltLogic & {- cache: { disposables?: DisposablesManager | null; [key: string]: any }+ cache: { disposables?: DisposablesManager; [key: string]: any }}// Global state for visibility tracking@@ -110,14 +118,15 @@ const initializeDisposablesManager = (logic: LogicWithCache): void => {return}- const getManager = (): DisposablesManager => logic.cache.disposables!-const manager: DisposablesManager = {registry: new Map(),keyCounter: 0,logicPath: logic.pathString,+ isDisposed: false,add: (setup: SetupFunction, key?: string, options?: DisposableOptions) => {- const manager = getManager()+ if (manager.isDisposed) {+ return+ }const disposableKey = key ?? `__auto_${manager.keyCounter++}`const disposableOptions: DisposableOptions = { pauseOnPageHidden: true, ...options }@@ -154,7 +163,9 @@ const initializeDisposablesManager = (logic: LogicWithCache): void => {}},dispose: (key: string) => {- const manager = getManager()+ if (manager.isDisposed) {+ return false+ }if (!manager.registry.has(key)) {return false}@@ -258,6 +269,12 @@ const initializeDisposablesManager = (logic: LogicWithCache): void => {* // Stop polling without unmounting* cache.disposables.dispose('pollingInterval')* ```+ *+ * ## Safe to call after unmount+ *+ * `add` and `dispose` become no-ops once the logic unmounts, so a listener or loader that resumes+ * after the unmount can call them without a null check. When such a continuation must also skip+ * work of its own (dispatching an action, reading `values`), branch on `cache.disposables.isDisposed`.*/export const disposablesPlugin: KeaPlugin = {name: 'disposables',@@ -268,16 +285,25 @@ export const disposablesPlugin: KeaPlugin = {},beforeUnmount(logic) {const typedLogic = logic as LogicWithCache+ const manager = typedLogic.cache.disposables// Only dispose on final unmount when logic.isMounted() becomes false- if (!typedLogic.isMounted() && typedLogic.cache.disposables) {+ if (!typedLogic.isMounted() && manager && !manager.isDisposed) {// Unregister from global visibility tracking- globalVisibilityState.allManagers.delete(typedLogic.cache.disposables)+ globalVisibilityState.allManagers.delete(manager)++ // Marked before the cleanups run, so that anything a cleanup wakes up (an aborted+ // request resuming inside a `finally`, for instance) sees an inert manager rather+ // than re-registering a resource on a logic that is going away.+ manager.isDisposed = true- // Clean up all disposables- typedLogic.cache.disposables.registry.forEach((entry) => {+ // Clean up all disposables. The manager itself stays on the cache instead of being+ // nulled, because async work that outlives the unmount still reaches for+ // `cache.disposables.dispose(...)`, and a null there throws a TypeError out of the+ // continuation rather than doing nothing.+ manager.registry.forEach((entry) => {safeCleanup(entry.cleanup, typedLogic.pathString)})- typedLogic.cache.disposables = null+ manager.registry.clear()// Detach global listener if no more managersdetachGlobalVisibilityListener()diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.tsindex 7318b90896fe..3140112d9da5 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts@@ -30,6 +30,13 @@ window.POSTHOG_APP_CONTEXT = {current_project: { id: MOCK_TEAM_ID },} as unknown as AppContext+// The disposables plugin pauses and resumes on `visibilitychange`, reading `document.hidden`, so a+// test that backgrounds the tab has to move the property before dispatching the event.+const setTabHidden = (hidden: boolean): void => {+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })+ document.dispatchEvent(new Event('visibilitychange'))+}+describe('infiniteListLogic', () => {let logic: ReturnType<typeof infiniteListLogic.build>@@ -699,6 +706,51 @@ describe('infiniteListLogic', () => {})expect(retryingLogic.values.totalResultCount).toBeGreaterThan(0)})++ it('backgrounding the tab neither cancels the request nor fails a search that succeeded', async () => {+ let respond: ((response: [number, Record<string, any>]) => void) | undefined+ useMocks({+ get: {+ '/api/projects/:team/event_definitions': () =>+ new Promise<[number, Record<string, any>]>((resolve) => {+ respond = resolve+ }),+ },+ })+ initKeaTests()+ jest.useFakeTimers()+ try {+ const backgroundedLogic = infiniteListLogic({+ taxonomicFilterLogicKey: 'backgroundedList',+ listGroupType: TaxonomicFilterGroupType.Events,+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],+ showNumericalPropsOnly: false,+ })+ backgroundedLogic.mount()+ backgroundedLogic.actions.setSearchQuery('user_signed_up')++ // Past the debounce, so the request is in flight rather than still queued.+ await jest.advanceTimersByTimeAsync(600)+ expect(backgroundedLogic.values.showLoadingState).toBe(true)++ setTabHidden(true)+ expect(backgroundedLogic.cache.abortController.signal.aborted).toBe(false)++ setTabHidden(false)+ respond?.([200, { results: [{ name: 'user_signed_up', id: 'uuid-1' }], count: 1 }])+ await jest.advanceTimersByTimeAsync(1)++ // Well past the watchdog. Coming back to the tab must not arm a second watchdog+ // against the request that already answered, or a successful search decays into+ // "couldn't load results".+ await jest.advanceTimersByTimeAsync(31000)+ expect(backgroundedLogic.values.showErrorState).toBe(false)+ expect(backgroundedLogic.values.totalResultCount).toBeGreaterThan(0)+ } finally {+ jest.useRealTimers()+ setTabHidden(false)+ }+ })})describe('SuggestedFilters aggregate holds the empty state until sibling groups settle', () => {diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.tsindex d2a1c3dd4e9e..ed128b33d184 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts@@ -2301,24 +2301,31 @@ export const infiniteListLogic = kea<infiniteListLogicType>([cache.disposables.dispose('abortController')// Add new abort controller- cache.disposables.add(() => {- const abortController = new AbortController()- // Store reference in cache for the fetch operation to use- cache.abortController = abortController- // Some of these list endpoints have no server-side statement timeout, so a query- // that wedges only fails when the gateway gives up two minutes later. Giving up- // first bounds how long the list can sit in its loading state. The failure is- // recorded here rather than in the loader's catch, because the catch cannot tell- // this abort apart from the one a newer query triggers.- const timeoutId = window.setTimeout(() => {- actions.remoteItemsFetchFailedForQuery(values.searchQuery)- abortController.abort()- }, REMOTE_ITEMS_REQUEST_TIMEOUT_MS)- return () => {- window.clearTimeout(timeoutId)- abortController.abort()- }- }, 'abortController')+ cache.disposables.add(+ () => {+ const abortController = new AbortController()+ // Store reference in cache for the fetch operation to use+ cache.abortController = abortController+ // Some of these list endpoints have no server-side statement timeout, so a query+ // that wedges only fails when the gateway gives up two minutes later. Giving up+ // first bounds how long the list can sit in its loading state. The failure is+ // recorded here rather than in the loader's catch, because the catch cannot tell+ // this abort apart from the one a newer query triggers.+ const timeoutId = window.setTimeout(() => {+ actions.remoteItemsFetchFailedForQuery(values.searchQuery)+ abortController.abort()+ }, REMOTE_ITEMS_REQUEST_TIMEOUT_MS)+ return () => {+ window.clearTimeout(timeoutId)+ abortController.abort()+ }+ },+ 'abortController',+ // This disposable bounds one specific request, so pausing it on hide would abort a+ // live fetch and re-running setup on show would arm a fresh 30s watchdog against a+ // request that no longer exists, failing the list 30s after the user comes back.+ { pauseOnPageHidden: false }+ )},retryRemoteItems: () => {actions.loadRemoteItems({ offset: 0, limit: values.limit })diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.tsindex c830d0502f5a..a619bd819bea 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/taskRunStreamLogic.ts@@ -503,8 +503,9 @@ export const taskRunStreamLogic = kea<taskRunStreamLogicType>([cache.disposables.dispose('task-run-sync')})const scheduleReconnect = (reason: string): void => {- // The run-detail fallback can resolve after an unmount, which tears the manager down.- if (!cache.disposables) {+ // The run-detail fallback can resolve after an unmount, and there is no stream+ // left to reconnect once the logic is gone.+ if (cache.disposables.isDisposed) {return}const attempt = ((cache.sseReconnectAttempt as number | undefined) ?? 0) + 1diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.tsindex 9aaf513af4db..ff9e795953ac 100644--- a/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.ts+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.ts@@ -564,7 +564,7 @@ export const aiEnrichmentLogic = kea<aiEnrichmentLogicType>([// The reducers above already clear runRows/runSummary on the same actions; this is the// half that actually cancels the network work and its in-flight-guard state.const stopRunIfInFlight = (): void => {- cache.disposables?.dispose('aiEnrichmentRunStream')+ cache.disposables.dispose('aiEnrichmentRunStream')if (values.isRunning) {actions.setIsRunning(false)}@@ -707,11 +707,7 @@ export const aiEnrichmentLogic = kea<aiEnrichmentLogicType>([}} finally {actions.setIsRunning(false)- // Optional: an unmount mid-run already disposed everything (including this entry)- // and nulled the registry (kea-disposables.ts's beforeUnmount) by the time this- // finally block resumes after the abort it triggered - dispose() on null would- // otherwise throw here as an unhandled rejection.- cache.disposables?.dispose('aiEnrichmentRunStream')+ cache.disposables.dispose('aiEnrichmentRunStream')}},consumeRunLine: ({ line }) => {