: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
feat(data-warehouse): preview diff before updating a view (#75294)
Anna Szelld9813cf47c0f
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsxindex 3de15b252d03..8df3ec2ff7e3 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryHistoryModal.tsx@@ -1,25 +1,36 @@-import useSize from '@react-hook/size'import clsx from 'clsx'import { useActions, useValues } from 'kea'-import { useRef, useState } from 'react'+import { useState } from 'react'-import { IconCode } from '@posthog/icons'+import { IconCode, IconRevert } from '@posthog/icons'import { LemonModal } from '@posthog/lemon-ui'import { LemonButton } from '@posthog/lemon-ui'import { SkeletonLog } from 'lib/components/ActivityLog/ActivityLog'import { HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'-import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'import { TZLabel } from 'lib/components/TZLabel'import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControl'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { QueryDiffViewer } from './components/QueryDiffViewer'import { editorSceneLogic } from './editorSceneLogic'import { InsightHistory } from './InsightHistory'import { queryHistoryLogic } from './queryHistoryLogic'+import { sqlEditorLogic } from './sqlEditorLogic'++// The query as of this edit — what "Restore" loads back into the editor.+function restorableQueryFromLog(logItem: HumanizedActivityLogItem): string | null {+ const change = logItem.unprocessed?.detail.changes?.find((c) => c.field === 'query' && extractQuery(c.after) !== '')+ return change ? extractQuery(change.after) : null+}function QueryHistoryLogRow({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {const [isExpanded, setIsExpanded] = useState(false)+ const { editingView } = useValues(editorSceneLogic)+ const { closeHistoryModal } = useActions(editorSceneLogic)+ const { setSuggestedQueryInput } = useActions(sqlEditorLogic)++ const restorableQuery = restorableQueryFromLog(logItem)return (<div className={clsx('flex flex-col px-1 py-0.5', isExpanded && 'border rounded')}>@@ -45,6 +56,22 @@ function QueryHistoryLogRow({ logItem }: { logItem: HumanizedActivityLogItem }):</div></div><div className="flex flex-row gap-2">+ {restorableQuery && restorableQuery !== (editingView?.query?.query ?? '') && (+ <LemonButton+ size="small"+ icon={<IconRevert />}+ tooltip="Load this version into the editor to review and restore"+ data-attr="sql-editor-view-history-restore"+ onClick={(e) => {+ e.stopPropagation()+ setSuggestedQueryInput(restorableQuery, 'query_history')+ // Close the modal so the restore diff in the editor is visible+ closeHistoryModal()+ }}+ >+ Restore+ </LemonButton>+ )}<LemonButton icon={<IconCode />} onClick={() => setIsExpanded(!isExpanded)} active={isExpanded} /></div></div>@@ -57,6 +84,14 @@ function QueryHistoryLogRow({ logItem }: { logItem: HumanizedActivityLogItem }):)}+function extractQuery(value: unknown): string {+ if (value && typeof value === 'object' && 'query' in value) {+ const query = (value as { query?: unknown }).query+ return typeof query === 'string' ? query : ''+ }+ return ''+}+function QueryHistoryLogDiff({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {const changes = logItem.unprocessed?.detail.changes@@ -65,7 +100,13 @@ function QueryHistoryLogDiff({ logItem }: { logItem: HumanizedActivityLogItem })<div className="flex flex-col deprecated-space-y-2">{changes?.length ? (changes.map((change, i) => {- return <QueryDiffViewer key={i} before={change.before} after={change.after} />+ return (+ <QueryDiffViewer+ key={i}+ original={extractQuery(change.before)}+ modified={extractQuery(change.after)}+ />+ )})) : (<div className="text-secondary">This item has no changes to compare</div>@@ -75,35 +116,6 @@ function QueryHistoryLogDiff({ logItem }: { logItem: HumanizedActivityLogItem }))}-interface QueryDiffViewerProps {- before: any- after: any-}--function QueryDiffViewer({ before, after }: QueryDiffViewerProps): JSX.Element {- const containerRef = useRef<HTMLDivElement>(null)- const [width] = useSize(containerRef)- return (- <div ref={containerRef} className="flex flex-col space-y-2 w-full">- <MonacoDiffEditor- key="diff-viewer"- original={before?.query ?? ''}- modified={after?.query ?? ''}- language="hogQL"- width={width}- options={{- renderOverviewRuler: false,- scrollBeyondLastLine: false,- renderGutterMenu: false,- scrollbar: {- alwaysConsumeMouseWheel: false,- },- }}- />- </div>- )-}-function QueryHistoryLog({ id }: { id?: number | string }): JSX.Element {const logic = queryHistoryLogic({ id: id as string })const { humanizedActivity, activityLoading, pagination } = useValues(logic)diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex bffb2f0adafa..d4e2107f1aec 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -370,7 +370,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {} = useValues(sqlEditorLogic)const { openHistoryModal } = useActions(editorSceneLogic)const {- updateView,+ reviewViewUpdate,updateInsight,closeEditingObject,saveAsInsight,@@ -589,7 +589,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {><LemonButtononClick={() =>- updateView({+ reviewViewUpdate({id: editingView.id,query: {...sourceQuery.source,diff --git a/frontend/src/scenes/data-warehouse/editor/components/QueryDiffViewer.tsx b/frontend/src/scenes/data-warehouse/editor/components/QueryDiffViewer.tsxnew file mode 100644index 000000000000..54b493b2a43b--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/components/QueryDiffViewer.tsx@@ -0,0 +1,33 @@+import useSize from '@react-hook/size'+import { useRef } from 'react'++import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'++interface QueryDiffViewerProps {+ original: string+ modified: string+}++export function QueryDiffViewer({ original, modified }: QueryDiffViewerProps): JSX.Element {+ const containerRef = useRef<HTMLDivElement>(null)+ const [width] = useSize(containerRef)+ return (+ <div ref={containerRef} className="flex flex-col space-y-2 w-full">+ <MonacoDiffEditor+ key="diff-viewer"+ original={original}+ modified={modified}+ language="hogQL"+ width={width}+ options={{+ renderOverviewRuler: false,+ scrollBeyondLastLine: false,+ renderGutterMenu: false,+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ }}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex e1c64baeb8ac..91783dc84a3e 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -1064,6 +1064,65 @@ describe('sqlEditorLogic', () => {expect(logic.values.editingView?.latest_history_id).toBe('server-head')expect(logic.values.suggestionPayload).toBe(null)})++ it('does not flag a conflict when the cached head is stale but the server query is unchanged', async () => {+ // The server has a query-change head that the editor's cached head does not match —+ // but the server query still equals the baseline this edit started from, so no one+ // else actually changed the query. This must save cleanly, not raise a false conflict.+ serverViewHistoryId = 'server-head'+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ logic.actions.createTab(MOCK_VIEW.query.query, { ...MOCK_VIEW, latest_history_id: 'stale-head' })+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])++ logic.actions.setQueryInput('SELECT 2')+ logic.actions.updateView({+ id: MOCK_VIEW.id,+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' },+ edited_history_id: 'stale-head',+ types: [],+ })+ await expectLogic(logic).toDispatchActions(['updateView', 'updateViewSuccess']).toFinishAllListeners()++ expect(logic.values.suggestionPayload).toBe(null)+ })++ it.each([+ [false, 'Update view'],+ [true, 'Update and re-materialize view'],+ ])(+ 'reviewViewUpdate gates the save behind the inline diff (shouldRematerialize=%s)',+ async (shouldRematerialize, acceptText) => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ logic.actions.createTab(MOCK_VIEW.query.query, MOCK_VIEW)+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])++ logic.actions.setQueryInput('SELECT 2')+ logic.actions.reviewViewUpdate({+ id: MOCK_VIEW.id,+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' },+ shouldRematerialize,+ types: [],+ })+ await expectLogic(logic).toDispatchActions(['reviewViewUpdate']).toFinishAllListeners()++ // The edit is shown as an accept/reject diff (saved query vs edits), not saved+ // immediately, and the accept label reflects whether it re-materializes.+ expect(logic.values.suggestionPayload?.originalValue).toBe(MOCK_VIEW.query.query)+ expect(logic.values.suggestionPayload?.acceptText).toBe(acceptText)+ }+ )})describe('inline insight metadata editing', () => {diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 85eec132054e..3dae6ab7db68 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -840,6 +840,13 @@ export interface sqlEditorLogicActions {reportAIQueryRejected: () => {value: true}+ reviewViewUpdate: (+ view: UpdateViewPayload,+ draftId?: string+ ) => {+ draftId: string | undefined+ view: UpdateViewPayload+ }runQuery: (queryOverride?: string,switchTab?: boolean@@ -1310,6 +1317,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([inProgressDraftEdits,}),deleteInProgressDraftEdit: (draftId: string) => ({ draftId }),+ reviewViewUpdate: (view: UpdateViewPayload, draftId?: string) => ({+ view,+ draftId,+ }),updateView: (view: UpdateViewPayload, draftId?: string) => ({view,draftId,@@ -2772,16 +2783,43 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}}},+ reviewViewUpdate: ({ view, draftId }) => {+ // Reuse the editor's inline accept/reject diff (QueryPane) instead of a separate+ // modal: show the saved query alongside the user's edits, and only run the update+ // once they accept. Mirrors the conflict-review diff in updateView below.+ const savedQuery = values.activeTab?.view?.query?.query ?? ''+ const editedQuery = values.queryInput ?? ''+ if (savedQuery === editedQuery) {+ actions.updateView(view, draftId)+ return+ }+ actions._setSuggestionPayload({+ suggestedValue: editedQuery,+ originalValue: savedQuery,+ acceptText: view.shouldRematerialize ? 'Update and re-materialize view' : 'Update view',+ rejectText: 'Cancel',+ diffShowRunButton: false,+ onAccept: () => {+ actions.updateView(view, draftId)+ },+ onReject: () => {},+ })+ },updateView: async ({ view, draftId }) => {const latestView = await api.dataWarehouseSavedQueries.get(view.id)- // Only check for conflicts if there's an activity log (latest_history_id exists)- // When there's no activity log, both edited_history_id and latest_history_id are null/undefined,- // and we should allow the update to proceed without showing a false conflict- if (+ // A real conflict means someone else changed the query text since this edit began.+ // Detect it by comparing the server's current query against the baseline this edit+ // started from (the tab's saved query) — not against the user's edited query, which+ // always differs. Keying off history ids alone gives false positives when the+ // editor's cached head has drifted from the server's (e.g. the head advanced for a+ // non-query reason, or the view was opened without one), wrongly telling a sole+ // editor the view was changed by someone else.+ const baselineQuery = values.activeTab?.view?.query?.query+ const foreignEdit =latestView?.latest_history_id != null &&- view.edited_history_id !== latestView.latest_history_id &&- view.query?.query !== latestView?.query?.query- ) {+ baselineQuery != null &&+ latestView.query?.query !== baselineQuery+ if (foreignEdit) {actions._setSuggestionPayload({suggestedValue: values.queryInput!,originalValue: latestView?.query?.query,@@ -2800,7 +2838,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})lemonToast.error('View has been edited by another user. Review changes to update.')} else {- await dataWarehouseViewsLogic.asyncActions.updateDataWarehouseSavedQuery(view)+ // No foreign edit — send the server's current head so the backend's own+ // edited_history_id check accepts the save even if the editor's cached head drifted.+ await dataWarehouseViewsLogic.asyncActions.updateDataWarehouseSavedQuery({+ ...view,+ edited_history_id: latestView?.latest_history_id ?? view.edited_history_id,+ })actions.updateViewSuccess(view, draftId)}},