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): fix update view for materialized and saved views (#67857)

Thiago Salvatore99526b47bb16
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 8485b4fc6165..d9591a35c7fb 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -235,9 +235,10 @@ export function SQLEditor({
)}
<div
data-attr="editor-scene"
- className="EditorScene flex min-h-0 grow flex-row overflow-hidden"
+ className="EditorScene relative flex min-h-0 grow flex-row overflow-hidden"
ref={ref}
>
+ <ViewLoadingOverlay />
<QueryWindow
mode={mode}
tabId={tabId || ''}
@@ -277,6 +278,18 @@ export function SQLEditor({
)
}
+function ViewLoadingOverlay(): JSX.Element | null {
+ const { viewQueryLoading } = useValues(sqlEditorLogic)
+ if (!viewQueryLoading) {
+ return null
+ }
+ return (
+ <div className="absolute inset-0 z-10 flex items-center justify-center bg-primary/70">
+ <Spinner className="text-2xl" />
+ </div>
+ )
+}
+
function MaterializationModal({ tabId }: { tabId: string }): JSX.Element {
const { materializationModalOpen, materializationModalView, viewLoading } = useValues(sqlEditorLogic)
const { closeMaterializationModal } = useActions(sqlEditorLogic)
@@ -445,16 +458,34 @@ function SQLEditorSceneTitle(): JSX.Element | null {
return ['Views must be a single query — remove extra statements to update', IconDownload]
}
- if (!response) {
- return ['Run query to update', IconDownload]
- }
-
if (!changesToSave) {
return ['No changes to save', IconDownload]
}
+ // Require the current (edited) query to have been run successfully before updating — a stale
+ // response from a previous run must not enable the button after further edits.
+ if (!isSourceQueryLastRun) {
+ return ['Run the latest query before updating the view', IconDownload]
+ }
+
+ if (responseLoading) {
+ return ['Running query...', Spinner]
+ }
+
+ if (responseError || !response) {
+ return ['Run the query successfully before updating the view', IconDownload]
+ }
+
return [undefined, IconDownload]
- }, [updatingDataWarehouseSavedQuery, changesToSave, response, isMultiQuery])
+ }, [
+ updatingDataWarehouseSavedQuery,
+ changesToSave,
+ isSourceQueryLastRun,
+ responseLoading,
+ responseError,
+ response,
+ isMultiQuery,
+ ])
const isMaterializedView = editingView?.is_materialized === true
const closeObjectTooltip = editingInsight
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 0b54c40d0938..1f13d4889eb3 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -169,8 +169,11 @@ describe('sqlEditorLogic', () => {
const TAB_ID = '1'
let queryEndpointMock: jest.Mock
let materializeEndpointMock: jest.Mock
+ // Lets a test control the server's current activity-log head returned by the saved-query GET.
+ let serverViewHistoryId: string | null = null
beforeEach(async () => {
+ serverViewHistoryId = null
queryEndpointMock = jest.fn(() => [200, { tables: {}, joins: [] }])
materializeEndpointMock = jest.fn(() => [200, {}])
useMocks({
@@ -188,7 +191,10 @@ describe('sqlEditorLogic', () => {
'/api/environments/:team_id/warehouse_saved_queries/': { results: [MOCK_VIEW] },
'/api/environments/:team_id/warehouse_saved_queries/:id/': ({ params }) => {
if (params.id === MOCK_VIEW.id) {
- return [200, MOCK_VIEW]
+ return [
+ 200,
+ { ...MOCK_VIEW, latest_history_id: serverViewHistoryId ?? MOCK_VIEW.latest_history_id },
+ ]
}
return [404]
},
@@ -220,6 +226,10 @@ describe('sqlEditorLogic', () => {
},
patch: {
'/api/user_home_settings/@me/': [200],
+ '/api/environments/:team_id/warehouse_saved_queries/:id/': ({ params }) => [
+ 200,
+ { ...MOCK_VIEW, id: params.id, latest_history_id: 'updated-history-id' },
+ ],
},
delete: {
'/api/environments/:team_id/query/:id/': [204],
@@ -760,6 +770,70 @@ describe('sqlEditorLogic', () => {
})
})
+ describe('Update view', () => {
+ it('advances the saved baseline after updating so reverting to the original query re-enables Update view', async () => {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+
+ // Open the saved view (query "SELECT 1") into a tab — no changes to save yet.
+ logic.actions.createTab(MOCK_VIEW.query.query, MOCK_VIEW)
+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
+ expect(logic.values.changesToSave).toBe(false)
+
+ // Editing the query surfaces changes to save.
+ logic.actions.setQueryInput('SELECT 2')
+ expect(logic.values.changesToSave).toBe(true)
+
+ // A successful update must advance the baseline to the just-saved query.
+ logic.actions.updateViewSuccess({
+ id: MOCK_VIEW.id,
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' },
+ types: [],
+ })
+ await expectLogic(logic).toDispatchActions(['updateViewSuccess', 'updateTab']).toFinishAllListeners()
+ expect(logic.values.editingView?.query?.query).toBe('SELECT 2')
+ expect(logic.values.changesToSave).toBe(false)
+
+ // Reverting to the original query is a real change again — the button stays enabled.
+ logic.actions.setQueryInput(MOCK_VIEW.query.query)
+ expect(logic.values.changesToSave).toBe(true)
+ })
+
+ it('re-bases the concurrency head to the server head after a successful update', async () => {
+ // The server reports 'server-head' as its current activity-log head.
+ serverViewHistoryId = 'server-head'
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+
+ // Open the view with an out-of-date head to prove the update re-reads the server's head.
+ logic.actions.createTab(MOCK_VIEW.query.query, { ...MOCK_VIEW, latest_history_id: 'stale-head' })
+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
+ expect(logic.values.editingView?.latest_history_id).toBe('stale-head')
+
+ logic.actions.setQueryInput('SELECT 2')
+ logic.actions.updateView({
+ id: MOCK_VIEW.id,
+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' },
+ edited_history_id: 'server-head',
+ types: [],
+ })
+ await expectLogic(logic).toDispatchActions(['updateView', 'updateViewSuccess']).toFinishAllListeners()
+
+ // The baseline history is re-based to the server's current head, so the next save's
+ // edited_history_id matches instead of tripping the "edited by another user" conflict.
+ expect(logic.values.editingView?.latest_history_id).toBe('server-head')
+ expect(logic.values.suggestionPayload).toBe(null)
+ })
+ })
+
describe('inline insight metadata editing', () => {
async function loadInsight(): Promise<void> {
logic = sqlEditorLogic({
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index f879920e7d9f..6a125014b8a9 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -550,6 +550,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setMetadataLoading: (loading: boolean) => ({ loading }),
setInsightLoading: (loading: boolean) => ({ loading }),
setViewLoading: (loading: boolean) => ({ loading }),
+ setViewQueryLoading: (loading: boolean) => ({ loading }),
setMaterializationModalOpen: (open: boolean) => ({ open }),
setMaterializationModalView: (view: DataWarehouseSavedQuery | null) => ({ view }),
editView: (query: string, view: DataWarehouseSavedQuery) => ({
@@ -808,6 +809,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setViewLoading: (_, { loading }) => loading,
},
],
+ // Scoped to the editor "open a view" flow so the editor-pane overlay does not flash
+ // during the materialization modal's own (also viewLoading-gated) fetch.
+ viewQueryLoading: [
+ false,
+ {
+ setViewQueryLoading: (_, { loading }) => loading,
+ },
+ ],
insightLoading: [
false,
{
@@ -1843,6 +1852,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
closeEditingObject: () => {
actions.setInsightLoading(false)
actions.setViewLoading(false)
+ actions.setViewQueryLoading(false)
if (!values.activeTab) {
actions.createTab(values.queryInput ?? '')
@@ -1957,10 +1967,35 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
actions.updateViewSuccess(view, draftId)
}
},
- updateViewSuccess: ({ view, draftId }) => {
+ updateViewSuccess: async ({ view, draftId }) => {
if (draftId) {
actions.deleteDraft(draftId, view?.name)
}
+ if (values.activeTab?.view && values.activeTab.view.id === view.id && view.query) {
+ // Refresh the baseline query immediately so `changesToSave` reflects the just-saved
+ // state (and the Update button disables) before we go back to the network.
+ actions.updateTab({
+ ...values.activeTab,
+ view: { ...values.activeTab.view, query: view.query },
+ })
+ // Re-read the server's activity-log head and adopt it as the new base. The concurrency
+ // check — both the frontend guard and the backend's edited_history_id check — keys off
+ // this head; without re-basing, reverting the query and saving again is misread as a
+ // foreign edit and wrongly raises "View has been edited by another user".
+ const refreshedView = await api.dataWarehouseSavedQueries.get(view.id)
+ if (refreshedView?.latest_history_id && values.activeTab?.view?.id === view.id) {
+ actions.updateTab({
+ ...values.activeTab,
+ view: { ...values.activeTab.view, latest_history_id: refreshedView.latest_history_id },
+ })
+ // Point the edit marker at the new head directly (not just clear it) so a fast
+ // revert-and-save can't re-base on the stale pre-save head before this refetch lands.
+ actions.setInProgressViewEdit(view.id, refreshedView.latest_history_id)
+ } else {
+ // No head to adopt — clear the stale marker and let the next edit re-base.
+ actions.deleteInProgressViewEdit(view.id)
+ }
+ }
},
deleteDraftSuccess: ({ draftId, viewName }) => {
if (values.activeTab && values.activeTab.draft?.id === draftId) {
@@ -2362,6 +2397,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const viewId = viewIdFromUrl
actions.setViewLoading(true)
+ actions.setViewQueryLoading(true)
if (values.dataWarehouseSavedQueries.length === 0) {
await dataWarehouseViewsLogic.asyncActions.loadDataWarehouseSavedQueries()
@@ -2371,6 +2407,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
if (!view) {
lemonToast.error('View not found')
actions.setViewLoading(false)
+ actions.setViewQueryLoading(false)
return
}
@@ -2381,6 +2418,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
} catch {
lemonToast.error('Failed to load view details')
actions.setViewLoading(false)
+ actions.setViewQueryLoading(false)
return
}
}
@@ -2393,6 +2431,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
actions.editView(queryToOpen, view)
}
actions.setViewLoading(false)
+ actions.setViewQueryLoading(false)
tabAdded = true
router.actions.replace(urls.sqlEditor(), undefined, getTabHash(values))
} else if (
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.py
index 69baa7cad28f..b53202731e0d 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query.py
@@ -68,6 +68,13 @@ from products.warehouse_sources.backend.facade.models import (
logger = structlog.get_logger(__name__)
+# A DataWarehouseSavedQuery's activity log also records materialization syncs and status
+# transitions (activity="sync_triggered", status changes) that advance the log without the query
+# being edited. Optimistic-concurrency ("modified by someone else") must key off the latest activity
+# that actually changed the query — otherwise every background sync of a materialized view looks
+# like a foreign edit and blocks the next save. This filter scopes activity lookups to query edits.
+QUERY_CHANGE_ACTIVITY_FILTER = {"detail__changes__contains": [{"field": "query"}]}
+
# Cadences offered for view materialization. 15min is the fastest — sub-15min intervals
# (1min, 5min) are source-only and not meaningful for materialized views, matching the
# frontend `DataModelingSyncInterval` type. All values are accepted by
@@ -479,7 +486,11 @@ class DataWarehouseSavedQuerySerializer(
if validated_data.get("query", None) and not soft_update:
edited_history_id = self.context["request"].data.get("edited_history_id", None)
latest_activity_id = (
- ActivityLog.objects.filter(item_id=locked_instance.id, scope="DataWarehouseSavedQuery")
+ ActivityLog.objects.filter(
+ item_id=locked_instance.id,
+ scope="DataWarehouseSavedQuery",
+ **QUERY_CHANGE_ACTIVITY_FILTER,
+ )
.order_by("-created_at")
.values_list("id", flat=True)
.first()
@@ -559,9 +570,13 @@ class DataWarehouseSavedQuerySerializer(
if activity_log:
self.context["activity_log"] = activity_log
else:
- # get latest activity log for this model
+ # get latest query-changing activity log for this model (see QUERY_CHANGE_ACTIVITY_FILTER)
latest_activity_log = (
- ActivityLog.objects.filter(item_id=locked_instance.id, scope="DataWarehouseSavedQuery")
+ ActivityLog.objects.filter(
+ item_id=locked_instance.id,
+ scope="DataWarehouseSavedQuery",
+ **QUERY_CHANGE_ACTIVITY_FILTER,
+ )
.order_by("-created_at")
.first()
)
@@ -831,12 +846,14 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
# This avoids the annotation when we're getting a single object for update/create/etc.
action = self.action if hasattr(self, "action") else None
if action == "list" or action == "retrieve":
- # Add latest activity id annotation to avoid N+1 queries
+ # Add latest query-changing activity id annotation to avoid N+1 queries. Scoped to query
+ # edits (see QUERY_CHANGE_ACTIVITY_FILTER) so materialization syncs don't advance the head.
latest_activity = (
ActivityLog.objects.filter(
scope="DataWarehouseSavedQuery",
item_id=Cast(OuterRef("id"), output_field=TextField()),
team_id=self.team_id,
+ **QUERY_CHANGE_ACTIVITY_FILTER,
)
.order_by("-created_at")
.values("id")[:1]
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index f347e690821a..6ba6952abe4b 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, patch
from parameterized import parameterized
from posthog.models import ActivityLog
+from posthog.models.activity_logging.activity_log import Detail
from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
from products.data_modeling.backend.facade.models import (
@@ -1214,6 +1215,48 @@ class TestSavedQuery(APIBaseTest):
self.assertEqual(response.status_code, 400, response.content)
self.assertEqual(response.json()["detail"], "The query was modified by someone else.")
+ def test_update_concurrency_ignores_non_query_activity(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",
+ {
+ "name": "sync_view",
+ "query": {"kind": "HogQLQuery", "query": "select event as event from events LIMIT 100"},
+ },
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+ saved_query = response.json()
+ query_change_history_id = saved_query["latest_history_id"]
+ self.assertIsNotNone(query_change_history_id)
+
+ # A materialized view's sync/status transitions write newer activity logs that do not change
+ # the query. They must not advance the optimistic-concurrency head.
+ query_activity = ActivityLog.objects.get(id=query_change_history_id)
+ ActivityLog.objects.create(
+ team_id=self.team.id,
+ organization_id=self.team.organization_id,
+ activity="sync_triggered",
+ scope="DataWarehouseSavedQuery",
+ item_id=str(saved_query["id"]),
+ detail=Detail(changes=[]),
+ created_at=query_activity.created_at + timedelta(minutes=1),
+ )
+
+ # The concurrency head still points at the last query edit, not the newer sync.
+ get_response = self.client.get(f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}/")
+ self.assertEqual(get_response.json()["latest_history_id"], query_change_history_id)
+
+ # Saving again based on that head must succeed despite the newer sync activity.
+ with patch.object(DataWarehouseSavedQuery, "get_columns") as mock_get_columns:
+ mock_get_columns.return_value = {}
+ update_response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",
+ {
+ "query": {"kind": "HogQLQuery", "query": "select event as event from events LIMIT 10"},
+ "edited_history_id": query_change_history_id,
+ },
+ )
+ self.assertEqual(update_response.status_code, 200, update_response.content)
+
def test_create_with_activity_log_existing_view(self):
response = self.client.post(
f"/api/environments/{self.team.id}/warehouse_saved_queries/",