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.

feat(endpoints): optimize with ai action in materialization settings (#68683)

Jovan Sakovicbe3a7097e709
diff --git a/common/storybook/.storybook/test-runner.ts b/common/storybook/.storybook/test-runner.ts
index a408e7ded980..e9e2dc87dbb5 100644
--- a/common/storybook/.storybook/test-runner.ts
+++ b/common/storybook/.storybook/test-runner.ts
@@ -542,7 +542,21 @@ async function waitForPageReady(page: Page, skipNetworkIdle = false): Promise<vo
await page.waitForLoadState('networkidle').catch(() => undefined)
}
- await page.evaluate(() => document.fonts.ready)
+ // `document.fonts.ready` only covers fonts that have already been *requested* — a story that
+ // renders no text until async data arrives (loaders, mocked API calls) requests RoundHog/Inter
+ // only close to capture time, and the screenshot races the font-display:swap repaint. Kicking
+ // the loads off explicitly here means late-mounted text renders in the real fonts directly, so
+ // there is no swap left to race. No-op once the fonts are cached.
+ await page
+ .evaluate(() =>
+ Promise.all(
+ ['400', '500', '700', '800'].flatMap((weight) => [
+ document.fonts.load(`${weight} 16px RoundHog`),
+ document.fonts.load(`${weight} 16px Inter`),
+ ])
+ ).then(() => document.fonts.ready)
+ )
+ .catch(() => undefined)
}
function applyStoryTimeouts(page: Page, viewportWidths?: ViewportWidthName[]): void {
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7f19e6d8b416..d6029496fce4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -685,9 +685,9 @@ snapshots:
components-hogcharts-legend--layout-right--light:
hash: v1.k794b7964.17728bea8eba3d28f4c755e1c360096ac1e00691da2dc30b0696b8f21f4d54f8.gQPEmyQw4lLaHGlk7GUFAyHg4DuLwCSE5e6cxwFoB-0
components-hogcharts-legend--layout-top--dark:
- hash: v1.k794b7964.c4109a35a9c00547a1300031b1e286658f891736f3f035ca09b2ae99c3ee96c3.oJ8uXhYfrcNSaeL75Hu-9q2WT0RjH_HQ-WVQlhE2vLQ
+ hash: v1.k794b7964.31cf43f4028e4e9d52ed4a072c4f2e2127200869c16ae295bbc200bc62b5ca0e.EsG-5eqO5ALl_Qa4RqO0GmKrknrgAJ8Yn51jFpvzy4Y
components-hogcharts-legend--layout-top--light:
- hash: v1.k794b7964.bdc703cc44e34614c78b2b2f111a133c97a817e4fa65156b576b92276aa48d2d.8J0fu2E-DXM6m3pdERHWc_ECGYqFZYXNao50w6TGKNk
+ hash: v1.k794b7964.a17c772c6170c3d697a4f62c440f081e52a786a8977eaedc61be167aabe47489.q9bW2znHcUoPyutFXYVcIpWWe0Wx1NssnzNQGcAVYDY
components-hogcharts-legend--legend-hidden--dark:
hash: v1.k794b7964.417591a464c5d90443535783f8b3308eefdcf407b88b492ae20d5e98a8e815ff.WLnH56E-fYhNCt5jvOCeHwLC004qIyP952D4MArBdKo
components-hogcharts-legend--legend-hidden--light:
@@ -1391,7 +1391,7 @@ snapshots:
components-playerinspector--with-logs-filter--dark:
hash: v1.k794b7964.4a27837802248b94d5c146c18b6962bfc713ce40ec3da10a23d4fc89639cf794.PRcX4NksDqdhgKXU-BTlmrZ4mkRVcQIAlLsj5nbUq9I
components-playerinspector--with-logs-filter--light:
- hash: v1.k794b7964.38aa19a7b129b0696518fb42d0dcdfc9e494e26b253983368459b3618a4eda41.Y_UKzWL0hrd0ogvUR7VRKscdpushkyhg2qEMimTjRf4
+ hash: v1.k794b7964.97c396a5d41b78e6f653cdcb59a7e59dce49c44d08a9c3903dd69324eb20fdd6.UcFWQBXiTFaua5umBEqB8d8UUCI6aLN4cXg2abaVyJ0
components-playerinspector--with-logs-filter-upsell--dark:
hash: v1.k794b7964.5e4afe863e34df7278c0dd092946adfd396ee778f0cd0a41e5e3f5e1771a9601.SBOdVp0jJnn1w2H4fMR-3Vf2ac00QSBFQjsl93AbcYA
components-playerinspector--with-logs-filter-upsell--light:
@@ -4589,9 +4589,9 @@ snapshots:
products-workflows-customerioimportmodal--step-4-track-not-configured--light:
hash: v1.k794b7964.0954891b73cdc0b1bce1275fa11a5fa4af2055b83b518bce82f3fde886097659.mgEq2W8sZg7x-vt8z2EpwEHPBGRzPI1GWtn-9tu-46o
queries-webvitals--web-vitals--dark:
- hash: v1.k794b7964.42f72a3a3d7754cea9e80214a1527946f8b14cfe34dda2a7441d4d106d643034.faqrLD6VBvkK4gbAq_j_pxDZQg4XFh_OmfMlhdjbbrU
+ hash: v1.k794b7964.a6d69dfd4718ccc9c5b9610eb2e92f2253ff222f58b5f8f2e17324273c0d3540.PwlwzgyyuTCXAXrqbEIumf0BYHMgEgkMTnF7RMeARWw
queries-webvitals--web-vitals--light:
- hash: v1.k794b7964.4b75f1ec45dda37ed2e73ef974431522361ad2be606c8f4ea520b00fa37199a5.yfVx13wmkNASeh7bwp4jfW_TdSL60TrjU_TIVlubB7E
+ hash: v1.k794b7964.9ee33a37c9dc8e70a61fba6ae6df1149dd3b879f632f5a0a4681d82ec1924446.f2YdyidQkukjaRYXqfWMNmkrJ1A4n5GiD3LauixzibU
queries-webvitalspathbreakdown--web-vitals-path-breakdown--dark:
hash: v1.k794b7964.5ad75695030b31559f83a36380a7c83078678002c669a23b450bd9a5d134ae70.BJSO9CULjFh8KlWBnKsep0Ep6jtur0r4s3T3_0YHjPs
queries-webvitalspathbreakdown--web-vitals-path-breakdown--light:
@@ -6197,9 +6197,9 @@ snapshots:
scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:
hash: v1.k794b7964.c15b997111d34fb17ad2dd192b97c01d0a7ab3a320c5edf9a3e20b0b63a4ff9b.UHxcXJdZkFGXRnzIMFWO99QMD_gZm0V47g8f1j4OFS0
scenes-app-mcp-analytics--dashboard--dark:
- hash: v1.k794b7964.2bc3b8604eace680bbd8e1fa657a8439e1804259a14e4355388f199a6bfa4a16.eLY6IqLrMHWmwR0wamegLkJJqdRPoMUKCxFcUu0V4N4
+ hash: v1.k794b7964.05490a43bcb92252f0270f3302f92f2ef896f9373e9a832e2a166714f4ea9e9d.hZfs_sWw_pq-GRMv5LKpUxYktqR8xoniQdom5iIW7Xw
scenes-app-mcp-analytics--dashboard--light:
- hash: v1.k794b7964.1fb4c7301efba42a966bf89e68e2ad85bbd433944272285552f22566e626b13b.cPkh_QqqLBg3MCavtqoMogCSumls7GI1SxwmjoeLQMg
+ hash: v1.k794b7964.49f850b518aa783296b3d178c4335a14048651a65980d230e22f2d140176b149.GdW1N70CXyKtRCe88ML3fwlrrHTXrIJ58dXsp7VIN6g
scenes-app-mcp-analytics--dashboard-with-menu-bar--dark:
hash: v1.k794b7964.e2c33e0d83a374dcb482a4f87ab282b6970f07b6a2f02d3b401c949d809655a2.pxgapCvTjPi-25Dyd4Jy72NRuWPIjPO_-8Gi6Mxp_zY
scenes-app-mcp-analytics--dashboard-with-menu-bar--light:
@@ -6217,9 +6217,9 @@ snapshots:
scenes-app-mcp-analytics--tool-quality--light:
hash: v1.k794b7964.ad0afc1d54e6b1e1636b111f6b5441963db055864379e1546baa8044638441c1.d5yYULnG731hp03Bh0veJtL14UcVQ27Nwz448eTDDiM
scenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:
- hash: v1.k794b7964.35efe2b95dcc1178dbeacef9e088b2d82a991f7f398f2c2ac0b11fdcbdda56e1.88qh1qEnSCr1jhBQjH1AiVgMO2AoTL8jPvr1hB8SK24
+ hash: v1.k794b7964.2d8dc7d50a9b0bb18090a2e5c29368e12754c133f5029fba10515afca766c9a4.6cPWYhvNfeMHrXHSOz8R-IvwxmTOlpko0UXkl4g920I
scenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--light:
- hash: v1.k794b7964.b7cefef587ac176989ee8149b0b7ffde267afaa091782ce69eca4ec29d836a69.LWDccp1mvN_WM7uEYPRMQQEbVfZOsyuMV14t35QXkz4
+ hash: v1.k794b7964.036b64dbb324cf0163342f393e403c3e3b7feb97bb5e3b88983f168c06f5b5fd.-rT11S5Rw9G17WjI2cK8efHwq2nmUsIMIA1hNd4F3BY
scenes-app-mcp-analytics-dashboard-cards--daily-tool-breakdown--dark:
hash: v1.k794b7964.accfc0a38802ff4dd38b7d92143b5bd3ca3e7b746a05efcfa31980810a6fe1f1.krPWvAaNVmgG9TLam2-YDPGIJtCMCXtQO3kk4Y5qPM4
scenes-app-mcp-analytics-dashboard-cards--daily-tool-breakdown--light:
@@ -6953,9 +6953,9 @@ snapshots:
scenes-app-surveys--new-survey-with-text-question-description-that-does-not-render-html--light:
hash: v1.k794b7964.74fa4b3e23fdeac8f701b748f3fcdc4403d77a1e580b70a782ddfe1d311d982b.jSyhLpcFiZ0g4Z8OCnVzXf_vfju_YI7VGCLI7eFurgE
scenes-app-surveys--survey-results--dark:
- hash: v1.k794b7964.a58a63f7c052961bec01ebf79d5baf683f30214e68aaee59d46f6eaad1f1a425.VcAYJUC2YaMq4SXNaDzb1e7uBkjlbexlTkL1E8rWpDM
+ hash: v1.k794b7964.776af7890a565513e5d4e01224bb8e328cd653ee6371adc46ba03fe0bddd568d.NU_EQHsZP4dA5sPE3YeHq8d60eryJt5BL1o1747SI-s
scenes-app-surveys--survey-results--light:
- hash: v1.k794b7964.b01b9be64e75b3b26c700ba8c3686a8d0b49bcf9aff879a9f9ed3c32458b28c0.Tm5axj56MR_LSVhoBf8gHz3fVG2xKXEsm6LEKlbWIok
+ hash: v1.k794b7964.159d3336c210da231f8f6481bead2cc41f0df60afe12c6246e15908c08c5c8d5.117vRRDfT1RdtLO665SJ_jl7mgyw_lsV_nGHhOtXuEk
scenes-app-surveys--surveys-global-settings--dark:
hash: v1.k794b7964.476a85556bb374416ca1ae0cccfb23f8cc6f6a2e0e71d3f7d0e37a2ad3d463aa.lCKgctegJe2jQZ7Bf7sXK6YhuGh17KhGftYqoY3s5PM
scenes-app-surveys--surveys-global-settings--light:
@@ -7105,9 +7105,9 @@ snapshots:
scenes-app-visual-review-run--tracking-only-master-run--light:
hash: v1.k794b7964.82f2750059b1ef9ab2adb777da603d4d0985b7213235780f24377be11e601a5e.BdVEZ3jDXINsbZgssAvaGfjq_qmGcGOqm2AhdvSYmXg
scenes-app-web-analytics--web-analytics-dashboard--dark:
- hash: v1.k794b7964.cbd196cdbf3b1bb63a5b595bf3664935ddbeea9864205775f3142d6c1fe8f9fe.rpGGWHZqpZrlVvvv0xueufnpBj8loVpVaTW5fRaQHtI
+ hash: v1.k794b7964.4943d4f2d8c1f5ee6b3718c290c548b6c455386398425994489f4282f44378d0.KIJ1bXqO1n1C8mT7pkG4JrDAtOoyCapmsZFWaVwgevc
scenes-app-web-analytics--web-analytics-dashboard--light:
- hash: v1.k794b7964.ba3ae25b65f6bdb5543544347e3dfda70829eddb82efe1399afe6a5d99c0d1ed.K4QHEV19HxB-2gJDTvB2KGA_7WqnG2hlIlZz3MA6C7c
+ hash: v1.k794b7964.17e5ad5877b77a22efc419c7c20cadd283ecbdbea0881bc46450fa5d9ab49c54.9KTUuD6_GGo5OTbK3oX4mASI7IVxNmke7E6yhvzBQEY
scenes-app-web-analytics--web-analytics-dashboard-loading--dark:
hash: v1.k794b7964.b013feb2079b7ea61e8729fa6dba5eaa004649c6605d055853f0e19c5b364436.EBImZsjSWcoLJsL83AAxzuqFX6hk_vu7QXICQPun8q0
scenes-app-web-analytics--web-analytics-dashboard-loading--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8fbe027fdd53..15f210d7a8a1 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -298,6 +298,7 @@ export const FEATURE_FLAGS = {
DWH_SOURCE_METRICS: 'dwh-source-metrics', // owner: #team-warehouse-sources
EDITOR_DRAFTS: 'editor-drafts', // owner: @EDsCODE #team-data-tools
ENDPOINTS: 'embedded-analytics', // owner: @sakce #team-clickhouse
+ ENDPOINTS_AI_MATERIALIZATION_FIX: 'endpoints-ai-materialization-fix', // owner: @sakce #team-data-modeling, gates the AI materialization rewrite (UI button + API action + MCP tools)
ENGINEERING_ANALYTICS: 'engineering-analytics', // owner: #team-devex
ERROR_TRACKING_ISSUE_CORRELATION: 'error-tracking-issue-correlation', // owner: @david #team-error-tracking
ERROR_TRACKING_ISSUE_SPLITTING: 'error-tracking-issue-splitting', // owner: @david #team-error-tracking
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 5968381a8301..69b3d1637641 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -217,7 +217,7 @@ export interface SuggestionPayload {
acceptText?: string
rejectText?: string
diffShowRunButton?: boolean
- source?: 'max_ai' | 'hogql_fixer'
+ source?: 'max_ai' | 'hogql_fixer' | 'materialization_fix'
onAccept: (
shouldRunQuery: boolean,
actions: sqlEditorLogicType['actions'],
@@ -986,8 +986,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
editor.focus()
},
setSuggestedQueryInput: ({ suggestedQueryInput, source }) => {
- // If there's no active tab, create one first to ensure Monaco Editor is available
- if (!values.activeTab) {
+ // If there's no active tab, create one first to ensure Monaco Editor is available.
+ // Embedded mode has no tabs at all — falling into createTab would replace the query
+ // outright instead of showing the accept/reject diff.
+ if (!values.activeTab && !values.isEmbeddedMode) {
actions.createTab(suggestedQueryInput)
return
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e633df090e9d..c28015eb08e8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3131,6 +3131,10 @@ importers:
react:
specifier: 18.3.1
version: 18.3.1
+ devDependencies:
+ '@storybook/react':
+ specifier: 'catalog:'
products/engineering_analytics:
dependencies:
diff --git a/products/endpoints/frontend/MaterializationSuggestionModal.tsx b/products/endpoints/frontend/MaterializationSuggestionModal.tsx
new file mode 100644
index 000000000000..a1ad0cf13e17
--- /dev/null
+++ b/products/endpoints/frontend/MaterializationSuggestionModal.tsx
@@ -0,0 +1,136 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import { endpointSceneLogic } from './endpointSceneLogic'
+
+export function MaterializationSuggestionModal(): JSX.Element {
+ const {
+ materializationSuggestionModalOpen,
+ materializationSuggestion,
+ materializationSuggestionLoading,
+ suggestionMatchesCurrentQuery,
+ } = useValues(endpointSceneLogic)
+ const { closeMaterializationSuggestionModal, applyMaterializationSuggestion, regenerateMaterializationSuggestion } =
+ useActions(endpointSceneLogic)
+
+ const suggestion = materializationSuggestion
+ const hasValidatedSuggestion = suggestion?.suggestion_status === 'ok' && !!suggestion.suggested_query
+ const suggestionFailed =
+ suggestion?.suggestion_status === 'invalid' || suggestion?.suggestion_status === 'model_error'
+ // The error banner already spells out the failed check — repeating it as context is noise
+ const showBlocker = !(suggestionFailed && suggestion?.error === suggestion?.original_reason)
+
+ return (
+ <LemonModal
+ isOpen={materializationSuggestionModalOpen}
+ onClose={closeMaterializationSuggestionModal}
+ title="Make this endpoint materializable"
+ description="AI rewrites your query into an equivalent form that passes our materialization checks. Nothing is saved until you apply the changes and update the endpoint."
+ width={768}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeMaterializationSuggestionModal}>
+ Close
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={regenerateMaterializationSuggestion}
+ loading={materializationSuggestionLoading}
+ disabledReason={materializationSuggestionLoading ? 'Waiting for the suggestion' : undefined}
+ tooltip="Ask the AI for a fresh rewrite, replacing this suggestion"
+ >
+ Regenerate
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={applyMaterializationSuggestion}
+ disabledReason={
+ materializationSuggestionLoading
+ ? 'Waiting for the suggestion'
+ : !hasValidatedSuggestion
+ ? 'No validated suggestion to apply'
+ : suggestionMatchesCurrentQuery
+ ? 'Your query already matches this suggestion'
+ : undefined
+ }
+ >
+ Apply changes to query
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-3">
+ {materializationSuggestionLoading ? (
+ <div className="flex items-center gap-2 py-8 justify-center text-muted">
+ <Spinner />
+ <span>Analyzing your query against the materialization rules…</span>
+ </div>
+ ) : suggestion ? (
+ <>
+ {showBlocker && (
+ <p className="text-secondary text-sm mb-0">Current blocker: {suggestion.original_reason}</p>
+ )}
+ {suggestion.suggestion_status === 'ok' && suggestionMatchesCurrentQuery && (
+ <LemonBanner type="info">
+ Your current query already matches this suggestion — there is nothing to apply. If you
+ haven't saved yet, update the endpoint to create the new version.
+ </LemonBanner>
+ )}
+ {suggestion.suggestion_status === 'ok' && !suggestionMatchesCurrentQuery && (
+ <>
+ {suggestion.explanation && (
+ <LemonMarkdown lowKeyHeadings disableImages>
+ {suggestion.explanation}
+ </LemonMarkdown>
+ )}
+ <CodeSnippet language={Language.SQL} wrap>
+ {suggestion.suggested_query ?? ''}
+ </CodeSnippet>
+ <p className="text-muted text-xs mb-0">
+ This rewrite passes the live materialization checks and keeps your variables
+ unchanged. Review it carefully — applying it and saving creates a new version.
+ </p>
+ </>
+ )}
+ {suggestion.suggestion_status === 'cannot_fix' && (
+ <LemonBanner type="info">
+ <LemonMarkdown lowKeyHeadings disableImages>
+ {suggestion.explanation ||
+ 'No semantically equivalent rewrite exists for this query.'}
+ </LemonMarkdown>
+ </LemonBanner>
+ )}
+ {suggestionFailed && (
+ <>
+ <LemonBanner type="error">
+ Couldn't produce a rewrite that passes the checks
+ {suggestion.error ? `: ${suggestion.error}` : '.'}
+ </LemonBanner>
+ {suggestion.suggested_query && (
+ <>
+ <p className="mb-0">
+ Last attempt (did not pass validation — shown as a starting point):
+ </p>
+ <CodeSnippet language={Language.SQL} wrap>
+ {suggestion.suggested_query}
+ </CodeSnippet>
+ </>
+ )}
+ </>
+ )}
+ </>
+ ) : (
+ <LemonBanner type="error">
+ The suggestion request failed. Check that AI data processing is enabled for your organization,
+ then try again.
+ </LemonBanner>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
index a8b7ee5f6042..a9fe53bb9d8b 100644
--- a/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
+++ b/products/endpoints/frontend/endpoint-tabs/EndpointConfiguration.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { IconClock, IconDatabase, IconInfo, IconList, IconRefresh } from '@posthog/icons'
+import { IconClock, IconDatabase, IconInfo, IconList, IconRefresh, IconSparkles } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -15,13 +15,16 @@ import {
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { MaterializationStatusModal } from 'scenes/data-warehouse/saved_queries/MaterializationStatusModal'
+import { NodeKind } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { endpointLogic } from '../endpointLogic'
import { endpointSceneLogic, MaterializationPreview } from '../endpointSceneLogic'
+import { MaterializationSuggestionModal } from '../MaterializationSuggestionModal'
const DATA_FRESHNESS_OPTIONS: { value: number; label: string }[] = [
{ value: 900, label: '15 minutes' },
@@ -232,14 +235,16 @@ function MaterializationContent(): JSX.Element {
materializationStatus: loadedMaterializationStatus,
materializationStatusLoading,
} = useValues(endpointLogic)
- const { setIsMaterialized, setBucketOverride } = useActions(endpointSceneLogic)
+ const { setIsMaterialized, setBucketOverride, openMaterializationSuggestionModal } = useActions(endpointSceneLogic)
const {
isMaterialized: localIsMaterialized,
viewingVersion,
materializationPreview,
bucketOverrides,
+ localQuery,
} = useValues(endpointSceneLogic)
const [runsModalOpen, setRunsModalOpen] = useState(false)
+ const materializationFixFlagEnabled = useFeatureFlag('ENDPOINTS_AI_MATERIALIZATION_FIX')
if (!endpoint) {
return <></>
@@ -275,6 +280,15 @@ function MaterializationContent(): JSX.Element {
setIsMaterialized(!isMaterialized)
}
+ // Offer an AI rewrite only where it can help: a SQL endpoint, on its latest version,
+ // whose live checks reject the query.
+ const isLatestVersion = !viewingVersion || viewingVersion.version === endpoint.current_version
+ const showOptimizeWithAI =
+ materializationFixFlagEnabled &&
+ isLatestVersion &&
+ endpoint.query?.kind === NodeKind.HogQLQuery &&
+ !isMaterialized
+
const rangePairs = materializationPreview?.range_pairs ?? []
return (
@@ -284,7 +298,32 @@ function MaterializationContent(): JSX.Element {
</p>
{!canMaterialize && cannotMaterializeReason && (
- <LemonBanner type="info">{cannotMaterializeReason}</LemonBanner>
+ <div className="flex flex-col gap-4 items-start">
+ <LemonBanner type="warning" hideIcon={false} className="w-full">
+ <div className="flex flex-col gap-1">
+ <span className="font-semibold">
+ This endpoint can't be materialized yet, so every execution runs the full query.
+ </span>
+ <span className="font-normal">Reason: {cannotMaterializeReason}</span>
+ </div>
+ </LemonBanner>
+ {showOptimizeWithAI && (
+ <LemonButton
+ type="secondary"
+ icon={<IconSparkles />}
+ onClick={openMaterializationSuggestionModal}
+ disabledReason={
+ localQuery
+ ? 'Save or discard your query changes first — the AI rewrites the saved query'
+ : undefined
+ }
+ tooltip="AI rewrites the query into an equivalent form that passes our materialization checks. You review the suggested change in the SQL editor before anything is saved."
+ data-attr="endpoint-optimize-with-ai"
+ >
+ Optimize with AI
+ </LemonButton>
+ )}
+ </div>
)}
{canMaterialize && (
@@ -403,6 +442,7 @@ function MaterializationContent(): JSX.Element {
viewName={endpoint.name}
kind="endpoint"
/>
+ <MaterializationSuggestionModal />
</div>
)
}
diff --git a/products/endpoints/frontend/endpointSceneLogic.test.ts b/products/endpoints/frontend/endpointSceneLogic.test.ts
index 0dc0ef6086cf..92982c16673e 100644
--- a/products/endpoints/frontend/endpointSceneLogic.test.ts
+++ b/products/endpoints/frontend/endpointSceneLogic.test.ts
@@ -1,12 +1,14 @@
import { router } from 'kea-router'
import api from 'lib/api'
+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
import { expectLogic } from '~/test/keaTestUtils'
import { endpointSceneLogic, EndpointTab } from './endpointSceneLogic'
+import { endpointsMaterializationSuggestionCreate } from './generated/api'
jest.mock('lib/api', () => ({
__esModule: true,
@@ -17,6 +19,29 @@ jest.mock('lib/api', () => ({
listVersions: jest.fn().mockResolvedValue({ results: [] }),
},
},
+ ApiConfig: {
+ getCurrentTeamId: jest.fn(() => 1),
+ },
+}))
+
+const mockEditorLogic = {
+ values: { queryInput: 'SELECT 1' },
+ actions: {
+ setQueryInput: jest.fn(),
+ setSourceQuery: jest.fn(),
+ setSuggestedQueryInput: jest.fn(),
+ },
+}
+
+jest.mock('scenes/data-warehouse/editor/sqlEditorLogic', () => ({
+ sqlEditorLogic: Object.assign(
+ jest.fn(() => ({ mount: jest.fn(() => jest.fn()) })),
+ { findMounted: jest.fn(() => mockEditorLogic) }
+ ),
+}))
+
+jest.mock('./generated/api', () => ({
+ endpointsMaterializationSuggestionCreate: jest.fn(),
}))
jest.mock('./endpointsLogic', () => ({
@@ -121,4 +146,63 @@ describe('endpointSceneLogic', () => {
version: 2,
})
})
+
+ describe('materialization suggestion', () => {
+ const hogqlEndpoint = {
+ ...endpoint,
+ query: { kind: 'HogQLQuery', query: 'SELECT count() FROM events WHERE 1 = 1 OR 0 = 1' },
+ }
+ const suggestion = {
+ suggestion_status: 'ok',
+ suggested_query: 'SELECT count() FROM events',
+ explanation: 'Dropped the redundant OR branch.',
+ attempts: 1,
+ error: null,
+ original_reason: 'Variables in OR conditions are not supported for materialization',
+ }
+
+ it('applies the suggestion to the latest-version editor even when the cached editor tab is stale', async () => {
+ logic.actions.loadEndpointSuccess(hogqlEndpoint)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadMaterializationSuggestionSuccess(suggestion as any)
+
+ logic.cache.sqlEditorTabId = 'endpoint-query-2'
+ logic.actions.applyMaterializationSuggestion()
+
+ expect((sqlEditorLogic as any).findMounted).toHaveBeenCalledWith(
+ expect.objectContaining({ tabId: 'endpoint-query-latest' })
+ )
+ expect(mockEditorLogic.actions.setSuggestedQueryInput).toHaveBeenCalledWith(
+ suggestion.suggested_query,
+ 'materialization_fix'
+ )
+ })
+
+ it('does nothing without a validated suggestion', async () => {
+ logic.actions.loadEndpointSuccess(hogqlEndpoint)
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.applyMaterializationSuggestion()
+
+ expect((sqlEditorLogic as any).findMounted).not.toHaveBeenCalled()
+ expect(mockEditorLogic.actions.setSuggestedQueryInput).not.toHaveBeenCalled()
+ })
+
+ it('reuses the cached suggestion on reopen and only re-requests on regenerate', async () => {
+ ;(endpointsMaterializationSuggestionCreate as jest.Mock).mockResolvedValue(suggestion)
+ logic.actions.loadEndpointSuccess(hogqlEndpoint)
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openMaterializationSuggestionModal()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.closeMaterializationSuggestionModal()
+ logic.actions.openMaterializationSuggestionModal()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(endpointsMaterializationSuggestionCreate).toHaveBeenCalledTimes(1)
+
+ logic.actions.regenerateMaterializationSuggestion()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(endpointsMaterializationSuggestionCreate).toHaveBeenCalledTimes(2)
+ })
+ })
})
diff --git a/products/endpoints/frontend/endpointSceneLogic.tsx b/products/endpoints/frontend/endpointSceneLogic.tsx
index 7d5247180c04..a66e04eeeef3 100644
--- a/products/endpoints/frontend/endpointSceneLogic.tsx
+++ b/products/endpoints/frontend/endpointSceneLogic.tsx
@@ -2,19 +2,29 @@ import { actions, connect, events, kea, listeners, path, reducers, selectors } f
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
-import api from 'lib/api'
+import api, { ApiConfig } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
-import { DataTableNode, EndpointRunRequest, InsightVizNode, Node, NodeKind } from '~/queries/schema/schema-general'
+import {
+ DataTableNode,
+ DataVisualizationNode,
+ EndpointRunRequest,
+ InsightVizNode,
+ Node,
+ NodeKind,
+} from '~/queries/schema/schema-general'
import { isHogQLQuery, isInsightQueryNode } from '~/queries/utils'
-import { Breadcrumb, EndpointType, EndpointVersionType } from '~/types'
+import { Breadcrumb, ChartDisplayType, EndpointType, EndpointVersionType } from '~/types'
import { endpointLogic } from './endpointLogic'
import type { endpointSceneLogicType } from './endpointSceneLogicType'
+import { endpointsMaterializationSuggestionCreate } from './generated/api'
+import type { EndpointMaterializationSuggestionApi } from './generated/api.schemas'
// Default data freshness when none is set on the endpoint version (must match backend DEFAULT_DATA_FRESHNESS_SECONDS)
const DEFAULT_DATA_FRESHNESS_SECONDS = 86400
@@ -141,6 +151,10 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([
loadMaterializationPreview: true,
keepSqlEditorMounted: (editorTabId: string) => ({ editorTabId }),
toggleMaterializationFromMenu: true,
+ openMaterializationSuggestionModal: true,
+ closeMaterializationSuggestionModal: true,
+ regenerateMaterializationSuggestion: true,
+ applyMaterializationSuggestion: true,
}),
reducers({
localQuery: [
@@ -240,8 +254,39 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([
loadEndpoint: () => null,
},
],
+ materializationSuggestionModalOpen: [
+ false,
+ {
+ openMaterializationSuggestionModal: () => true,
+ closeMaterializationSuggestionModal: () => false,
+ loadEndpoint: () => false,
+ },
+ ],
+ // Cached across modal open/close (each request is a full LLM round-trip); cleared when
+ // switching endpoints or when the endpoint is updated (the saved query may have changed)
+ materializationSuggestion: [
+ null as EndpointMaterializationSuggestionApi | null,
+ {
+ loadEndpoint: () => null,
+ updateEndpointSuccess: () => null,
+ },
+ ],
}),
loaders(({ values }) => ({
+ materializationSuggestion: {
+ __default: null as EndpointMaterializationSuggestionApi | null,
+ loadMaterializationSuggestion: async () => {
+ const endpoint = values.endpoint
+ if (!endpoint?.name) {
+ return null
+ }
+ return await endpointsMaterializationSuggestionCreate(
+ String(ApiConfig.getCurrentTeamId()),
+ endpoint.name,
+ {}
+ )
+ },
+ },
materializationPreview: {
__default: null as MaterializationPreview | null,
loadMaterializationPreview: async () => {
@@ -285,6 +330,15 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([
viewingVersion: EndpointVersionType | null
): Node | null => localQuery || viewingVersion?.query || endpoint?.query || null,
],
+ suggestionMatchesCurrentQuery: [
+ (s) => [s.materializationSuggestion, s.currentQuery],
+ (suggestion: EndpointMaterializationSuggestionApi | null, currentQuery: Node | null): boolean => {
+ if (!suggestion?.suggested_query || !currentQuery || !isHogQLQuery(currentQuery)) {
+ return false
+ }
+ return suggestion.suggested_query.trim() === (currentQuery.query || '').trim()
+ },
+ ],
queryToRender: [
(s) => [s.currentQuery],
(currentQuery: Node | null): Node | null => {
@@ -390,6 +444,58 @@ export const endpointSceneLogic = kea<endpointSceneLogicType>([
setBucketOverride: () => {
actions.loadMaterializationPreview()
},
+ openMaterializationSuggestionModal: () => {
+ // Reuse a cached suggestion — the saved query can't have changed while it's valid
+ // (updates clear it), and each request is a full LLM round-trip
+ if (!values.materializationSuggestion && !values.materializationSuggestionLoading) {
+ actions.loadMaterializationSuggestion()
+ }
+ },
+ regenerateMaterializationSuggestion: () => {
+ actions.loadMaterializationSuggestion()
+ },
+ applyMaterializationSuggestion: () => {
+ const suggestion = values.materializationSuggestion
+ const current = values.currentQuery
+ if (!suggestion?.suggested_query || !current || !isHogQLQuery(current)) {
+ return
+ }
+ if (values.suggestionMatchesCurrentQuery) {
+ lemonToast.info('Your query already matches the suggestion — nothing to apply')
+ actions.closeMaterializationSuggestionModal()
+ return
+ }
+
+ actions.setActiveTab(EndpointTab.QUERY)
+ if (values.endpoint?.name) {
+ const { searchParams, hashParams } = router.values
+ const { tab: _tab, ...nextSearchParams } = searchParams
+ router.actions.replace(urls.endpoint(values.endpoint.name), nextSearchParams, hashParams)
+ }
+
+ // Always target the latest version's editor: apply is only reachable on the latest
+ // version, and cache.sqlEditorTabId can still point at an old version's editor when
+ // the Query tab was last mounted while browsing that version.
+ const editorTabId = 'endpoint-query-latest'
+ actions.keepSqlEditorMounted(editorTabId)
+ const editorLogic = sqlEditorLogic.findMounted({ tabId: editorTabId, mode: SQLEditorMode.Embedded })
+
+ // If the editor was never initialized (e.g. the user came straight to Configuration and
+ // the Query tab never mounted), seed it with the saved query first so the suggestion
+ // always renders as an accept/reject diff. The seeded state also keeps the query tab's
+ // init effect from re-initializing and clobbering the diff.
+ if (editorLogic && !editorLogic.values.queryInput?.trim()) {
+ editorLogic.actions.setQueryInput(current.query || '')
+ editorLogic.actions.setSourceQuery({
+ kind: NodeKind.DataVisualizationNode,
+ source: { ...current },
+ display: ChartDisplayType.ActionsLineGraph,
+ } as DataVisualizationNode)
+ }
+ editorLogic?.actions.setSuggestedQueryInput(suggestion.suggested_query, 'materialization_fix')
+ lemonToast.success('Review the suggested changes in the editor — accept to apply them')
+ actions.closeMaterializationSuggestionModal()
+ },
toggleMaterializationFromMenu: () => {
if (!values.endpoint?.name) {
return
diff --git a/products/endpoints/package.json b/products/endpoints/package.json
index 6ab21a6125b4..ab47613e3525 100644
--- a/products/endpoints/package.json
+++ b/products/endpoints/package.json
@@ -10,6 +10,9 @@
"kea-loaders": "catalog:",
"kea-router": "catalog:"
},
+ "devDependencies": {
+ "@storybook/react": "catalog:"
+ },
"peerDependencies": {
"@posthog/icons": "catalog:",
"@types/react": "*",