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): refresh schema after saved-view mutations (#70055)

Thiago Salvatore5635e9288043
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
index b1a839badda9..94aefe624b39 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
@@ -94,6 +94,48 @@ describe('databaseTableListLogic', () => {
expect(posthog.captureException).not.toHaveBeenCalled()
})
+ it('refreshDatabaseSchema issues a fresh request instead of piggybacking on an in-flight load', () => {
+ ;(performQuery as jest.Mock).mockImplementation(() => new Promise(() => {}))
+
+ logic = databaseTableListLogic()
+ logic.mount()
+ logic.actions.setConnection('conn-123')
+
+ logic.actions.loadDatabase()
+ expect(performQuery).toHaveBeenCalledTimes(1)
+
+ // A plain reload would dedupe onto the in-flight request and return its (pre-mutation)
+ // result; the forced refresh must issue its own request.
+ logic.actions.refreshDatabaseSchema()
+ expect(performQuery).toHaveBeenCalledTimes(2)
+ })
+
+ it('discards a superseded in-flight response so a refreshed post-deletion schema is not overwritten', async () => {
+ let resolveStale: ((value: { tables: Record<string, unknown>; joins: never[] }) => void) | undefined
+ let resolveFresh: ((value: { tables: Record<string, unknown>; joins: never[] }) => void) | undefined
+ ;(performQuery as jest.Mock)
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveStale = resolve)))
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveFresh = resolve)))
+
+ logic = databaseTableListLogic()
+ logic.mount()
+
+ const stalePreDeletion = logic.asyncActions.loadDatabase()
+ const freshPostDeletion = logic.asyncActions.loadDatabase({ force: true })
+ expect(performQuery).toHaveBeenCalledTimes(2)
+
+ // The forced (post-deletion) refresh resolves first: the deleted view is gone.
+ resolveFresh?.({ tables: {}, joins: [] })
+ await freshPostDeletion
+ expect(logic.values.views).toEqual([])
+
+ // The older in-flight request resolves later, still carrying the deleted view. It is
+ // superseded and must not clobber the refreshed schema.
+ resolveStale?.({ tables: { my_view: { name: 'my_view', type: 'view' } }, joins: [] })
+ await stalePreDeletion
+ expect(logic.values.views).toEqual([])
+ })
+
it('does not let a stale schema response overwrite the selected connection schema', async () => {
let resolvePosthogQuery:
| ((value: { tables: Record<string, { name: string; type: 'posthog' }>; joins: never[] }) => void)
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
index 762a2285c31a..027e10c2198e 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
@@ -1,4 +1,4 @@
-import { actions, kea, path, reducers, selectors } from 'kea'
+import { actions, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { objectsEqual } from 'lib/utils/objects'
@@ -39,29 +39,49 @@ const toMapById = <T extends { id: string }>(items: T[]): Record<string, T> =>
let inFlightDatabaseLoadKey: string | null = null
let inFlightDatabaseLoadPromise: Promise<Required<DatabaseSchemaQueryResponse> | null> | null = null
+// Monotonic epoch advanced only when a load issues a fresh request. A newer load (e.g. one
+// triggered by a schema mutation via refreshDatabaseSchema) supersedes older in-flight ones, so a
+// slow or out-of-order response can never overwrite a fresher schema. Piggybacking loads adopt the
+// in-flight request's epoch rather than advancing it, so they never make the original fetcher look
+// superseded.
+let latestDatabaseLoadEpoch = 0
+let inFlightDatabaseLoadEpoch = 0
+
export const databaseTableListLogic = kea<databaseTableListLogicType>([
path(['scenes', 'data-management', 'database', 'databaseTableListLogic']),
actions({
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setConnection: (connectionId: string | null) => ({ connectionId }),
+ refreshDatabaseSchema: true,
}),
loaders(({ values }) => ({
database: [
null as Required<DatabaseSchemaQueryResponse> | null,
{
- loadDatabase: async (): Promise<Required<DatabaseSchemaQueryResponse> | null> => {
+ loadDatabase: async ({
+ force,
+ }: { force?: boolean } = {}): Promise<Required<DatabaseSchemaQueryResponse> | null> => {
const requestConnectionId = values.connectionId ?? undefined
const requestKey = requestConnectionId ?? '__posthog__'
- if (inFlightDatabaseLoadKey === requestKey && inFlightDatabaseLoadPromise) {
- const inFlight = inFlightDatabaseLoadPromise
- const result = await inFlight
+ // Non-forced loads may piggyback on an identical in-flight request and adopt its
+ // epoch (they don't start a new generation). A forced refresh always issues a
+ // fresh request so it can never return pre-mutation data (and never waits on a
+ // hung stale request).
+ if (!force && inFlightDatabaseLoadKey === requestKey && inFlightDatabaseLoadPromise) {
+ const epoch = inFlightDatabaseLoadEpoch
+ const result = await inFlightDatabaseLoadPromise
+ // Reading `values` post-unmount throws kea's path-not-found error.
if (!databaseTableListLogic.isMounted()) {
return null
}
+ if (epoch !== latestDatabaseLoadEpoch) {
+ return values.database
+ }
return result
}
+ const epoch = ++latestDatabaseLoadEpoch
const request = performQuery(
setLatestVersionsOnQuery({
kind: NodeKind.DatabaseSchemaQuery,
@@ -71,12 +91,15 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
inFlightDatabaseLoadKey = requestKey
inFlightDatabaseLoadPromise = request
+ inFlightDatabaseLoadEpoch = epoch
let database: Required<DatabaseSchemaQueryResponse> | null = null
try {
database = await request
} finally {
- if (inFlightDatabaseLoadKey === requestKey) {
+ // Identity check, not key equality: a concurrent forced refresh may have
+ // replaced the in-flight slot with its own request under the same key.
+ if (inFlightDatabaseLoadPromise === request) {
inFlightDatabaseLoadKey = null
inFlightDatabaseLoadPromise = null
}
@@ -87,6 +110,12 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
return null
}
+ // A newer load or refresh started after us: discard this possibly-stale response
+ // rather than clobbering the fresher schema.
+ if (epoch !== latestDatabaseLoadEpoch) {
+ return values.database
+ }
+
const currentConnectionId = values.connectionId ?? undefined
if (currentConnectionId !== requestConnectionId) {
return values.database
@@ -268,4 +297,9 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
{ resultEqualityCheck: objectsEqual },
],
}),
+ listeners(({ actions }) => ({
+ refreshDatabaseSchema: () => {
+ actions.loadDatabase({ force: true })
+ },
+ })),
])
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
new file mode 100644
index 000000000000..5f94ea8234a2
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
@@ -0,0 +1,42 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'
+
+describe('dataWarehouseViewsLogic', () => {
+ let logic: ReturnType<typeof dataWarehouseViewsLogic.build>
+ let databaseLogic: ReturnType<typeof databaseTableListLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/warehouse_saved_queries/': { results: [] },
+ },
+ delete: {
+ '/api/environments/:team_id/warehouse_saved_queries/:id/': [204],
+ },
+ })
+ initKeaTests()
+ databaseLogic = databaseTableListLogic()
+ databaseLogic.mount()
+ logic = dataWarehouseViewsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ 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 () => {
+ await expectLogic(logic, () => {
+ logic.actions.deleteDataWarehouseSavedQuery('view-123')
+ }).toDispatchActions(['deleteDataWarehouseSavedQuerySuccess', 'refreshDatabaseSchema'])
+ })
+})
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
index 18fe2f7af1a7..002b91ac1fe9 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
@@ -17,7 +17,7 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
path(['scenes', 'warehouse', 'dataWarehouseSavedQueriesLogic']),
connect(() => ({
values: [userLogic, ['user'], databaseTableListLogic, ['views', 'databaseLoading']],
- actions: [databaseTableListLogic, ['loadDatabase']],
+ actions: [databaseTableListLogic, ['refreshDatabaseSchema']],
})),
reducers({
initialDataWarehouseSavedQueryLoading: [
@@ -118,7 +118,7 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
})),
listeners(({ actions }) => ({
createDataWarehouseSavedQuerySuccess: () => {
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
},
createDataWarehouseSavedQueryFolderSuccess: () => {
actions.loadDataWarehouseSavedQueries()
@@ -146,7 +146,7 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
}
actions.loadDataWarehouseSavedQueries()
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
},
updateDataWarehouseSavedQueryError: () => {
lemonToast.error('Failed to update view')
@@ -154,11 +154,12 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
},
deleteDataWarehouseSavedQuerySuccess: () => {
lemonToast.success('View deleted')
+ actions.refreshDatabaseSchema()
},
deleteDataWarehouseSavedQueryFolderSuccess: () => {
lemonToast.success('Folder deleted')
actions.loadDataWarehouseSavedQueries()
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
},
runDataWarehouseSavedQuery: async ({ viewId }) => {
try {
@@ -186,7 +187,7 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
sync_frequency: '24hour',
})
actions.loadDataWarehouseSavedQueries()
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
} catch {
lemonToast.error(`Failed to materialize view`)
}
@@ -196,7 +197,7 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
await api.dataWarehouseSavedQueries.revertMaterialization(viewId)
lemonToast.success('Materialization reverted')
actions.loadDataWarehouseSavedQueries()
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
} catch {
lemonToast.error(`Failed to revert materialization`)
}
diff --git a/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts b/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts
index 3c0ebc0f9762..802459be034a 100644
--- a/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts
+++ b/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts
@@ -49,7 +49,7 @@ export const dataWarehouseSettingsSceneLogic = kea<dataWarehouseSettingsSceneLog
dataWarehouseViewsLogic,
['deleteDataWarehouseSavedQuery', 'updateDataWarehouseSavedQuery', 'updateDataWarehouseSavedQuerySuccess'],
databaseTableListLogic,
- ['loadDatabase', 'loadDatabaseSuccess', 'loadDatabaseFailure'],
+ ['loadDatabase', 'refreshDatabaseSchema', 'loadDatabaseSuccess', 'loadDatabaseFailure'],
],
})),
actions(({ values }) => ({
@@ -214,7 +214,7 @@ export const dataWarehouseSettingsSceneLogic = kea<dataWarehouseSettingsSceneLog
deleteDataWarehouseSavedQuery: async (tableId) => {
await api.dataWarehouseSavedQueries.delete(tableId)
actions.selectRow(null)
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
lemonToast.success('View successfully deleted')
},
selectRow: () => {
@@ -243,7 +243,7 @@ export const dataWarehouseSettingsSceneLogic = kea<dataWarehouseSettingsSceneLog
try {
await api.dataWarehouseTables.updateSchema(tableId, schemaUpdates)
- actions.loadDatabase()
+ actions.refreshDatabaseSchema()
if (values.selectedRow) {
posthog.capture('source schema saved', {