: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(notebooks): retain recent query results across navigation (#116051)
Marius Andrab92ee2595b20
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.tsindex e21edc8873ac..ccb814e5366b 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts@@ -15,6 +15,8 @@ import { DashboardFilter, HogQLVariable, NodeKind } from '~/queries/schema/schemimport { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'+import { RESPONSE_CACHE_TTL } from './responseCache'+const SCAN_ENDPOINT = '/api/environments/:team_id/query/scan/:cache_key/'// The scan endpoint answers with an empty body while the job runs.const PENDING_SCAN = {}@@ -69,6 +71,48 @@ describe('dataNodeLogic', () => {})afterEach(() => logic?.unmount())+ it.each(['same', 'query', 'filters', 'expired', 'disabled'] as const)(+ 'reuses a completed notebook response on remount: %s',+ async (change) => {+ const clock = jest.spyOn(Date, 'now').mockReturnValue(10_000)+ const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })+ const props: DataNodeLogicProps = { key: testUniqueKey, query, retainResponseOnUnmount: true }+ mockedQuery.mockReset()+ mockedQuery.mockResolvedValue({ results: [[1]], columns: ['value'] })+ try {+ logic = dataNodeLogic(props)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadDataSuccess'])+ logic.unmount()++ if (change === 'query') {+ props.query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 2' })+ } else if (change === 'filters') {+ props.filtersOverride = { date_from: '-14d' }+ } else if (change === 'expired') {+ clock.mockReturnValue(10_000 + RESPONSE_CACHE_TTL)+ } else if (change === 'disabled') {+ props.retainResponseOnUnmount = false+ }+ logic = dataNodeLogic(props)+ logic.mount()+ if (change === 'same') {+ dataNodeLogic({ ...props, cachedResults: { result: null } })+ expect(logic.values.response).toEqual({ results: [[1]], columns: ['value'] })+ expect(mockedQuery).toHaveBeenCalledTimes(1)+ await expectLogic(logic, () => logic.actions.loadData('force_blocking')).toDispatchActions([+ 'loadDataSuccess',+ ])+ } else {+ await expectLogic(logic).toDispatchActions(['loadDataSuccess'])+ }+ expect(mockedQuery).toHaveBeenCalledTimes(2)+ } finally {+ clock.mockRestore()+ }+ }+ )+it('does not resubmit a capacity-limited query after unmount', async () => {jest.useFakeTimers()const submit = jestdiff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.tsindex 02d48950bc75..6b26c04b4355 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts@@ -110,12 +110,20 @@ import type {TraceSpansTreeQueryResponse,} from '../../schema/schema-general'import type { DataNodeRegisteredProps } from './dataNodeCollectionLogic'+import {+ forgetRetainedResponse,+ getRetainedResponse,+ isCompleteResponse,+ responseCacheKey,+ retainResponse,+} from './responseCache'export interface DataNodeLogicProps {key: stringquery: DataNode/** Cached results when fetching nodes in bulk (list endpoint), sharing or exporting. */cachedResults?: AnyResponseType+ retainResponseOnUnmount?: boolean/** Disabled data fetching and only allow cached results. */doNotLoad?: boolean/** Refresh behaviour for queries. */@@ -959,7 +967,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([],})),props({ query: {}, variablesOverride: undefined, autoLoad: true } as DataNodeLogicProps),- propsChanged(({ actions, props }, oldProps) => {+ propsChanged(({ actions, props, values }, oldProps) => {if (!props.query) {return // Can't do anything without a query}@@ -998,7 +1006,15 @@ export const dataNodeLogic = kea<dataNodeLogicType>([}actions.loadData(refreshType)- } else if (props.cachedResults) {+ } else if (+ props.cachedResults &&+ !(+ props.retainResponseOnUnmount &&+ !hasQueryChanged &&+ isCompleteResponse(values.response) &&+ !isCompleteResponse(props.cachedResults)+ )+ ) {// Use cached results if available, otherwise this logic will load the data againactions.setResponse(props.cachedResults)}@@ -2113,10 +2129,15 @@ export const dataNodeLogic = kea<dataNodeLogicType>([actions.resetLoadingTimer()},loadData: ({ overrideQuery }) => {+ cache.responseCacheKey = overrideQuery+ ? null+ : responseCacheKey(props, values.user?.id, values.currentTeamId)+ forgetRetainedResponse(cache.responseCacheKey)actions.collectionNodeLoadData(props.key, (overrideQuery ?? props.query)?.kind)actions.resetLoadingTimer()},loadDataSuccess: ({ response }) => {+ retainResponse(cache.responseCacheKey, response)props.onData?.(response as Record<string, unknown> | null | undefined)actions.collectionNodeLoadDataSuccess(props.key, {isCached: !!response && typeof response === 'object' && 'is_cached' in response && !!response.is_cached,@@ -2212,7 +2233,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([}},})),- afterMount(({ actions, props, cache }) => {+ afterMount(({ actions, props, cache, values }) => {cache.localResults = {}actions.mountDataNode(props.key, {@@ -2221,7 +2242,10 @@ export const dataNodeLogic = kea<dataNodeLogicType>([cancelQuery: actions.cancelQuery,})- if (props.cachedResults) {+ const retainedResponse = getRetainedResponse(responseCacheKey(props, values.user?.id, values.currentTeamId))+ if (retainedResponse) {+ actions.setResponse(retainedResponse)+ } else if (props.cachedResults) {// Use cached results if available, otherwise this logic will load the data again.// We need to set them here, as the propsChanged listener will not trigger on mount// and if we never change the props, the cached results will never be used.diff --git a/frontend/src/queries/nodes/DataNode/responseCache.test.ts b/frontend/src/queries/nodes/DataNode/responseCache.test.tsnew file mode 100644index 000000000000..6ece6b6cc315--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/responseCache.test.ts@@ -0,0 +1,42 @@+import { NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { getRetainedResponse, responseCacheKey, retainResponse } from './responseCache'++beforeEach(() => initKeaTests())++test('isolates retained results by user and project and clones mutable data', () => {+ const props = {+ key: 'example',+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },+ retainResponseOnUnmount: true,+ }+ const key = responseCacheKey(props, 1, 1)!+ const response = { results: [[1]] }+ retainResponse(key, response)+ response.results[0][0] = 2+ expect(getRetainedResponse(key)).toEqual({ results: [[1]] })+ expect(getRetainedResponse(responseCacheKey(props, 2, 1))).toBeNull()+ expect(getRetainedResponse(responseCacheKey(props, 1, 2))).toBeNull()+ expect(getRetainedResponse(responseCacheKey(props, undefined, 1))).toBeNull()+})++test.each([+ { result: null },+ { results: [], query_status: { complete: false } },+ { results: [], error: 'failed' },+ { results: ['x'.repeat(200_001)] },+])('does not retain unusable or oversized results: %p', (response) => {+ retainResponse('example', response)+ expect(getRetainedResponse('example')).toBeNull()+})++test('evicts the least recently used result when capacity is reached', () => {+ for (let index = 0; index < 100; index++) {+ retainResponse(String(index), { results: [index] })+ }+ getRetainedResponse('0')+ retainResponse('next', { results: [] })+ expect(getRetainedResponse('0')).toEqual({ results: [0] })+ expect(getRetainedResponse('1')).toBeNull()+})diff --git a/frontend/src/queries/nodes/DataNode/responseCache.ts b/frontend/src/queries/nodes/DataNode/responseCache.tsnew file mode 100644index 000000000000..7cc135630e8f--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/responseCache.ts@@ -0,0 +1,87 @@+import { getContext } from 'kea'++import { AnyResponseType } from '~/queries/schema/schema-general'++import type { DataNodeLogicProps } from './dataNodeLogic'++const MAX_ENTRIES = 100+const MAX_ENTRY_LENGTH = 200_000+export const RESPONSE_CACHE_TTL = 2 * 60 * 1000++type Entry = { response: AnyResponseType; expiresAt: number }+const caches = new WeakMap<ReturnType<typeof getContext>, Map<string, Entry>>()++export function responseCacheKey(+ props: DataNodeLogicProps,+ userId: number | undefined,+ teamId: number | null+): string | null {+ return props.retainResponseOnUnmount && !props.doNotLoad && !props.refresh?.startsWith('force_') && userId && teamId+ ? JSON.stringify([+ userId,+ teamId,+ props.key,+ props.query,+ props.filtersOverride,+ props.variablesOverride,+ props.modifiers,+ props.limitContext,+ ])+ : null+}++export function isCompleteResponse(response: AnyResponseType | null | undefined): response is AnyResponseType {+ return (+ !!response &&+ !('error' in response && response.error) &&+ response.query_status?.complete !== false &&+ (('result' in response && response.result != null) || ('results' in response && response.results != null))+ )+}++function getCache(): Map<string, Entry> {+ const context = getContext()+ let cache = caches.get(context)+ if (!cache) {+ cache = new Map()+ caches.set(context, cache)+ }+ return cache+}++export function getRetainedResponse(key: string | null): AnyResponseType | null {+ if (!key) {+ return null+ }+ const cache = getCache()+ const entry = cache.get(key)+ if (!entry || entry.expiresAt <= Date.now()) {+ cache.delete(key)+ return null+ }+ cache.delete(key)+ cache.set(key, entry)+ return structuredClone(entry.response)+}++export function forgetRetainedResponse(key: string | null): void {+ if (key) {+ getCache().delete(key)+ }+}++export function retainResponse(key: string | null, response: AnyResponseType | null | undefined): void {+ if (!key || !isCompleteResponse(response)) {+ return+ }+ const serialized = JSON.stringify(response)+ if (serialized.length > MAX_ENTRY_LENGTH) {+ return+ }+ const cache = getCache()+ cache.delete(key)+ cache.set(key, { response: JSON.parse(serialized), expiresAt: Date.now() + RESPONSE_CACHE_TTL })+ while (cache.size > MAX_ENTRIES) {+ cache.delete(cache.keys().next().value!)+ }+}diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsxindex 62ba39651493..75d42620d217 100644--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx@@ -177,6 +177,7 @@ export function DataTable({query: query.source,key: context?.dataNodeLogicKey ?? vizKey,cachedResults: cachedResults,+ retainResponseOnUnmount: insightProps.retainResponseOnUnmount,dataNodeCollectionId: context?.insightProps?.dataNodeCollectionId || dataKey,refresh: context?.refresh,maxPaginationLimit: context?.dataTableMaxPaginationLimit,diff --git a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts b/frontend/src/queries/nodes/DataTable/dataTableLogic.tsindex 19897246c5dd..dd115c481caa 100644--- a/frontend/src/queries/nodes/DataTable/dataTableLogic.ts+++ b/frontend/src/queries/nodes/DataTable/dataTableLogic.ts@@ -237,6 +237,7 @@ export const dataTableLogic = kea<dataTableLogicType>([props.dataNodeLogicKey ?? props.dataKey),loadPriority: props.context?.insightProps?.loadPriority,+ retainResponseOnUnmount: props.context?.insightProps?.retainResponseOnUnmount,}),['response', 'responseLoading', 'responseError'],],diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsxindex 8e320024f152..2063b9be5f75 100644--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx@@ -121,6 +121,7 @@ export function DataTableVisualization({dashboardId: insightProps.dashboardId,dataNodeCollectionId,loadPriority: insightProps.loadPriority,+ retainResponseOnUnmount: insightProps.retainResponseOnUnmount,editMode,setQuery: (setter) => {applyDataVisualizationQueryUpdate(queryRef, setter, setQuery)@@ -133,6 +134,7 @@ export function DataTableVisualization({const dataNodeLogicProps: DataNodeLogicProps = {query: getBIVisualizationSource(query),+ retainResponseOnUnmount: insightProps.retainResponseOnUnmount,key: vizKey,cachedResults,loadPriority: insightProps.loadPriority,diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.tsindex bcb0e2dcb01b..73b9bd171a5e 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts@@ -126,6 +126,7 @@ export interface DataVisualizationLogicProps {insightLoading?: booleandashboardId?: DashboardType['id']loadPriority?: number+ retainResponseOnUnmount?: boolean/** Dashboard variables to override the ones in the query */variablesOverride?: Record<string, HogQLVariable> | nullfiltersOverride?: DashboardFilter | null@@ -981,6 +982,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([query: getBIVisualizationSource(props.query),dataNodeCollectionId: props.dataNodeCollectionId,loadPriority: props.loadPriority,+ retainResponseOnUnmount: props.retainResponseOnUnmount,variablesOverride: props.variablesOverride,filtersOverride: props.filtersOverride,limitContext: props.limitContext,@@ -1000,6 +1002,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([actions: [dataNodeLogic({cachedResults: props.cachedResults,+ retainResponseOnUnmount: props.retainResponseOnUnmount,key: props.key,query: getBIVisualizationSource(props.query),dataNodeCollectionId: props.dataNodeCollectionId,diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.tsx b/frontend/src/queries/nodes/InsightViz/InsightViz.tsxindex b2edcbaf109f..64d85d47c752 100644--- a/frontend/src/queries/nodes/InsightViz/InsightViz.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.tsx@@ -79,6 +79,7 @@ export function InsightViz({query: query.source,key: vizKey,cachedResults: cachedResults || getCachedResults(insightProps.cachedInsight, query.source),+ retainResponseOnUnmount: insightProps.retainResponseOnUnmount,doNotLoad: insightProps.doNotLoad,onData: insightProps.onData,loadPriority: insightProps.loadPriority,diff --git a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsxindex 9dcbea3a7353..21b17e003a98 100644--- a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx+++ b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx@@ -29,7 +29,10 @@ export function SavedInsight({attachTo,editMode,}: InsightProps): JSX.Element {- const insightProps: InsightLogicProps = { dashboardItemId: propsQuery.shortId }+ const insightProps: InsightLogicProps = {+ dashboardItemId: propsQuery.shortId,+ retainResponseOnUnmount: context?.insightProps?.retainResponseOnUnmount,+ }const { insight, insightLoading, insightMissing } = useValues(insightLogic(insightProps))const { query: dataQuery } = useValues(insightDataLogic(insightProps))@@ -60,6 +63,7 @@ export function SavedInsight({return (<Query+ attachTo={attachTo}query={query}cachedResults={insight}context={{ ...context, insightProps }}diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsxindex 689aeff7c8d8..4d69814d5258 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeQuery.tsx@@ -110,6 +110,7 @@ const Component = ({query.kind === NodeKind.SavedInsightNode? insightLogicProps: { dashboardItemId: `new-AdHoc.notebook.${notebookLogic.props.shortId}.${nodeId}`, query }+ dataframeInsightProps.retainResponseOnUnmount = !isSharedconst { insightName } = useValues(insightLogic(insightLogicProps))const isOutputPaneOpen = componentPanelState?.showViewPanel ?? expandedconst showSqlOutputToolbar = getNotebookSqlOutputToolbarVisibility({@@ -240,7 +241,7 @@ const Component = ({<QueryuniqueKey={nodeId + '-component'}query={modifiedQuery}- context={isInsightVizNode(modifiedQuery) ? { insightProps: dataframeInsightProps } : undefined}+ context={{ insightProps: dataframeInsightProps }}attachTo={notebookLogic}setQuery={(t) => {updateAttributes({diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 7f43ca4cd2b4..3bb07468e84f 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -3774,6 +3774,8 @@ export interface InsightLogicProps<Q extends QuerySchema = QuerySchema> {dashboardId?: DashboardType['id']/** cached insight */cachedInsight?: Partial<InsightModel> | null+ /** Reuse recent completed responses when this embedded insight remounts. */+ retainResponseOnUnmount?: boolean/** enable this to avoid API requests */doNotLoad?: booleanloadPriority?: number