: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(hogql): offer a fix for a filter that cannot use its index (#93460)
George Munyorof40506483157
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex aca401abfaba..e2ca91e031cf 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7985,9 +7985,65 @@ snapshots:scenes-app-data-warehouse-query-index-usage--refreshing-after-an-edit--light:hash: v1.k794b7964.f78066e01a69667a48e1e869c1c68dd0b741dcc49b6ef524bef7d4d86ddc95dd.Hm8P3Va8Xi--tajenCleRBUZ6Y813IyfCzm9_huabH4scenes-app-data-warehouse-query-index-usage--some-filters-scan--dark:- hash: v1.k794b7964.0294ddfda0b0e43413c60dbde62d947c90c6ae72ad995763c8fa4c20c864a404.KdjhHgnYl1jq1yo8C4tTH79O-M1MefHWEB1V_f-5wxY+ hash: v1.k794b7964.5455f3ec94016b7fc41aa9aeb676045f8af0c111502a992e9c0cbebbfc1e23a4.ZIL0-eH98MqVTxMkOZzHd2EgWcq2cfdWq-cqoDoHhFQscenes-app-data-warehouse-query-index-usage--some-filters-scan--light:- hash: v1.k794b7964.992eb504adc18600876c965dea224ae77f277d1fd8033784813d20187b42a497.jgO2O4E-p2e97zY9OrOO6NnZrllkBdAuuFrskzGR9d4+ hash: v1.k794b7964.bcac8e0feee869559ac8b967bda19961ffcfedb0f908252dd16f6dcee8c1d2cf.J0yf0nXwig_U_JZmQxzmkP2xBwlkXhz9RrMn925Rx0s+ scenes-app-data-warehouse-query-index-usage-fix-actions--edit-property-type--narrow--dark:+ hash: v1.k794b7964.07c09dbb4f5cd4acf0f486767d927a02b584068da48f6c688a15ca7693841006.u5S5dlEoj3L9UAwxS4EoL-lv3LuF1S-xxNJdvaXU-Hk+ scenes-app-data-warehouse-query-index-usage-fix-actions--edit-property-type--narrow--light:+ hash: v1.k794b7964.c5cd8e4cdc7960a45ef83c9fa892a63ec87c6fe8fa458172e76dabdd96830210.357c4u3hc_XeM2Rk-Du6PnaahoovY2KqRtrK4G19hnM+ scenes-app-data-warehouse-query-index-usage-fix-actions--edit-property-type--wide--dark:+ hash: v1.k794b7964.07c09dbb4f5cd4acf0f486767d927a02b584068da48f6c688a15ca7693841006.9P7uZkGgUQ8CTzpH-Fm3VfVxV5ypjpwL5wyCbLrLonw+ scenes-app-data-warehouse-query-index-usage-fix-actions--edit-property-type--wide--light:+ hash: v1.k794b7964.c5cd8e4cdc7960a45ef83c9fa892a63ec87c6fe8fa458172e76dabdd96830210.X70Tjs6A9yBt3BlxgTADLgtJjf51K1XGXA40JR3ZHiY+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai--narrow--dark:+ hash: v1.k794b7964.129f5a8f04bab0bf3a7ff3c451c780170677e7fa102996b17c7d0d95b025ce93.VG-WexiEYINwnQZ7yzZ4oavLgRfrlCSMNBRrrPy-YjE+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai--narrow--light:+ hash: v1.k794b7964.5d210cf62fe6096ce928dc075b2ac02b4d9fd22400349cb85c2db03ecbaf1ab4.vrBKnLEesy4pEewfiwrouN4UGhpcj1vVL2dkbCDqNag+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai--wide--dark:+ hash: v1.k794b7964.129f5a8f04bab0bf3a7ff3c451c780170677e7fa102996b17c7d0d95b025ce93.ihMM-vpHvTBkF7hBvHRRKp23hKA6eoU6FsBc3uz_Ud0+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai--wide--light:+ hash: v1.k794b7964.5d210cf62fe6096ce928dc075b2ac02b4d9fd22400349cb85c2db03ecbaf1ab4.AwQXCvE_uVvqtMS2NXZ-Q-959WxY_AeMxza9enC_Ir0+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai-in-flight--narrow--dark:+ hash: v1.k794b7964.305932bb81c03c2cdcd50344bef3b3f10a23c2a9bba2e71481b0f425b5f917a4.D31ixi-FNm9KLxxL4ZqE84sTwjNujkylOH2nZAjTvHY+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai-in-flight--narrow--light:+ hash: v1.k794b7964.c3c31421caa6c90a9d0e44624b5daad0e56aa25ed5b395d84936c3d0656f1846.cai-hOPrHjTzwbKGISG_4mpp1nMZDJ5DJNZTJ0f7-KQ+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai-in-flight--wide--dark:+ hash: v1.k794b7964.305932bb81c03c2cdcd50344bef3b3f10a23c2a9bba2e71481b0f425b5f917a4.xDxvlwDpLo_yBN9ca6eFl_Ghewwb7vdX6ZGCaAy7Cn8+ scenes-app-data-warehouse-query-index-usage-fix-actions--fix-with-ai-in-flight--wide--light:+ hash: v1.k794b7964.c3c31421caa6c90a9d0e44624b5daad0e56aa25ed5b395d84936c3d0656f1846.9NKp1q3P6YAJcqEimBUSWNleVxs0VJ2_5FCIQ5j64Vs+ scenes-app-data-warehouse-query-index-usage-fix-actions--materialize-the-property--narrow--dark:+ hash: v1.k794b7964.3388f2c6685de0db912a7d9f51ed318c2940945ea550b4225534840e048acef8.6W5mNEiCpA8NZo68KRINhZJ4K4z91Sp4KUe39cSmbDw+ scenes-app-data-warehouse-query-index-usage-fix-actions--materialize-the-property--narrow--light:+ hash: v1.k794b7964.985c2680606f21ee56742beaf9d340cdabd21186e34ab1b3f09ba119ccb54124.4bIqTqRebCZikmbChjoO919X6avFwUufGDtcJ2i63wI+ scenes-app-data-warehouse-query-index-usage-fix-actions--materialize-the-property--wide--dark:+ hash: v1.k794b7964.4a1dfc953a38485a8e5a908656c4560c5db4d832a4d7fe75cddb9db59b59c261.h1sokZnYhgsWHOI_uyrO06QaDkZplajDTRv1WBkngMQ+ scenes-app-data-warehouse-query-index-usage-fix-actions--materialize-the-property--wide--light:+ hash: v1.k794b7964.82e4f53821c90d68525833a87a19e9d3e57b71c597ae24144017781375e9b025.3xty0MH2XsENRGz3vDG2UbgqA7np7a-0AygNTVo6Qic+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-literal--narrow--dark:+ hash: v1.k794b7964.ec1266fa88ec3b206edd1dc10bb8f2493f15310eadfc311700bdac2d5907a8df.B9-Uf7Aj-IE2H_5VV7ox1LmMe85xl1k_2IYd246sb1g+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-literal--narrow--light:+ hash: v1.k794b7964.0984b29a92dec4292578961c2e749c76ba189b5cdca5d78de5f63655c73aa496.tBYn0nROq6TpTtOaoUXhUzLLCu5BoYLhWcDXvt9x6r4+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-literal--wide--dark:+ hash: v1.k794b7964.ec1266fa88ec3b206edd1dc10bb8f2493f15310eadfc311700bdac2d5907a8df.oMDGr1XqHl0ulHOJlMD4QAFf9Z9R56eEFfk2op1aIrE+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-literal--wide--light:+ hash: v1.k794b7964.0984b29a92dec4292578961c2e749c76ba189b5cdca5d78de5f63655c73aa496.KqHKrhzmPilGuq71__e9P7GlLS2maqlggjpO-2-iNwY+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-long-list--narrow--dark:+ hash: v1.k794b7964.49ef5b68221d192da35c9bf28cb0b94e4857346a0b0418115ce7ea503cef1719.zNP-SATX-oFmf12gOIrpU3BVgcWFN1hwt3kT_MRY6ug+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-long-list--narrow--light:+ hash: v1.k794b7964.c0b356e0379498adf204a0f3987cb7d9431266b09cf53428af63b87e1701cb88.TsoINYRxHPJTk5KKJj1iHAnmI6g3fXNgva2ULJIkxEY+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-long-list--wide--dark:+ hash: v1.k794b7964.49ef5b68221d192da35c9bf28cb0b94e4857346a0b0418115ce7ea503cef1719.5SxQGuu1kqZcssaWU9A8tSCnOkp4mw9iY_mkWVy2jeY+ scenes-app-data-warehouse-query-index-usage-fix-actions--replace-a-long-list--wide--light:+ hash: v1.k794b7964.c0b356e0379498adf204a0f3987cb7d9431266b09cf53428af63b87e1701cb88.I2RrWc6bj_o1vfxtVb5lV66V7B-iSj3CBnoCv0HEBus+ scenes-app-data-warehouse-query-index-usage-fix-actions--report-still-catching-up--narrow--dark:+ hash: v1.k794b7964.d8a99a7d7bcfe36920f9d8173ae8f480b93997229c986f058768b5eddeb5474c.v3M8UmDRYXlwLxi9x6eH1ywi2rc-XIfwFky3Or-dYFY+ scenes-app-data-warehouse-query-index-usage-fix-actions--report-still-catching-up--narrow--light:+ hash: v1.k794b7964.0c5a2526511088eca0ef17402714414283b393d4ca94fb375a3f63f32e13999a.u3X41bZMJZVfEmgIXYDA2Yw3nANF1iXMW9nxnA73al4+ scenes-app-data-warehouse-query-index-usage-fix-actions--report-still-catching-up--wide--dark:+ hash: v1.k794b7964.d8a99a7d7bcfe36920f9d8173ae8f480b93997229c986f058768b5eddeb5474c.RfV4yI1Hovb47bR9_HJMKzYxTqZJJfFjz2MkCzoWP-s+ scenes-app-data-warehouse-query-index-usage-fix-actions--report-still-catching-up--wide--light:+ hash: v1.k794b7964.0c5a2526511088eca0ef17402714414283b393d4ca94fb375a3f63f32e13999a.Am5ahhnXBQ0aZ3GyFwRzL_3wes-0XTj4uS5pw4WAJCYscenes-app-data-warehouse-settings-api-version-deprecation-banner--with-sunset-date--dark:hash: v1.k794b7964.5a4d9d3ac30fd4e7a83925bb77a89685f5ad1b95e44431dc87696251acd62941.STCVyoJPmpKL8izqztWRz12VuY1AJPSbVh74dSG4k4Uscenes-app-data-warehouse-settings-api-version-deprecation-banner--with-sunset-date--light:diff --git a/frontend/src/lib/monaco/codeEditorLogic.tsx b/frontend/src/lib/monaco/codeEditorLogic.tsxindex 095162620c8b..a8f84cfe793e 100644--- a/frontend/src/lib/monaco/codeEditorLogic.tsx+++ b/frontend/src/lib/monaco/codeEditorLogic.tsx@@ -26,6 +26,7 @@ import {import { setLatestVersionsOnQuery } from '~/queries/utils'import type { FeatureFlagsSet } from '../logic/featureFlagLogic'+import { characterOffsetToUtf16 } from './offsets'import { getContextSourceQuery } from './sourceQueryUtils'const METADATA_LANGUAGES = [HogLanguage.hog, HogLanguage.hogQL, HogLanguage.hogQLExpr, HogLanguage.hogTemplate]@@ -212,8 +213,14 @@ export const codeEditorLogic = kea<codeEditorLogicType>([const markerOffset = props.metadataQueryOffset ?? 0function noticeToMarker(error: HogQLNotice, severity: MarkerSeverity): ModelMarker {- const start = model!.getPositionAt((error.start ?? 0) + markerOffset)- const end = model!.getPositionAt((error.end ?? query.length) + markerOffset)+ // Notice offsets count characters, so they need converting to the UTF-16+ // units Monaco addresses before they can locate anything in the model.+ const start = model!.getPositionAt(+ characterOffsetToUtf16(query, error.start ?? 0) + markerOffset+ )+ const end = model!.getPositionAt(+ characterOffsetToUtf16(query, error.end ?? query.length) + markerOffset+ )return {start: error.start ?? 0,startLineNumber: start.lineNumber,diff --git a/frontend/src/lib/monaco/hogQLMetadataProvider.test.ts b/frontend/src/lib/monaco/hogQLMetadataProvider.test.tsindex 160c4ef90a9e..07d85db28a10 100644--- a/frontend/src/lib/monaco/hogQLMetadataProvider.test.ts+++ b/frontend/src/lib/monaco/hogQLMetadataProvider.test.ts@@ -15,14 +15,30 @@ describe('hogQLMetadataProvider', () => {return starts}- const codeActionsAt = (markers: ModelMarker[], activeMarker: ModelMarker): languagesCodeAction[] => {- const starts = lineStarts(SCRIPT)+ const MODEL_VERSION = 7++ const codeActionsAt = (+ markers: ModelMarker[],+ activeMarker: ModelMarker,+ { metadataLoading = false, modelText = SCRIPT }: { metadataLoading?: boolean; modelText?: string } = {}+ ): languagesCodeAction[] => {+ const starts = lineStarts(modelText)const model = {uri: 'inmemory://model/1',- codeEditorLogic: { isMounted: () => true, values: { modelMarkers: markers } },+ codeEditorLogic: {+ isMounted: () => true,+ props: { metadataQueryOffset: SECOND_STATEMENT_OFFSET },+ values: {+ modelMarkers: markers,+ metadataLoading,+ // The metadata query covered the second statement.+ metadata: [SCRIPT.slice(SECOND_STATEMENT_OFFSET), {}],+ },+ },getOffsetAt: ({ lineNumber, column }: { lineNumber: number; column: number }) =>starts[lineNumber - 1] + column - 1,- getValue: () => SCRIPT,+ getValue: () => modelText,+ getVersionId: () => MODEL_VERSION,}const result = hogQLMetadataProvider().provideCodeActions?.(model as any,@@ -35,6 +51,7 @@ describe('hogQLMetadataProvider', () => {interface languagesCodeAction {title: string+ edit?: { edits: { versionId?: number }[] }}// `event = 'pageview'` sits in the second statement. Its statement-relative offsets are small,@@ -59,6 +76,21 @@ describe('hogQLMetadataProvider', () => {const actions = codeActionsAt([marker], marker)expect(actions.map((action) => action.title)).toEqual(["Replace with: '$pageview'"])+ expect(actions[0].edit?.edits[0].versionId).toEqual(MODEL_VERSION)+ })++ // Typing before the analyzed statement shifts the text under the stored marker range, and a+ // refresh in flight means the stored ranges are about to be replaced. Either way the offered+ // edit would land on the wrong text.+ it.each([+ ['metadata is still loading', { metadataLoading: true }],+ ['the model text has moved on from the analyzed text', { modelText: ` ${SCRIPT}` }],+ ])('offers nothing when %s', (_, options) => {+ const marker = taxonomyMarker()++ const actions = codeActionsAt([marker], marker, options)++ expect(actions).toEqual([])})it('does not offer a quick fix when the caret is on an unrelated marker', () => {diff --git a/frontend/src/lib/monaco/hogQLMetadataProvider.tsx b/frontend/src/lib/monaco/hogQLMetadataProvider.tsxindex 2a5c046ff7a3..a7a66e19c110 100644--- a/frontend/src/lib/monaco/hogQLMetadataProvider.tsx+++ b/frontend/src/lib/monaco/hogQLMetadataProvider.tsx@@ -7,6 +7,19 @@ export const hogQLMetadataProvider: () => languages.CodeActionProvider = () => (provideCodeActions: (model, _range, context) => {const logic: BuiltLogic<codeEditorLogicType> | undefined = (model as any).codeEditorLogicif (logic?.isMounted()) {+ // The stored marker ranges describe the text the server analyzed. Monaco shifts the+ // markers it reports as the user types, but the stored ranges do not move, so applying+ // one would rewrite whatever now sits at the old position. Offer nothing until a report+ // for the current text is in.+ const analyzed = logic.values.metadata?.[0]+ const analyzedOffset = logic.props.metadataQueryOffset ?? 0+ if (+ logic.values.metadataLoading ||+ analyzed === undefined ||+ model.getValue().slice(analyzedOffset, analyzedOffset + analyzed.length) !== analyzed+ ) {+ return { actions: [], dispose: () => {} }+ }// Monaco gives us a list of markers that we're looking at, but without the quick fixes.const markersFromMonaco = context.markers// We have a list of _all_ markers returned from the HogQL metadata query@@ -54,7 +67,9 @@ export const hogQLMetadataProvider: () => languages.CodeActionProvider = () => (range: rawMarker,text: rawMarker.hogQLFix,},- versionId: undefined,+ // Monaco refuses the edit if the model changed after the+ // action was offered, which the checks above cannot cover.+ versionId: model.getVersionId(),},],},diff --git a/frontend/src/lib/monaco/offsets.test.ts b/frontend/src/lib/monaco/offsets.test.tsnew file mode 100644index 000000000000..e97e81bd892d--- /dev/null+++ b/frontend/src/lib/monaco/offsets.test.ts@@ -0,0 +1,36 @@+import { characterOffsetToUtf16 } from './offsets'++describe('characterOffsetToUtf16', () => {+ const QUERY = "SELECT '😀', count() FROM events WHERE properties.$browser_version = 120"++ it('leaves offsets untouched when every character is one code unit', () => {+ const plain = 'SELECT 1 FROM events'+ expect(characterOffsetToUtf16(plain, 7)).toBe(7)+ })++ it('shifts an offset that follows an emoji so it selects the intended text', () => {+ // The parser reports the literal at its character offset; reading that offset as UTF-16+ // selects ' 12' instead of '120', so a replacement produces ='120'0.+ const characterOffset = Array.from(QUERY).indexOf('1')+ const utf16Offset = characterOffsetToUtf16(QUERY, characterOffset)++ expect(QUERY.slice(characterOffset, characterOffset + 3)).toBe(' 12')+ expect(QUERY.slice(utf16Offset, utf16Offset + 3)).toBe('120')+ })++ it.each([+ ['before the emoji', 3],+ ['at the emoji', 8],+ ['after two emoji', 12],+ ])('round-trips a character offset %s', (_name: string, characterOffset: number) => {+ const text = "a😀b😀c '120'"+ const characters = Array.from(text)+ const utf16Offset = characterOffsetToUtf16(text, characterOffset)++ expect(text.slice(utf16Offset)).toBe(characters.slice(characterOffset).join(''))+ })++ it('clamps an offset past the end of the text', () => {+ expect(characterOffsetToUtf16('abc', 99)).toBe(3)+ })+})diff --git a/frontend/src/lib/monaco/offsets.ts b/frontend/src/lib/monaco/offsets.tsnew file mode 100644index 000000000000..e26dec1f9548--- /dev/null+++ b/frontend/src/lib/monaco/offsets.ts@@ -0,0 +1,28 @@+const SURROGATE = /[\uD800-\uDBFF]/++/**+ * The HogQL parser counts characters, Monaco counts UTF-16 code units.+ *+ * They agree until a query holds a character outside the Basic Multilingual Plane. An emoji is one+ * character to Python and two code units to Monaco, so every offset after it points one unit short+ * per emoji, and a marker or a replacement lands in the wrong place.+ *+ * Convert against the exact text the offset was measured in, which is the statement the server+ * analyzed rather than the whole editor, then add that statement's own offset.+ */+export function characterOffsetToUtf16(text: string, characterOffset: number): number {+ // Without a surrogate pair the two counts agree, which is every SQL query that holds no emoji.+ // Skipping the scan keeps this off the hot path, since it runs twice per marker on every+ // metadata response.+ if (!SURROGATE.test(text)) {+ return Math.min(characterOffset, text.length)+ }+ let utf16Offset = 0+ let characters = 0+ while (characters < characterOffset && utf16Offset < text.length) {+ // A code point above 0xffff is stored as a surrogate pair, which is two units to Monaco.+ utf16Offset += (text.codePointAt(utf16Offset) ?? 0) > 0xffff ? 2 : 1+ characters += 1+ }+ return utf16Offset+}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 8058498a8ead..2526cd98e906 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -39555,10 +39555,18 @@"enum": ["pending", "in_progress", "completed"],"type": "string"},+ "PredicateFixAction": {+ "enum": ["edit_query", "edit_property_type", "materialize"],+ "type": "string"+ },"PredicateIndexUsage": {"additionalProperties": false,"description": "How one property filter in the query reads its data, decided before the query runs.","properties": {+ "ai_fix_prompt": {+ "description": "Instruction for an AI rewrite of the query, set when a query edit would help.",+ "type": "string"+ },"column_name": {"type": "string"},@@ -39566,8 +39574,12 @@"$ref": "#/definitions/integer"},"fix": {+ "description": "Prose advice for a reader.","type": "string"},+ "fix_action": {+ "$ref": "#/definitions/PredicateFixAction"+ },"message": {"type": "string"},@@ -39582,6 +39594,10 @@"property_name": {"type": "string"},+ "quickfix": {+ "$ref": "#/definitions/PredicateQuickfix",+ "description": "A deterministic query edit that unblocks the index."+ },"scope": {"$ref": "#/definitions/PredicateScope"},@@ -39624,6 +39640,25 @@"enum": ["indexed", "blocked", "unindexed_column", "unindexed_json", "operator_not_indexable"],"type": "string"},+ "PredicateQuickfix": {+ "additionalProperties": false,+ "properties": {+ "end": {+ "$ref": "#/definitions/integer",+ "description": "Character offset in the query where the replaced range ends."+ },+ "start": {+ "$ref": "#/definitions/integer",+ "description": "Character offset in the query where the replaced range starts."+ },+ "text": {+ "description": "Replacement text, substituted for the range verbatim.",+ "type": "string"+ }+ },+ "required": ["start", "end", "text"],+ "type": "object"+ },"PredicateScope": {"enum": ["event", "person", "group", "unknown"],"type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 08713d041e72..c5b52f5dd63f 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -869,6 +869,24 @@ export enum PredicateScope {Unknown = 'unknown',}+export enum PredicateFixAction {+ /** A query edit unblocks an index that already exists. */+ EditQuery = 'edit_query',+ /** The property definition declares a type its stored values do not have. */+ EditPropertyType = 'edit_property_type',+ /** The property has no dedicated column to index. */+ Materialize = 'materialize',+}++export interface PredicateQuickfix {+ /** Character offset in the query where the replaced range starts. */+ start: integer+ /** Character offset in the query where the replaced range ends. */+ end: integer+ /** Replacement text, substituted for the range verbatim. */+ text: string+}+/** How one property filter in the query reads its data, decided before the query runs. */export interface PredicateIndexUsage {property_name: string@@ -886,7 +904,13 @@ export interface PredicateIndexUsage {usable_indexes: string[]verdict: PredicateIndexVerdictmessage: string+ /** Prose advice for a reader. */fix?: string+ fix_action?: PredicateFixAction+ /** Instruction for an AI rewrite of the query, set when a query edit would help. */+ ai_fix_prompt?: string+ /** A deterministic query edit that unblocks the index. */+ quickfix?: PredicateQuickfixstart?: integerend?: integer}diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsxindex 9ef50fe0d0b7..8881d955f840 100644--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx@@ -95,6 +95,7 @@ import {} from '../../../queries/nodes/DataTable/clipboardUtils'import { EditorQueryScanBanner } from './components/EditorQueryScanBanner'import { FixErrorButton } from './components/FixErrorButton'+import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'import { QueryIndexUsageBar } from './output-pane-tabs/QueryIndexUsageBar'import { OutputTab, outputPaneLogic } from './outputPaneLogic'import { sqlEditorLogic } from './sqlEditorLogic'@@ -623,9 +624,18 @@ export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareTconst { activeTab } = useValues(outputPaneLogic)const { setActiveTab } = useActions(outputPaneLogic)- const { sourceQuery, exportContext, insightLoading, hasQueryInput, isEmbeddedMode, metadata, metadataLoading } =- useValues(sqlEditorLogic)- const { setSourceQuery } = useActions(sqlEditorLogic)+ const {+ sourceQuery,+ exportContext,+ insightLoading,+ hasQueryInput,+ isEmbeddedMode,+ metadata,+ metadataLoading,+ indexReportStale,+ } = useValues(sqlEditorLogic)+ const { setSourceQuery, applyIndexQuickfix, fixIndexUsageWithAI } = useActions(sqlEditorLogic)+ const { responseLoading: fixWithAILoading } = useValues(fixSQLErrorsLogic)const { isDarkModeOn } = useValues(themeLogic)const {response: dataNodeResponse,@@ -946,7 +956,14 @@ export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareTreturn (<div className="OutputPane flex flex-col w-full flex-1 min-h-0 bg-white dark:bg-black">- <QueryIndexUsageBar predicates={metadata?.index_usage ?? []} refreshing={metadataLoading} />+ <QueryIndexUsageBar+ predicates={metadata?.index_usage ?? []}+ refreshing={metadataLoading}+ stale={indexReportStale}+ onApplyQuickfix={applyIndexQuickfix}+ onFixWithAI={fixIndexUsageWithAI}+ fixWithAILoading={fixWithAILoading}+ />{outputContent}<div className="flex justify-between px-2 border-t"><div>{response && !responseError ? <LoadPreviewText localResponse={response} /> : <></>}</div>diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex 2c220bc4dbe3..c559addf6c7a 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -121,7 +121,7 @@ export function QueryWindow({} = useActions(logic)const { setEditorView } = useActions(biLogic)- const { setSuggestedQueryInput, reportAIQueryPromptOpen } = useActions(logic)+ const { setSuggestedQueryInput, reportAIQueryPromptOpen, fixIndexUsageWithAI } = useActions(logic)const biModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_BI_MODE')const vimModeFeatureEnabled = useFeatureFlag('SQL_EDITOR_VIM_MODE')const { editorVimModeEnabled } = useValues(userPreferencesLogic)@@ -377,6 +377,7 @@ export function QueryWindow({// that mounts against an existing model never runs that path, and would then// ask for metadata without the index report.indexUsage: true,+ onFixWithAI: (prompt) => fixIndexUsageWithAI(prompt),onChange: (v) => {setQueryInput(v ?? '')},diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.stories.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.stories.tsxindex 87b8fecc1596..dea1d60af2e4 100644--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.stories.tsx@@ -1,6 +1,11 @@import type { Meta, StoryObj } from '@storybook/react'-import { PredicateIndexUsage, PredicateIndexVerdict, PredicateScope } from '~/queries/schema/schema-general'+import {+ PredicateFixAction,+ PredicateIndexUsage,+ PredicateIndexVerdict,+ PredicateScope,+} from '~/queries/schema/schema-general'import { QueryIndexUsageBar } from './QueryIndexUsageBar'@@ -23,7 +28,8 @@ const PREDICATES: PredicateIndexUsage[] = [physical_type: 'String',usable_indexes: ['bloom_filter'],verdict: PredicateIndexVerdict.Indexed,- message: "Event property '$browser' uses its bloom filter index, so this filter skips rows that cannot match.",+ message:+ "Event property '$browser' has a bloom filter index that covers this comparison. How much data it skips depends on how the values are spread across the table.",},{property_name: 'duration',@@ -37,7 +43,27 @@ const PREDICATES: PredicateIndexUsage[] = [verdict: PredicateIndexVerdict.Blocked,message:"Event property 'duration' is stored as String but compared as Float, so every row is converted before the filter runs and the index on 'duration' cannot skip any data.",- fix: "If 'duration' is not really Float, correct its type in data management. Otherwise add a filter that can skip data, such as a date range on timestamp.",+ fix: "If 'duration' does not really hold a number, correct its type in data management.",+ fix_action: PredicateFixAction.EditPropertyType,+ },+ {+ property_name: '$browser_version',+ scope: PredicateScope.Event,+ operator: '==',+ source_label: 'materialized column',+ column_name: 'mat_$browser_version',+ semantic_type: 'String',+ physical_type: 'String',+ usable_indexes: [],+ verdict: PredicateIndexVerdict.Blocked,+ message:+ "Event property '$browser_version' is compared against a value of another type, so every row has to be converted and the index on '$browser_version' goes unused.",+ fix: "Write the value as text: '120'.",+ fix_action: PredicateFixAction.EditQuery,+ ai_fix_prompt: "Rewrite this filter so '$browser_version' is compared against a String value.",+ quickfix: { start: 58, end: 61, text: "'120'" },+ start: 33,+ end: 61,},{property_name: 'plan_tier',@@ -52,6 +78,7 @@ const PREDICATES: PredicateIndexUsage[] = [message:"Person property 'plan_tier' is read out of the properties JSON on every row, with no index to skip data.",fix: "Materialize 'plan_tier' so this filter reads a dedicated column instead of parsing the JSON.",+ fix_action: PredicateFixAction.Materialize,},{property_name: '$current_url',@@ -71,7 +98,7 @@ const PREDICATES: PredicateIndexUsage[] = [export const SomeFiltersScan: Story = {render: () => (<div className="max-w-3xl">- <QueryIndexUsageBar predicates={PREDICATES} />+ <QueryIndexUsageBar predicates={PREDICATES} onApplyQuickfix={() => {}} onFixWithAI={() => {}} /></div>),}diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.tsxindex 47f2666efc9d..51223e30fcbb 100644--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.tsx+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.tsx@@ -4,7 +4,7 @@ import { IconInfo, IconWarning } from '@posthog/icons'import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'-import { PredicateIndexUsage, PredicateIndexVerdict } from '~/queries/schema/schema-general'+import { PredicateIndexUsage, PredicateIndexVerdict, PredicateQuickfix } from '~/queries/schema/schema-general'import { QueryIndexUsageTable } from './QueryIndexUsageTable'@@ -30,9 +30,21 @@ interface QueryIndexUsageBarProps {predicates: PredicateIndexUsage[]/** A refresh is in flight, so the report still describes the SQL the server last saw. */refreshing?: boolean+ /** The report does not describe the text the editor holds, so its offsets would land elsewhere. */+ stale?: boolean+ onApplyQuickfix?: (quickfix: PredicateQuickfix) => void+ onFixWithAI?: (prompt: string) => void+ fixWithAILoading?: boolean}-export function QueryIndexUsageBar({ predicates, refreshing }: QueryIndexUsageBarProps): JSX.Element | null {+export function QueryIndexUsageBar({+ predicates,+ refreshing,+ stale,+ onApplyQuickfix,+ onFixWithAI,+ fixWithAILoading,+}: QueryIndexUsageBarProps): JSX.Element | null {if (predicates.length === 0) {return null}@@ -58,7 +70,15 @@ export function QueryIndexUsageBar({ predicates, refreshing }: QueryIndexUsageBa{refreshing ? 'Checking filters' : text}</span>),- content: <QueryIndexUsageTable predicates={predicates} />,+ content: (+ <QueryIndexUsageTable+ predicates={predicates}+ stale={stale}+ onApplyQuickfix={onApplyQuickfix}+ onFixWithAI={onFixWithAI}+ fixWithAILoading={fixWithAILoading}+ />+ ),},]}/>diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageFixActions.stories.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageFixActions.stories.tsxnew file mode 100644index 000000000000..95244adb667b--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageFixActions.stories.tsx@@ -0,0 +1,130 @@+import type { Meta, StoryObj } from '@storybook/react'+import type { ComponentProps } from 'react'++import {+ PredicateFixAction,+ PredicateIndexUsage,+ PredicateIndexVerdict,+ PredicateScope,+} from '~/queries/schema/schema-general'++import { QueryIndexUsageFixActions } from './QueryIndexUsageFixActions'++// These render inside a table row that the index usage bar keeps collapsed, so a story on the bar+// never reaches them.+const meta: Meta<typeof QueryIndexUsageFixActions> = {+ title: 'Scenes-App/Data Warehouse/Query index usage fix actions',+ component: QueryIndexUsageFixActions,+ parameters: {+ testOptions: {+ viewportWidths: ['narrow', 'wide'],+ },+ },+}+export default meta++type Story = StoryObj<typeof QueryIndexUsageFixActions>++const BLOCKED: PredicateIndexUsage = {+ property_name: '$browser_version',+ scope: PredicateScope.Event,+ operator: '==',+ source_label: 'materialized column',+ semantic_type: 'String',+ physical_type: 'String',+ usable_indexes: [],+ verdict: PredicateIndexVerdict.Blocked,+ message: "Event property '$browser_version' is compared against a value of another type.",+ fix: "Write the value as text: '120'.",+ fix_action: PredicateFixAction.EditQuery,+ ai_fix_prompt: "Rewrite this filter so '$browser_version' is compared against a String value.",+ quickfix: { start: 58, end: 61, text: "'120'" },+}++const noop = (): void => {}++type RowProps = Omit<ComponentProps<typeof QueryIndexUsageFixActions>, 'onApplyQuickfix' | 'onFixWithAI'>++function Row({ predicate, ...rest }: RowProps): JSX.Element {+ return (+ <div className="flex flex-col gap-1 px-2 py-1 text-xs max-w-2xl">+ <p className="mb-0">{predicate.message}</p>+ {predicate.fix && <p className="mb-0 font-semibold">{predicate.fix}</p>}+ <QueryIndexUsageFixActions predicate={predicate} onApplyQuickfix={noop} onFixWithAI={noop} {...rest} />+ </div>+ )+}++export const ReplaceALiteral: Story = { render: () => <Row predicate={BLOCKED} /> }++// A long IN list: the label names the action rather than repeating a replacement that would widen+// the row until the table scrolls sideways.+export const ReplaceALongList: Story = {+ render: () => (+ <Row+ predicate={{+ ...BLOCKED,+ operator: 'in',+ fix: "Write the values as text: ('1', '2', '3', '4', '5', '6', '7', '8').",+ quickfix: { start: 40, end: 64, text: "('1', '2', '3', '4', '5', '6', '7', '8')" },+ }}+ />+ ),+}++// No quickfix, because a float's text form is not the text a row stores.+export const FixWithAi: Story = {+ render: () => (+ <Row predicate={{ ...BLOCKED, fix: "Compare '$browser_version' against text.", quickfix: undefined }} />+ ),+}++export const FixWithAiInFlight: Story = {+ // The spinner is the point of this story, so it never settles and the runner must not wait.+ parameters: { testOptions: { waitForLoadersToDisappear: false, viewportWidths: ['narrow', 'wide'] } },+ render: () => (+ <Row+ predicate={{ ...BLOCKED, fix: "Compare '$browser_version' against text.", quickfix: undefined }}+ fixWithAILoading+ />+ ),+}++export const ReportStillCatchingUp: Story = { render: () => <Row predicate={BLOCKED} stale /> }++export const EditPropertyType: Story = {+ render: () => (+ <Row+ predicate={{+ ...BLOCKED,+ property_name: 'duration',+ operator: '>',+ semantic_type: 'Float',+ message: "Event property 'duration' is stored as String but compared as Float.",+ fix: "If 'duration' does not really hold a number, correct its type in data management.",+ fix_action: PredicateFixAction.EditPropertyType,+ ai_fix_prompt: undefined,+ quickfix: undefined,+ }}+ />+ ),+}++export const MaterializeTheProperty: Story = {+ render: () => (+ <Row+ predicate={{+ ...BLOCKED,+ property_name: 'plan_tier',+ scope: PredicateScope.Person,+ source_label: 'JSON blob',+ verdict: PredicateIndexVerdict.UnindexedJson,+ message: "Person property 'plan_tier' is read out of the properties JSON on every row.",+ fix: "Materialize 'plan_tier' so this filter reads a dedicated column instead of parsing the JSON.",+ fix_action: PredicateFixAction.Materialize,+ ai_fix_prompt: undefined,+ quickfix: undefined,+ }}+ />+ ),+}diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageFixActions.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageFixActions.tsxnew file mode 100644index 000000000000..065924eb0a10--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageFixActions.tsx@@ -0,0 +1,126 @@+import { useValues } from 'kea'+import { combineUrl } from 'kea-router'++import { LemonButton } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import {+ PredicateFixAction,+ PredicateIndexUsage,+ PredicateQuickfix,+ PredicateScope,+} from '~/queries/schema/schema-general'++// Longer than this and the label stops being readable at a glance, so it names the action instead.+const MAX_LITERAL_IN_LABEL = 24++// The definitions list filters by `type`; group properties would also need a group type index the+// report does not carry, so they get no link.+const DEFINITION_LIST_TYPES: Partial<Record<PredicateScope, string>> = {+ [PredicateScope.Event]: 'event',+ [PredicateScope.Person]: 'person',+}++interface QueryIndexUsageFixActionsProps {+ predicate: PredicateIndexUsage+ /** The report describes older text than the editor holds, so a query edit would land in the wrong place. */+ stale?: boolean+ onApplyQuickfix?: (quickfix: PredicateQuickfix) => void+ onFixWithAI?: (prompt: string) => void+ fixWithAILoading?: boolean+}++export function QueryIndexUsageFixActions({+ predicate,+ stale,+ onApplyQuickfix,+ onFixWithAI,+ fixWithAILoading,+}: QueryIndexUsageFixActionsProps): JSX.Element | null {+ const { user } = useValues(userLogic)++ if (predicate.fix_action === PredicateFixAction.EditQuery) {+ const staleReason = stale+ ? 'Still checking the latest version of this query. Try again in a moment.'+ : undefined+ if (predicate.quickfix && onApplyQuickfix) {+ const quickfix = predicate.quickfix+ // An IN list produces a replacement as long as the list, which would widen the row and+ // push the table into sideways scroll in a narrow pane. The tooltip keeps the full text.+ const showsLiteral = quickfix.text.length <= MAX_LITERAL_IN_LABEL+ return (+ <div className="flex">+ <LemonButton+ size="xsmall"+ type="secondary"+ disabledReason={staleReason}+ tooltip={showsLiteral ? undefined : quickfix.text}+ onClick={() => onApplyQuickfix(quickfix)}+ data-attr="sql-editor-index-usage-apply-quickfix"+ >+ {showsLiteral ? `Replace with ${quickfix.text}` : 'Write the values as text'}+ </LemonButton>+ </div>+ )+ }+ if (predicate.ai_fix_prompt && onFixWithAI) {+ const prompt = predicate.ai_fix_prompt+ return (+ <div className="flex">+ <LemonButton+ size="xsmall"+ type="secondary"+ loading={fixWithAILoading}+ disabledReason={staleReason}+ onClick={() => onFixWithAI(prompt)}+ data-attr="sql-editor-index-usage-fix-with-ai"+ >+ Fix with AI+ </LemonButton>+ </div>+ )+ }+ return null+ }++ if (predicate.fix_action === PredicateFixAction.EditPropertyType) {+ const type = DEFINITION_LIST_TYPES[predicate.scope]+ if (!type) {+ return null+ }+ return (+ <div className="flex">+ <LemonButton+ size="xsmall"+ type="secondary"+ to={combineUrl(urls.propertyDefinitions(type), { property: predicate.property_name }).url}+ targetBlank+ data-attr="sql-editor-index-usage-edit-property-type"+ >+ Edit property type+ </LemonButton>+ </div>+ )+ }++ // Materialization is a staff-only page, so everyone else keeps the prose and no dead link.+ if (predicate.fix_action === PredicateFixAction.Materialize && user?.is_staff) {+ return (+ <div className="flex">+ <LemonButton+ size="xsmall"+ type="secondary"+ to={urls.materializedColumns()}+ targetBlank+ data-attr="sql-editor-index-usage-materialize"+ >+ Open materialized columns+ </LemonButton>+ </div>+ )+ }++ return null+}diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageTable.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageTable.tsxindex f1d75c0721e3..6f0f826e72a8 100644--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageTable.tsx+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageTable.tsx@@ -2,7 +2,14 @@ import { LemonTable } from '@posthog/lemon-ui'import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'-import { PredicateIndexUsage, PredicateIndexVerdict, PredicateScope } from '~/queries/schema/schema-general'+import {+ PredicateIndexUsage,+ PredicateIndexVerdict,+ PredicateQuickfix,+ PredicateScope,+} from '~/queries/schema/schema-general'++import { QueryIndexUsageFixActions } from './QueryIndexUsageFixActions'// `Indexed` is deliberately not a success tag. It means an index covers the comparison, which is a// schema fact; whether granules are actually dropped depends on data we do not look at.@@ -30,9 +37,20 @@ const SCOPE_PREFIXES: Partial<Record<PredicateScope, string>> = {interface QueryIndexUsageTableProps {predicates: PredicateIndexUsage[]+ /** The report describes an older version of the query, so a query edit would land in the wrong place. */+ stale?: boolean+ onApplyQuickfix?: (quickfix: PredicateQuickfix) => void+ onFixWithAI?: (prompt: string) => void+ fixWithAILoading?: boolean}-export function QueryIndexUsageTable({ predicates }: QueryIndexUsageTableProps): JSX.Element | null {+export function QueryIndexUsageTable({+ predicates,+ stale,+ onApplyQuickfix,+ onFixWithAI,+ fixWithAILoading,+}: QueryIndexUsageTableProps): JSX.Element | null {if (predicates.length === 0) {return null}@@ -50,6 +68,13 @@ export function QueryIndexUsageTable({ predicates }: QueryIndexUsageTableProps):<div className="flex flex-col gap-1 px-2 py-1 text-xs"><p className="mb-0">{predicate.message}</p>{predicate.fix && <p className="mb-0 font-semibold">{predicate.fix}</p>}+ <QueryIndexUsageFixActions+ predicate={predicate}+ stale={stale}+ onApplyQuickfix={onApplyQuickfix}+ onFixWithAI={onFixWithAI}+ fixWithAILoading={fixWithAILoading}+ /></div>),}}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 54646d747f6e..f83c4ffac2ad 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -22,6 +22,7 @@ import {DataTableNode,DataVisualizationNode,HogQLFilters,+ HogQLMetadataResponse,HogQLQuery,NodeKind,} from '~/queries/schema/schema-general'@@ -315,6 +316,167 @@ describe('sqlEditorLogic', () => {databaseLogic?.unmount()})+ describe('index quickfix', () => {+ // A Monaco model and editor that apply an edit to real text, so a test asserts the resulting+ // SQL rather than the range that produced it. Offsets are UTF-16, as Monaco's are.+ const createQuickfixEditor = (initial: string): any => {+ let value = initial+ const offsetAt = (position: { lineNumber: number; column: number }): number => {+ const lines = value.split('\n')+ let offset = 0+ for (let line = 0; line < position.lineNumber - 1; line++) {+ offset += lines[line].length + 1+ }+ return offset + position.column - 1+ }+ const model = {+ getValue: () => value,+ getPositionAt: (offset: number) => {+ const lines = value.slice(0, offset).split('\n')+ return { lineNumber: lines.length, column: lines[lines.length - 1].length + 1 }+ },+ }+ return {+ getModel: () => model,+ getSelection: () => null,+ getPosition: () => null,+ setModel: jest.fn(),+ focus: jest.fn(),+ getValue: () => value,+ // Diff mode swaps the model under the editor for one holding the suggested query.+ setValue: (next: string) => {+ value = next+ },+ executeEdits: jest.fn((_source: string, edits: any[]) => {+ const { range, text } = edits[0]+ const start = offsetAt({ lineNumber: range.startLineNumber, column: range.startColumn })+ const end = offsetAt({ lineNumber: range.endLineNumber, column: range.endColumn })+ value = value.slice(0, start) + text + value.slice(end)+ }),+ }+ }++ // The offsets the backend sends count characters, which is what Python measures.+ const characterOffsetsOf = (statement: string, literal: string): { start: number; end: number } => {+ const characters = Array.from(statement)+ const start = Array.from(statement.slice(0, statement.indexOf(literal))).length+ return {+ start,+ end: start + Array.from(literal).length,+ characters: characters.length,+ } as any+ }++ const mountWithReport = (fullText: string, statement: string, statementOffset: number): any => {+ const editor = createQuickfixEditor(fullText)+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor })+ logic.mount()+ logic.actions.setQueryInput(fullText)+ logic.actions.setActiveQueryText(statement, statementOffset)+ logic.actions.setMetadataLoading(false)+ logic.actions.setMetadata({ query: statement } as HogQLMetadataResponse)+ return editor+ }++ it('replaces the literal the offsets point at', () => {+ const query = 'select 1 from events where properties.$browser_version = 120'+ const editor = mountWithReport(query, query, 0)++ logic.actions.applyIndexQuickfix({ ...characterOffsetsOf(query, '120'), text: "'120'" })++ expect(editor.getValue()).toBe("select 1 from events where properties.$browser_version = '120'")+ })++ it('replaces the right literal when an emoji shifts the character count', () => {+ // The parser counts the emoji as one character and Monaco as two, so applying the raw+ // offset selects ' 12' and writes ='120'0.+ const query = "select '😀' from events where properties.$browser_version = 120"+ const editor = mountWithReport(query, query, 0)++ logic.actions.applyIndexQuickfix({ ...characterOffsetsOf(query, '120'), text: "'120'" })++ expect(editor.getValue()).toBe("select '😀' from events where properties.$browser_version = '120'")+ })++ it('replaces inside the statement the report describes, not the first one', () => {+ const first = 'select 1 from events;\n'+ const statement = 'select 2 from events where properties.$browser_version = 120'+ const editor = mountWithReport(first + statement, statement, first.length)++ logic.actions.applyIndexQuickfix({ ...characterOffsetsOf(statement, '120'), text: "'120'" })++ expect(editor.getValue()).toBe(first + "select 2 from events where properties.$browser_version = '120'")+ })++ it('does not edit when the report describes text the editor no longer holds', () => {+ const query = 'select 1 from events where properties.$browser_version = 120'+ const editor = mountWithReport(query, query, 0)+ logic.actions.setMetadata({+ query: 'select 1 from events where properties.other = 120',+ } as HogQLMetadataResponse)++ logic.actions.applyIndexQuickfix({ ...characterOffsetsOf(query, '120'), text: "'120'" })++ expect(editor.executeEdits).not.toHaveBeenCalled()+ expect(editor.getValue()).toBe(query)+ })++ it('does not edit the suggested query while a suggestion diff is open', () => {+ // In diff mode the editor holds the suggestion, while the offsets index the text behind+ // it, so an edit here would splice into the wrong string.+ const query = 'select 1 from events where properties.$browser_version = 120'+ const suggestion = 'select 42 from events where properties.other = 1'+ const editor = mountWithReport(query, query, 0)+ // Diff mode points `props.editor` at the modified sub-editor, whose model holds the+ // suggestion. Setting the model is what makes this the diff case; the suggestion action+ // itself also touches tab and router state, which would leak into later tests.+ editor.setValue(suggestion)++ logic.actions.applyIndexQuickfix({ ...characterOffsetsOf(query, '120'), text: "'120'" })++ expect(editor.getValue()).toBe(suggestion)+ })+ })++ describe('indexReportStale', () => {+ const mountLogic = (): void => {+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })+ logic.mount()+ }++ it.each([+ [+ 'the report describes the whole editor text and there is no active statement',+ 'select 1',+ null,+ 'select 1',+ false,+ false,+ ],+ ['the report describes the active statement', 'select 1;\nselect 2', 'select 2', 'select 2', false, false],+ ['the editor text has moved on from the report', 'select 2', null, 'select 1', false, true],+ ['a refresh is in flight', 'select 1', null, 'select 1', true, true],+ ])(+ 'is %s',+ (+ _name: string,+ queryInput: string,+ activeQueryText: string | null,+ analyzed: string,+ metadataLoading: boolean,+ expected: boolean+ ) => {+ mountLogic()+ logic.actions.setQueryInput(queryInput)+ logic.actions.setActiveQueryText(activeQueryText, 0)+ logic.actions.setMetadata({ query: analyzed } as HogQLMetadataResponse)+ logic.actions.setMetadataLoading(metadataLoading)++ expect(logic.values.indexReportStale).toBe(expected)+ }+ )+ })+it('keeps configured filters when the filters placeholder is removed from the query text', () => {logic = sqlEditorLogic({tabId: TAB_ID,diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex bef6bab3d46f..a3959f76b3e6 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -43,6 +43,7 @@ import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'import { findQueryAtCursor, type QueryRange, splitQueries } from 'lib/monaco/multiQueryUtils'+import { characterOffsetToUtf16 } from 'lib/monaco/offsets'import { objectsEqual } from 'lib/utils/objects'import { lazyWithRetry } from 'lib/utils/retryImport'import { slugify } from 'lib/utils/strings'@@ -73,6 +74,7 @@ import {HogQLMetadataResponse,HogQLQuery,NodeKind,+ PredicateQuickfix,} from '~/queries/schema/schema-general'import {AccessControlResourceType,@@ -583,6 +585,7 @@ export interface sqlEditorLogicValues {hoveredNode: string | nullinProgressDraftEdits: Record<string, string>inProgressViewEdits: Record<string, string>+ indexReportStale: booleaninsightLoading: booleanisDraft: booleanisEditingMaterializedView: boolean@@ -783,6 +786,9 @@ export interface sqlEditorLogicActions {_setSuggestionPayload: (payload: SuggestionPayload | null) => {payload: SuggestionPayload | null}+ applyIndexQuickfix: (quickfix: PredicateQuickfix) => {+ quickfix: PredicateQuickfix+ }closeAccessControlModal: () => {value: true}@@ -834,6 +840,9 @@ export interface sqlEditorLogicActions {enforceConnectionRawQueryMode: () => {value: true}+ fixIndexUsageWithAI: (prompt: string) => {+ prompt: string+ }initialize: () => {value: true}@@ -1152,6 +1161,13 @@ export interface sqlEditorLogicMeta {hasFiltersPlaceholder: (queryInput: string | null) => booleanfiltersPlaceholderBindings: (queryInput: string | null) => string[] | nullhasQueryInput: (queryInput: string | null) => boolean+ indexReportStale: (+ metadata: HogQLMetadataResponse | null,+ activeQueryText: string | null,+ queryInput: string | null,+ suggestedQueryInput: string,+ metadataLoading: boolean+ ) => booleanisEmbeddedMode: (arg: SQLEditorMode | undefined) => booleandataLogicKey: (tabId: string) => stringisDraft: (activeTab: QueryTab | null) => boolean@@ -1401,6 +1417,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}),syncUrlWithQuery: true,insertTextAtCursor: (text: string) => ({ text }),+ applyIndexQuickfix: (quickfix: PredicateQuickfix) => ({ quickfix }),+ fixIndexUsageWithAI: (prompt: string) => ({ prompt }),setEditorSource: (source: SqlEditorSource) => ({ source }),runSubquery: true,setSendRawQuery: (sendRawQuery: boolean) => ({ sendRawQuery }),@@ -1771,6 +1789,66 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([reportAIQueryPromptOpen: () => {posthog.capture('ai_query_prompt_open')},+ applyIndexQuickfix: ({ quickfix }) => {+ const editor = props.editor+ const model = editor?.getModel()+ if (!editor || !model) {+ return+ }+ // The offsets describe the SQL the server analyzed. Once the text has moved on they+ // would land the edit somewhere else, so wait for the next report instead of guessing.+ if (values.indexReportStale) {+ return+ }+ // The offsets count characters; Monaco counts UTF-16 units. Convert against the+ // analyzed statement before adding its offset, which the editor already measures+ // in Monaco's units.+ const analyzed = values.activeQueryText ?? (values.suggestedQueryInput || values.queryInput) ?? ''+ // The model is the authority on what is being edited, and it is not always the text+ // the report describes: with a suggestion open, `props.editor` is the diff's modified+ // editor holding the suggested query while the offsets index the text behind it.+ // Splicing there would corrupt the suggestion, so confirm the analyzed text is still+ // sitting where the offsets say before writing anything.+ if (+ model.getValue().slice(values.activeQueryOffset, values.activeQueryOffset + analyzed.length) !==+ analyzed+ ) {+ lemonToast.info('Still checking the latest version of this query. Try again in a moment.')+ return+ }+ const start = model.getPositionAt(+ characterOffsetToUtf16(analyzed, quickfix.start) + values.activeQueryOffset+ )+ const end = model.getPositionAt(+ characterOffsetToUtf16(analyzed, quickfix.end) + values.activeQueryOffset+ )+ editor.executeEdits('index-quickfix', [+ {+ range: {+ startLineNumber: start.lineNumber,+ startColumn: start.column,+ endLineNumber: end.lineNumber,+ endColumn: end.column,+ },+ text: quickfix.text,+ },+ ])+ posthog.capture('sql-editor-index-quickfix-applied')+ },+ fixIndexUsageWithAI: ({ prompt }) => {+ // The prompt names a filter the server found in the text it analyzed. Sending it with+ // newer text asks for a rewrite of a filter that may no longer be there. The editor+ // lightbulb can still offer the action in that window, so the guard lives here rather+ // than only on the table button, and it says why instead of doing nothing.+ if (values.indexReportStale) {+ lemonToast.info('Still checking the latest version of this query. Try again in a moment.')+ return+ }+ // The error fixer takes free text as its "error", so an index instruction rides the+ // same suggestion flow and lands as a reviewable diff rather than a silent rewrite.+ actions.fixErrors(values.queryInput ?? '', prompt, values.selectedConnectionId)+ posthog.capture('sql-editor-index-fix-with-ai')+ },insertTextAtCursor: ({ text }) => {const editor = props.editorif (!editor) {@@ -3281,6 +3359,20 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([{ resultEqualityCheck: objectsEqual },],hasQueryInput: [(s) => [s.queryInput], (queryInput: string | null) => !!queryInput],+ // A quickfix carries character offsets into the SQL the server analyzed, so it can only be+ // applied while the editor still holds that exact text. The comparison mirrors the fallback+ // in `codeEditorLogic`, which analyzes the whole editor text whenever there is no active+ // statement; comparing against the active statement alone reads as stale forever there.+ indexReportStale: [+ (s) => [s.metadata, s.activeQueryText, s.queryInput, s.suggestedQueryInput, s.metadataLoading],+ (+ metadata: HogQLMetadataResponse | null,+ activeQueryText: string | null,+ queryInput: string | null,+ suggestedQueryInput: string,+ metadataLoading: boolean+ ) => metadataLoading || metadata?.query !== (activeQueryText ?? (suggestedQueryInput || queryInput) ?? ''),+ ],isEmbeddedMode: [() => [(_, p: SqlEditorLogicProps) => p.mode],(mode: SQLEditorMode | undefined) => isEmbeddedSQLEditorMode(mode ?? SQLEditorMode.FullScene),diff --git a/posthog/hogql/index_eligibility.py b/posthog/hogql/index_eligibility.pyindex 774189b16329..c31f14036774 100644--- a/posthog/hogql/index_eligibility.py+++ b/posthog/hogql/index_eligibility.py@@ -20,18 +20,20 @@ from enum import StrEnumfrom posthog.hogql import astfrom posthog.hogql.base import ASTfrom posthog.hogql.context import HogQLContext+from posthog.hogql.escape_sql import escape_hogql_stringfrom posthog.hogql.property_planner import (PropertyComparisonPlan,+ PropertyLiteralConversion,PropertyMinmaxBlocker,PropertyScope,PropertySourceKind,plan_property_comparison,)-from posthog.hogql.type_system import ComparisonCompatibility, comparison_compatibility+from posthog.hogql.type_system import ComparisonCompatibility, comparison_compatibility, runtime_type_from_constant_typefrom posthog.hogql.visitor import TraversingVisitor, clone_exprfrom posthog.dataclasses import frozen-from posthog.schema_enums import QueryIndexUsage+from posthog.schema_enums import PredicateFixAction, QueryIndexUsageclass IndexKind(StrEnum):@@ -80,6 +82,12 @@ _OPERATOR_INDEXES: dict[ast.CompareOperationOp, frozenset[IndexKind]] = {_COMPATIBLE_COMPARISONS = frozenset({ComparisonCompatibility.DEFINITELY_COMPATIBLE, ComparisonCompatibility.CHEAP_CAST})+# Operators whose meaning survives comparing the value as text. A range comparison does not: '900' is+# above '1000' as text and below it as numbers, so quoting the literal would change which rows match.+_TEXT_REWRITABLE_OPERATORS = frozenset(+ {ast.CompareOperationOp.Eq, ast.CompareOperationOp.In, ast.CompareOperationOp.GlobalIn}+)+_COLUMN_SOURCE_KINDS = frozenset({PropertySourceKind.MATERIALIZED_COLUMN,@@ -131,6 +139,19 @@ def _plain_type(printed_type: str) -> str:return _PLAIN_TYPE_WORDS.get(printed_type, printed_type)+@frozen+class PredicateQuickfix:+ """A query edit that unblocks the index: replacement text for one range of the query.++ The editor substitutes ``text`` for the range verbatim, so it has to be valid HogQL on its own+ and the range has to cover exactly the expression being replaced.+ """++ start: int+ end: int+ text: str++@dataclass(frozen=True, slots=True, kw_only=True)class PredicateIndexEligibility:property_name: str@@ -151,6 +172,9 @@ class PredicateIndexEligibility:substitute into the marked range, so this must never be handed to an editor marker directly."""ai_fix_prompt: str | None"""Instruction for the editor's "Fix with AI" action, set only where rewriting the query helps."""+ fix_action: PredicateFixAction | None+ quickfix: PredicateQuickfix | None+ """A deterministic edit, set when the compared value is a literal the analysis can rewrite itself."""start: int | Noneend: int | None@@ -166,9 +190,7 @@ class PredicateIndexEligibility:the property definition, not about the query, so underlining a correct comparison leaves thereader nothing to edit and teaches them to ignore the markers that do carry an edit."""- if self.verdict != PredicateIndexVerdict.BLOCKED:- return False- return self.blocker != PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE+ return self.fix_action == PredicateFixAction.EDIT_QUERY@dataclass(frozen=True, slots=True)@@ -232,14 +254,12 @@ def eligibility_from_plan(negated: bool = False,start: int | None = None,end: int | None = None,+ value_expr: ast.Expr | None = None,) -> PredicateIndexEligibility:source = plan.access.sourceavailable = _available_indexes(plan)relevant = frozenset() if negated else _OPERATOR_INDEXES.get(plan.operator, frozenset())- # `_minmax_blocker` reports the absent-index case first, so any other value it returns is a type- # problem that makes the printer wrap the column in a cast. A cast defeats every skip index on- # that column, not just the minmax one.- type_blocker = plan.minmax_blocker if plan.minmax_blocker != PropertyMinmaxBlocker.NO_MINMAX_INDEX else None+ type_blocker = _type_blocker(plan)if type_blocker is not None and _set_members_match_source(plan):type_blocker = Noneusable: tuple[IndexKind, ...] = () if type_blocker is not None else tuple(sorted(available & relevant))@@ -253,6 +273,12 @@ def eligibility_from_plan()semantic_type = plan.access.semantic_type.print_type()physical_type = source.physical_type.print_type()+ quickfix = (+ _string_literal_quickfix(plan, value_expr)+ if verdict == PredicateIndexVerdict.BLOCKED+ and type_blocker == PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE+ else None+ )copy = _copy_for(verdict=verdict,plan=plan,@@ -260,6 +286,7 @@ def eligibility_from_plan(type_blocker=type_blocker,semantic_type=semantic_type,physical_type=physical_type,+ quickfix=quickfix,)return PredicateIndexEligibility(@@ -278,11 +305,93 @@ def eligibility_from_plan(message=copy.message,fix=copy.fix,ai_fix_prompt=copy.ai_fix_prompt,+ fix_action=copy.action,+ quickfix=quickfix,start=start,end=end,)+def _type_blocker(plan: PropertyComparisonPlan) -> PropertyMinmaxBlocker | None:+ """The type problem that makes the printer wrap the column in a cast, if there is one.++ Read off the plan's compatibility facts rather than ``plan.minmax_blocker``: that field reports+ the absence of a minmax index ahead of any type problem, so on a column carrying only a bloom+ filter it would hide the mismatch. A cast defeats every skip index on the column, not just the+ minmax one, so the check has to run whatever indexes the column has.+ """+ if not plan.source_matches_semantics:+ return PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE+ # An UNKNOWN compatibility means the value's type could not be inferred, which a subquery or a+ # placeholder on the right-hand side produces. Reporting a mismatch there would warn about a+ # filter that is very likely fine, so the analysis only claims a blocker it can substantiate.+ if (+ plan.physical_compatibility not in _COMPATIBLE_COMPARISONS+ and plan.physical_compatibility != ComparisonCompatibility.UNKNOWN+ and plan.literal_conversion == PropertyLiteralConversion.NONE+ ):+ return PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE+ return None+++def _write_as_text_fix(quickfix: PredicateQuickfix) -> str:+ """Advice naming the replacement, in the plural when the comparison is against a set."""+ if quickfix.text.startswith(("(", "[")):+ return f"Write the values as text: {quickfix.text}."+ return f"Write the value as text: {quickfix.text}."+++def _string_literal_quickfix(plan: PropertyComparisonPlan, value_expr: ast.Expr | None) -> PredicateQuickfix | None:+ """Quote a whole-number literal so a text column is compared as text and keeps its index.++ Only plain integers qualify. A boolean's text form is a guess (``'true'`` or ``'1'``), a float's+ depends on how Python renders it (``2.0`` and ``1e+20`` do not match the text a row stores), and+ anything computed has no literal to rewrite, so those fall back to the AI prompt.+ """+ if (+ value_expr is None+ or plan.operator not in _TEXT_REWRITABLE_OPERATORS+ or runtime_type_from_constant_type(plan.access.source.physical_type).family != "string"+ ):+ return None++ while isinstance(value_expr, ast.Alias):+ value_expr = value_expr.expr+ if value_expr.start is None or value_expr.end is None:+ return None++ if isinstance(value_expr, ast.Constant):+ text = _quoted_number(value_expr)+ elif isinstance(value_expr, ast.Tuple | ast.Array):+ members = _quoted_numbers(value_expr.exprs)+ if members is None:+ return None+ open_bracket, close_bracket = ("(", ")") if isinstance(value_expr, ast.Tuple) else ("[", "]")+ text = f"{open_bracket}{', '.join(members)}{close_bracket}"+ else:+ return None++ if text is None:+ return None+ return PredicateQuickfix(start=value_expr.start, end=value_expr.end, text=text)+++def _quoted_numbers(exprs: list[ast.Expr]) -> list[str] | None:+ quoted: list[str] = []+ for member in exprs:+ text = _quoted_number(member) if isinstance(member, ast.Constant) else None+ if text is None:+ return None+ quoted.append(text)+ return quoted or None+++def _quoted_number(constant: ast.Constant) -> str | None:+ if isinstance(constant.value, bool) or not isinstance(constant.value, int):+ return None+ return escape_hogql_string(str(constant.value))++def _set_members_match_source(plan: PropertyComparisonPlan) -> bool:"""Whether an IN compares the column against a set whose members all match how it is stored.@@ -350,6 +459,7 @@ class _PredicateCopy:message: strfix: str | None = Noneai_fix_prompt: str | None = None+ action: PredicateFixAction | None = Nonedef _copy_for(@@ -359,6 +469,7 @@ def _copy_for(type_blocker: PropertyMinmaxBlocker | None,semantic_type: str,physical_type: str,+ quickfix: PredicateQuickfix | None,) -> _PredicateCopy:# Messages name the property, never the physical column behind it. A reader cannot select,# create or drop `mat_$browser`, so naming it spends words on something they cannot act on.@@ -384,14 +495,33 @@ def _copy_for(f"{_plain_type(semantic_type)}, so every row is converted before the filter runs and the index on "f"'{name}' cannot skip any data.",fix=f"If '{name}' does not really hold {_plain_type(semantic_type)}, correct its type in data management.",+ action=PredicateFixAction.EDIT_PROPERTY_TYPE,+ )+ if plan.operator not in _TEXT_REWRITABLE_OPERATORS:+ # Comparing text against a number with an ordering operator has no safe query rewrite:+ # reading the value as text reorders the results, and reading the column as a number is+ # the cast that already defeats the index. Whichever the reader meant, the type the+ # property declares is the thing that is wrong.+ return _PredicateCopy(+ message=f"{label} '{name}' holds {_plain_type(physical_type)} but is compared against "+ f"{_plain_type(plan.value_type.print_type())}, so every row has to be converted and the index on "+ f"'{name}' goes unused.",+ fix=f"If '{name}' holds numbers, correct its type in data management. Comparing it as text would "+ "order the values differently.",+ action=PredicateFixAction.EDIT_PROPERTY_TYPE,)return _PredicateCopy(- message=f"{label} '{name}' is compared against a value of another type, so every row has to be "- f"converted and the index on '{name}' goes unused.",- fix=f"Compare '{name}' against {_plain_type(physical_type)}.",+ message=f"{label} '{name}' is compared against a value of another type, so the index on "+ f"'{name}' cannot be used.",+ fix=(+ _write_as_text_fix(quickfix)+ if quickfix is not None+ else f"Compare '{name}' against {_plain_type(physical_type)}."+ ),# The AI prompt keeps the engine's type name: its reader is a model rewriting HogQL, not# someone looking for a setting in the UI.ai_fix_prompt=f"Rewrite this filter so '{name}' is compared against a {physical_type} value.",+ action=PredicateFixAction.EDIT_QUERY,)if verdict == PredicateIndexVerdict.UNINDEXED_JSON:@@ -401,6 +531,7 @@ def _copy_for(return _PredicateCopy(message=f"{label} '{name}' is read out of the properties JSON on every row, with no index to skip data.",fix=f"Materialize '{name}' so this filter reads a dedicated column instead of parsing the JSON.",+ action=PredicateFixAction.MATERIALIZE,)if verdict == PredicateIndexVerdict.UNINDEXED_COLUMN:@@ -469,4 +600,7 @@ class _FilterPredicateCollector(TraversingVisitor):returnself._seen.add(key)- self.predicates.append(eligibility_from_plan(plan, negated=negated, start=node.start, end=node.end))+ value_expr = node.right if plan.property_side == "left" else node.left+ self.predicates.append(+ eligibility_from_plan(plan, negated=negated, start=node.start, end=node.end, value_expr=value_expr)+ )diff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.pyindex 0d5d2a95633a..5138a59016e8 100644--- a/posthog/hogql/metadata.py+++ b/posthog/hogql/metadata.py@@ -13,6 +13,7 @@ from posthog.schema import (HogQLQuery,PredicateIndexUsage,PredicateIndexVerdict,+ PredicateQuickfix,PredicateScope,)@@ -26,7 +27,7 @@ from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_dirfrom posthog.hogql.direct_sql import get_adapterfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.filters import replace_filters-from posthog.hogql.index_eligibility import build_index_eligibility_report+from posthog.hogql.index_eligibility import IndexEligibilityReport, build_index_eligibility_reportfrom posthog.hogql.metadata_heuristics import run_metadata_heuristicsfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.observability import (@@ -252,17 +253,26 @@ def _attach_index_usage(stored is not something the editor can change, so marking either would bury the predicates wherea type mismatch is wasting an index that already exists."""- with INDEX_ELIGIBILITY_DURATION_SECONDS.time():- try:+ try:+ with INDEX_ELIGIBILITY_DURATION_SECONDS.time():report = build_index_eligibility_report(hogql_ast, context)- except Exception:- # Index eligibility is advisory. A query that compiles must not be reported as invalid- # because the analysis over it failed. The counter is the only user-visible trace of that:- # the response just comes back without a report.- INDEX_ELIGIBILITY_TOTAL.labels(result="failed").inc()- logger.exception("hogql_index_eligibility_failed", team_id=context.team_id)- return+ _record_index_usage(response, report, context)+ except Exception:+ # Index eligibility is advisory. A query that compiles must not be reported as invalid+ # because the analysis over it failed, so the whole of it is swallowed rather than only the+ # analysis: converting a verdict to its schema enum raises if the two ever drift, and the+ # caller turns any exception here into an invalid query. The counter is the only+ # user-visible trace: the response just comes back without a report.+ INDEX_ELIGIBILITY_TOTAL.labels(result="failed").inc()+ logger.exception("hogql_index_eligibility_failed", team_id=context.team_id)++def _record_index_usage(+ response: HogQLMetadataResponse,+ report: IndexEligibilityReport,+ context: HogQLContext,+) -> None:+ """Turn a finished report into the response fields and the editor's warnings."""INDEX_ELIGIBILITY_TOTAL.labels(result="ok").inc()for predicate in report.predicates:INDEX_ELIGIBILITY_VERDICT_TOTAL.labels(@@ -283,6 +293,15 @@ def _attach_index_usage(verdict=PredicateIndexVerdict(predicate.verdict.value),message=predicate.message,fix=predicate.fix,+ fix_action=predicate.fix_action,+ ai_fix_prompt=predicate.ai_fix_prompt,+ quickfix=(+ PredicateQuickfix(+ start=predicate.quickfix.start, end=predicate.quickfix.end, text=predicate.quickfix.text+ )+ if predicate.quickfix+ else None+ ),start=predicate.start,end=predicate.end,)@@ -290,16 +309,25 @@ def _attach_index_usage(]for predicate in report.predicates:- if predicate.editor_actionable:- # `HogQLNotice.fix` is literal replacement text for the marked range (see- # taxonomy_validation), so the prose advice must not go here. The `ai_prompt:` form is- # the editor's other contract: it becomes a "Fix with AI" action instead of an edit.+ if not predicate.editor_actionable:+ continue+ # `HogQLNotice.fix` is literal replacement text for the marked range (see taxonomy_validation),+ # so a quickfix marks exactly the literal it rewrites, and prose advice never goes here. The+ # `ai_prompt:` form is the editor's other contract: a "Fix with AI" action instead of an edit.+ if predicate.quickfix is not None:context.add_warning(message=predicate.message,- start=predicate.start,- end=predicate.end,- fix=f"ai_prompt:{predicate.ai_fix_prompt}" if predicate.ai_fix_prompt else None,+ start=predicate.quickfix.start,+ end=predicate.quickfix.end,+ fix=predicate.quickfix.text,)+ continue+ context.add_warning(+ message=predicate.message,+ start=predicate.start,+ end=predicate.end,+ fix=f"ai_prompt:{predicate.ai_fix_prompt}" if predicate.ai_fix_prompt else None,+ )def enrich_hogql_validation_error(diff --git a/posthog/hogql/test/test_index_eligibility.py b/posthog/hogql/test/test_index_eligibility.pyindex cad02f80bf4d..b0fbfe4f6660 100644--- a/posthog/hogql/test/test_index_eligibility.py+++ b/posthog/hogql/test/test_index_eligibility.py@@ -8,7 +8,12 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.schema import HogLanguage, HogQLMetadata, HogQLMetadataResponse+from posthog.schema import (+ HogLanguage,+ HogQLMetadata,+ HogQLMetadataResponse,+ PredicateIndexVerdict as SchemaPredicateIndexVerdict,+)from posthog.hogql import astfrom posthog.hogql.context import HogQLContext@@ -19,6 +24,7 @@ from posthog.hogql.index_eligibility import (IndexKind,PredicateIndexEligibility,PredicateIndexVerdict,+ PredicateQuickfix,analyze_index_eligibility,build_index_eligibility_report,eligibility_from_plan,@@ -39,7 +45,7 @@ from posthog.hogql.property_planner import (from posthog.hogql.resolver import resolve_typesfrom posthog.hogql.transforms.property_types import build_property_swapper-from posthog.schema_enums import QueryIndexUsage+from posthog.schema_enums import PredicateFixAction, QueryIndexUsagefrom products.event_definitions.backend.models.property_definition import PropertyDefinitionfrom products.event_definitions.backend.property_type import PropertyType@@ -62,6 +68,7 @@ def _plan(semantic_type: ast.ConstantType | None = None,physical_type: ast.ConstantType | None = None,value_type: ast.ConstantType | None = None,+ physical_compatibility: ComparisonCompatibility | None = None,) -> PropertyComparisonPlan:source = PropertySourcePlan(kind=kind,@@ -92,13 +99,28 @@ def _plan(operator=operator,value_type=value_type or ast.StringType(nullable=True),semantic_compatibility=ComparisonCompatibility.DEFINITELY_COMPATIBLE,- physical_compatibility=ComparisonCompatibility.DEFINITELY_COMPATIBLE,+ physical_compatibility=physical_compatibility+ or (+ ComparisonCompatibility.EXPENSIVE_CAST+ if blocker == PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE+ else ComparisonCompatibility.DEFINITELY_COMPATIBLE+ ),literal_conversion=PropertyLiteralConversion.NONE,source_matches_semantics=blocker != PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE,minmax_blocker=blocker,)+class TestIndexEnumsMatchTheSchema(SimpleTestCase):+ def test_verdict_wire_values_match_the_generated_enum(self) -> None:+ # The verdict enum is deliberately declared twice: the local one carries the ClickHouse+ # reasoning in its docstrings. `metadata.py` converts by value, so a new member added on one+ # side only raises once a query happens to produce it.+ assert {member.value for member in PredicateIndexVerdict} == {+ member.value for member in SchemaPredicateIndexVerdict+ }++class TestIndexEligibilityVerdicts(SimpleTestCase):@parameterized.expand([@@ -148,6 +170,20 @@ class TestIndexEligibilityVerdicts(SimpleTestCase):PredicateIndexVerdict.BLOCKED,(),),+ (+ # The planner reports the missing minmax index ahead of the type problem, so the verdict+ # has to find the cast on its own or a bloom-only column reads as indexed.+ "value_type_mismatch_defeats_a_bloom_filter_too",+ _plan(+ kind=PropertySourceKind.MATERIALIZED_COLUMN,+ bloom=True,+ blocker=PropertyMinmaxBlocker.NO_MINMAX_INDEX,+ value_type=ast.IntegerType(),+ physical_compatibility=ComparisonCompatibility.EXPENSIVE_CAST,+ ),+ PredicateIndexVerdict.BLOCKED,+ (),+ ),("negated_equality_prunes_nothing",_plan(operator=Op.NotEq, kind=PropertySourceKind.MATERIALIZED_COLUMN, minmax=True, bloom=True),@@ -310,6 +346,101 @@ class TestIndexEligibilityVerdicts(SimpleTestCase):assert eligibility.editor_actionable is Trueassert eligibility.ai_fix_prompt is not None+ @parameterized.expand(+ [+ ("integer", ast.Constant(value=120, start=10, end=13), "'120'"),+ # A float's text form is Python's, not the row's: 2.0 stores as "2" and 1e20 as "1e+20".+ ("float", ast.Constant(value=1.5, start=10, end=13), None),+ (+ "tuple_of_numbers",+ ast.Tuple(exprs=[ast.Constant(value=1), ast.Constant(value=2)], start=10, end=16),+ "('1', '2')",+ ),+ ("string_already", ast.Constant(value="120", start=10, end=15), None),+ ("boolean_has_no_certain_text_form", ast.Constant(value=True, start=10, end=14), None),+ ("computed_value", ast.Call(name="now", args=[], start=10, end=15), None),+ (+ "tuple_with_a_computed_member",+ ast.Tuple(exprs=[ast.Constant(value=1), ast.Call(name="now", args=[])], start=10, end=20),+ None,+ ),+ ("literal_without_a_position", ast.Constant(value=120), None),+ ]+ )+ def test_quickfix_quotes_only_plain_numeric_literals(+ self, _name: str, value_expr: ast.Expr, expected_text: str | None+ ) -> None:+ operator = Op.In if isinstance(value_expr, ast.Tuple) else Op.Eq+ plan = _plan(+ operator=operator,+ kind=PropertySourceKind.MATERIALIZED_COLUMN,+ bloom=True,+ blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE,+ value_type=ast.IntegerType(),+ )++ eligibility = eligibility_from_plan(plan, value_expr=value_expr)++ assert eligibility.verdict == PredicateIndexVerdict.BLOCKED+ assert eligibility.fix_action == PredicateFixAction.EDIT_QUERY+ if expected_text is None:+ assert eligibility.quickfix is None+ assert eligibility.ai_fix_prompt is not None+ else:+ assert eligibility.quickfix == PredicateQuickfix(+ start=value_expr.start or 0, end=value_expr.end or 0, text=expected_text+ )+ assert expected_text in (eligibility.fix or "")++ @parameterized.expand([(Op.Gt,), (Op.GtEq,), (Op.Lt,), (Op.LtEq,)])+ def test_an_ordering_comparison_is_never_rewritten_as_text(self, operator: ast.CompareOperationOp) -> None:+ # Quoting the literal would reorder the results, because '900' is above '1000' as text and+ # below it as numbers. A marker or an AI prompt here would offer that swap as a fix.+ plan = _plan(+ operator=operator,+ kind=PropertySourceKind.MATERIALIZED_COLUMN,+ minmax=True,+ blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE,+ value_type=ast.IntegerType(),+ )++ eligibility = eligibility_from_plan(plan, value_expr=ast.Constant(value=1000, start=10, end=14))++ assert eligibility.verdict == PredicateIndexVerdict.BLOCKED+ assert eligibility.quickfix is None+ assert eligibility.ai_fix_prompt is None+ assert eligibility.editor_actionable is False+ assert eligibility.fix_action == PredicateFixAction.EDIT_PROPERTY_TYPE++ def test_an_uninferable_value_type_is_not_reported_as_a_mismatch(self) -> None:+ # A subquery or placeholder on the right-hand side leaves the value type unknown. Claiming a+ # mismatch there warns about a filter that is very likely correct.+ plan = _plan(+ kind=PropertySourceKind.MATERIALIZED_COLUMN,+ bloom=True,+ blocker=PropertyMinmaxBlocker.NO_MINMAX_INDEX,+ physical_compatibility=ComparisonCompatibility.UNKNOWN,+ )++ eligibility = eligibility_from_plan(plan)++ assert eligibility.verdict == PredicateIndexVerdict.INDEXED+ assert eligibility.editor_actionable is False++ def test_a_storage_type_mismatch_never_gets_a_quickfix(self) -> None:+ plan = _plan(+ operator=Op.Gt,+ kind=PropertySourceKind.MATERIALIZED_COLUMN,+ minmax=True,+ blocker=PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE,+ semantic_type=ast.FloatType(nullable=True),+ )++ eligibility = eligibility_from_plan(plan, value_expr=ast.Constant(value=100, start=10, end=13))++ assert eligibility.quickfix is None+ assert eligibility.fix_action == PredicateFixAction.EDIT_PROPERTY_TYPE+def test_a_denied_property_reports_the_same_as_an_unmaterialized_one(self) -> None:denied = eligibility_from_plan(_plan(restricted=True))allowed = eligibility_from_plan(_plan())@@ -351,6 +482,8 @@ class TestIndexEligibilityVerdicts(SimpleTestCase):message="",fix=None,ai_fix_prompt=None,+ fix_action=None,+ quickfix=None,start=None,end=None,)@@ -436,6 +569,51 @@ class TestIndexEligibilityThroughThePlanner(BaseTest):assert predicate.fix is not Noneassert predicate.editor_actionable is False+ def test_number_against_a_text_column_gets_a_quoted_quickfix(self) -> None:+ query = "select count() from events where properties.$browser_version = 120"+ report = self._report(+ query,+ columns={"events": {("$browser_version", "properties"): _materialized("$browser_version", bloom=True)}},+ property_types={"$browser_version": {"type": PropertyType.String.value}},+ )++ [predicate] = report.predicates+ assert predicate.verdict == PredicateIndexVerdict.BLOCKED+ assert predicate.quickfix is not None+ assert predicate.quickfix.text == "'120'"+ assert query[predicate.quickfix.start : predicate.quickfix.end] == "120"++ def test_an_in_list_quickfix_covers_the_whole_bracketed_list(self) -> None:+ # The replacement text stands in for everything the range covers. If a Tuple's span ever+ # stopped including its parentheses, the edit would write `in (('120', '121'))`, which is+ # valid SQL that matches nothing.+ query = "select count() from events where properties.$browser_version in (120, 121)"+ report = self._report(+ query,+ columns={"events": {("$browser_version", "properties"): _materialized("$browser_version", bloom=True)}},+ property_types={"$browser_version": {"type": PropertyType.String.value}},+ )++ [predicate] = report.predicates+ assert predicate.quickfix is not None+ assert query[predicate.quickfix.start : predicate.quickfix.end] == "(120, 121)"+ assert predicate.quickfix.text == "('120', '121')"++ def test_an_ordering_comparison_through_the_planner_offers_no_rewrite(self) -> None:+ # The operator table and the copy are unit tested on a constructed plan, so this covers the+ # seam: that a real ordering comparison on a text column still reaches that state.+ report = self._report(+ "select count() from events where properties.$browser_version > 120",+ columns={"events": {("$browser_version", "properties"): _materialized("$browser_version", minmax=True)}},+ property_types={"$browser_version": {"type": PropertyType.String.value}},+ )++ [predicate] = report.predicates+ assert predicate.verdict == PredicateIndexVerdict.BLOCKED+ assert predicate.quickfix is None+ assert predicate.editor_actionable is False+ assert predicate.fix_action == PredicateFixAction.EDIT_PROPERTY_TYPE+class TestIndexEligibilityAnalysis(BaseTest):def _report(self, query: str) -> IndexEligibilityReport:@@ -490,6 +668,34 @@ class TestIndexEligibilityAnalysis(BaseTest):assert usage.property_name == "duration"assert usage.fix is not None+ def test_metadata_marks_only_the_literal_a_quickfix_rewrites(self) -> None:+ query = "select count() from events where properties.$browser_version = 120"+ columns: MaterializedColumnsByTable = {+ "events": {("$browser_version", "properties"): _materialized("$browser_version", bloom=True)}+ }+ PropertyDefinition.objects.create(team=self.team, name="$browser_version", property_type=PropertyType.String)++ with patch(+ "posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table", return_value=columns+ ):+ response = self._metadata(query)++ [warning] = response.warnings+ assert warning.fix == "'120'"+ assert query[warning.start : warning.end] == "120"+ [predicate] = response.index_usage or []+ assert predicate.quickfix is not None and predicate.quickfix.text == "'120'"++ def test_a_failed_analysis_leaves_the_query_valid(self) -> None:+ # The caller turns any exception from here into an invalid query, so a report that blows up+ # while it is being written into the response would tell the editor a working query is broken.+ with patch("posthog.hogql.metadata._record_index_usage", side_effect=ValueError("boom")):+ response = self._metadata("select count() from events where properties.duration > 100")++ assert response.isValid is True+ assert response.errors == []+ assert not response.index_usage+def test_metadata_reports_no_index_usage_without_property_filters(self) -> None:response = self._metadata("select count() from events where event = '$pageview'")diff --git a/posthog/schema.py b/posthog/schema.pyindex 0c5eb73929a6..8958578938c4 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -222,6 +222,7 @@ from posthog.schema_enums import (PlanningStepStatus as PlanningStepStatus,Position as Position,PrecomputationMode as PrecomputationMode,+ PredicateFixAction as PredicateFixAction,PredicateIndexVerdict as PredicateIndexVerdict,PredicateScope as PredicateScope,ProductIntentContext as ProductIntentContext,@@ -6692,26 +6693,16 @@ class PlanningStep(BaseModel):status: PlanningStepStatus-class PredicateIndexUsage(BaseModel):+class PredicateQuickfix(BaseModel):model_config = ConfigDict(extra="forbid",)- column_name: str | None = None- end: int | None = None- fix: str | None = None- message: str- operator: str = Field(..., description="HogQL comparison operator, e.g. `==`, `in`, `ilike`.")- physical_type: str = Field(..., description="Type the value is physically stored as.")- property_name: str- scope: PredicateScope- semantic_type: str = Field(..., description="Type the property definition declares.")- source_label: str = Field(+ end: int = Field(..., description="Character offset in the query where the replaced range ends.")+ start: int = Field(...,- description=("Where the value is physically read from, e.g. `materialized column` or `JSON blob`."),+ description="Character offset in the query where the replaced range starts.",)- start: int | None = None- usable_indexes: list[str] = Field(..., description="Skip indexes this predicate can actually use.")- verdict: PredicateIndexVerdict+ text: str = Field(..., description="Replacement text, substituted for the range verbatim.")class PreprocessingConfig(BaseModel):@@ -6760,23 +6751,6 @@ class PropertyValueItem(BaseModel):name: str | float | bool | None = None-class QueryResponseAlternative9(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- ch_table_names: list[str] | None = None- errors: list[HogQLNotice]- index_usage: list[PredicateIndexUsage] | None = Field(- default=None, description="One entry per property filter, in query order."- )- isUsingIndices: QueryIndexUsage | None = None- isValid: bool | None = None- notices: list[HogQLNotice]- query: str | None = None- table_names: list[str] | None = None- warnings: list[HogQLNotice]--class QueryResponseAlternative10(BaseModel):model_config = ConfigDict(extra="forbid",@@ -18036,76 +18010,6 @@ class HBOSDetectorConfig(BaseModel):)-class HogQLMetadataResponse(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- ch_table_names: list[str] | None = None- errors: list[HogQLNotice]- index_usage: list[PredicateIndexUsage] | None = Field(- default=None, description="One entry per property filter, in query order."- )- isUsingIndices: QueryIndexUsage | None = None- isValid: bool | None = None- notices: list[HogQLNotice]- query: str | None = None- table_names: list[str] | None = None- warnings: list[HogQLNotice]---class HogQLQueryResponse(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")- columns: list | None = Field(default=None, description="Returned columns")- error: str | None = Field(- default=None,- description=(- "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."- ),- )- explain: list[str] | None = Field(default=None, description="Query explanation output")- hasMore: bool | None = None- hogql: str | None = Field(default=None, description="Generated HogQL query.")- limit: int | None = None- metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- offset: int | None = None- query: str | None = Field(default=None, description="Input query string")- query_status: QueryStatus | None = Field(- default=None,- description=("Query status indicates whether next to the provided data, a query is still running."),- )- resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(- default=None,- description=("The resolved previous/comparison period date range, when comparing against another period"),- )- resolved_date_range: ResolvedDateRangeResponse | None = Field(- default=None, description="The date range used for the query"- )- results: list- timings: list[QueryTiming] | None = Field(- default=None,- description=("Measured timings for different parts of the query generation process"),- )- types: list | None = Field(default=None, description="Types of returned columns")- used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(- default=None,- description=("Connector-synced data warehouse sources referenced by this query, if any."),- )- warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(- default=None,- description=(- "Warnings about data warehouse sources referenced by the query whose"- " latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Also carries"- " access control warnings when a system-table query filters out objects"- " the user can't access."- ),- )--class IQRDetectorConfig(BaseModel):model_config = ConfigDict(extra="forbid",@@ -19847,6 +19751,36 @@ class PlanningMessage(BaseModel):type: Literal["ai/planning"] = "ai/planning"+class PredicateIndexUsage(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ ai_fix_prompt: str | None = Field(+ default=None,+ description=("Instruction for an AI rewrite of the query, set when a query edit would help."),+ )+ column_name: str | None = None+ end: int | None = None+ fix: str | None = Field(default=None, description="Prose advice for a reader.")+ fix_action: PredicateFixAction | None = None+ message: str+ operator: str = Field(..., description="HogQL comparison operator, e.g. `==`, `in`, `ilike`.")+ physical_type: str = Field(..., description="Type the value is physically stored as.")+ property_name: str+ quickfix: PredicateQuickfix | None = Field(+ default=None, description="A deterministic query edit that unblocks the index."+ )+ scope: PredicateScope+ semantic_type: str = Field(..., description="Type the property definition declares.")+ source_label: str = Field(+ ...,+ description=("Where the value is physically read from, e.g. `materialized column` or `JSON blob`."),+ )+ start: int | None = None+ usable_indexes: list[str] = Field(..., description="Skip indexes this predicate can actually use.")+ verdict: PredicateIndexVerdict++class PropertyValuesQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -20170,57 +20104,21 @@ class QueryResponseAlternative6(BaseModel):)-class QueryResponseAlternative8(BaseModel):+class QueryResponseAlternative9(BaseModel):model_config = ConfigDict(extra="forbid",)- clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")- columns: list | None = Field(default=None, description="Returned columns")- error: str | None = Field(- default=None,- description=(- "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."- ),- )- explain: list[str] | None = Field(default=None, description="Query explanation output")- hasMore: bool | None = None- hogql: str | None = Field(default=None, description="Generated HogQL query.")- limit: int | None = None- metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- offset: int | None = None- query: str | None = Field(default=None, description="Input query string")- query_status: QueryStatus | None = Field(- default=None,- description=("Query status indicates whether next to the provided data, a query is still running."),- )- resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(- default=None,- description=("The resolved previous/comparison period date range, when comparing against another period"),- )- resolved_date_range: ResolvedDateRangeResponse | None = Field(- default=None, description="The date range used for the query"- )- results: list- timings: list[QueryTiming] | None = Field(- default=None,- description=("Measured timings for different parts of the query generation process"),- )- types: list | None = Field(default=None, description="Types of returned columns")- used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(- default=None,- description=("Connector-synced data warehouse sources referenced by this query, if any."),- )- warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(- default=None,- description=(- "Warnings about data warehouse sources referenced by the query whose"- " latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Also carries"- " access control warnings when a system-table query filters out objects"- " the user can't access."- ),+ ch_table_names: list[str] | None = None+ errors: list[HogQLNotice]+ index_usage: list[PredicateIndexUsage] | None = Field(+ default=None, description="One entry per property filter, in query order.")+ isUsingIndices: QueryIndexUsage | None = None+ isValid: bool | None = None+ notices: list[HogQLNotice]+ query: str | None = None+ table_names: list[str] | None = None+ warnings: list[HogQLNotice]class QueryResponseAlternative11(BaseModel):@@ -21505,59 +21403,6 @@ class QueryResponseAlternative40(BaseModel):)-class QueryResponseAlternative41(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")- columns: list | None = Field(default=None, description="Returned columns")- error: str | None = Field(- default=None,- description=(- "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."- ),- )- explain: list[str] | None = Field(default=None, description="Query explanation output")- hasMore: bool | None = None- hogql: str | None = Field(default=None, description="Generated HogQL query.")- limit: int | None = None- metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- offset: int | None = None- query: str | None = Field(default=None, description="Input query string")- query_status: QueryStatus | None = Field(- default=None,- description=("Query status indicates whether next to the provided data, a query is still running."),- )- resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(- default=None,- description=("The resolved previous/comparison period date range, when comparing against another period"),- )- resolved_date_range: ResolvedDateRangeResponse | None = Field(- default=None, description="The date range used for the query"- )- results: list- timings: list[QueryTiming] | None = Field(- default=None,- description=("Measured timings for different parts of the query generation process"),- )- types: list | None = Field(default=None, description="Types of returned columns")- used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(- default=None,- description=("Connector-synced data warehouse sources referenced by this query, if any."),- )- warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(- default=None,- description=(- "Warnings about data warehouse sources referenced by the query whose"- " latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Also carries"- " access control warnings when a system-table query filters out objects"- " the user can't access."- ),- )--class QueryResponseAlternative42(BaseModel):model_config = ConfigDict(extra="forbid",@@ -25579,49 +25424,7 @@ class ActorsPropertyTaxonomyQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")-class AnyResponseType(- RootModel[- dict[str, Any]- | HogQueryResponse- | HogQLQueryResponse- | HogQLMetadataResponse- | HogQLAutocompleteResponse- | Any- | EventsQueryResponse- | SessionsQueryResponse- | ErrorTrackingQueryResponse- | LogsQueryResponse- | LogAttributesQueryResponse- | LogValuesQueryResponse- | MetricsQueryResponse- | TraceSpansQueryResponse- | TraceSpansAggregationQueryResponse- | TraceSpansTreeQueryResponse- | TraceSpansAttributeBreakdownQueryResponse- ]-):- root: (- dict[str, Any]- | HogQueryResponse- | HogQLQueryResponse- | HogQLMetadataResponse- | HogQLAutocompleteResponse- | Any- | EventsQueryResponse- | SessionsQueryResponse- | ErrorTrackingQueryResponse- | LogsQueryResponse- | LogAttributesQueryResponse- | LogValuesQueryResponse- | MetricsQueryResponse- | TraceSpansQueryResponse- | TraceSpansAggregationQueryResponse- | TraceSpansTreeQueryResponse- | TraceSpansAttributeBreakdownQueryResponse- )---class AssistantBasePropertyFilter(+class AssistantBasePropertyFilter(RootModel[AssistantDateTimePropertyFilter| AssistantSetPropertyFilter@@ -26163,74 +25966,6 @@ class CachedErrorTrackingQueryResponse(BaseModel):)-class CachedHogQLQueryResponse(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- cache_key: str- cache_target_age: AwareDatetime | None = None- calculation_trigger: str | None = Field(- default=None,- description=("What triggered the calculation of the query, leave empty if user/immediate"),- )- clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")- columns: list | None = Field(default=None, description="Returned columns")- error: str | None = Field(- default=None,- description=(- "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."- ),- )- explain: list[str] | None = Field(default=None, description="Query explanation output")- hasMore: bool | None = None- hogql: str | None = Field(default=None, description="Generated HogQL query.")- is_cached: bool- last_refresh: AwareDatetime- limit: int | None = None- metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- next_allowed_client_refresh: AwareDatetime- offset: int | None = None- query: str | None = Field(default=None, description="Input query string")- query_metadata: dict[str, Any] | None = None- query_scan: QueryScanSummary | None = Field(- default=None,- description=("The rows and time of the run that produced these results, with its analysis once it is stored."),- )- query_status: QueryStatus | None = Field(- default=None,- description=("Query status indicates whether next to the provided data, a query is still running."),- )- resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(- default=None,- description=("The resolved previous/comparison period date range, when comparing against another period"),- )- resolved_date_range: ResolvedDateRangeResponse | None = Field(- default=None, description="The date range used for the query"- )- results: list- timezone: str- timings: list[QueryTiming] | None = Field(- default=None,- description=("Measured timings for different parts of the query generation process"),- )- types: list | None = Field(default=None, description="Types of returned columns")- used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(- default=None,- description=("Connector-synced data warehouse sources referenced by this query, if any."),- )- warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(- default=None,- description=(- "Warnings about data warehouse sources referenced by the query whose"- " latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Also carries"- " access control warnings when a system-table query filters out objects"- " the user can't access."- ),- )--class CachedInsightActorsQueryOptionsResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -26653,59 +26388,6 @@ class DashboardFilter(BaseModel):properties: list[AnyPropertyFilterDiscriminated] | None = None-class Response3(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")- columns: list | None = Field(default=None, description="Returned columns")- error: str | None = Field(- default=None,- description=(- "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."- ),- )- explain: list[str] | None = Field(default=None, description="Query explanation output")- hasMore: bool | None = None- hogql: str | None = Field(default=None, description="Generated HogQL query.")- limit: int | None = None- metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- offset: int | None = None- query: str | None = Field(default=None, description="Input query string")- query_status: QueryStatus | None = Field(- default=None,- description=("Query status indicates whether next to the provided data, a query is still running."),- )- resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(- default=None,- description=("The resolved previous/comparison period date range, when comparing against another period"),- )- resolved_date_range: ResolvedDateRangeResponse | None = Field(- default=None, description="The date range used for the query"- )- results: list- timings: list[QueryTiming] | None = Field(- default=None,- description=("Measured timings for different parts of the query generation process"),- )- types: list | None = Field(default=None, description="Types of returned columns")- used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(- default=None,- description=("Connector-synced data warehouse sources referenced by this query, if any."),- )- warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(- default=None,- description=(- "Warnings about data warehouse sources referenced by the query whose"- " latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Also carries"- " access control warnings when a system-table query filters out objects"- " the user can't access."- ),- )--class Response14(BaseModel):model_config = ConfigDict(extra="forbid",@@ -27440,43 +27122,74 @@ class HogQLFilters(BaseModel):properties: list[AnyPropertyFilterDiscriminated] | None = None-class HogQLQuery(BaseModel):+class HogQLMetadataResponse(BaseModel):model_config = ConfigDict(extra="forbid",)- connectionId: str | None = Field(- default=None,- description=(- "Optional id of a direct-query-capable external data source to run against"- " instead of ClickHouse — a pure-direct source, or a synced source with"- " direct query enabled."- ),+ ch_table_names: list[str] | None = None+ errors: list[HogQLNotice]+ index_usage: list[PredicateIndexUsage] | None = Field(+ default=None, description="One entry per property filter, in query order.")- explain: bool | None = None- filters: HogQLFilters | None = Field(+ isUsingIndices: QueryIndexUsage | None = None+ isValid: bool | None = None+ notices: list[HogQLNotice]+ query: str | None = None+ table_names: list[str] | None = None+ warnings: list[HogQLNotice]+++class HogQLQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")+ columns: list | None = Field(default=None, description="Returned columns")+ error: str | None = Field(default=None,description=(- "Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder"+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)- kind: Literal["HogQLQuery"] = "HogQLQuery"+ explain: list[str] | None = Field(default=None, description="Query explanation output")+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- name: str | None = Field(default=None, description="Client provided name of the query")- query: str- response: HogQLQueryResponse | None = None- sendRawQuery: bool | None = Field(+ offset: int | None = None+ query: str | None = Field(default=None, description="Input query string")+ query_status: QueryStatus | None = Field(default=None,- description=("Run the selected connection query directly without translating it through HogQL first"),+ description=("Query status indicates whether next to the provided data, a query is still running."),)- tags: QueryLogTags | None = None- values: dict[str, Any] | None = Field(+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(default=None,- description=("Constant values that can be referenced with the {placeholder} syntax in the query"),+ description=("The resolved previous/comparison period date range, when comparing against another period"),)- variables: dict[str, HogQLVariable] | None = Field(- default=None, description="Variables to be substituted into the query"+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ types: list | None = Field(default=None, description="Types of returned columns")+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(+ default=None,+ description=("Connector-synced data warehouse sources referenced by this query, if any."),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Also carries"+ " access control warnings when a system-table query filters out objects"+ " the user can't access."+ ),)- version: float | None = Field(default=None, description="version of the node, used for schema migrations")class InsightActorsQueryOptionsResponse(BaseModel):@@ -28487,22 +28200,26 @@ class PropertyValuesQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")-class QueryResponseAlternative17(BaseModel):+class QueryResponseAlternative8(BaseModel):model_config = ConfigDict(extra="forbid",)- columns: list[str] | None = None+ clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")+ columns: list | None = Field(default=None, description="Returned columns")error: str | None = Field(default=None,description=("Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)+ explain: list[str] | None = Field(default=None, description="Query explanation output")hasMore: bool | None = Nonehogql: str | None = Field(default=None, description="Generated HogQL query.")limit: int | None = None+ metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: int | None = None+ query: str | None = Field(default=None, description="Input query string")query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -28514,11 +28231,12 @@ class QueryResponseAlternative17(BaseModel):resolved_date_range: ResolvedDateRangeResponse | None = Field(default=None, description="The date range used for the query")- results: list[ErrorTrackingCorrelatedIssue]+ results: listtimings: list[QueryTiming] | None = Field(default=None,description=("Measured timings for different parts of the query generation process"),)+ types: list | None = Field(default=None, description="Types of returned columns")used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -28528,32 +28246,184 @@ class QueryResponseAlternative17(BaseModel):description=("Warnings about data warehouse sources referenced by the query whose"" latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Accumulated"- " across every HogQL execution that contributes to this response — so"- " insights backed by warehouse tables (Trends, Funnels, etc.) receive"- " the same warnings as raw HogQL queries. Also carries access control"- " warnings when a system-table query filters out objects the user can't"- " access."+ " stale. Results may not reflect current source data. Also carries"+ " access control warnings when a system-table query filters out objects"+ " the user can't access."),)-class RecordingsQuery(BaseModel):+class QueryResponseAlternative17(BaseModel):model_config = ConfigDict(extra="forbid",)- actions: list[dict[str, Any]] | None = None- after: str | None = Field(+ columns: list[str] | None = None+ error: str | None = Field(default=None,description=(- "Cursor for pagination. Contains the ordering value and session_id from the"- " last record of the previous page."+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)- comment_text: RecordingPropertyFilter | None = None- console_log_filters: list[LogEntryPropertyFilter] | None = None- date_from: str | None = "-3d"- date_to: str | None = None+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[ErrorTrackingCorrelatedIssue]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(+ default=None,+ description=("Connector-synced data warehouse sources referenced by this query, if any."),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Accumulated"+ " across every HogQL execution that contributes to this response — so"+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"+ " the same warnings as raw HogQL queries. Also carries access control"+ " warnings when a system-table query filters out objects the user can't"+ " access."+ ),+ )+++class QueryResponseAlternative41(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")+ columns: list | None = Field(default=None, description="Returned columns")+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ explain: list[str] | None = Field(default=None, description="Query explanation output")+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query: str | None = Field(default=None, description="Input query string")+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ types: list | None = Field(default=None, description="Types of returned columns")+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(+ default=None,+ description=("Connector-synced data warehouse sources referenced by this query, if any."),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Also carries"+ " access control warnings when a system-table query filters out objects"+ " the user can't access."+ ),+ )+++class QueryResponseAlternative53(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ columns: list[str] | None = None+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list[ErrorTrackingCorrelatedIssue]+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(+ default=None,+ description=("Connector-synced data warehouse sources referenced by this query, if any."),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Accumulated"+ " across every HogQL execution that contributes to this response — so"+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"+ " the same warnings as raw HogQL queries. Also carries access control"+ " warnings when a system-table query filters out objects the user can't"+ " access."+ ),+ )+++class RecordingsQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ actions: list[dict[str, Any]] | None = None+ after: str | None = Field(+ default=None,+ description=(+ "Cursor for pagination. Contains the ordering value and session_id from the"+ " last record of the previous page."+ ),+ )+ comment_text: RecordingPropertyFilter | None = None+ console_log_filters: list[LogEntryPropertyFilter] | None = None+ date_from: str | None = "-3d"+ date_to: str | None = Nonedistinct_ids: list[str] | None = Noneevents: list[dict[str, Any]] | None = Noneexperiment_exposure: RecordingsQueryExperimentExposureFilter | None = Field(@@ -28973,6 +28843,48 @@ class AnyEntityNodeDataWarehouseNode(RootModel[EventsNode | ActionsNode | DataWaroot: EventsNode | ActionsNode | DataWarehouseNode+class AnyResponseType(+ RootModel[+ dict[str, Any]+ | HogQueryResponse+ | HogQLQueryResponse+ | HogQLMetadataResponse+ | HogQLAutocompleteResponse+ | Any+ | EventsQueryResponse+ | SessionsQueryResponse+ | ErrorTrackingQueryResponse+ | LogsQueryResponse+ | LogAttributesQueryResponse+ | LogValuesQueryResponse+ | MetricsQueryResponse+ | TraceSpansQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansTreeQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse+ ]+):+ root: (+ dict[str, Any]+ | HogQueryResponse+ | HogQLQueryResponse+ | HogQLMetadataResponse+ | HogQLAutocompleteResponse+ | Any+ | EventsQueryResponse+ | SessionsQueryResponse+ | ErrorTrackingQueryResponse+ | LogsQueryResponse+ | LogAttributesQueryResponse+ | LogValuesQueryResponse+ | MetricsQueryResponse+ | TraceSpansQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansTreeQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse+ )++class AssistantFunnelsActorsQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -29139,6 +29051,74 @@ class CachedErrorTrackingIssueCorrelationQueryResponse(BaseModel):)+class CachedHogQLQueryResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ cache_key: str+ cache_target_age: AwareDatetime | None = None+ calculation_trigger: str | None = Field(+ default=None,+ description=("What triggered the calculation of the query, leave empty if user/immediate"),+ )+ clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")+ columns: list | None = Field(default=None, description="Returned columns")+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ explain: list[str] | None = Field(default=None, description="Query explanation output")+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ is_cached: bool+ last_refresh: AwareDatetime+ limit: int | None = None+ metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ next_allowed_client_refresh: AwareDatetime+ offset: int | None = None+ query: str | None = Field(default=None, description="Input query string")+ query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(+ default=None,+ description=("The resolved previous/comparison period date range, when comparing against another period"),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list+ timezone: str+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ types: list | None = Field(default=None, description="Types of returned columns")+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(+ default=None,+ description=("Connector-synced data warehouse sources referenced by this query, if any."),+ )+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(+ default=None,+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Also carries"+ " access control warnings when a system-table query filters out objects"+ " the user can't access."+ ),+ )++class CoreEvent(BaseModel):model_config = ConfigDict(extra="forbid",@@ -29170,22 +29150,26 @@ class CustomerAnalyticsConfig(BaseModel):subscription_event: EventsNode | ActionsNode-class Response15(BaseModel):+class Response3(BaseModel):model_config = ConfigDict(extra="forbid",)- columns: list[str] | None = None+ clickhouse: str | None = Field(default=None, description="Executed ClickHouse query")+ columns: list | None = Field(default=None, description="Returned columns")error: str | None = Field(default=None,description=("Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."),)+ explain: list[str] | None = Field(default=None, description="Query explanation output")hasMore: bool | None = Nonehogql: str | None = Field(default=None, description="Generated HogQL query.")limit: int | None = None+ metadata: HogQLMetadataResponse | None = Field(default=None, description="Query metadata output")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: int | None = None+ query: str | None = Field(default=None, description="Input query string")query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -29197,11 +29181,12 @@ class Response15(BaseModel):resolved_date_range: ResolvedDateRangeResponse | None = Field(default=None, description="The date range used for the query")- results: list[ErrorTrackingCorrelatedIssue]+ results: listtimings: list[QueryTiming] | None = Field(default=None,description=("Measured timings for different parts of the query generation process"),)+ types: list | None = Field(default=None, description="Types of returned columns")used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(default=None,description=("Connector-synced data warehouse sources referenced by this query, if any."),@@ -29211,95 +29196,62 @@ class Response15(BaseModel):description=("Warnings about data warehouse sources referenced by the query whose"" latest sync failed, is paused, hit a billing limit, or is otherwise"- " stale. Results may not reflect current source data. Accumulated"- " across every HogQL execution that contributes to this response — so"- " insights backed by warehouse tables (Trends, Funnels, etc.) receive"- " the same warnings as raw HogQL queries. Also carries access control"- " warnings when a system-table query filters out objects the user can't"- " access."+ " stale. Results may not reflect current source data. Also carries"+ " access control warnings when a system-table query filters out objects"+ " the user can't access."),)-class DataVisualizationNode(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- chartSettings: ChartSettings | None = None- display: ChartDisplayType | None = None- kind: Literal["DataVisualizationNode"] = "DataVisualizationNode"- source: HogQLQuery- tableSettings: TableSettings | None = None- version: float | None = Field(default=None, description="version of the node, used for schema migrations")---class DatabaseSchemaEndpointTable(BaseModel):+class Response15(BaseModel):model_config = ConfigDict(extra="forbid",)- certification: DatabaseSchemaTableCertification | None = Field(+ columns: list[str] | None = None+ error: str | None = Field(default=None,- description=("Present only when the table or view carries a settled data catalog certification."),+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),)- fields: dict[str, DatabaseSchemaField]- id: str- name: str- query: HogQLQuery- row_count: float | None = None- status: str | None = None- type: Literal["endpoint"] = "endpoint"---class DatabaseSchemaManagedViewTable(BaseModel):- model_config = ConfigDict(- extra="forbid",+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),)- certification: DatabaseSchemaTableCertification | None = Field(+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(default=None,- description=("Present only when the table or view carries a settled data catalog certification."),+ description=("The resolved previous/comparison period date range, when comparing against another period"),)- fields: dict[str, DatabaseSchemaField]- id: str- kind: DatabaseSchemaManagedViewTableKind- name: str- query: HogQLQuery- row_count: float | None = None- source_id: str | None = None- type: Literal["managed_view"] = "managed_view"---class DatabaseSchemaMaterializedViewTable(BaseModel):- model_config = ConfigDict(- extra="forbid",+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query")- certification: DatabaseSchemaTableCertification | None = Field(+ results: list[ErrorTrackingCorrelatedIssue]+ timings: list[QueryTiming] | None = Field(default=None,- description=("Present only when the table or view carries a settled data catalog certification."),+ description=("Measured timings for different parts of the query generation process"),)- fields: dict[str, DatabaseSchemaField]- id: str- last_run_at: str | None = None- name: str- query: HogQLQuery- row_count: float | None = None- status: str | None = None- type: Literal["materialized_view"] = "materialized_view"---class DatabaseSchemaViewTable(BaseModel):- model_config = ConfigDict(- extra="forbid",+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(+ default=None,+ description=("Connector-synced data warehouse sources referenced by this query, if any."),)- certification: DatabaseSchemaTableCertification | None = Field(+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(default=None,- description=("Present only when the table or view carries a settled data catalog certification."),+ description=(+ "Warnings about data warehouse sources referenced by the query whose"+ " latest sync failed, is paused, hit a billing limit, or is otherwise"+ " stale. Results may not reflect current source data. Accumulated"+ " across every HogQL execution that contributes to this response — so"+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"+ " the same warnings as raw HogQL queries. Also carries access control"+ " warnings when a system-table query filters out objects the user can't"+ " access."+ ),)- fields: dict[str, DatabaseSchemaField]- id: str- name: str- query: HogQLQuery- row_count: float | None = None- type: Literal["view"] = "view"class EnsembleDetectorConfig(BaseModel):@@ -29452,6 +29404,45 @@ class FunnelsFilter(BaseModel):useUdf: bool | None = None+class HogQLQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ connectionId: str | None = Field(+ default=None,+ description=(+ "Optional id of a direct-query-capable external data source to run against"+ " instead of ClickHouse — a pure-direct source, or a synced source with"+ " direct query enabled."+ ),+ )+ explain: bool | None = None+ filters: HogQLFilters | None = Field(+ default=None,+ description=(+ "Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder"+ ),+ )+ kind: Literal["HogQLQuery"] = "HogQLQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ name: str | None = Field(default=None, description="Client provided name of the query")+ query: str+ response: HogQLQueryResponse | None = None+ sendRawQuery: bool | None = Field(+ default=None,+ description=("Run the selected connection query directly without translating it through HogQL first"),+ )+ tags: QueryLogTags | None = None+ values: dict[str, Any] | None = Field(+ default=None,+ description=("Constant values that can be referenced with the {placeholder} syntax in the query"),+ )+ variables: dict[str, HogQLVariable] | None = Field(+ default=None, description="Variables to be substituted into the query"+ )+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class InsightFilter(RootModel[TrendsFilter@@ -29671,6 +29662,87 @@ class TraceSpansTreeQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class DataVisualizationNode(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ chartSettings: ChartSettings | None = None+ display: ChartDisplayType | None = None+ kind: Literal["DataVisualizationNode"] = "DataVisualizationNode"+ source: HogQLQuery+ tableSettings: TableSettings | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")+++class DatabaseSchemaEndpointTable(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ certification: DatabaseSchemaTableCertification | None = Field(+ default=None,+ description=("Present only when the table or view carries a settled data catalog certification."),+ )+ fields: dict[str, DatabaseSchemaField]+ id: str+ name: str+ query: HogQLQuery+ row_count: float | None = None+ status: str | None = None+ type: Literal["endpoint"] = "endpoint"+++class DatabaseSchemaManagedViewTable(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ certification: DatabaseSchemaTableCertification | None = Field(+ default=None,+ description=("Present only when the table or view carries a settled data catalog certification."),+ )+ fields: dict[str, DatabaseSchemaField]+ id: str+ kind: DatabaseSchemaManagedViewTableKind+ name: str+ query: HogQLQuery+ row_count: float | None = None+ source_id: str | None = None+ type: Literal["managed_view"] = "managed_view"+++class DatabaseSchemaMaterializedViewTable(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ certification: DatabaseSchemaTableCertification | None = Field(+ default=None,+ description=("Present only when the table or view carries a settled data catalog certification."),+ )+ fields: dict[str, DatabaseSchemaField]+ id: str+ last_run_at: str | None = None+ name: str+ query: HogQLQuery+ row_count: float | None = None+ status: str | None = None+ type: Literal["materialized_view"] = "materialized_view"+++class DatabaseSchemaViewTable(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ certification: DatabaseSchemaTableCertification | None = Field(+ default=None,+ description=("Present only when the table or view carries a settled data catalog certification."),+ )+ fields: dict[str, DatabaseSchemaField]+ id: str+ name: str+ query: HogQLQuery+ row_count: float | None = None+ type: Literal["view"] = "view"++class DetectorConfig(RootModel[EnsembleDetectorConfig@@ -30167,24 +30239,6 @@ class PathsV2Query(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")-class QueryResponseAlternative69(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- joins: list[DataWarehouseViewLink]- tables: dict[- str,- DatabaseSchemaPostHogTable- | DatabaseSchemaSystemTable- | DatabaseSchemaDataWarehouseTable- | DatabaseSchemaViewTable- | DatabaseSchemaManagedViewTable- | DatabaseSchemaBatchExportTable- | DatabaseSchemaMaterializedViewTable- | DatabaseSchemaEndpointTable,- ]--class SessionsQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -30270,24 +30324,6 @@ class CalendarHeatmapQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")-class DatabaseSchemaQueryResponse(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- joins: list[DataWarehouseViewLink]- tables: dict[- str,- DatabaseSchemaPostHogTable- | DatabaseSchemaSystemTable- | DatabaseSchemaDataWarehouseTable- | DatabaseSchemaViewTable- | DatabaseSchemaManagedViewTable- | DatabaseSchemaBatchExportTable- | DatabaseSchemaMaterializedViewTable- | DatabaseSchemaEndpointTable,- ]--class ExperimentFunnelMetric(BaseModel):model_config = ConfigDict(extra="forbid",@@ -30482,6 +30518,24 @@ class PathsV2ActorsQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")+class QueryResponseAlternative69(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ joins: list[DataWarehouseViewLink]+ tables: dict[+ str,+ DatabaseSchemaPostHogTable+ | DatabaseSchemaSystemTable+ | DatabaseSchemaDataWarehouseTable+ | DatabaseSchemaViewTable+ | DatabaseSchemaManagedViewTable+ | DatabaseSchemaBatchExportTable+ | DatabaseSchemaMaterializedViewTable+ | DatabaseSchemaEndpointTable,+ ]++class StickinessQuery(BaseModel):model_config = ConfigDict(extra="forbid",@@ -30518,30 +30572,22 @@ class StickinessQuery(BaseModel):version: float | None = Field(default=None, description="version of the node, used for schema migrations")-class DatabaseSchemaQuery(BaseModel):+class DatabaseSchemaQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",)- connectionId: str | None = Field(- default=None,- description="Optional direct external data source id for schema introspection",- )- includeFields: bool | None = Field(- default=None,- description=("When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true."),- )- kind: Literal["DatabaseSchemaQuery"] = "DatabaseSchemaQuery"- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")- response: DatabaseSchemaQueryResponse | None = None- tables: list[str] | None = Field(- default=None,- description=(- "Only serialize these tables (keys as returned in the response, e.g."- " `events` or `zendesk.groups`). Omit for all tables."- ),- )- tags: QueryLogTags | None = None- version: float | None = Field(default=None, description="version of the node, used for schema migrations")+ joins: list[DataWarehouseViewLink]+ tables: dict[+ str,+ DatabaseSchemaPostHogTable+ | DatabaseSchemaSystemTable+ | DatabaseSchemaDataWarehouseTable+ | DatabaseSchemaViewTable+ | DatabaseSchemaManagedViewTable+ | DatabaseSchemaBatchExportTable+ | DatabaseSchemaMaterializedViewTable+ | DatabaseSchemaEndpointTable,+ ]class ExperimentMetricTypeProps(@@ -30682,6 +30728,32 @@ class Response17(BaseModel):)+class DatabaseSchemaQuery(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ connectionId: str | None = Field(+ default=None,+ description="Optional direct external data source id for schema introspection",+ )+ includeFields: bool | None = Field(+ default=None,+ description=("When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true."),+ )+ kind: Literal["DatabaseSchemaQuery"] = "DatabaseSchemaQuery"+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ response: DatabaseSchemaQueryResponse | None = None+ tables: list[str] | None = Field(+ default=None,+ description=(+ "Only serialize these tables (keys as returned in the response, e.g."+ " `events` or `zendesk.groups`). Omit for all tables."+ ),+ )+ tags: QueryLogTags | None = None+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")++class EndpointRequest(BaseModel):model_config = ConfigDict(extra="forbid",@@ -31022,6 +31094,7 @@ class QueryResponseAlternative(| QueryResponseAlternative50| QueryResponseAlternative51| QueryResponseAlternative52+ | QueryResponseAlternative53| QueryResponseAlternative54| QueryResponseAlternative55| QueryResponseAlternative56@@ -31134,6 +31207,7 @@ class QueryResponseAlternative(| QueryResponseAlternative50| QueryResponseAlternative51| QueryResponseAlternative52+ | QueryResponseAlternative53| QueryResponseAlternative54| QueryResponseAlternative55| QueryResponseAlternative56diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 692bbb8465ba..07a8858e25c5 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2246,6 +2246,12 @@ class PlanningStepStatus(StrEnum):COMPLETED = "completed"+class PredicateFixAction(StrEnum):+ EDIT_QUERY = "edit_query"+ EDIT_PROPERTY_TYPE = "edit_property_type"+ MATERIALIZE = "materialize"++class PredicateIndexVerdict(StrEnum):INDEXED = "indexed"BLOCKED = "blocked"diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 3bc97a2ea296..142b49019a2b 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -4861,6 +4861,23 @@ export interface HogQLNoticeApi {start?: number | null}+export type PredicateFixActionApi = (typeof PredicateFixActionApi)[keyof typeof PredicateFixActionApi]++export const PredicateFixActionApi = {+ EditQuery: 'edit_query',+ EditPropertyType: 'edit_property_type',+ Materialize: 'materialize',+} as const++export interface PredicateQuickfixApi {+ /** Character offset in the query where the replaced range ends. */+ end: number+ /** Character offset in the query where the replaced range starts. */+ start: number+ /** Replacement text, substituted for the range verbatim. */+ text: string+}+export type PredicateScopeApi = (typeof PredicateScopeApi)[keyof typeof PredicateScopeApi]export const PredicateScopeApi = {@@ -4881,15 +4898,21 @@ export const PredicateIndexVerdictApi = {} as constexport interface PredicateIndexUsageApi {+ /** Instruction for an AI rewrite of the query, set when a query edit would help. */+ ai_fix_prompt?: string | nullcolumn_name?: string | nullend?: number | null+ /** Prose advice for a reader. */fix?: string | null+ fix_action?: PredicateFixActionApi | nullmessage: string/** HogQL comparison operator, e.g. `==`, `in`, `ilike`. */operator: string/** Type the value is physically stored as. */physical_type: stringproperty_name: string+ /** A deterministic query edit that unblocks the index. */+ quickfix?: PredicateQuickfixApi | nullscope: PredicateScopeApi/** Type the property definition declares. */semantic_type: stringdiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 3c98e4416efd..bcc2edf59b77 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -3821,6 +3821,23 @@ export interface HogQLNoticeApi {start?: number | null}+export type PredicateFixActionApi = (typeof PredicateFixActionApi)[keyof typeof PredicateFixActionApi]++export const PredicateFixActionApi = {+ EditQuery: 'edit_query',+ EditPropertyType: 'edit_property_type',+ Materialize: 'materialize',+} as const++export interface PredicateQuickfixApi {+ /** Character offset in the query where the replaced range ends. */+ end: number+ /** Character offset in the query where the replaced range starts. */+ start: number+ /** Replacement text, substituted for the range verbatim. */+ text: string+}+export type PredicateScopeApi = (typeof PredicateScopeApi)[keyof typeof PredicateScopeApi]export const PredicateScopeApi = {@@ -3841,15 +3858,21 @@ export const PredicateIndexVerdictApi = {} as constexport interface PredicateIndexUsageApi {+ /** Instruction for an AI rewrite of the query, set when a query edit would help. */+ ai_fix_prompt?: string | nullcolumn_name?: string | nullend?: number | null+ /** Prose advice for a reader. */fix?: string | null+ fix_action?: PredicateFixActionApi | nullmessage: string/** HogQL comparison operator, e.g. `==`, `in`, `ilike`. */operator: string/** Type the value is physically stored as. */physical_type: stringproperty_name: string+ /** A deterministic query edit that unblocks the index. */+ quickfix?: PredicateQuickfixApi | nullscope: PredicateScopeApi/** Type the property definition declares. */semantic_type: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b0e2272b93c5..abbf7f61cebd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -5975,6 +5975,24 @@ export namespace Schemas {start?: number | null;}+ export type PredicateFixAction = typeof PredicateFixAction[keyof typeof PredicateFixAction];+++ export const PredicateFixAction = {+ EditQuery: 'edit_query',+ EditPropertyType: 'edit_property_type',+ Materialize: 'materialize',+ } as const;++ export interface PredicateQuickfix {+ /** Character offset in the query where the replaced range ends. */+ end: number;+ /** Character offset in the query where the replaced range starts. */+ start: number;+ /** Replacement text, substituted for the range verbatim. */+ text: string;+ }+export type PredicateScope = typeof PredicateScope[keyof typeof PredicateScope];@@ -5997,15 +6015,21 @@ export namespace Schemas {} as const;export interface PredicateIndexUsage {+ /** Instruction for an AI rewrite of the query, set when a query edit would help. */+ ai_fix_prompt?: string | null;column_name?: string | null;end?: number | null;+ /** Prose advice for a reader. */fix?: string | null;+ fix_action?: PredicateFixAction | null;message: string;/** HogQL comparison operator, e.g. `==`, `in`, `ilike`. */operator: string;/** Type the value is physically stored as. */physical_type: string;property_name: string;+ /** A deterministic query edit that unblocks the index. */+ quickfix?: PredicateQuickfix | null;scope: PredicateScope;/** Type the property definition declares. */semantic_type: string;@@ -82283,6 +82307,32 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}+ export interface QueryResponseAlternative53 {+ columns?: string[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null;+ hasMore?: boolean | null;+ /** Generated HogQL query. */+ hogql?: string | null;+ limit?: number | null;+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ offset?: number | null;+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatus | null;+ /** The resolved previous/comparison period date range, when comparing against another period */+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: ErrorTrackingCorrelatedIssue[];+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ /** Connector-synced data warehouse sources referenced by this query, if any. */+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;+ }+export type QueryResponseAlternative54CredibleIntervals = {[key: string]: number[]};export type QueryResponseAlternative54InsightItemItem = { [key: string]: unknown };@@ -83578,7 +83628,7 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | unknown | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112 | QueryResponseAlternative113;+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | unknown | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112 | QueryResponseAlternative113;export interface QueryScanResponse {analysis?: QueryScanAnalysis | null;