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): reuse query results across navigation (#116871)

Marius Andra889b6739f2b6
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index f73120b80d35..c17cd9a7d9ef 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -26,6 +26,8 @@ The SQL editor keeps unrun edits in browser storage, scoped to the user, project
An **Edited** label marks changes to a saved view or insight. **Discard changes** restores the saved copy already loaded in memory, then refreshes it from the server. The refresh preserves edits made after discarding.
Insights can be saved or updated before running the SQL. Updating a view still requires a successful run of the current SQL so its result types match the saved query. **Continue in a notebook** is in the update button's dropdown for saved views and insights.
+Returning to a notebook can reuse completed query results from the last two minutes in the same browser session. Saved insights still fetch their latest definition; changed queries load their own results. Explicit **Run** and refresh actions fetch results again. This browser cache is bounded and excludes shared notebooks, errors, incomplete responses, and large results; it does not change server cache freshness.
+
## Choosing data in Business intelligence
**Business intelligence** lists saved worksheets at `/bi` when the `sql-editor-bi-mode` feature flag is enabled. Search all worksheets or switch to those viewed in the last 30 days. **New worksheet** opens `/bi/new`; selecting a saved worksheet opens `/bi/<short_id>` in edit mode. The project tree's **New → Worksheet** entry opens the same editor. Worksheets retain their insight identities and folder placements, but use their own file subtype and no longer appear in the Product analytics insights list. Legacy `/bi?open_insight=...` links and shared worksheet URLs still open the editor. Business intelligence and SQL keep separate unsaved working copies, and existing SQL editor links with `mode=bi` open in Business intelligence.
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
index ccb814e5366b..391e4c290478 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
@@ -1,6 +1,7 @@
import { expectLogic, partial } from 'kea-test-utils'
import api, { ApiError } from 'lib/api'
+import { promiseResolveReject } from 'lib/utils/async'
import { useMocks } from '~/mocks/jest'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
@@ -71,6 +72,66 @@ describe('dataNodeLogic', () => {
})
afterEach(() => logic?.unmount())
+ it.each(['pending', 'failed'] as const)('restores a retained query after another query is %s', async (state) => {
+ const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })
+ const response = { results: [[1]], columns: ['value'] }
+ const props: DataNodeLogicProps = { key: testUniqueKey, query, retainResponseOnUnmount: true }
+ const pending = promiseResolveReject<typeof response>()
+ mockedQuery.mockReset()
+ mockedQuery.mockResolvedValueOnce(response).mockReturnValueOnce(pending.promise)
+ logic = dataNodeLogic(props)
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadDataSuccess'])
+
+ dataNodeLogic({
+ ...props,
+ query: setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 2' }),
+ })
+ expect(logic.values.dataLoading).toBe(true)
+ if (state === 'failed') {
+ await expectLogic(logic, () => pending.reject(new Error('Query failed')))
+ .toDispatchActions(['loadDataFailure'])
+ .toMatchValues({ responseError: 'Query failed', responseErrorObject: expect.any(Error) })
+ }
+
+ dataNodeLogic(props)
+ pending.resolve({ results: [[2]], columns: ['value'] })
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ response,
+ responseLoading: false,
+ dataLoading: false,
+ responseError: null,
+ responseErrorObject: null,
+ queryCancelled: false,
+ })
+ expect(mockedQuery).toHaveBeenCalledTimes(2)
+ expect(mockedQuery.mock.calls[1][1]?.signal?.aborted).toBe(true)
+ })
+
+ it.each(['query', 'insight response'] as const)(
+ 'restores notebook results when the query arrives after mount: %s',
+ async (source) => {
+ const query = setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' })
+ const response = { results: [[1]], columns: ['value'] }
+ const props: DataNodeLogicProps = { key: testUniqueKey, query, retainResponseOnUnmount: true }
+ mockedQuery.mockReset()
+ mockedQuery.mockResolvedValue(response)
+ logic = dataNodeLogic(source === 'query' ? props : { ...props, cachedResults: response })
+ logic.mount()
+ if (source === 'query') {
+ await expectLogic(logic).toDispatchActions(['loadDataSuccess'])
+ }
+ logic.unmount()
+ mockedQuery.mockClear()
+
+ logic = dataNodeLogic({ key: props.key } as DataNodeLogicProps)
+ logic.mount()
+ dataNodeLogic(props)
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ response })
+ expect(mockedQuery).not.toHaveBeenCalled()
+ }
+ )
+
it.each(['same', 'query', 'filters', 'expired', 'disabled'] as const)(
'reuses a completed notebook response on remount: %s',
async (change) => {
@@ -90,6 +151,11 @@ describe('dataNodeLogic', () => {
} else if (change === 'filters') {
props.filtersOverride = { date_from: '-14d' }
} else if (change === 'expired') {
+ clock.mockReturnValue(10_000 + RESPONSE_CACHE_TTL / 2)
+ logic = dataNodeLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
clock.mockReturnValue(10_000 + RESPONSE_CACHE_TTL)
} else if (change === 'disabled') {
props.retainResponseOnUnmount = false
@@ -97,6 +163,7 @@ describe('dataNodeLogic', () => {
logic = dataNodeLogic(props)
logic.mount()
if (change === 'same') {
+ await expectLogic(logic).toFinishAllListeners()
dataNodeLogic({ ...props, cachedResults: { result: null } })
expect(logic.values.response).toEqual({ results: [[1]], columns: ['value'] })
expect(mockedQuery).toHaveBeenCalledTimes(1)
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index 6b26c04b4355..6ac7f1eca5e1 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -979,6 +979,15 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
})
const queryVarsHaveChanged = haveVariablesOrFiltersChanged(props.query, oldProps.query)
+ // Insight logics can mount this node before the component supplies its query.
+ const retainedResponse =
+ (hasQueryChanged || props.retainResponseOnUnmount !== oldProps.retainResponseOnUnmount) &&
+ getRetainedResponse(responseCacheKey(props, values.user?.id, values.currentTeamId))
+ if (retainedResponse) {
+ actions.loadData()
+ return
+ }
+
const queryStatus = (props.cachedResults?.query_status || null) as QueryStatus | null
if (hasQueryChanged && queryStatus?.complete === false) {
// If there is an incomplete query, load the data with the same query_id which should return its status
@@ -1016,6 +1025,9 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
)
) {
// Use cached results if available, otherwise this logic will load the data again
+ if (props.cachedResults !== oldProps.cachedResults) {
+ retainResponse(responseCacheKey(props, values.user?.id, values.currentTeamId), props.cachedResults)
+ }
actions.setResponse(props.cachedResults)
}
}),
@@ -1055,6 +1067,22 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
setResponse: (response) => response,
clearResponse: () => null,
loadData: async ({ refresh: refreshArg, queryId, pollOnly, overrideQuery }, breakpoint) => {
+ actions.abortAnyRunningQuery()
+ actions.setPollResponse(null)
+ const key = responseCacheKey(
+ overrideQuery ? { ...props, query: overrideQuery } : props,
+ values.user?.id,
+ values.currentTeamId
+ )
+ const retainedResponse = !pollOnly && !refreshArg?.startsWith('force_') && getRetainedResponse(key)
+ // Do not extend the retained response's lifetime when displaying it again.
+ cache.responseCacheKey = retainedResponse ? null : key
+ if (retainedResponse) {
+ await Promise.resolve()
+ breakpoint()
+ return retainedResponse
+ }
+ forgetRetainedResponse(key)
const rawQuery = overrideQuery ?? props.query
if (!rawQuery || typeof rawQuery !== 'object' || !('kind' in rawQuery)) {
return null
@@ -1104,8 +1132,6 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
return null
}
- actions.abortAnyRunningQuery()
- actions.setPollResponse(null)
const abortController = new AbortController()
cache.disposables.add(() => () => abortController.abort(), 'query', { pauseOnPageHidden: false })
const methodOptions: ApiMethodOptions = {
@@ -2129,10 +2155,6 @@ 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()
},
@@ -2244,11 +2266,12 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
const retainedResponse = getRetainedResponse(responseCacheKey(props, values.user?.id, values.currentTeamId))
if (retainedResponse) {
- actions.setResponse(retainedResponse)
+ actions.loadData()
} 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.
+ retainResponse(responseCacheKey(props, values.user?.id, values.currentTeamId), props.cachedResults)
actions.setResponse(props.cachedResults)
} else if (props.autoLoad && Object.keys(props.query || {}).length > 0) {
// Initial load should use non-force variant
diff --git a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx
index 21b17e003a98..ae857ac23f7e 100644
--- a/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx
+++ b/frontend/src/queries/nodes/SavedInsight/SavedInsight.tsx
@@ -65,7 +65,7 @@ export function SavedInsight({
<Query
attachTo={attachTo}
query={query}
- cachedResults={insight}
+ cachedResults={insightProps.retainResponseOnUnmount ? undefined : insight}
context={{ ...context, insightProps }}
embedded={embedded}
readOnly={readOnly}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 00465a7c5c88..225f110399c7 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -328,6 +328,41 @@ describe('sqlEditorLogic', () => {
databaseLogic?.unmount()
})
+ it('restores a notebook SQL result on remount but still executes an explicit run', async () => {
+ const response = { results: [[42]], columns: ['value'], types: [['value', 'UInt8']] }
+ const querySpy = jest.spyOn(queryRunner, 'performQuery').mockResolvedValue(response as never)
+ const props = { tabId: 'notebook-navigation', mode: SQLEditorMode.Embedded }
+ try {
+ logic = sqlEditorLogic(props)
+ logic.mount()
+ await expectLogic(databaseLogic).toFinishAllListeners()
+ querySpy.mockClear()
+ logic.actions.runQuery('SELECT 42', undefined, true)
+ let dataLogic = dataNodeLogic.findMounted({ key: logic.values.dataLogicKey })!
+ await expectLogic(dataLogic).toDispatchActions(['loadDataSuccess']).toMatchValues({ response })
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ expect(querySpy.mock.calls[0][2]).toBe('blocking')
+ logic.unmount()
+
+ logic = sqlEditorLogic(props)
+ logic.mount()
+ await expectLogic(databaseLogic).toFinishAllListeners()
+ querySpy.mockClear()
+ logic.actions.runQuery('SELECT 42', undefined, true)
+ dataLogic = dataNodeLogic.findMounted({ key: logic.values.dataLogicKey })!
+ await expectLogic(dataLogic).toFinishAllListeners().toMatchValues({ response })
+ expect(querySpy).not.toHaveBeenCalled()
+
+ await expectLogic(dataLogic, () => logic.actions.runQuery('SELECT 42')).toDispatchActions([
+ 'loadDataSuccess',
+ ])
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ expect(querySpy.mock.calls[0][2]).toBe('force_blocking')
+ } finally {
+ querySpy.mockRestore()
+ }
+ })
+
describe('local draft recovery', () => {
const mountEditor = (mode = SQLEditorMode.FullScene): void => {
logic = sqlEditorLogic({ tabId: TAB_ID, mode, monaco: createMockMonaco(), editor: createMockEditor() })
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 451b2280ce8c..51f6a811fe27 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -64,7 +64,7 @@ import { userLogic } from 'scenes/userLogic'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
-import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
import { performQuery, queryExportContext } from '~/queries/query'
import {
@@ -980,9 +980,11 @@ export interface sqlEditorLogicActions {
}
runQuery: (
queryOverride?: string,
- switchTab?: boolean
+ switchTab?: boolean,
+ reuseResults?: boolean
) => {
queryOverride: string | undefined
+ reuseResults: boolean
switchTab: boolean | undefined
}
runSubquery: () => {
@@ -1334,9 +1336,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
activeQueryText,
activeQueryOffset,
}),
- runQuery: (queryOverride?: string, switchTab?: boolean) => ({
+ runQuery: (queryOverride?: string, switchTab?: boolean, reuseResults: boolean = false) => ({
queryOverride,
switchTab,
+ reuseResults,
}),
createTab: (
query?: string,
@@ -2303,7 +2306,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
draft: draft,
})
},
- runQuery: ({ queryOverride, switchTab }) => {
+ runQuery: ({ queryOverride, switchTab, reuseResults }) => {
// Cmd+Enter reaches this listener even while the run button is disabled
if (values.singleStatementDisabledReason) {
return
@@ -2388,17 +2391,21 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
actions.setSourceQuery(nextSourceQuery)
actions.setLastRunQuery(nextSourceQuery)
+ const dataProps: DataNodeLogicProps = {
+ key: values.dataLogicKey,
+ query: executedSource,
+ autoLoad: false,
+ ...(reuseResults ? { retainResponseOnUnmount: true } : {}),
+ }
if (!cache.umountDataNode) {
- cache.umountDataNode = dataNodeLogic({
- key: values.dataLogicKey,
- query: executedSource,
- }).mount()
+ cache.umountDataNode = dataNodeLogic(dataProps).mount()
}
- dataNodeLogic({
- key: values.dataLogicKey,
- query: executedSource,
- }).actions.loadData(!switchTab ? 'force_async' : 'async', undefined, executedSource)
+ dataNodeLogic(dataProps).actions.loadData(
+ reuseResults || switchTab ? 'async' : 'force_async',
+ undefined,
+ executedSource
+ )
// Mark the first query task as complete when the query is run
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.RunFirstQuery)
diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.ts
index 1fb221044958..7a0cffbbd636 100644
--- a/frontend/src/scenes/insights/insightLogic.test.ts
+++ b/frontend/src/scenes/insights/insightLogic.test.ts
@@ -437,6 +437,23 @@ describe('insightLogic', () => {
})
describe('takes data from other logics if available', () => {
+ it.each([true, false])('only fetches the definition when notebook retention is %s', async (retain) => {
+ const requests: URL[] = []
+ useMocks({
+ get: {
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ requests.push(new URL(request.url))
+ return { results: [insightModelWith({})] }
+ },
+ },
+ })
+ logic = insightLogic({ dashboardItemId: Insight42, retainResponseOnUnmount: retain })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])
+ expect(requests).toHaveLength(1)
+ expect(requests[0].searchParams.get('basic')).toBe(retain ? 'true' : null)
+ })
+
const verifyItLoadsFromTheAPI = async (logicUnderTest: ReturnType<typeof insightLogic.build>): Promise<void> =>
expectLogic(logicUnderTest)
.toDispatchActions(['loadInsight'])
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 6283390099dc..eefe2f7b3426 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -689,7 +689,9 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
)
const insight = await insightsApi.getByShortId(
shortId,
- undefined,
+ // Notebook data nodes own execution and can restore a recent response.
+ // Fetching results here would start a query before that cache is checked.
+ props.retainResponseOnUnmount ? true : undefined,
hasOverrides ? 'async_except_on_cache_miss' : 'async',
filtersOverride,
variablesOverride,
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
index 05788f2c0a84..3a61725f46f3 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
@@ -201,7 +201,7 @@ export function useNotebookQuerySQLEditorSync<T extends { query: QuerySchema }>(
isFirstSeed &&
!hasAlreadyRunSqlEditorSourceQuery(editorSourceQuery, lastRunQuery)
) {
- runQuery(editorSourceQuery.source.query)
+ runQuery(editorSourceQuery.source.query, undefined, true)
}
return
}
@@ -259,7 +259,7 @@ function useNotebookQuerySQLEditorOutputSync<T extends { query: QuerySchema }>({
setQueryInput(editorSourceQuery.source.query)
setSourceQuery(editorSourceQuery)
if (isFirstSeed && !hasAlreadyRunSqlEditorSourceQuery(editorSourceQuery, lastRunQuery)) {
- runQuery(editorSourceQuery.source.query)
+ runQuery(editorSourceQuery.source.query, undefined, true)
}
}, [editorSourceQuery, lastRunQuery, runQuery, setQueryInput, setSourceQuery, tabId])
diff --git a/products/logs/frontend/components/LogsSqlEditor/logsSqlEditorTrackingLogic.ts b/products/logs/frontend/components/LogsSqlEditor/logsSqlEditorTrackingLogic.ts
index f06fb580cf08..f6cc9fc0df8e 100644
--- a/products/logs/frontend/components/LogsSqlEditor/logsSqlEditorTrackingLogic.ts
+++ b/products/logs/frontend/components/LogsSqlEditor/logsSqlEditorTrackingLogic.ts
@@ -17,9 +17,11 @@ const captureSaved = (target: SaveAsMenuItem['action']): void => {
export interface logsSqlEditorTrackingLogicActions {
sqlEditorRunQuery: (
queryOverride?: string | undefined,
- switchTab?: boolean | undefined
+ switchTab?: boolean | undefined,
+ reuseResults?: boolean | undefined
) => {
queryOverride: string | undefined
+ reuseResults: boolean
switchTab: boolean | undefined
} // sqlEditorLogic
sqlEditorSaveAsEndpointSubmit: (
diff --git a/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts
index 0cae997c0c4f..33d7c56b6bed 100644
--- a/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts
+++ b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts
@@ -18,9 +18,11 @@ export interface MetricsSqlEditorTrackingLogicProps {
export interface metricsSqlEditorTrackingLogicActions {
sqlEditorRunQuery: (
queryOverride?: string | undefined,
- switchTab?: boolean | undefined
+ switchTab?: boolean | undefined,
+ reuseResults?: boolean | undefined
) => {
queryOverride: string | undefined
+ reuseResults: boolean
switchTab: boolean | undefined
} // sqlEditorLogic
sqlEditorSaveAsEndpointSubmit: (
diff --git a/products/tracing/frontend/components/TracingSqlEditor/tracingSqlEditorTrackingLogic.ts b/products/tracing/frontend/components/TracingSqlEditor/tracingSqlEditorTrackingLogic.ts
index 52ab854a05d5..107185fe005d 100644
--- a/products/tracing/frontend/components/TracingSqlEditor/tracingSqlEditorTrackingLogic.ts
+++ b/products/tracing/frontend/components/TracingSqlEditor/tracingSqlEditorTrackingLogic.ts
@@ -17,9 +17,11 @@ const captureSaved = (target: SaveAsMenuItem['action']): void => {
export interface tracingSqlEditorTrackingLogicActions {
sqlEditorRunQuery: (
queryOverride?: string | undefined,
- switchTab?: boolean | undefined
+ switchTab?: boolean | undefined,
+ reuseResults?: boolean | undefined
) => {
queryOverride: string | undefined
+ reuseResults: boolean
switchTab: boolean | undefined
} // sqlEditorLogic
sqlEditorSaveAsEndpointSubmit: (