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(data-warehouse): keep SQL editor sidebar in sync on view mutations (#70088)

Thiago Salvatore6a6eae9026a9
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index 8d6fb5335799..30b5e6e93978 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -871,7 +871,8 @@ const createViewNode = (
options?: {
expandedLazyNodeIds?: Set<string>
},
- schemaTable?: DatabaseSchemaTable
+ schemaTable?: DatabaseSchemaTable,
+ isMaterializing = false
): TreeDataItem => {
const viewChildren: TreeDataItem[] = []
const isMaterializedView = view.is_materialized === true
@@ -896,7 +897,9 @@ const createViewNode = (
id: viewId,
name: view.name,
type: 'node',
- icon: isManagedViewsetView ? (
+ icon: isMaterializing ? (
+ <Spinner />
+ ) : isManagedViewsetView ? (
<IconBolt />
) : isManagedView || isMaterializedView ? (
<IconDatabase />
@@ -1379,6 +1382,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
'dataWarehouseSavedQueryFolders',
'dataWarehouseSavedQueryMapById',
'dataWarehouseSavedQueriesLoading',
+ 'materializingViewIds',
],
draftsLogic,
['drafts', 'draftsResponseLoading', 'hasMoreDrafts'],
@@ -1793,13 +1797,15 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.searchTerm,
s.featureFlags,
s.expandedSearchFolders,
+ s.materializingViewIds,
],
(
searchTreeSourceContext: SearchTreeSourceContext,
searchTreeMatches: SearchTreeMatches,
searchTerm: string,
featureFlags: FeatureFlagsSet,
- expandedSearchFolders: string[]
+ expandedSearchFolders: string[],
+ materializingViewIds: string[]
): TreeDataItem[] => {
if (!searchTerm) {
return []
@@ -1899,9 +1905,18 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
})
// Add saved queries
+ const materializingViewIdSet = new Set(materializingViewIds)
relevantSavedQueries.forEach(([view, matches]) => {
const schemaTable = getSavedQuerySchemaTable(view, allTablesMap)
- const viewNode = createViewNode(view, matches, true, tableLookup, tableNodeOptions, schemaTable)
+ const viewNode = createViewNode(
+ view,
+ matches,
+ true,
+ tableLookup,
+ tableNodeOptions,
+ schemaTable,
+ materializingViewIdSet.has(view.id)
+ )
if (view.folder_id) {
const currentChildren = viewChildrenByFolderId.get(view.folder_id) ?? []
currentChildren.push(viewNode)
@@ -2023,6 +2038,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.featureFlags,
s.queryTabState,
s.expandedFolders,
+ s.materializingViewIds,
],
(
treeDataContext: TreeDataContext,
@@ -2033,7 +2049,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
hasMoreDrafts: boolean,
featureFlags: FeatureFlagsSet,
queryTabState: QueryTabState | null,
- expandedFolders: string[]
+ expandedFolders: string[],
+ materializingViewIds: string[]
): TreeDataItem[] => {
const {
allPosthogTables,
@@ -2134,11 +2151,20 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
})
} else {
const viewChildrenByFolderId = new Map<string, TreeDataItem[]>()
+ const materializingViewIdSet = new Set(materializingViewIds)
// Add saved queries
dataWarehouseSavedQueries.forEach((view) => {
const schemaTable = getSavedQuerySchemaTable(view, allTablesMap)
- const viewNode = createViewNode(view, null, false, tableLookup, tableNodeOptions, schemaTable)
+ const viewNode = createViewNode(
+ view,
+ null,
+ false,
+ tableLookup,
+ tableNodeOptions,
+ schemaTable,
+ materializingViewIdSet.has(view.id)
+ )
if (view.folder_id) {
const folderChildren = viewChildrenByFolderId.get(view.folder_id) ?? []
folderChildren.push(viewNode)
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
index 5f94ea8234a2..f18365ba9829 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
@@ -32,11 +32,121 @@ describe('dataWarehouseViewsLogic', () => {
databaseLogic.unmount()
})
- // Regression: deleting a view used to leave the shared database schema stale, so the deleted
- // view kept showing up in dashboard/insight pickers. Deletion must trigger a schema refresh.
- it('refreshes the database schema after a saved query is deleted', async () => {
+ // Regression: delete must drop the view from the sidebar (via the loader's optimistic filter)
+ // and refresh the picker (schema), but must NOT reload the whole list — that replaces every
+ // row's identity and makes the tree flash.
+ it('optimistically removes the view and refreshes the schema on delete, without reloading the list', async () => {
+ // Let the mount's initial (empty) load settle before seeding, so the two don't race.
+ await expectLogic(logic).toDispatchActions(['loadDataWarehouseSavedQueriesSuccess'])
+
+ let listCalls = 0
+ useMocks({
+ get: {
+ '/api/environments/:team_id/warehouse_saved_queries/': () => {
+ listCalls += 1
+ return [200, { results: [{ id: 'view-123', name: 'v' }] }]
+ },
+ },
+ delete: { '/api/environments/:team_id/warehouse_saved_queries/:id/': [204] },
+ })
+
+ logic.actions.loadDataWarehouseSavedQueries()
+ await expectLogic(logic).toDispatchActions(['loadDataWarehouseSavedQueriesSuccess'])
+ expect(logic.values.dataWarehouseSavedQueries.map((view) => view.id)).toEqual(['view-123'])
+ expect(listCalls).toBe(1)
+
await expectLogic(logic, () => {
logic.actions.deleteDataWarehouseSavedQuery('view-123')
}).toDispatchActions(['deleteDataWarehouseSavedQuerySuccess', 'refreshDatabaseSchema'])
+
+ // Row leaves via the loader's optimistic filter, and the list is not reloaded (no flash).
+ expect(logic.values.dataWarehouseSavedQueries).toEqual([])
+ expect(listCalls).toBe(1)
+ })
+
+ // Regression: a freshly materialized view showed as a plain view in the sidebar until a manual
+ // refresh because is_materialized flips asynchronously and the list was fetched only once. The
+ // poll must keep reloading until it settles, then stop (not loop forever).
+ it('polls the saved-query list after materialization until is_materialized settles', async () => {
+ jest.useFakeTimers()
+ let isMaterialized = false
+ let listCalls = 0
+ useMocks({
+ get: {
+ '/api/environments/:team_id/warehouse_saved_queries/': () => {
+ listCalls += 1
+ return [200, { results: [{ id: 'view-1', name: 'v1', is_materialized: isMaterialized }] }]
+ },
+ },
+ post: {
+ '/api/environments/:team_id/warehouse_saved_queries/:id/materialize/': [200],
+ },
+ })
+
+ logic.actions.materializeDataWarehouseSavedQuery('view-1')
+ await jest.advanceTimersByTimeAsync(0) // flush materialize + first reload
+ expect(listCalls).toBe(1)
+ // The view is marked materializing so the sidebar shows a spinner on its icon.
+ expect(logic.values.materializingViewIds).toEqual(['view-1'])
+
+ // Still materializing → poll reloads again after the interval.
+ await jest.advanceTimersByTimeAsync(5000)
+ expect(listCalls).toBe(2)
+ expect(logic.values.materializingViewIds).toEqual(['view-1'])
+
+ // Backend flips the flag; the next reload observes it settled.
+ isMaterialized = true
+ await jest.advanceTimersByTimeAsync(5000)
+ expect(listCalls).toBe(3)
+ // Settled → cleared, so the spinner flips to the materialized icon.
+ expect(logic.values.materializingViewIds).toEqual([])
+
+ // Settled → polling stops; advancing time triggers no further reloads.
+ await jest.advanceTimersByTimeAsync(30000)
+ expect(listCalls).toBe(3)
+
+ jest.useRealTimers()
+ })
+
+ // Regression: the poll budget must be per-view. With a shared attempt counter, a view that
+ // caps out clears every still-materializing view's spinner, so a second view started later
+ // loses its spinner before its own materialization settles.
+ it('gives each materializing view its own poll budget', async () => {
+ jest.useFakeTimers()
+ useMocks({
+ get: {
+ '/api/environments/:team_id/warehouse_saved_queries/': () => [
+ 200,
+ {
+ results: [
+ { id: 'A', name: 'a', is_materialized: false },
+ { id: 'B', name: 'b', is_materialized: false },
+ ],
+ },
+ ],
+ },
+ post: {
+ '/api/environments/:team_id/warehouse_saved_queries/:id/materialize/': [200],
+ },
+ })
+
+ logic.actions.materializeDataWarehouseSavedQuery('A')
+ await jest.advanceTimersByTimeAsync(0)
+ // Let A burn several attempts before B starts.
+ for (let i = 0; i < 3; i++) {
+ await jest.advanceTimersByTimeAsync(5000)
+ }
+ logic.actions.materializeDataWarehouseSavedQuery('B')
+ await jest.advanceTimersByTimeAsync(0)
+ expect([...logic.values.materializingViewIds].sort()).toEqual(['A', 'B'])
+
+ // Advance enough for A to hit its own cap (12 attempts) but not B's (started 4 ticks later).
+ for (let i = 0; i < 8; i++) {
+ await jest.advanceTimersByTimeAsync(5000)
+ }
+ // A capped out and its spinner cleared; B is still materializing on its own budget.
+ expect(logic.values.materializingViewIds).toEqual(['B'])
+
+ jest.useRealTimers()
})
})
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
index 002b91ac1fe9..dc877a18acc9 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
@@ -13,6 +13,13 @@ import { DataWarehouseSavedQuery, DataWarehouseSavedQueryFolder } from '~/types'
import type { dataWarehouseViewsLogicType } from './dataWarehouseViewsLogicType'
+// Materialization is async: enabling it flips `is_materialized` either synchronously (the
+// /materialize action) or later, when the Temporal job runs (scheduled sync frequency). After
+// kicking it off we reload the saved-query list a few times so the sidebar reflects the settled
+// state without a manual refresh, then stop.
+const MATERIALIZATION_POLL_INTERVAL_MS = 5000
+const MATERIALIZATION_POLL_MAX_ATTEMPTS = 12
+
export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
path(['scenes', 'warehouse', 'dataWarehouseSavedQueriesLogic']),
connect(() => ({
@@ -35,12 +42,24 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
updateDataWarehouseSavedQueryFailure: () => false,
},
],
+ // Views whose materialization is in flight. Reactive so the sidebar can show a spinner in
+ // place of the view icon while it materializes (a stable state, unlike the transient list
+ // loading flag), then flip to the materialized icon once it settles.
+ materializingViewIds: [
+ [] as string[],
+ {
+ addMaterializingViews: (state, { viewIds }) => Array.from(new Set([...state, ...viewIds])),
+ clearMaterializingView: (state, { viewId }) => state.filter((id) => id !== viewId),
+ },
+ ],
}),
actions({
runDataWarehouseSavedQuery: (viewId: string) => ({ viewId }),
cancelDataWarehouseSavedQuery: (viewId: string) => ({ viewId }),
materializeDataWarehouseSavedQuery: (viewId: string) => ({ viewId }),
revertMaterialization: (viewId: string) => ({ viewId }),
+ addMaterializingViews: (viewIds: string[]) => ({ viewIds }),
+ clearMaterializingView: (viewId: string) => ({ viewId }),
}),
loaders(({ values }) => ({
dataWarehouseSavedQueries: [
@@ -116,8 +135,53 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
},
],
})),
- listeners(({ actions }) => ({
+ listeners(({ actions, values, cache }) => ({
+ loadDataWarehouseSavedQueriesSuccess: ({ dataWarehouseSavedQueries }) => {
+ const materializing = values.materializingViewIds
+ if (materializing.length === 0) {
+ return
+ }
+ const settledIds = new Set(
+ dataWarehouseSavedQueries.filter((view) => view.id && view.is_materialized).map((view) => view.id)
+ )
+ // Per-view attempt counts so concurrent materializations don't share a budget — one view
+ // settling or capping out never clears another view's spinner early.
+ const attempts: Record<string, number> = cache.materializationPollAttempts ?? {}
+ const stillPending: string[] = []
+ for (const id of materializing) {
+ if (settledIds.has(id)) {
+ // Settled → spinner flips to the materialized icon.
+ actions.clearMaterializingView(id)
+ delete attempts[id]
+ continue
+ }
+ const nextAttempt = (attempts[id] ?? 0) + 1
+ if (nextAttempt >= MATERIALIZATION_POLL_MAX_ATTEMPTS) {
+ // Give up waiting on this view so its spinner doesn't get stuck forever.
+ actions.clearMaterializingView(id)
+ delete attempts[id]
+ } else {
+ attempts[id] = nextAttempt
+ stillPending.push(id)
+ }
+ }
+ cache.materializationPollAttempts = attempts
+ if (stillPending.length === 0) {
+ cache.disposables.dispose('materializationPoll')
+ return
+ }
+ cache.disposables.add(() => {
+ const timeoutId = setTimeout(
+ () => actions.loadDataWarehouseSavedQueries(),
+ MATERIALIZATION_POLL_INTERVAL_MS
+ )
+ return () => clearTimeout(timeoutId)
+ }, 'materializationPoll')
+ },
createDataWarehouseSavedQuerySuccess: () => {
+ // The create loader already appends the new view optimistically, so the row appears
+ // without an extra reload. A reload here would also race the materialize reload below
+ // (create-with-materialize) and could revert is_materialized back to false.
actions.refreshDatabaseSchema()
},
createDataWarehouseSavedQueryFolderSuccess: () => {
@@ -145,6 +209,12 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
actions.runDataWarehouseSavedQuery(payload.id)
}
+ // Enabling a sync frequency schedules materialization, whose is_materialized flip can
+ // land asynchronously — mark it materializing (spinner) and poll until it settles.
+ if (payload?.id && payload.sync_frequency) {
+ actions.addMaterializingViews([payload.id])
+ }
+
actions.loadDataWarehouseSavedQueries()
actions.refreshDatabaseSchema()
},
@@ -154,6 +224,9 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
},
deleteDataWarehouseSavedQuerySuccess: () => {
lemonToast.success('View deleted')
+ // The delete loader already filters the view out of the list, so the sidebar row leaves
+ // immediately. Reloading the whole list here just replaces every row's identity and
+ // makes the tree flash — skip it and let refreshDatabaseSchema update the picker.
actions.refreshDatabaseSchema()
},
deleteDataWarehouseSavedQueryFolderSuccess: () => {
@@ -186,6 +259,7 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
posthog.capture('materialized view created', {
sync_frequency: '24hour',
})
+ actions.addMaterializingViews([viewId])
actions.loadDataWarehouseSavedQueries()
actions.refreshDatabaseSchema()
} catch {
@@ -196,6 +270,9 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
try {
await api.dataWarehouseSavedQueries.revertMaterialization(viewId)
lemonToast.success('Materialization reverted')
+ // No longer materializing — drop it so the spinner stops and we don't wait for a
+ // flag that will never flip.
+ actions.clearMaterializingView(viewId)
actions.loadDataWarehouseSavedQueries()
actions.refreshDatabaseSchema()
} catch {