Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hogql): report per-filter index eligibility before a query runs (#83131)

George Munyoroacb0fc6cb193
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 77664f1a4776..1f273edfebd7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6312,6 +6312,18 @@ snapshots:
hash: v1.k794b7964.f90080b48e02650b50bee9d714dc226f41aec9108a4878a67abccc18735aa7a2.9vBFfiHItb00dBAS4YWq2EugPAeQUVjYFkobGWL8pHE
scenes-app-data-pipelines-event-filtering--switch-mode-to-dry-run--light:
hash: v1.k794b7964.3708d5dd091da98ff4fe36c820270151d0fbd4a5cec31afa03956f1a85bfefa4.96jKaZE5nf0iQjd6-CQo8JSaAcQ64JssqLmmwhMs5cM
+ scenes-app-data-warehouse-query-index-usage--every-filter-indexed--dark:
+ hash: v1.k794b7964.5593a848fb86d8d93d2d347b17de81b878cff3e9d69ccf976562e60bddeb71fa.-EnSwW5B20DYmE0dRl-8VfENfxJMJrMl-vWmmkJ1sG0
+ scenes-app-data-warehouse-query-index-usage--every-filter-indexed--light:
+ hash: v1.k794b7964.7e4a5eda2f4069a0900025a0bf5b3cf872f6df3a2c6e26a2ca77eb08abaaf0d9.20l9G4blkJXWxPJDzJEyijy4MCRT4GJwV_zfCyB_a3I
+ scenes-app-data-warehouse-query-index-usage--refreshing-after-an-edit--dark:
+ hash: v1.k794b7964.9b9bd0992795d1670ea1aff5182440e3e8a8ca1b03b6cc152c328376a6a3389a.sMHpFBf4hTvSGkub_Zb4B3q5kPPpVkvWvRzWEonct3w
+ scenes-app-data-warehouse-query-index-usage--refreshing-after-an-edit--light:
+ hash: v1.k794b7964.f78066e01a69667a48e1e869c1c68dd0b741dcc49b6ef524bef7d4d86ddc95dd.Hm8P3Va8Xi--tajenCleRBUZ6Y813IyfCzm9_huabH4
+ scenes-app-data-warehouse-query-index-usage--some-filters-scan--dark:
+ hash: v1.k794b7964.0294ddfda0b0e43413c60dbde62d947c90c6ae72ad995763c8fa4c20c864a404.KdjhHgnYl1jq1yo8C4tTH79O-M1MefHWEB1V_f-5wxY
+ scenes-app-data-warehouse-query-index-usage--some-filters-scan--light:
+ hash: v1.k794b7964.992eb504adc18600876c965dea224ae77f277d1fd8033784813d20187b42a497.jgO2O4E-p2e97zY9OrOO6NnZrllkBdAuuFrskzGR9d4
scenes-app-data-warehouse-settings-api-version-deprecation-banner--with-sunset-date--dark:
hash: v1.k794b7964.5a4d9d3ac30fd4e7a83925bb77a89685f5ad1b95e44431dc87696251acd62941.STCVyoJPmpKL8izqztWRz12VuY1AJPSbVh74dSG4k4U
scenes-app-data-warehouse-settings-api-version-deprecation-banner--with-sunset-date--light:
diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsx
index 479e39423840..b888390cb23a 100644
--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx
+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx
@@ -40,6 +40,8 @@ export interface CodeEditorProps extends Omit<EditorProps, 'loading' | 'theme'>
sourceQuery?: AnyDataNode
globals?: Record<string, any>
schema?: Record<string, any> | null
+ /** Ask for per-filter index eligibility. Costs a second resolution pass server-side, so set it only where the result is rendered. */
+ indexUsage?: boolean
onMetadata?: (metadata: HogQLMetadataResponse | null) => void
onMetadataLoading?: (loading: boolean) => void
onFixWithAI?: (prompt: string) => void
@@ -151,6 +153,7 @@ export function CodeEditor({
sourceQuery,
schema,
onError,
+ indexUsage,
onMetadata,
onMetadataLoading,
onFixWithAI,
@@ -189,6 +192,7 @@ export function CodeEditor({
monaco: monaco,
editor: editor,
onError,
+ indexUsage,
onMetadata,
onMetadataLoading,
onFixWithAI,
diff --git a/frontend/src/lib/monaco/codeEditorLogic.tsx b/frontend/src/lib/monaco/codeEditorLogic.tsx
index 48db75457556..095162620c8b 100644
--- a/frontend/src/lib/monaco/codeEditorLogic.tsx
+++ b/frontend/src/lib/monaco/codeEditorLogic.tsx
@@ -51,6 +51,8 @@ export interface CodeEditorLogicProps {
editor?: editor.IStandaloneCodeEditor | null
globals?: Record<string, any>
onError?: (error: string | null) => void
+ /** Ask for per-filter index eligibility. Costs a second resolution pass server-side, so set it only where the result is rendered. */
+ indexUsage?: boolean
onMetadata?: (metadata: HogQLMetadataResponse | null) => void
onMetadataLoading?: (loading: boolean) => void
onFixWithAI?: (prompt: string) => void
@@ -185,6 +187,7 @@ export const codeEditorLogic = kea<codeEditorLogicType>([
sourceQuery,
variables,
connectionId,
+ indexUsage: props.indexUsage,
},
{ recursion: false }
)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f07cb5b080b4..5f3551c0f448 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -28635,6 +28635,10 @@
"description": "Extra globals for the query",
"type": "object"
},
+ "indexUsage": {
+ "description": "Analyze how each property filter reads its data. Costs a second type-resolution pass, so only editors that render the result should ask for it.",
+ "type": "boolean"
+ },
"kind": {
"const": "HogQLMetadata",
"type": "string"
@@ -28691,6 +28695,13 @@
},
"type": "array"
},
+ "index_usage": {
+ "description": "One entry per property filter, in query order.",
+ "items": {
+ "$ref": "#/definitions/PredicateIndexUsage"
+ },
+ "type": "array"
+ },
"isUsingIndices": {
"$ref": "#/definitions/QueryIndexUsage"
},
@@ -38476,6 +38487,79 @@
"enum": ["pending", "in_progress", "completed"],
"type": "string"
},
+ "PredicateIndexUsage": {
+ "additionalProperties": false,
+ "description": "How one property filter in the query reads its data, decided before the query runs.",
+ "properties": {
+ "column_name": {
+ "type": "string"
+ },
+ "end": {
+ "$ref": "#/definitions/integer"
+ },
+ "fix": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "operator": {
+ "description": "HogQL comparison operator, e.g. `==`, `in`, `ilike`.",
+ "type": "string"
+ },
+ "physical_type": {
+ "description": "Type the value is physically stored as.",
+ "type": "string"
+ },
+ "property_name": {
+ "type": "string"
+ },
+ "scope": {
+ "$ref": "#/definitions/PredicateScope"
+ },
+ "semantic_type": {
+ "description": "Type the property definition declares.",
+ "type": "string"
+ },
+ "source_label": {
+ "description": "Where the value is physically read from, e.g. `materialized column` or `JSON blob`.",
+ "type": "string"
+ },
+ "start": {
+ "$ref": "#/definitions/integer"
+ },
+ "usable_indexes": {
+ "description": "Skip indexes this predicate can actually use.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "verdict": {
+ "$ref": "#/definitions/PredicateIndexVerdict"
+ }
+ },
+ "required": [
+ "property_name",
+ "scope",
+ "operator",
+ "source_label",
+ "semantic_type",
+ "physical_type",
+ "usable_indexes",
+ "verdict",
+ "message"
+ ],
+ "type": "object"
+ },
+ "PredicateIndexVerdict": {
+ "enum": ["indexed", "blocked", "unindexed_column", "unindexed_json", "operator_not_indexable"],
+ "type": "string"
+ },
+ "PredicateScope": {
+ "enum": ["event", "person", "group", "unknown"],
+ "type": "string"
+ },
"PreprocessingConfig": {
"additionalProperties": false,
"description": "Preprocessing transforms applied to the time series before detection",
@@ -39804,6 +39888,13 @@
},
"type": "array"
},
+ "index_usage": {
+ "description": "One entry per property filter, in query order.",
+ "items": {
+ "$ref": "#/definitions/PredicateIndexUsage"
+ },
+ "type": "array"
+ },
"isUsingIndices": {
"$ref": "#/definitions/QueryIndexUsage"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 745f2f797f65..02b70972ed7b 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -763,10 +763,54 @@ export enum QueryIndexUsage {
Yes = 'yes',
}
+export enum PredicateIndexVerdict {
+ /** A skip index on the source column prunes granules for this predicate. */
+ Indexed = 'indexed',
+ /** The source carries an index this operator could use, but a type mismatch defeats it. */
+ Blocked = 'blocked',
+ /** The property reads from a dedicated column, but no index prunes this operator. */
+ UnindexedColumn = 'unindexed_column',
+ /** The property is parsed out of the JSON blob on every row. */
+ UnindexedJson = 'unindexed_json',
+ /** Negations, regexes and case-sensitive LIKE cannot be pruned by any skip index. */
+ OperatorNotIndexable = 'operator_not_indexable',
+}
+
+export enum PredicateScope {
+ Event = 'event',
+ Person = 'person',
+ Group = 'group',
+ Unknown = 'unknown',
+}
+
+/** How one property filter in the query reads its data, decided before the query runs. */
+export interface PredicateIndexUsage {
+ property_name: string
+ scope: PredicateScope
+ /** HogQL comparison operator, e.g. `==`, `in`, `ilike`. */
+ operator: string
+ /** Where the value is physically read from, e.g. `materialized column` or `JSON blob`. */
+ source_label: string
+ column_name?: string
+ /** Type the property definition declares. */
+ semantic_type: string
+ /** Type the value is physically stored as. */
+ physical_type: string
+ /** Skip indexes this predicate can actually use. */
+ usable_indexes: string[]
+ verdict: PredicateIndexVerdict
+ message: string
+ fix?: string
+ start?: integer
+ end?: integer
+}
+
export interface HogQLMetadataResponse {
query?: string
isValid?: boolean
isUsingIndices?: QueryIndexUsage
+ /** One entry per property filter, in query order. */
+ index_usage?: PredicateIndexUsage[]
errors: HogQLNotice[]
warnings: HogQLNotice[]
notices: HogQLNotice[]
@@ -874,6 +918,8 @@ export interface HogQLMetadata extends DataNode<HogQLMetadataResponse> {
variables?: Record<string, HogQLVariable>
/** Enable more verbose output, usually run from the /debug page */
debug?: boolean
+ /** Analyze how each property filter reads its data. Costs a second type-resolution pass, so only editors that render the result should ask for it. */
+ indexUsage?: boolean
}
export interface HogQLAutocomplete extends DataNode<HogQLAutocompleteResponse> {
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index dde452be9f07..d4961efd1f38 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -80,6 +80,7 @@ import {
copyTableToMarkdown,
} from '../../../queries/nodes/DataTable/clipboardUtils'
import { FixErrorButton } from './components/FixErrorButton'
+import { QueryIndexUsageBar } from './output-pane-tabs/QueryIndexUsageBar'
import { OutputTab, outputPaneLogic } from './outputPaneLogic'
import { sqlEditorLogic } from './sqlEditorLogic'
import { trimRedundantTail } from './syncWarnings'
@@ -587,7 +588,8 @@ export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareT
const { activeTab } = useValues(outputPaneLogic)
const { setActiveTab } = useActions(outputPaneLogic)
- const { sourceQuery, exportContext, insightLoading, hasQueryInput, isEmbeddedMode } = useValues(sqlEditorLogic)
+ const { sourceQuery, exportContext, insightLoading, hasQueryInput, isEmbeddedMode, metadata, metadataLoading } =
+ useValues(sqlEditorLogic)
const { setSourceQuery } = useActions(sqlEditorLogic)
const { isDarkModeOn } = useValues(themeLogic)
const {
@@ -892,6 +894,7 @@ export function OutputPane({ tabId, showToolbar = true, biMode = false, onShareT
return (
<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} />
{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.tsx
index ccd68fb2eeac..f33ffa423f9a 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -363,6 +363,10 @@ export function QueryWindow({
keepCurrentModel: true,
metadataQuery: activeQueryText ?? undefined,
metadataQueryOffset: activeQueryOffset,
+ // Set here rather than only where the tab's Monaco model is created: an editor
+ // that mounts against an existing model never runs that path, and would then
+ // ask for metadata without the index report.
+ indexUsage: true,
onChange: (v) => {
setQueryInput(v ?? '')
},
@@ -460,7 +464,6 @@ function RunButton({
const { responseLoading } = useValues(dataNodeLogic)
const { metadata, queryInput, isSourceQueryLastRun } = useValues(sqlEditorLogic)
- const isUsingIndices = metadata?.isUsingIndices === 'yes'
const isRunning = onRunQuery ? !!runQueryLoading : responseLoading
// The external-run path shows a cancel affordance only when a canceller is provided.
const showCancel = isRunning && (!onRunQuery || !!onCancelQuery)
@@ -477,25 +480,11 @@ function RunButton({
return ['var(--primary)', 'No changes to run']
}
- if (!metadata || isUsingIndices || queryInput?.trim().length === 0) {
- return ['var(--success)', 'New changes to run']
- }
-
- const tooltip = !isUsingIndices
- ? 'This query is not using indices optimally, which may result in slower performance.'
- : undefined
-
- return ['var(--warning)', tooltip]
- }, [
- metadata,
- isUsingIndices,
- queryInput,
- isSourceQueryLastRun,
- onRunQuery,
- runQueryTooltip,
- isRunning,
- onCancelQuery,
- ])
+ // No index verdict colors this button. The per-filter report counts filters, and a count does
+ // not track what a query costs: one selective filter bounds the read however many others scan,
+ // and nothing here yet looks at the time range, which is what really decides how much is read.
+ return ['var(--success)', 'New changes to run']
+ }, [metadata, queryInput, isSourceQueryLastRun, onRunQuery, runQueryTooltip, isRunning, onCancelQuery])
const sideAction = useMemo(
() =>
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.tsx
new file mode 100644
index 000000000000..87b8fecc1596
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.stories.tsx
@@ -0,0 +1,93 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { PredicateIndexUsage, PredicateIndexVerdict, PredicateScope } from '~/queries/schema/schema-general'
+
+import { QueryIndexUsageBar } from './QueryIndexUsageBar'
+
+const meta: Meta<typeof QueryIndexUsageBar> = {
+ title: 'Scenes-App/Data Warehouse/Query index usage',
+ component: QueryIndexUsageBar,
+}
+export default meta
+
+type Story = StoryObj<typeof QueryIndexUsageBar>
+
+const PREDICATES: PredicateIndexUsage[] = [
+ {
+ property_name: '$browser',
+ scope: PredicateScope.Event,
+ operator: '==',
+ source_label: 'materialized column',
+ column_name: 'mat_$browser',
+ semantic_type: 'String',
+ 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.",
+ },
+ {
+ property_name: 'duration',
+ scope: PredicateScope.Event,
+ operator: '>',
+ source_label: 'materialized column',
+ column_name: 'mat_duration',
+ semantic_type: 'Float',
+ physical_type: 'String',
+ usable_indexes: [],
+ 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.",
+ },
+ {
+ property_name: 'plan_tier',
+ scope: PredicateScope.Person,
+ operator: '==',
+ source_label: 'JSON blob',
+ column_name: 'person_properties',
+ semantic_type: 'String',
+ physical_type: 'String',
+ usable_indexes: [],
+ verdict: PredicateIndexVerdict.UnindexedJson,
+ 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.",
+ },
+ {
+ property_name: '$current_url',
+ scope: PredicateScope.Event,
+ operator: '!=',
+ source_label: 'materialized column',
+ column_name: 'mat_$current_url',
+ semantic_type: 'String',
+ physical_type: 'String',
+ usable_indexes: [],
+ verdict: PredicateIndexVerdict.OperatorNotIndexable,
+ message:
+ "Event property '$current_url' is filtered with '!=', which reads every row because no index can rule one out.",
+ },
+]
+
+export const SomeFiltersScan: Story = {
+ render: () => (
+ <div className="max-w-3xl">
+ <QueryIndexUsageBar predicates={PREDICATES} />
+ </div>
+ ),
+}
+
+export const EveryFilterIndexed: Story = {
+ render: () => (
+ <div className="max-w-3xl">
+ <QueryIndexUsageBar predicates={[PREDICATES[0]]} />
+ </div>
+ ),
+}
+
+export const RefreshingAfterAnEdit: Story = {
+ render: () => (
+ <div className="max-w-3xl">
+ <QueryIndexUsageBar predicates={PREDICATES} refreshing />
+ </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.tsx
new file mode 100644
index 000000000000..47f2666efc9d
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageBar.tsx
@@ -0,0 +1,66 @@
+import clsx from 'clsx'
+
+import { IconInfo, IconWarning } from '@posthog/icons'
+
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
+
+import { PredicateIndexUsage, PredicateIndexVerdict } from '~/queries/schema/schema-general'
+
+import { QueryIndexUsageTable } from './QueryIndexUsageTable'
+
+function summarize(predicates: PredicateIndexUsage[]): { text: string; scanning: boolean } {
+ const total = predicates.length
+ const scanning = predicates.filter((predicate) => predicate.verdict !== PredicateIndexVerdict.Indexed).length
+
+ // Says an index exists, not that the filter is cheap. Whether an index drops any data depends on
+ // the table's sort order and the value being compared, which the report does not look at.
+ if (scanning === 0) {
+ return { text: total === 1 ? '1 filter has an index' : `All ${total} filters have an index`, scanning: false }
+ }
+ if (scanning === total) {
+ return {
+ text: total === 1 ? '1 filter reads every row' : `${total} filters read every row`,
+ scanning: true,
+ }
+ }
+ return { text: `${scanning} of ${total} filters read every row`, scanning: true }
+}
+
+interface QueryIndexUsageBarProps {
+ predicates: PredicateIndexUsage[]
+ /** A refresh is in flight, so the report still describes the SQL the server last saw. */
+ refreshing?: boolean
+}
+
+export function QueryIndexUsageBar({ predicates, refreshing }: QueryIndexUsageBarProps): JSX.Element | null {
+ if (predicates.length === 0) {
+ return null
+ }
+
+ const { text, scanning } = summarize(predicates)
+
+ return (
+ <LemonCollapse
+ embedded
+ size="small"
+ className={clsx('border-b rounded-none', refreshing && 'opacity-60')}
+ panels={[
+ {
+ key: 'index-usage',
+ dataAttr: 'sql-editor-index-usage',
+ header: (
+ <span className="flex items-center gap-2 text-xs">
+ {refreshing || !scanning ? (
+ <IconInfo className="text-secondary" />
+ ) : (
+ <IconWarning className="text-warning" />
+ )}
+ {refreshing ? 'Checking filters' : text}
+ </span>
+ ),
+ content: <QueryIndexUsageTable predicates={predicates} />,
+ },
+ ]}
+ />
+ )
+}
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.tsx
new file mode 100644
index 000000000000..f1d75c0721e3
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryIndexUsageTable.tsx
@@ -0,0 +1,99 @@
+import { LemonTable } from '@posthog/lemon-ui'
+
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+
+import { PredicateIndexUsage, PredicateIndexVerdict, PredicateScope } from '~/queries/schema/schema-general'
+
+// `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.
+const VERDICT_TAGS: Record<PredicateIndexVerdict, { type: LemonTagType; label: string }> = {
+ [PredicateIndexVerdict.Indexed]: { type: 'default', label: 'Index applies' },
+ [PredicateIndexVerdict.Blocked]: { type: 'danger', label: 'Index unused' },
+ [PredicateIndexVerdict.UnindexedColumn]: { type: 'warning', label: 'Column scan' },
+ [PredicateIndexVerdict.UnindexedJson]: { type: 'warning', label: 'JSON scan' },
+ [PredicateIndexVerdict.OperatorNotIndexable]: { type: 'muted', label: 'Full scan' },
+}
+
+const INDEX_LABELS: Record<string, string> = {
+ minmax: 'min-max',
+ bloom_filter: 'bloom filter',
+ ngram_lower: 'n-gram',
+ bloom_filter_lower: 'bloom filter',
+}
+
+// Scope prefixes tell `properties.x` apart from `person.properties.x`; event properties are the
+// common case and read fine unprefixed.
+const SCOPE_PREFIXES: Partial<Record<PredicateScope, string>> = {
+ [PredicateScope.Person]: 'person.',
+ [PredicateScope.Group]: 'group.',
+}
+
+interface QueryIndexUsageTableProps {
+ predicates: PredicateIndexUsage[]
+}
+
+export function QueryIndexUsageTable({ predicates }: QueryIndexUsageTableProps): JSX.Element | null {
+ if (predicates.length === 0) {
+ return null
+ }
+
+ return (
+ <>
+ <p className="text-xs px-2 pt-1 mb-1">
+ How each property filter reads its data. A filter with no index behind it reads every row.
+ </p>
+ <LemonTable
+ size="small"
+ dataSource={predicates}
+ expandable={{
+ expandedRowRender: (predicate) => (
+ <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>}
+ </div>
+ ),
+ }}
+ columns={[
+ {
+ key: 'filter',
+ title: 'Filter',
+ render: (_, { property_name, operator, scope }) => (
+ <code className="text-xs">
+ {SCOPE_PREFIXES[scope] ?? ''}
+ {property_name} {operator === '==' ? '=' : operator} …
+ </code>
+ ),
+ },
+ {
+ key: 'source',
+ title: 'Reads from',
+ // The physical column name is on the response but stays out of the UI: it is not
+ // something a reader can select, create or drop.
+ render: (_, { source_label }) => <span className="text-xs">{source_label}</span>,
+ },
+ {
+ key: 'index',
+ title: 'Index',
+ render: (_, { usable_indexes }) =>
+ usable_indexes.length > 0 ? (
+ <span className="text-xs">
+ {[...new Set(usable_indexes.map((index) => INDEX_LABELS[index] ?? index))].join(
+ ', '
+ )}
+ </span>
+ ) : (
+ <span className="text-secondary text-xs">None</span>
+ ),
+ },
+ {
+ key: 'verdict',
+ title: 'Reads',
+ render: (_, { verdict }) => (
+ <LemonTag type={VERDICT_TAGS[verdict].type}>{VERDICT_TAGS[verdict].label}</LemonTag>
+ ),
+ },
+ ]}
+ />
+ </>
+ )
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 5285c09a2206..257b1f21242f 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -1920,6 +1920,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
key: `hogql-editor-${props.tabId}`,
query: values.sourceQuery?.source.query ?? '',
language: 'hogQL',
+ indexUsage: true,
})
)
}
diff --git a/posthog/hogql/index_eligibility.py b/posthog/hogql/index_eligibility.py
new file mode 100644
index 000000000000..774189b16329
--- /dev/null
+++ b/posthog/hogql/index_eligibility.py
@@ -0,0 +1,472 @@
+"""Per-predicate index eligibility for a query, decided before it runs.
+
+``property_planner`` already resolves where a property physically lives (materialized column,
+dynamic materialized column, property group, or the raw JSON blob) and which skip indexes sit on
+that source. This module turns those facts into a per-predicate answer to "will this filter prune
+data, and if not, why not" by pairing the source plan with the comparison operator: a minmax index
+prunes range comparisons, a bloom filter prunes equality and IN, and neither prunes anything under
+a negation.
+
+The analysis runs on the AST as it looks straight after ``resolve_types``, which is the only point
+where property reads are still recognizable as ``PropertyType``. Later stages lower them into bare
+physical-column expressions.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import StrEnum
+
+from posthog.hogql import ast
+from posthog.hogql.base import AST
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.property_planner import (
+ PropertyComparisonPlan,
+ PropertyMinmaxBlocker,
+ PropertyScope,
+ PropertySourceKind,
+ plan_property_comparison,
+)
+from posthog.hogql.type_system import ComparisonCompatibility, comparison_compatibility
+from posthog.hogql.visitor import TraversingVisitor, clone_expr
+
+from posthog.dataclasses import frozen
+from posthog.schema_enums import QueryIndexUsage
+
+
+class IndexKind(StrEnum):
+ MINMAX = "minmax"
+ BLOOM_FILTER = "bloom_filter"
+ NGRAM_LOWER = "ngram_lower"
+ BLOOM_FILTER_LOWER = "bloom_filter_lower"
+
+
+class PredicateIndexVerdict(StrEnum):
+ INDEXED = "indexed"
+ """A skip index on the source column covers this predicate's operator.
+
+ Whether it drops granules is a separate question this analysis does not answer: that depends on
+ the table's sort order and on how selective the compared value is. Read as "an index applies",
+ never as "this filter is fast".
+ """
+
+ BLOCKED = "blocked"
+ """The source carries an index this operator could use, but a type mismatch defeats it."""
+
+ UNINDEXED_COLUMN = "unindexed_column"
+ """The property reads from a dedicated column, but no index prunes this operator."""
+
+ UNINDEXED_JSON = "unindexed_json"
+ """The property is parsed out of the JSON blob on every row."""
+
+ OPERATOR_NOT_INDEXABLE = "operator_not_indexable"
+ """Negations, regexes and case-sensitive LIKE match granules that skip indexes cannot exclude."""
+
+
+# Which skip indexes ClickHouse can use to drop granules for a given operator. Negated operators are
+# absent on purpose: a granule holding one non-matching row still satisfies `!=`, so no skip index
+# can exclude it. `like` is absent because only a prefix pattern prunes, and whether a pattern is a
+# prefix is decided at runtime from the literal rather than from the operator.
+_OPERATOR_INDEXES: dict[ast.CompareOperationOp, frozenset[IndexKind]] = {
+ ast.CompareOperationOp.Eq: frozenset({IndexKind.MINMAX, IndexKind.BLOOM_FILTER}),
+ ast.CompareOperationOp.In: frozenset({IndexKind.MINMAX, IndexKind.BLOOM_FILTER}),
+ ast.CompareOperationOp.GlobalIn: frozenset({IndexKind.MINMAX, IndexKind.BLOOM_FILTER}),
+ ast.CompareOperationOp.Gt: frozenset({IndexKind.MINMAX}),
+ ast.CompareOperationOp.GtEq: frozenset({IndexKind.MINMAX}),
+ ast.CompareOperationOp.Lt: frozenset({IndexKind.MINMAX}),
+ ast.CompareOperationOp.LtEq: frozenset({IndexKind.MINMAX}),
+ ast.CompareOperationOp.ILike: frozenset({IndexKind.NGRAM_LOWER, IndexKind.BLOOM_FILTER_LOWER}),
+}
+
+_COMPATIBLE_COMPARISONS = frozenset({ComparisonCompatibility.DEFINITELY_COMPATIBLE, ComparisonCompatibility.CHEAP_CAST})
+
+_COLUMN_SOURCE_KINDS = frozenset(
+ {
+ PropertySourceKind.MATERIALIZED_COLUMN,
+ PropertySourceKind.DYNAMIC_MATERIALIZED_COLUMN,
+ PropertySourceKind.PROPERTY_GROUP,
+ }
+)
+
+_SCOPE_LABELS: dict[PropertyScope, str] = {
+ PropertyScope.EVENT: "Event property",
+ PropertyScope.PERSON: "Person property",
+ PropertyScope.GROUP: "Group property",
+ PropertyScope.UNKNOWN: "Property",
+}
+
+_INDEX_LABELS: dict[IndexKind, str] = {
+ IndexKind.MINMAX: "min-max",
+ IndexKind.BLOOM_FILTER: "bloom filter",
+ IndexKind.NGRAM_LOWER: "n-gram",
+ IndexKind.BLOOM_FILTER_LOWER: "bloom filter",
+}
+
+_SOURCE_LABELS: dict[PropertySourceKind, str] = {
+ PropertySourceKind.JSON: "JSON blob",
+ PropertySourceKind.MATERIALIZED_COLUMN: "materialized column",
+ PropertySourceKind.DYNAMIC_MATERIALIZED_COLUMN: "materialized column",
+ PropertySourceKind.PROPERTY_GROUP: "property group",
+}
+
+
+_PLAIN_TYPE_WORDS: dict[str, str] = {
+ "String": "text",
+ "Float": "a number",
+ "Integer": "a number",
+ "DateTime": "a date",
+ "Date": "a date",
+ "Boolean": "true or false",
+}
+
+
+def _plain_type(printed_type: str) -> str:
+ """A reader-facing word for a HogQL type.
+
+ The type names the engine prints are not the ones the property-type picker offers: it has
+ `Numeric` and `Duration` where the engine has `Float`, and no `Float` at all. Naming the engine's
+ type would send a reader looking for a setting that is not there, so the copy describes the kind
+ of value instead and leaves the exact type to the structured fields.
+ """
+ return _PLAIN_TYPE_WORDS.get(printed_type, printed_type)
+
+
+@dataclass(frozen=True, slots=True, kw_only=True)
+class PredicateIndexEligibility:
+ property_name: str
+ scope: PropertyScope
+ operator: ast.CompareOperationOp
+ source_kind: PropertySourceKind
+ source_label: str
+ column_name: str | None
+ semantic_type: str
+ physical_type: str
+ available_indexes: tuple[IndexKind, ...]
+ usable_indexes: tuple[IndexKind, ...]
+ verdict: PredicateIndexVerdict
+ blocker: PropertyMinmaxBlocker | None
+ message: str
+ fix: str | None
+ """Prose advice for a reader. Not a replacement string: `HogQLNotice.fix` means literal text to
+ 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."""
+ start: int | None
+ end: int | None
+
+ @property
+ def prunes_data(self) -> bool:
+ return self.verdict == PredicateIndexVerdict.INDEXED
+
+ @property
+ def editor_actionable(self) -> bool:
+ """Whether a marker on this predicate would point at text the reader can change.
+
+ A marker is a claim about the range it underlines. How a property is stored is a fact about
+ the property definition, not about the query, so underlining a correct comparison leaves the
+ reader 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
+
+
+@dataclass(frozen=True, slots=True)
+class IndexEligibilityReport:
+ predicates: tuple[PredicateIndexEligibility, ...] = ()
+
+ @property
+ def usage(self) -> QueryIndexUsage:
+ if not self.predicates:
+ return QueryIndexUsage.UNDECISIVE
+ pruning = sum(1 for predicate in self.predicates if predicate.prunes_data)
+ if pruning == len(self.predicates):
+ return QueryIndexUsage.YES
+ if pruning == 0:
+ return QueryIndexUsage.NO
+ return QueryIndexUsage.PARTIAL
+
+
+def analyze_index_eligibility(node: AST, context: HogQLContext) -> IndexEligibilityReport:
+ """Build the report from an AST that has been through ``resolve_types`` and nothing further."""
+ collector = _FilterPredicateCollector(context)
+ collector.visit(node)
+ return IndexEligibilityReport(predicates=tuple(collector.predicates))
+
+
+def build_index_eligibility_report(
+ node: ast.SelectQuery | ast.SelectSetQuery,
+ context: HogQLContext,
+) -> IndexEligibilityReport:
+ """Resolve a copy of the user's query far enough to plan its property reads, then analyze it.
+
+ Resolution happens on a clone because the analysis has to see the AST at a stage the print
+ pipeline has already moved past, and because callers hand us the node they still intend to use.
+ The property-definition registry is reused when the caller's context already loaded it, so a
+ caller that has printed the query first pays no extra Postgres round trip.
+
+ That second resolution is the cost of running outside the print pipeline. Analyzing in-pipeline
+ (between ``build_property_swapper`` and the first ``PropertySwapper`` pass, the one window where
+ property types are still intact and the registry is loaded) would make it free, but the AST there
+ has already been through simplification and projection pushdown, so the character offsets the
+ editor squiggles with are no longer guaranteed to be the ones the user typed.
+ """
+ # Deferred: these pull in the resolver and the Django-side property-definition loader, neither of
+ # which should sit on this module's import path (it is imported by the metadata endpoint).
+ from posthog.hogql.resolver import resolve_types # noqa: PLC0415
+ from posthog.hogql.transforms.property_types import build_property_swapper # noqa: PLC0415
+
+ if context.database is None:
+ return IndexEligibilityReport()
+
+ with context.timings.measure("index_eligibility"):
+ resolved = resolve_types(clone_expr(node), context, dialect="clickhouse")
+ if context.property_metadata is None:
+ build_property_swapper(resolved, context)
+ return analyze_index_eligibility(resolved, context)
+
+
+def eligibility_from_plan(
+ plan: PropertyComparisonPlan,
+ *,
+ negated: bool = False,
+ start: int | None = None,
+ end: int | None = None,
+) -> PredicateIndexEligibility:
+ source = plan.access.source
+ available = _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
+ if type_blocker is not None and _set_members_match_source(plan):
+ type_blocker = None
+ usable: tuple[IndexKind, ...] = () if type_blocker is not None else tuple(sorted(available & relevant))
+
+ verdict = _verdict(
+ source_kind=source.kind,
+ relevant=relevant,
+ available=available,
+ usable=usable,
+ type_blocker=type_blocker,
+ )
+ semantic_type = plan.access.semantic_type.print_type()
+ physical_type = source.physical_type.print_type()
+ copy = _copy_for(
+ verdict=verdict,
+ plan=plan,
+ usable=usable,
+ type_blocker=type_blocker,
+ semantic_type=semantic_type,
+ physical_type=physical_type,
+ )
+
+ return PredicateIndexEligibility(
+ property_name=plan.access.property_name,
+ scope=plan.access.scope,
+ operator=plan.operator,
+ source_kind=source.kind,
+ source_label=_SOURCE_LABELS[source.kind],
+ column_name=source.column_name,
+ semantic_type=semantic_type,
+ physical_type=physical_type,
+ available_indexes=tuple(sorted(available)),
+ usable_indexes=usable,
+ verdict=verdict,
+ blocker=type_blocker,
+ message=copy.message,
+ fix=copy.fix,
+ ai_fix_prompt=copy.ai_fix_prompt,
+ start=start,
+ end=end,
+ )
+
+
+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.
+
+ ``plan.minmax_blocker`` compares the property against the whole right-hand side, so an IN reads
+ as String-versus-Tuple and is reported as a type mismatch. The printer disagrees: it emits
+ ``has([...], column)`` with the column bare, and the skip index still applies. The mismatch that
+ matters for a set membership is between the column and the set's members.
+ """
+ if plan.operator not in (ast.CompareOperationOp.In, ast.CompareOperationOp.GlobalIn):
+ return False
+
+ value_type = plan.value_type
+ if isinstance(value_type, ast.TupleType):
+ member_types: list[ast.ConstantType] = list(value_type.item_types)
+ elif isinstance(value_type, ast.ArrayType):
+ member_types = [value_type.item_type]
+ else:
+ return False
+
+ if not member_types:
+ return False
+
+ return all(
+ comparison_compatibility(plan.access.source.physical_type, member_type) in _COMPATIBLE_COMPARISONS
+ for member_type in member_types
+ )
+
+
+def _available_indexes(plan: PropertyComparisonPlan) -> frozenset[IndexKind]:
+ source = plan.access.source
+ indexes: set[IndexKind] = set()
+ if source.has_minmax_index:
+ indexes.add(IndexKind.MINMAX)
+ if source.has_bloom_filter_index:
+ indexes.add(IndexKind.BLOOM_FILTER)
+ if source.has_ngram_lower_index:
+ indexes.add(IndexKind.NGRAM_LOWER)
+ if source.has_bloom_filter_lower_index:
+ indexes.add(IndexKind.BLOOM_FILTER_LOWER)
+ return frozenset(indexes)
+
+
+def _verdict(
+ source_kind: PropertySourceKind,
+ relevant: frozenset[IndexKind],
+ available: frozenset[IndexKind],
+ usable: tuple[IndexKind, ...],
+ type_blocker: PropertyMinmaxBlocker | None,
+) -> PredicateIndexVerdict:
+ if not relevant:
+ return PredicateIndexVerdict.OPERATOR_NOT_INDEXABLE
+ if usable:
+ return PredicateIndexVerdict.INDEXED
+ if type_blocker is not None and available & relevant:
+ return PredicateIndexVerdict.BLOCKED
+ if source_kind in _COLUMN_SOURCE_KINDS:
+ return PredicateIndexVerdict.UNINDEXED_COLUMN
+ return PredicateIndexVerdict.UNINDEXED_JSON
+
+
+@frozen
+class _PredicateCopy:
+ """What a reader is told about one predicate: the finding, the advice, the AI rewrite."""
+
+ message: str
+ fix: str | None = None
+ ai_fix_prompt: str | None = None
+
+
+def _copy_for(
+ verdict: PredicateIndexVerdict,
+ plan: PropertyComparisonPlan,
+ usable: tuple[IndexKind, ...],
+ type_blocker: PropertyMinmaxBlocker | None,
+ semantic_type: str,
+ physical_type: str,
+) -> _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.
+ # The column name stays on the structured `column_name` field for callers that want it.
+ label = _SCOPE_LABELS[plan.access.scope]
+ name = plan.access.property_name
+
+ if verdict == PredicateIndexVerdict.INDEXED:
+ index_names = ", ".join(sorted({_INDEX_LABELS[index] for index in usable}))
+ return _PredicateCopy(
+ message=f"{label} '{name}' has a {index_names} index that covers this comparison. How much data it "
+ "skips depends on how the values are spread across the table.",
+ )
+
+ if verdict == PredicateIndexVerdict.BLOCKED:
+ if type_blocker == PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE:
+ # No fix here changes how the value is stored: both auto-materialized and slot-backed
+ # columns are String, so a numeric or datetime property is always converted at read time.
+ # Correcting the definition only helps when the definition is the thing that is wrong.
+ # No AI prompt: how the value is stored is not something a query rewrite can change.
+ return _PredicateCopy(
+ message=f"{label} '{name}' is stored as {_plain_type(physical_type)} but compared as "
+ 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.",
+ )
+ 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)}.",
+ # 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.",
+ )
+
+ if verdict == PredicateIndexVerdict.UNINDEXED_JSON:
+ # A property the reader is denied gets the same copy as one that simply is not materialized.
+ # The printer drops restricted keys from the JSON blob rather than erroring, so a denied
+ # property reads as one that was never set; copy that named the restriction would undo that.
+ 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.",
+ )
+
+ if verdict == PredicateIndexVerdict.UNINDEXED_COLUMN:
+ return _PredicateCopy(
+ message=f"{label} '{name}' has its own column, but no index on it covers '{plan.operator}'.",
+ )
+
+ return _PredicateCopy(
+ message=f"{label} '{name}' is filtered with '{plan.operator}', which reads every row because no index "
+ "can rule one out.",
+ )
+
+
+class _FilterPredicateCollector(TraversingVisitor):
+ """Collects property comparisons from filtering positions only.
+
+ A comparison in a select expression or a HAVING clause never prunes a read, so reporting it as
+ unindexed would send the reader after a fix that changes nothing. Descends through and/or/not so
+ a predicate nested in a boolean tree is still found, and treats anything under a negation as
+ unprunable for the same reason `!=` is.
+ """
+
+ def __init__(self, context: HogQLContext) -> None:
+ super().__init__()
+ self.context = context
+ self.predicates: list[PredicateIndexEligibility] = []
+ self._seen: set[tuple[int | None, int | None, str, ast.CompareOperationOp]] = set()
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ for filter_expr in (node.where, node.prewhere):
+ if filter_expr is not None:
+ self._collect(filter_expr, negated=False)
+ super().visit_select_query(node)
+
+ def _collect(self, node: ast.Expr, negated: bool) -> None:
+ if isinstance(node, ast.Not):
+ self._collect(node.expr, negated=not negated)
+ return
+ if isinstance(node, ast.And | ast.Or):
+ for child in node.exprs:
+ self._collect(child, negated=negated)
+ return
+ # `not x` parses to a Call rather than an ast.Not, and `and`/`or` can be written in call form,
+ # so the boolean connectives have to be recognized in both shapes.
+ if isinstance(node, ast.Call):
+ name = node.name.lower()
+ if name == "not" and len(node.args) == 1:
+ self._collect(node.args[0], negated=not negated)
+ elif name in ("and", "or"):
+ for arg in node.args:
+ self._collect(arg, negated=negated)
+ return
+ if isinstance(node, ast.CompareOperation):
+ self._record(node, negated=negated)
+
+ def _record(self, node: ast.CompareOperation, negated: bool) -> None:
+ plan = plan_property_comparison(node, self.context)
+ if plan is None:
+ return
+
+ # A rewritten query can carry the same predicate twice with identical spans; the property name
+ # and operator keep distinct predicates apart when they share a span, which is every predicate
+ # in a JSON-sourced node, where there are no locations at all.
+ key = (node.start, node.end, plan.access.property_name, plan.operator)
+ if key in self._seen:
+ return
+ self._seen.add(key)
+
+ self.predicates.append(eligibility_from_plan(plan, negated=negated, start=node.start, end=node.end))
diff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.py
index fcb60e046562..aca3c898a496 100644
--- a/posthog/hogql/metadata.py
+++ b/posthog/hogql/metadata.py
@@ -2,9 +2,19 @@ from typing import Literal, Optional, Union, cast
from django.conf import settings
+import structlog
from pydantic import BaseModel
-from posthog.schema import HogLanguage, HogQLMetadata, HogQLMetadataResponse, HogQLNotice, HogQLQuery
+from posthog.schema import (
+ HogLanguage,
+ HogQLMetadata,
+ HogQLMetadataResponse,
+ HogQLNotice,
+ HogQLQuery,
+ PredicateIndexUsage,
+ PredicateIndexVerdict,
+ PredicateScope,
+)
from posthog.hogql import ast
from posthog.hogql.base import AST
@@ -16,8 +26,14 @@ from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_dir
from posthog.hogql.direct_sql import get_adapter
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.filters import replace_filters
+from posthog.hogql.index_eligibility import build_index_eligibility_report
from posthog.hogql.metadata_heuristics import run_metadata_heuristics
from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.observability import (
+ INDEX_ELIGIBILITY_DURATION_SECONDS,
+ INDEX_ELIGIBILITY_TOTAL,
+ INDEX_ELIGIBILITY_VERDICT_TOTAL,
+)
from posthog.hogql.parser import parse_expr, parse_program, parse_select, parse_string_template
from posthog.hogql.placeholders import find_placeholders, replace_placeholders
from posthog.hogql.printer import prepare_and_print_ast
@@ -28,6 +44,9 @@ from posthog.hogql.visitor import TraversingVisitor, clone_expr
from posthog.hogql_queries.query_runner import get_query_runner
from posthog.models import Team
from posthog.models.user import User
+from posthog.ph_client import feature_enabled_or_false
+
+logger = structlog.get_logger(__name__)
def get_hogql_metadata(
@@ -124,6 +143,9 @@ def get_hogql_metadata(
if prepared_ast:
response.ch_table_names = get_table_names(prepared_ast)
+
+ if source is None and query.indexUsage and _index_usage_enabled(team):
+ _attach_index_usage(response, hogql_ast, context)
else:
raise ValueError(f"Unsupported language: {query.language}")
except Exception as e:
@@ -166,6 +188,86 @@ def get_hogql_metadata(
return response
+def _index_usage_enabled(team: Team) -> bool:
+ """Index eligibility is still being calibrated against real query plans, so it stays off by default.
+
+ The verdicts are reasoned from ClickHouse semantics rather than measured, and a wrong verdict is
+ indistinguishable from a right one to whoever reads it. Rolling out behind a flag keeps that
+ exposure where the analysis can be checked against what queries actually do.
+ """
+ return feature_enabled_or_false(
+ "hogql-index-eligibility",
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ )
+
+
+def _attach_index_usage(
+ response: HogQLMetadataResponse,
+ hogql_ast: Union[ast.SelectQuery, ast.SelectSetQuery],
+ context: HogQLContext,
+) -> None:
+ """Report which property filters will prune data, and warn about the ones a fix would unblock.
+
+ Every predicate reaches the response; only the ones a query edit can unblock become warnings.
+ Reading a property out of the JSON blob is the normal case for most teams, and how a property is
+ stored is not something the editor can change, so marking either would bury the predicates where
+ a type mismatch is wasting an index that already exists.
+ """
+ with INDEX_ELIGIBILITY_DURATION_SECONDS.time():
+ try:
+ 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
+
+ INDEX_ELIGIBILITY_TOTAL.labels(result="ok").inc()
+ for predicate in report.predicates:
+ INDEX_ELIGIBILITY_VERDICT_TOTAL.labels(
+ verdict=predicate.verdict.value, source_kind=predicate.source_kind.value
+ ).inc()
+
+ response.isUsingIndices = report.usage
+ response.index_usage = [
+ PredicateIndexUsage(
+ property_name=predicate.property_name,
+ scope=PredicateScope(predicate.scope.value),
+ operator=predicate.operator.value,
+ source_label=predicate.source_label,
+ column_name=predicate.column_name,
+ semantic_type=predicate.semantic_type,
+ physical_type=predicate.physical_type,
+ usable_indexes=[index.value for index in predicate.usable_indexes],
+ verdict=PredicateIndexVerdict(predicate.verdict.value),
+ message=predicate.message,
+ fix=predicate.fix,
+ start=predicate.start,
+ end=predicate.end,
+ )
+ for predicate in report.predicates
+ ]
+
+ 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.
+ 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(
query: BaseModel | None,
team: Team,
diff --git a/posthog/hogql/observability.py b/posthog/hogql/observability.py
index 875f1c99e052..f09a5d213d94 100644
--- a/posthog/hogql/observability.py
+++ b/posthog/hogql/observability.py
@@ -120,6 +120,25 @@ TYPE_SIMPLIFICATION_TOTAL = PromCounter(
)
+INDEX_ELIGIBILITY_TOTAL = PromCounter(
+ "hogql_index_eligibility_total",
+ "Index-eligibility analysis runs by result. 'failed' counts swallowed analysis errors, which are "
+ "invisible to the user: a query that compiles still returns, just with no index report.",
+ labelnames=["result"],
+)
+INDEX_ELIGIBILITY_DURATION_SECONDS = Histogram(
+ "hogql_index_eligibility_duration_seconds",
+ "Wall-clock duration of the index-eligibility pass, which re-resolves a clone of the query.",
+ buckets=(0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),
+)
+INDEX_ELIGIBILITY_VERDICT_TOTAL = PromCounter(
+ "hogql_index_eligibility_verdict_total",
+ "Property-filter predicates by index verdict. Property names are deliberately absent: they are "
+ "user-supplied and unbounded, so they can be neither a label value nor a label name.",
+ labelnames=["verdict", "source_kind"],
+)
+
+
def _log_observability_error(stage: str) -> None:
"""Record and log a swallowed observability failure. Must never raise."""
try:
diff --git a/posthog/hogql/test/test_index_eligibility.py b/posthog/hogql/test/test_index_eligibility.py
new file mode 100644
index 000000000000..ece92f3a4e07
--- /dev/null
+++ b/posthog/hogql/test/test_index_eligibility.py
@@ -0,0 +1,487 @@
+from typing import cast
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import HogLanguage, HogQLMetadata, HogQLMetadataResponse
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.schema.events import EventsTable
+from posthog.hogql.index_eligibility import (
+ IndexEligibilityReport,
+ IndexKind,
+ PredicateIndexEligibility,
+ PredicateIndexVerdict,
+ analyze_index_eligibility,
+ build_index_eligibility_report,
+ eligibility_from_plan,
+)
+from posthog.hogql.metadata import get_hogql_metadata
+from posthog.hogql.parser import parse_select
+from posthog.hogql.property_metadata import MaterializedColumnsByTable, PropertyMetadata
+from posthog.hogql.property_planner import (
+ ComparisonCompatibility,
+ PropertyAccessPlan,
+ PropertyComparisonPlan,
+ PropertyLiteralConversion,
+ PropertyMinmaxBlocker,
+ PropertyScope,
+ PropertySourceKind,
+ PropertySourcePlan,
+)
+from posthog.hogql.resolver import resolve_types
+from posthog.hogql.transforms.property_types import build_property_swapper
+
+from posthog.schema_enums import QueryIndexUsage
+
+from products.event_definitions.backend.models.property_definition import PropertyDefinition
+from products.event_definitions.backend.property_type import PropertyType
+
+from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
+
+Op = ast.CompareOperationOp
+
+
+def _plan(
+ *,
+ operator: ast.CompareOperationOp = Op.Eq,
+ kind: PropertySourceKind = PropertySourceKind.JSON,
+ minmax: bool = False,
+ bloom: bool = False,
+ ngram_lower: bool = False,
+ bloom_lower: bool = False,
+ blocker: PropertyMinmaxBlocker | None = None,
+ restricted: bool = False,
+ semantic_type: ast.ConstantType | None = None,
+ physical_type: ast.ConstantType | None = None,
+ value_type: ast.ConstantType | None = None,
+) -> PropertyComparisonPlan:
+ source = PropertySourcePlan(
+ kind=kind,
+ table_name="events",
+ field_name="properties",
+ column_name="properties" if kind == PropertySourceKind.JSON else "mat_duration",
+ physical_type=physical_type or ast.StringType(nullable=True),
+ is_nullable=True,
+ has_minmax_index=minmax,
+ has_bloom_filter_index=bloom,
+ has_ngram_lower_index=ngram_lower,
+ has_bloom_filter_lower_index=bloom_lower,
+ restricted=restricted,
+ )
+ access = PropertyAccessPlan(
+ property_name="duration",
+ scope=PropertyScope.EVENT,
+ semantic_type=semantic_type or ast.StringType(nullable=True),
+ source=source,
+ property_type=ast.PropertyType(
+ chain=["duration"],
+ field_type=ast.FieldType(name="properties", table_type=ast.TableType(table=EventsTable())),
+ ),
+ )
+ return PropertyComparisonPlan(
+ access=access,
+ property_side="left",
+ operator=operator,
+ value_type=value_type or ast.StringType(nullable=True),
+ semantic_compatibility=ComparisonCompatibility.DEFINITELY_COMPATIBLE,
+ physical_compatibility=ComparisonCompatibility.DEFINITELY_COMPATIBLE,
+ literal_conversion=PropertyLiteralConversion.NONE,
+ source_matches_semantics=blocker != PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE,
+ minmax_blocker=blocker,
+ )
+
+
+class TestIndexEligibilityVerdicts(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "json_equality_has_no_index",
+ _plan(),
+ PredicateIndexVerdict.UNINDEXED_JSON,
+ (),
+ ),
+ (
+ "bloom_filter_covers_equality",
+ _plan(kind=PropertySourceKind.MATERIALIZED_COLUMN, bloom=True),
+ PredicateIndexVerdict.INDEXED,
+ (IndexKind.BLOOM_FILTER,),
+ ),
+ (
+ "bloom_filter_does_not_cover_ranges",
+ _plan(operator=Op.Gt, kind=PropertySourceKind.MATERIALIZED_COLUMN, bloom=True),
+ PredicateIndexVerdict.UNINDEXED_COLUMN,
+ (),
+ ),
+ (
+ "minmax_covers_ranges",
+ _plan(operator=Op.Gt, kind=PropertySourceKind.MATERIALIZED_COLUMN, minmax=True),
+ PredicateIndexVerdict.INDEXED,
+ (IndexKind.MINMAX,),
+ ),
+ (
+ "storage_type_mismatch_defeats_the_index",
+ _plan(
+ operator=Op.Gt,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE,
+ ),
+ PredicateIndexVerdict.BLOCKED,
+ (),
+ ),
+ (
+ "value_type_mismatch_defeats_the_index",
+ _plan(
+ operator=Op.Gt,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE,
+ ),
+ PredicateIndexVerdict.BLOCKED,
+ (),
+ ),
+ (
+ "negated_equality_prunes_nothing",
+ _plan(operator=Op.NotEq, kind=PropertySourceKind.MATERIALIZED_COLUMN, minmax=True, bloom=True),
+ PredicateIndexVerdict.OPERATOR_NOT_INDEXABLE,
+ (),
+ ),
+ (
+ "regex_prunes_nothing",
+ _plan(operator=Op.Regex, kind=PropertySourceKind.MATERIALIZED_COLUMN, minmax=True, bloom=True),
+ PredicateIndexVerdict.OPERATOR_NOT_INDEXABLE,
+ (),
+ ),
+ (
+ "ngram_covers_case_insensitive_like",
+ _plan(operator=Op.ILike, kind=PropertySourceKind.MATERIALIZED_COLUMN, ngram_lower=True),
+ PredicateIndexVerdict.INDEXED,
+ (IndexKind.NGRAM_LOWER,),
+ ),
+ (
+ "case_sensitive_like_is_not_claimed_as_indexed",
+ _plan(operator=Op.Like, kind=PropertySourceKind.MATERIALIZED_COLUMN, ngram_lower=True),
+ PredicateIndexVerdict.OPERATOR_NOT_INDEXABLE,
+ (),
+ ),
+ (
+ "property_group_equality_uses_its_bloom_filter",
+ _plan(kind=PropertySourceKind.PROPERTY_GROUP, bloom=True),
+ PredicateIndexVerdict.INDEXED,
+ (IndexKind.BLOOM_FILTER,),
+ ),
+ (
+ "absent_index_is_not_a_type_blocker",
+ _plan(blocker=PropertyMinmaxBlocker.NO_MINMAX_INDEX),
+ PredicateIndexVerdict.UNINDEXED_JSON,
+ (),
+ ),
+ (
+ "in_against_matching_members_still_prunes",
+ _plan(
+ operator=Op.In,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE,
+ value_type=ast.TupleType(item_types=[ast.StringType(), ast.StringType()]),
+ ),
+ PredicateIndexVerdict.INDEXED,
+ (IndexKind.MINMAX,),
+ ),
+ (
+ "in_against_mismatched_members_does_not",
+ _plan(
+ operator=Op.In,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE,
+ value_type=ast.TupleType(item_types=[ast.IntegerType(), ast.IntegerType()]),
+ ),
+ PredicateIndexVerdict.BLOCKED,
+ (),
+ ),
+ ]
+ )
+ def test_verdict_for_operator_and_source(
+ self,
+ _name: str,
+ plan: PropertyComparisonPlan,
+ expected_verdict: PredicateIndexVerdict,
+ expected_indexes: tuple[IndexKind, ...],
+ ) -> None:
+ eligibility = eligibility_from_plan(plan)
+
+ assert eligibility.verdict == expected_verdict
+ assert eligibility.usable_indexes == expected_indexes
+
+ @parameterized.expand(
+ [
+ (PredicateIndexVerdict.UNINDEXED_JSON, _plan(), True),
+ (
+ PredicateIndexVerdict.BLOCKED,
+ _plan(minmax=True, blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE),
+ True,
+ ),
+ (
+ PredicateIndexVerdict.BLOCKED,
+ _plan(
+ operator=Op.Gt,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE,
+ semantic_type=ast.FloatType(nullable=True),
+ ),
+ True,
+ ),
+ (PredicateIndexVerdict.INDEXED, _plan(kind=PropertySourceKind.MATERIALIZED_COLUMN, bloom=True), False),
+ ]
+ )
+ def test_only_actionable_verdicts_carry_a_fix(
+ self,
+ expected_verdict: PredicateIndexVerdict,
+ plan: PropertyComparisonPlan,
+ expects_fix: bool,
+ ) -> None:
+ eligibility = eligibility_from_plan(plan)
+
+ assert eligibility.verdict == expected_verdict
+ assert (eligibility.fix is not None) == expects_fix
+
+ @parameterized.expand(
+ [
+ (
+ "value_type_mismatch_is_fixable_in_the_query",
+ _plan(minmax=True, blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE),
+ True,
+ ),
+ (
+ "source_type_mismatch_is_not",
+ _plan(
+ operator=Op.Gt,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.SOURCE_TYPE_DIFFERS_FROM_PROPERTY_TYPE,
+ semantic_type=ast.FloatType(nullable=True),
+ ),
+ False,
+ ),
+ ("json_reads_are_not", _plan(), False),
+ ("indexed_reads_are_not", _plan(kind=PropertySourceKind.MATERIALIZED_COLUMN, bloom=True), False),
+ ]
+ )
+ def test_only_query_fixable_predicates_get_a_marker(
+ self, _name: str, plan: PropertyComparisonPlan, expects_marker: bool
+ ) -> None:
+ assert eligibility_from_plan(plan).editor_actionable == expects_marker
+
+ @parameterized.expand(
+ [
+ (
+ "value_type_mismatch",
+ _plan(minmax=True, blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE),
+ ),
+ (
+ "in_against_mismatched_members",
+ _plan(
+ operator=Op.In,
+ kind=PropertySourceKind.MATERIALIZED_COLUMN,
+ minmax=True,
+ blocker=PropertyMinmaxBlocker.VALUE_TYPE_NOT_SOURCE_COMPATIBLE,
+ value_type=ast.TupleType(item_types=[ast.IntegerType(), ast.IntegerType()]),
+ ),
+ ),
+ ]
+ )
+ def test_marked_predicates_carry_an_ai_prompt_never_prose(self, _name: str, plan: PropertyComparisonPlan) -> None:
+ # `HogQLNotice.fix` is substituted into the query verbatim by the editor's quick fix, so the
+ # marker path may only ever emit an `ai_prompt:` instruction. `metadata.py` derives that value
+ # from `ai_fix_prompt`, so a marked predicate without one would put nothing there and a marked
+ # predicate carrying only prose would put advice into the user's query.
+ eligibility = eligibility_from_plan(plan)
+
+ assert eligibility.editor_actionable is True
+ assert eligibility.ai_fix_prompt is not None
+
+ 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())
+
+ assert denied == allowed
+
+ def test_negation_overrides_an_otherwise_usable_index(self) -> None:
+ plan = _plan(kind=PropertySourceKind.MATERIALIZED_COLUMN, bloom=True)
+
+ assert eligibility_from_plan(plan).verdict == PredicateIndexVerdict.INDEXED
+ assert eligibility_from_plan(plan, negated=True).verdict == PredicateIndexVerdict.OPERATOR_NOT_INDEXABLE
+
+ @parameterized.expand(
+ [
+ ([], QueryIndexUsage.UNDECISIVE),
+ ([PredicateIndexVerdict.INDEXED], QueryIndexUsage.YES),
+ ([PredicateIndexVerdict.INDEXED, PredicateIndexVerdict.UNINDEXED_JSON], QueryIndexUsage.PARTIAL),
+ ([PredicateIndexVerdict.UNINDEXED_JSON, PredicateIndexVerdict.BLOCKED], QueryIndexUsage.NO),
+ ]
+ )
+ def test_report_usage_summarizes_predicates(
+ self, verdicts: list[PredicateIndexVerdict], expected: QueryIndexUsage
+ ) -> None:
+ report = IndexEligibilityReport(
+ predicates=tuple(
+ PredicateIndexEligibility(
+ property_name="duration",
+ scope=PropertyScope.EVENT,
+ operator=Op.Eq,
+ source_kind=PropertySourceKind.JSON,
+ source_label="JSON blob",
+ column_name="properties",
+ semantic_type="String",
+ physical_type="String",
+ available_indexes=(),
+ usable_indexes=(),
+ verdict=verdict,
+ blocker=None,
+ message="",
+ fix=None,
+ ai_fix_prompt=None,
+ start=None,
+ end=None,
+ )
+ for verdict in verdicts
+ )
+ )
+
+ assert report.usage == expected
+
+
+def _materialized(property_name: str, *, minmax: bool = False, bloom: bool = False) -> MaterializedColumn:
+ return MaterializedColumn(
+ name=f"mat_{property_name}",
+ details=MaterializedColumnDetails(
+ table_column="properties",
+ property_name=property_name,
+ is_disabled=False,
+ ),
+ is_nullable=False,
+ has_minmax_index=minmax,
+ has_bloom_filter_index=bloom,
+ )
+
+
+class TestIndexEligibilityThroughThePlanner(BaseTest):
+ """Verdicts reached through the real planner rather than a constructed plan.
+
+ Every other verdict test hands `eligibility_from_plan` a `PropertyComparisonPlan` built by the
+ test, so it proves the operator mapping and nothing about whether `plan_property_comparison`
+ emits such a plan for a real query. These two cover that seam: a synthetic materialized-column
+ registry stands in for ClickHouse, and the query goes through resolution and planning as it does
+ in production.
+ """
+
+ def _report(
+ self,
+ query: str,
+ *,
+ columns: MaterializedColumnsByTable,
+ property_types: dict[str, dict[str, str | None]] | None = None,
+ ) -> IndexEligibilityReport:
+ context = HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True)
+ context.database = Database.create_for(context.team_id, modifiers=context.modifiers, team=context.team)
+ # Pre-setting the bundle stands in for ClickHouse and skips the Postgres-backed loader, so the
+ # planner sees a materialized column with the indexes this test is about.
+ context.property_metadata = PropertyMetadata(
+ event_properties=property_types or {},
+ materialized_columns=lambda: columns,
+ )
+ return build_index_eligibility_report(parse_select(query), context)
+
+ def test_materialized_column_with_a_bloom_filter_is_indexed(self) -> None:
+ report = self._report(
+ "select count() from events where properties.$browser = 'Chrome'",
+ columns={"events": {("$browser", "properties"): _materialized("$browser", bloom=True)}},
+ )
+
+ [predicate] = report.predicates
+ assert predicate.verdict == PredicateIndexVerdict.INDEXED
+ assert predicate.usable_indexes == (IndexKind.BLOOM_FILTER,)
+ assert report.usage == QueryIndexUsage.YES
+
+ def test_numeric_property_stored_as_string_is_blocked(self) -> None:
+ report = self._report(
+ "select count() from events where properties.duration > 100",
+ columns={"events": {("duration", "properties"): _materialized("duration", minmax=True)}},
+ property_types={"duration": {"type": PropertyType.Numeric.value}},
+ )
+
+ [predicate] = report.predicates
+ assert predicate.verdict == PredicateIndexVerdict.BLOCKED
+ assert predicate.usable_indexes == ()
+ # The advice is real but not a query edit, so it must not become an editor marker.
+ assert predicate.fix is not None
+ assert predicate.editor_actionable is False
+
+
+class TestIndexEligibilityAnalysis(BaseTest):
+ def _report(self, query: str) -> IndexEligibilityReport:
+ context = HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True)
+ context.database = Database.create_for(context.team_id, modifiers=context.modifiers, team=context.team)
+ node = cast(ast.SelectQuery, resolve_types(parse_select(query), context, dialect="clickhouse"))
+ build_property_swapper(node, context)
+ return analyze_index_eligibility(node, context)
+
+ def test_only_filtering_positions_are_reported(self) -> None:
+ report = self._report(
+ "select properties.selected = '1' from events "
+ "where properties.filtered = '2' "
+ "group by properties.grouped having properties.grouped != '3'"
+ )
+
+ assert [predicate.property_name for predicate in report.predicates] == ["filtered"]
+
+ def test_predicates_inside_a_boolean_tree_are_reported(self) -> None:
+ report = self._report(
+ "select count() from events where (properties.a = '1' or properties.b = '2') and not (properties.c = '3')"
+ )
+
+ verdicts = {predicate.property_name: predicate.verdict for predicate in report.predicates}
+ assert verdicts == {
+ "a": PredicateIndexVerdict.UNINDEXED_JSON,
+ "b": PredicateIndexVerdict.UNINDEXED_JSON,
+ "c": PredicateIndexVerdict.OPERATOR_NOT_INDEXABLE,
+ }
+
+ def _metadata(self, query: str) -> HogQLMetadataResponse:
+ with patch("posthog.hogql.metadata.feature_enabled_or_false", return_value=True):
+ return get_hogql_metadata(
+ HogQLMetadata(
+ kind="HogQLMetadata",
+ language=HogLanguage.HOG_QL,
+ query=query,
+ indexUsage=True,
+ ),
+ self.team,
+ )
+
+ def test_metadata_reports_index_usage_for_a_json_backed_filter(self) -> None:
+ PropertyDefinition.objects.create(team=self.team, name="duration", property_type=PropertyType.Numeric)
+
+ response = self._metadata("select count() from events where properties.duration > 100")
+
+ assert response.isValid is True
+ assert response.isUsingIndices == QueryIndexUsage.NO
+ assert response.index_usage is not None
+ [usage] = response.index_usage
+ assert usage.property_name == "duration"
+ assert usage.fix is not None
+
+ def test_metadata_reports_no_index_usage_without_property_filters(self) -> None:
+ response = self._metadata("select count() from events where event = '$pageview'")
+
+ assert response.isUsingIndices == QueryIndexUsage.UNDECISIVE
+ assert response.index_usage == []
diff --git a/posthog/schema.py b/posthog/schema.py
index a838cce3fabd..3ba50d0aba90 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -210,6 +210,8 @@ from posthog.schema_enums import (
PlanningStepStatus as PlanningStepStatus,
Position as Position,
PrecomputationMode as PrecomputationMode,
+ PredicateIndexVerdict as PredicateIndexVerdict,
+ PredicateScope as PredicateScope,
ProductIntentContext as ProductIntentContext,
ProductItemCategory as ProductItemCategory,
ProductKey as ProductKey,
@@ -6316,6 +6318,28 @@ class PlanningStep(BaseModel):
status: PlanningStepStatus
+class PredicateIndexUsage(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(
+ ...,
+ 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 PreprocessingConfig(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -6368,6 +6392,9 @@ class QueryResponseAlternative9(BaseModel):
)
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]
@@ -16948,6 +16975,9 @@ class HogQLMetadataResponse(BaseModel):
)
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]
@@ -30324,6 +30354,14 @@ class HogQLMetadata(BaseModel):
),
)
globals: dict[str, Any] | None = Field(default=None, description="Extra globals for the query")
+ indexUsage: bool | None = Field(
+ default=None,
+ description=(
+ "Analyze how each property filter reads its data. Costs a second"
+ " type-resolution pass, so only editors that render the result should ask"
+ " for it."
+ ),
+ )
kind: Literal["HogQLMetadata"] = "HogQLMetadata"
language: HogLanguage = Field(..., description="Language to validate")
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 20b0aef0bd42..c8759e0f80ac 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3458,6 +3458,21 @@ class PlanningStepStatus(StrEnum):
COMPLETED = "completed"
+class PredicateIndexVerdict(StrEnum):
+ INDEXED = "indexed"
+ BLOCKED = "blocked"
+ UNINDEXED_COLUMN = "unindexed_column"
+ UNINDEXED_JSON = "unindexed_json"
+ OPERATOR_NOT_INDEXABLE = "operator_not_indexable"
+
+
+class PredicateScope(StrEnum):
+ EVENT = "event"
+ PERSON = "person"
+ GROUP = "group"
+ UNKNOWN = "unknown"
+
+
class ProductIntentContext(StrEnum):
ONBOARDING_PRODUCT_SELECTED___PRIMARY = "onboarding product selected - primary"
ONBOARDING_PRODUCT_SELECTED___SECONDARY = "onboarding product selected - secondary"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 30d7db58b423..a8832e77253c 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -4496,6 +4496,46 @@ export interface HogQLNoticeApi {
start?: number | null
}
+export type PredicateScopeApi = (typeof PredicateScopeApi)[keyof typeof PredicateScopeApi]
+
+export const PredicateScopeApi = {
+ Event: 'event',
+ Person: 'person',
+ Group: 'group',
+ Unknown: 'unknown',
+} as const
+
+export type PredicateIndexVerdictApi = (typeof PredicateIndexVerdictApi)[keyof typeof PredicateIndexVerdictApi]
+
+export const PredicateIndexVerdictApi = {
+ Indexed: 'indexed',
+ Blocked: 'blocked',
+ UnindexedColumn: 'unindexed_column',
+ UnindexedJson: 'unindexed_json',
+ OperatorNotIndexable: 'operator_not_indexable',
+} as const
+
+export interface PredicateIndexUsageApi {
+ column_name?: string | null
+ end?: number | null
+ fix?: string | 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
+ scope: PredicateScopeApi
+ /** Type the property definition declares. */
+ semantic_type: string
+ /** Where the value is physically read from, e.g. `materialized column` or `JSON blob`. */
+ source_label: string
+ start?: number | null
+ /** Skip indexes this predicate can actually use. */
+ usable_indexes: string[]
+ verdict: PredicateIndexVerdictApi
+}
+
export type QueryIndexUsageApi = (typeof QueryIndexUsageApi)[keyof typeof QueryIndexUsageApi]
export const QueryIndexUsageApi = {
@@ -4508,6 +4548,8 @@ export const QueryIndexUsageApi = {
export interface HogQLMetadataResponseApi {
ch_table_names?: string[] | null
errors: HogQLNoticeApi[]
+ /** One entry per property filter, in query order. */
+ index_usage?: PredicateIndexUsageApi[] | null
isUsingIndices?: QueryIndexUsageApi | null
isValid?: boolean | null
notices: HogQLNoticeApi[]
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 50deeae9c378..f4d5cb17d484 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3658,6 +3658,46 @@ export interface HogQLNoticeApi {
start?: number | null
}
+export type PredicateScopeApi = (typeof PredicateScopeApi)[keyof typeof PredicateScopeApi]
+
+export const PredicateScopeApi = {
+ Event: 'event',
+ Person: 'person',
+ Group: 'group',
+ Unknown: 'unknown',
+} as const
+
+export type PredicateIndexVerdictApi = (typeof PredicateIndexVerdictApi)[keyof typeof PredicateIndexVerdictApi]
+
+export const PredicateIndexVerdictApi = {
+ Indexed: 'indexed',
+ Blocked: 'blocked',
+ UnindexedColumn: 'unindexed_column',
+ UnindexedJson: 'unindexed_json',
+ OperatorNotIndexable: 'operator_not_indexable',
+} as const
+
+export interface PredicateIndexUsageApi {
+ column_name?: string | null
+ end?: number | null
+ fix?: string | 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
+ scope: PredicateScopeApi
+ /** Type the property definition declares. */
+ semantic_type: string
+ /** Where the value is physically read from, e.g. `materialized column` or `JSON blob`. */
+ source_label: string
+ start?: number | null
+ /** Skip indexes this predicate can actually use. */
+ usable_indexes: string[]
+ verdict: PredicateIndexVerdictApi
+}
+
export type QueryIndexUsageApi = (typeof QueryIndexUsageApi)[keyof typeof QueryIndexUsageApi]
export const QueryIndexUsageApi = {
@@ -3670,6 +3710,8 @@ export const QueryIndexUsageApi = {
export interface HogQLMetadataResponseApi {
ch_table_names?: string[] | null
errors: HogQLNoticeApi[]
+ /** One entry per property filter, in query order. */
+ index_usage?: PredicateIndexUsageApi[] | null
isUsingIndices?: QueryIndexUsageApi | null
isValid?: boolean | null
notices: HogQLNoticeApi[]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 111fe3c0b709..7689d6ca6436 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5368,6 +5368,48 @@ export namespace Schemas {
start?: number | null;
}
+ export type PredicateScope = typeof PredicateScope[keyof typeof PredicateScope];
+
+
+ export const PredicateScope = {
+ Event: 'event',
+ Person: 'person',
+ Group: 'group',
+ Unknown: 'unknown',
+ } as const;
+
+ export type PredicateIndexVerdict = typeof PredicateIndexVerdict[keyof typeof PredicateIndexVerdict];
+
+
+ export const PredicateIndexVerdict = {
+ Indexed: 'indexed',
+ Blocked: 'blocked',
+ UnindexedColumn: 'unindexed_column',
+ UnindexedJson: 'unindexed_json',
+ OperatorNotIndexable: 'operator_not_indexable',
+ } as const;
+
+ export interface PredicateIndexUsage {
+ column_name?: string | null;
+ end?: number | null;
+ fix?: string | 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;
+ scope: PredicateScope;
+ /** Type the property definition declares. */
+ semantic_type: string;
+ /** Where the value is physically read from, e.g. `materialized column` or `JSON blob`. */
+ source_label: string;
+ start?: number | null;
+ /** Skip indexes this predicate can actually use. */
+ usable_indexes: string[];
+ verdict: PredicateIndexVerdict;
+ }
+
export type QueryIndexUsage = typeof QueryIndexUsage[keyof typeof QueryIndexUsage];
@@ -5381,6 +5423,8 @@ export namespace Schemas {
export interface HogQLMetadataResponse {
ch_table_names?: string[] | null;
errors: HogQLNotice[];
+ /** One entry per property filter, in query order. */
+ index_usage?: PredicateIndexUsage[] | null;
isUsingIndices?: QueryIndexUsage | null;
isValid?: boolean | null;
notices: HogQLNotice[];
@@ -44442,6 +44486,8 @@ export namespace Schemas {
filters?: HogQLFilters | null;
/** Extra globals for the query */
globals?: HogQLMetadataGlobals;
+ /** Analyze how each property filter reads its data. Costs a second type-resolution pass, so only editors that render the result should ask for it. */
+ indexUsage?: boolean | null;
kind?: 'HogQLMetadata';
/** Language to validate */
language: HogLanguage;
@@ -70109,6 +70155,8 @@ export namespace Schemas {
export interface QueryResponseAlternative9 {
ch_table_names?: string[] | null;
errors: HogQLNotice[];
+ /** One entry per property filter, in query order. */
+ index_usage?: PredicateIndexUsage[] | null;
isUsingIndices?: QueryIndexUsage | null;
isValid?: boolean | null;
notices: HogQLNotice[];