: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(frontend): stop listeners reading their logic after it unmounts (#102435)
Georges-Antoine Assi1eb112a0946d
diff --git a/common/storybook/.storybook/decorators/withKea/kea-story.tsx b/common/storybook/.storybook/decorators/withKea/kea-story.tsxindex 9ec88241e56c..6a1ec7c0d37d 100644--- a/common/storybook/.storybook/decorators/withKea/kea-story.tsx+++ b/common/storybook/.storybook/decorators/withKea/kea-story.tsx@@ -18,8 +18,30 @@ import { userLogic } from 'scenes/userLogic'import { initKea } from '~/initKea'import { worker } from '~/mocks/browser'+/**+ * `resetContext` drops the context without unmounting, so `beforeUnmount` never runs. That is where+ * kea invalidates in-flight listeners, and without it they resume against the next story's store.+ */+function unmountLogicsOfPreviousStory(): void {+ const context = getContext()+ if (!context) {+ return+ }+ for (const [pathString, logic] of Object.entries(context.mount.mounted)) {+ // Unmounting one logic also unmounts the logics it connects to, so re-read the count.+ while (context.mount.counter[pathString] > 0) {+ try {+ logic.unmount()+ } catch {+ break // one logic throwing must not strand the rest+ }+ }+ }+}+export function resetKeaStory(): void {worker.resetHandlers()+ unmountLogicsOfPreviousStory()const history = createMemoryHistory({});(history as any).pushState = history.pushdiff --git a/frontend/src/models/propertyDefinitionsModel.test.ts b/frontend/src/models/propertyDefinitionsModel.test.tsindex 169fe3047290..9842987d9a18 100644--- a/frontend/src/models/propertyDefinitionsModel.test.ts+++ b/frontend/src/models/propertyDefinitionsModel.test.ts@@ -226,6 +226,50 @@ describe('the property definitions model', () => {})})+ it('drops a definitions response that arrives after the logic is gone', async () => {+ let releaseRequest: (() => void) | undefined+ let requestStarted: () => void+ let requestAnswered: () => void+ const inFlight = new Promise<void>((resolve) => (requestStarted = resolve))+ const answered = new Promise<void>((resolve) => (requestAnswered = resolve))+ useMocks({+ get: {+ '/api/projects/:team_id/property_definitions/': async () => {+ requestStarted()+ await new Promise<void>((release) => (releaseRequest = release))+ requestAnswered()+ return [200, { count: 0, results: [], next: undefined }]+ },+ },+ })++ const detachedPathErrors: unknown[] = []+ const captureRejection = (reason: unknown): void => {+ if (String((reason as Error)?.message).includes('Can not find path')) {+ detachedPathErrors.push(reason)+ }+ }+ process.on('unhandledRejection', captureRejection)+ try {+ logic.actions.loadPropertyDefinitions(['a string'], PropertyDefinitionType.Event)+ await inFlight+ // permanentlyMount() holds a reference of its own, so one unmount leaves it mounted.+ while (propertyDefinitionsModel.findMounted()) {+ logic.unmount()+ }+ releaseRequest?.()+ await answered+ // The listener resumes on the turn the response lands, and node reports an+ // unhandled rejection at the end of the turn that produced it.+ await new Promise((resolve) => setImmediate(resolve))+ await new Promise((resolve) => setImmediate(resolve))+ } finally {+ process.off('unhandledRejection', captureRejection)+ }++ expect(detachedPathErrors).toEqual([])+ })+it('handles local definitions', async () => {await expectLogic(logic, () => {logic.actions.loadPropertyDefinitions(['$session_duration'], PropertyDefinitionType.Event)diff --git a/frontend/src/models/propertyDefinitionsModel.ts b/frontend/src/models/propertyDefinitionsModel.tsindex 0611bf6c9362..81fd44931548 100644--- a/frontend/src/models/propertyDefinitionsModel.ts+++ b/frontend/src/models/propertyDefinitionsModel.ts@@ -441,6 +441,10 @@ export const propertyDefinitionsModel = kea<propertyDefinitionsModelType>([actions.fetchAllPendingDefinitions()},fetchAllPendingDefinitions: async (_, breakpoint) => {+ // The reads below touch this logic's own reducer, and a request can outlive it: an+ // unmount detaches the path, and storybook swaps the whole store between stories.+ // `breakpoint()` is not the guard, because it would drop a slower reply (see below).+ const startedOn = propertyDefinitionsModel.findMounted()// take 10ms to debounce property definition requests, preventing a lot of small queriesawait breakpoint(10)if (values.pendingProperties.length === 0) {@@ -518,6 +522,10 @@ export const propertyDefinitionsModel = kea<propertyDefinitionsModelType>([})}+ if (propertyDefinitionsModel.findMounted() !== startedOn) {+ return+ }+for (const propertyDefinition of propertyDefinitions.results) {newProperties[`${type}/${propertyDefinition.name}`] = propertyDefinition}@@ -534,6 +542,9 @@ export const propertyDefinitionsModel = kea<propertyDefinitionsModelType>([actions.updatePropertyDefinitions(newProperties)}} catch {+ if (propertyDefinitionsModel.findMounted() !== startedOn) {+ return+ }const newProperties: PropertyDefinitionStorage = {}for (const [type, pending] of Object.entries(pendingByType)) {for (const property of pending) {diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex 678cbea5214f..ba03d791249b 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -943,9 +943,9 @@ export const sceneLogic = kea<sceneLogicType>([} finally {window.clearTimeout(timeout)}- if (values.sceneId !== sceneId) {- breakpoint()- }+ // Break before the `values` read below: the import can outlive this logic, and a+ // detached path throws. The `sceneId` check this replaces read `values` itself.+ breakpoint()const { default: defaultExport, logic, scene: _scene, ...others } = importedSceneif (_scene) {