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(query-scan): mark actionable findings, name by-design reads (#101946)

Sandy Spicer42bb3f9abd26
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx
index 961f2f26d4a9..274b67c852eb 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.test.tsx
@@ -72,6 +72,17 @@ describe('InsightMeta', () => {
})
})
+ it.each([
+ { actionable: true, shown: 'insight-card-query-scan', hidden: 'insight-card-query-scan-note' },
+ { actionable: false, shown: 'insight-card-query-scan-note', hidden: 'insight-card-query-scan' },
+ ])('marks a slow tile by whether a finding is actionable: $actionable', ({ actionable, shown, hidden }) => {
+ const { container } = render(
+ <InsightMetaContent title="Test" queryScanTooltip={<span>advice</span>} queryScanActionable={actionable} />
+ )
+ expect(container.querySelector(`[data-attr="${shown}"]`)).toBeInTheDocument()
+ expect(container.querySelector(`[data-attr="${hidden}"]`)).toBeNull()
+ })
+
it('hides description in non-compact mode when showDescription is false', () => {
const { container } = render(
<InsightMetaContent title="Test" description={description} compact={false} showDescription={false} />
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index a8f5f0b39211..539c38fa24e0 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import React, { useCallback, useEffect, useRef, useState } from 'react'
-import { IconInfo, IconPulse, IconThumbsDown, IconThumbsUp, IconWarning } from '@posthog/icons'
+import { IconClock, IconInfo, IconPulse, IconThumbsDown, IconThumbsUp, IconWarning } from '@posthog/icons'
import { lemonToast } from '@posthog/lemon-ui'
import { CardMeta } from 'lib/components/Cards/CardMeta'
@@ -46,6 +46,7 @@ import { isSurveyableFunnelInsight, SurveyableFunnelInsight } from 'scenes/surve
import { urls } from 'scenes/urls'
import { insightsModel } from '~/models/insightsModel'
+import { queryScanHasActionableFinding } from '~/queries/nodes/DataNode/queryScan'
import { QueryScanTileTooltip } from '~/queries/nodes/DataNode/QueryScanTileTooltip'
import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'
import { Node, ProductKey } from '~/queries/schema/schema-general'
@@ -248,7 +249,6 @@ export function InsightMeta({
// A killed run has no result to carry the scan, so it arrives on the query status instead.
const queryScan: QueryBasedInsightModel['query_scan'] = insight.query_scan ?? insight.query_status?.query_scan
const scanFindings = queryScan?.analysis?.findings ?? []
- // Without a finding the tag can only say that PostHog was slow, which leaves the viewer nothing to do.
const queryScanTooltip =
canEditInsight && queryScan && scanFindings.length > 0 ? (
<QueryScanTileTooltip summary={queryScan} findings={scanFindings} />
@@ -463,6 +463,7 @@ export function InsightMeta({
showDescription={tile?.show_description !== false}
dataRetentionWarning={dataRetentionWarning}
queryScanTooltip={queryScanTooltip}
+ queryScanActionable={queryScanHasActionableFinding(scanFindings)}
infoPopover={
showCompactTile ? (
<CompactInfoPopover
@@ -794,6 +795,7 @@ export function InsightMetaContent({
infoPopover,
dataRetentionWarning,
queryScanTooltip,
+ queryScanActionable,
}: {
title: string
fallbackTitle?: string
@@ -807,6 +809,8 @@ export function InsightMetaContent({
infoPopover?: JSX.Element | null
dataRetentionWarning?: string | null
queryScanTooltip?: JSX.Element | null
+ /** Whether the person can act on a finding. Without one the tile only notes that the query is slow. */
+ queryScanActionable?: boolean
}): JSX.Element {
const dataRetentionIndicator = dataRetentionWarning ? (
<Tooltip title={dataRetentionWarning}>
@@ -815,9 +819,16 @@ export function InsightMetaContent({
) : null
const queryScanIndicator = queryScanTooltip ? (
<Tooltip title={queryScanTooltip}>
- <LemonTag type="warning" size="small" className="ml-1.5 shrink-0" data-attr="insight-card-query-scan">
- Slow query
- </LemonTag>
+ {queryScanActionable ? (
+ <LemonTag type="warning" size="small" className="ml-1.5 shrink-0" data-attr="insight-card-query-scan">
+ Slow query
+ </LemonTag>
+ ) : (
+ <IconClock
+ className="ml-1.5 text-base shrink-0 text-secondary"
+ data-attr="insight-card-query-scan-note"
+ />
+ )}
</Tooltip>
) : null
const titleContent = (
diff --git a/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsx b/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsx
index fcb5e5dc5532..833ed0f1f9ef 100644
--- a/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsx
+++ b/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsx
@@ -18,16 +18,26 @@ const FINDING: QueryScanWarning = {
kind: 'no_event_filter',
message: 'This query read every event in its date range.',
fix: 'Add an event filter naming the events this question is about.',
+ actionable: true,
}
const INSIGHT_SIDE_FINDING: QueryScanWarning = {
...FINDING,
kind: 'no_start_date',
- reason: 'filters',
+ fix_location: 'insight_date_range',
message: 'No date range is set for this insight or dashboard.',
fix: 'Set a date range on the insight or the dashboard.',
}
+const BY_DESIGN_FINDING: QueryScanWarning = {
+ ...FINDING,
+ kind: 'no_start_date',
+ by_design: true,
+ message: 'This query finds a first event ever, so it reads all your data by design.',
+ fix: 'Do not propose a time bound for that read.',
+ actionable: false,
+}
+
describe('QueryScanBanner', () => {
beforeEach(() => {
initKeaTests()
@@ -36,12 +46,22 @@ describe('QueryScanBanner', () => {
afterEach(() => cleanup())
it.each([
- { label: 'nothing to advise', findings: [], assistantPrompt: null, advice: null, fixer: false },
+ {
+ label: 'nothing to advise',
+ findings: [],
+ assistantPrompt: null,
+ advice: [],
+ banner: false,
+ note: false,
+ fixer: false,
+ },
{
label: 'a finding the assistant can fix',
findings: [FINDING],
assistantPrompt: 'Help me get what this query is trying to find, as fast as possible.',
- advice: FINDING.message,
+ advice: [FINDING.message],
+ banner: true,
+ note: false,
fixer: true,
},
// The backend sends no prompt for a finding fixed on the insight, so there is nothing to hand the assistant.
@@ -49,14 +69,40 @@ describe('QueryScanBanner', () => {
label: 'a finding fixed on the insight',
findings: [INSIGHT_SIDE_FINDING],
assistantPrompt: null,
- advice: INSIGHT_SIDE_FINDING.message,
+ advice: [INSIGHT_SIDE_FINDING.message],
+ banner: true,
+ note: false,
fixer: false,
},
- ])('keeps the stat line and shows $label', ({ findings, assistantPrompt, advice, fixer }) => {
- render(
+ // A by-design finding explains the read; shown as a note, it must not read as something to fix.
+ {
+ label: 'a finding the person cannot act on',
+ findings: [BY_DESIGN_FINDING],
+ assistantPrompt: null,
+ advice: [BY_DESIGN_FINDING.message],
+ banner: false,
+ note: true,
+ fixer: false,
+ },
+ {
+ label: 'a by-design finding beside one to act on',
+ findings: [BY_DESIGN_FINDING, FINDING],
+ assistantPrompt: 'Help me get what this query is trying to find, as fast as possible.',
+ advice: [BY_DESIGN_FINDING.message, FINDING.message],
+ banner: true,
+ note: true,
+ fixer: true,
+ },
+ ])('keeps the stat line and shows $label', ({ findings, assistantPrompt, advice, banner, note, fixer }) => {
+ const { container } = render(
<Provider>
<QueryScanBanner
- queryScan={{ summary: SUMMARY, findings, cacheKey: 'cache-key', assistantPrompt }}
+ queryScan={{
+ summary: SUMMARY,
+ findings,
+ cacheKey: 'cache-key',
+ assistantPrompt,
+ }}
onFixWithAI={jest.fn()}
/>
</Provider>
@@ -64,7 +110,11 @@ describe('QueryScanBanner', () => {
expect(screen.getByText(/Read 8,400,000,000 rows in 19.0 s/)).toBeVisible()
const shown = findings.map((finding) => finding.message).filter((message) => screen.queryByText(message))
- expect(shown).toEqual(advice ? [advice] : [])
+ expect(shown).toEqual(advice)
+ expect(!!container.querySelector('.LemonBanner')).toBe(banner)
+ expect(!!container.querySelector('[data-attr="query-scan-note"]')).toBe(note)
+ // Each finding sits at its own level: the by-design one never inside the warning.
+ expect(container.querySelector('.LemonBanner')?.textContent ?? '').not.toContain(BY_DESIGN_FINDING.message)
expect(!!screen.queryByText('Fix with AI')).toBe(fixer)
})
})
diff --git a/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsx b/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsx
index 215dc8571124..ece7062e5628 100644
--- a/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsx
+++ b/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsx
@@ -21,14 +21,15 @@ export function QueryScanBanner({ queryScan, onFixWithAI, className }: QueryScan
}
const { summary, findings, assistantPrompt } = queryScan
- const showFindings = findings.length > 0
+ const fixable = findings.filter((finding) => finding.actionable)
+ const notes = findings.filter((finding) => !finding.actionable)
return (
<div className={clsx('flex flex-col gap-2 shrink-0', className)} data-attr="query-scan">
<span className="text-xs text-secondary">{queryScanStatLine(summary)}</span>
- {showFindings && (
+ {fixable.length > 0 && (
<LemonBanner type="warning">
- <QueryScanFindingList findings={findings} dropBulletIfSingle />
+ <QueryScanFindingList findings={fixable} dropBulletIfSingle />
{onFixWithAI && assistantPrompt && (
<LemonButton
className="mt-2"
@@ -43,6 +44,11 @@ export function QueryScanBanner({ queryScan, onFixWithAI, className }: QueryScan
)}
</LemonBanner>
)}
+ {notes.length > 0 && (
+ <div className="text-xs text-secondary" data-attr="query-scan-note">
+ <QueryScanFindingList findings={notes} dropBulletIfSingle />
+ </div>
+ )}
</div>
)
}
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
index 68e57098f8af..295c915bcf1a 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
@@ -22,6 +22,7 @@ const DONE_SCAN = {
kind: 'no_event_filter',
message: 'This query read every event in its date range.',
fix: 'Add an event filter.',
+ actionable: true,
},
],
range_share: 0.42,
diff --git a/frontend/src/queries/nodes/DataNode/queryScan.test.ts b/frontend/src/queries/nodes/DataNode/queryScan.test.ts
index 3cd5f38e3069..961bc8efa2fe 100644
--- a/frontend/src/queries/nodes/DataNode/queryScan.test.ts
+++ b/frontend/src/queries/nodes/DataNode/queryScan.test.ts
@@ -19,6 +19,16 @@ const FINDING: QueryScanWarning = {
kind: 'no_event_filter',
message: 'This query read every event in its date range.',
fix: 'Add an event filter naming the events this question is about.',
+ actionable: true,
+}
+
+// A by-design finding explains the read and leaves the person nothing to change.
+const BY_DESIGN_FINDING: QueryScanWarning = {
+ kind: 'no_start_date',
+ by_design: true,
+ message: 'This query finds a first event ever, so it reads all your data by design.',
+ fix: 'Do not propose a time bound for that read.',
+ actionable: false,
}
function tile(id: number, insight: Partial<QueryBasedInsightModel> | null): DashboardTile<QueryBasedInsightModel> {
@@ -28,13 +38,13 @@ function tile(id: number, insight: Partial<QueryBasedInsightModel> | null): Dash
function slowInsight(
shortId: string,
name: string,
- findings: number,
+ findings: QueryScanWarning[],
summary: Partial<QueryScanSummary> = {}
): Partial<QueryBasedInsightModel> {
return {
short_id: shortId as InsightShortId,
name,
- query_scan: { ...SUMMARY, ...summary, analysis: { findings: Array(findings).fill(FINDING) } },
+ query_scan: { ...SUMMARY, ...summary, analysis: { findings } },
}
}
@@ -85,22 +95,26 @@ describe('queryScan', () => {
expect(queryScanTileStatLine({ ...SUMMARY, ...summary })).toEqual(expected)
})
- it('names only the insights whose last run has advice', () => {
+ it('names only the insights whose last run has advice the viewer can act on', () => {
const entries = queryScanDashboardEntries([
tile(1, null),
- tile(2, slowInsight('aaa', 'Active users', 2)),
- tile(3, slowInsight('bbb', 'Fast enough', 0)),
+ tile(2, slowInsight('aaa', 'Active users', [FINDING, FINDING])),
+ tile(3, slowInsight('bbb', 'Fast enough', [])),
tile(4, { short_id: 'ccc' as InsightShortId, name: 'Still analyzing', query_scan: SUMMARY }),
- tile(5, { ...slowInsight('ddd', 'Deleted', 1), deleted: true }),
+ tile(5, { ...slowInsight('ddd', 'Deleted', [FINDING]), deleted: true }),
tile(6, { short_id: 'eee' as InsightShortId, derived_name: 'Never run' }),
- tile(7, { ...slowInsight('fff', '', 1), derived_name: 'Pageview count' }),
- tile(8, slowInsight('ggg', '', 1)),
+ tile(7, { ...slowInsight('fff', '', [FINDING]), derived_name: 'Pageview count' }),
+ tile(8, slowInsight('ggg', '', [FINDING])),
+ // Reads all history by design: nothing for the banner to send the viewer to change.
+ tile(9, slowInsight('hhh', 'First purchases', [BY_DESIGN_FINDING])),
+ tile(10, slowInsight('iii', 'Mixed', [BY_DESIGN_FINDING, FINDING])),
])
expect(entries).toEqual([
{ tileId: 2, shortId: 'aaa', name: 'Active users', findingCount: 2 },
{ tileId: 7, shortId: 'fff', name: 'Pageview count', findingCount: 1 },
{ tileId: 8, shortId: 'ggg', name: 'Untitled', findingCount: 1 },
+ { tileId: 10, shortId: 'iii', name: 'Mixed', findingCount: 1 },
])
})
})
diff --git a/frontend/src/queries/nodes/DataNode/queryScan.ts b/frontend/src/queries/nodes/DataNode/queryScan.ts
index b2817b4e6cba..9795de2c08cc 100644
--- a/frontend/src/queries/nodes/DataNode/queryScan.ts
+++ b/frontend/src/queries/nodes/DataNode/queryScan.ts
@@ -12,6 +12,10 @@ export interface QueryScanState {
assistantPrompt: string | null
}
+export function queryScanHasActionableFinding(findings: QueryScanWarning[]): boolean {
+ return findings.some((finding) => finding.actionable)
+}
+
export interface QueryScanPollResult {
cacheKey: string
analysis: QueryScanAnalysis
@@ -55,9 +59,10 @@ export function resolveQueryScan(
// A poll outlives the run that started it, so a result for an earlier query would otherwise
// decorate whatever response is on screen when it lands.
const summary = polled && polled.cacheKey === cacheKey ? { ...stored, analysis: polled.analysis } : stored
+ const findings = summary.analysis?.findings ?? []
return {
summary,
- findings: summary.analysis?.findings ?? [],
+ findings,
cacheKey,
assistantPrompt: summary.analysis?.assistant_prompt ?? null,
}
@@ -100,7 +105,7 @@ export interface QueryScanDashboardEntry {
findingCount: number
}
-/** The insights on a dashboard whose last fresh run has advice for the viewer. */
+/** The insights on a dashboard whose last fresh run has advice the viewer can act on. */
export function queryScanDashboardEntries(tiles: DashboardTile<QueryBasedInsightModel>[]): QueryScanDashboardEntry[] {
const entries: QueryScanDashboardEntry[] = []
for (const tile of tiles) {
@@ -110,7 +115,7 @@ export function queryScanDashboardEntries(tiles: DashboardTile<QueryBasedInsight
}
// A killed run has no result to carry the scan, so it arrives on the query status instead.
const summary = insight.query_scan ?? insight.query_status?.query_scan
- const findingCount = summary?.analysis?.findings.length ?? 0
+ const findingCount = (summary?.analysis?.findings ?? []).filter((finding) => finding.actionable).length
if (findingCount === 0) {
continue
}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 4288437584cf..46cafdffc95b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -48430,7 +48430,7 @@
"type": "string"
},
"findings": {
- "description": "Empty when the analysis found nothing to fix.",
+ "description": "Every finding, fixable or not. Empty when the analysis found none.",
"items": {
"$ref": "#/definitions/QueryScanWarning"
},
@@ -48453,9 +48453,9 @@
"enum": ["no_event_filter", "no_start_date", "persons_join"],
"type": "string"
},
- "QueryScanFindingReason": {
- "description": "Why a filter the query does have did not narrow the read. `in_or`: it sits inside an OR. `wrapped`: `event` is inside a function call. `negated`: it excludes events, which narrows nothing. `dynamic`: `event` is compared to a column. `not_pruned`: ClickHouse reported it unused. `filters`: the date range comes from `{filters}` and the insight left it open.",
- "enum": ["in_or", "wrapped", "negated", "dynamic", "not_pruned", "filters"],
+ "QueryScanFixLocation": {
+ "description": "Where the change that fixes a finding goes. `insight_date_range` is the range a SQL insight takes through `{filters}`.",
+ "enum": ["query", "subquery", "view", "insight_date_range", "dashboard_date_filter"],
"type": "string"
},
"QueryScanResponse": {
@@ -48500,6 +48500,18 @@
"additionalProperties": false,
"description": "One finding of a query's analysis.",
"properties": {
+ "actionable": {
+ "description": "Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and \"Fix with AI\" only when a finding is actionable.",
+ "type": "boolean"
+ },
+ "by_design": {
+ "description": "True when the query reads this much on purpose, so reading less would change the answer. Absent means no.",
+ "type": "boolean"
+ },
+ "cause": {
+ "description": "A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change.",
+ "type": "string"
+ },
"evidence": {
"description": "The one fact the finding rests on.",
"type": "string"
@@ -48508,19 +48520,19 @@
"description": "What \"Fix with AI\" and the assistant are told to do.",
"type": "string"
},
+ "fix_location": {
+ "$ref": "#/definitions/QueryScanFixLocation",
+ "description": "Where the change goes. Absent means the query itself."
+ },
"kind": {
"$ref": "#/definitions/QueryScanFindingKind"
},
"message": {
"description": "Shown to the person: what happened and what to do.",
"type": "string"
- },
- "reason": {
- "$ref": "#/definitions/QueryScanFindingReason",
- "description": "Only with `no_event_filter` and `no_start_date`."
}
},
- "required": ["kind", "message", "fix"],
+ "required": ["kind", "message", "fix", "actionable"],
"type": "object"
},
"QuerySchema": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 25dc893a0c2f..f1b6d49193ad 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -601,30 +601,31 @@ export interface AccessControlFilterWarning {
*/
export type QueryScanFindingKind = 'no_event_filter' | 'no_start_date' | 'persons_join'
-/**
- * Why a filter the query does have did not narrow the read. `in_or`: it sits inside an OR. `wrapped`:
- * `event` is inside a function call. `negated`: it excludes events, which narrows nothing. `dynamic`:
- * `event` is compared to a column. `not_pruned`: ClickHouse reported it unused. `filters`: the date
- * range comes from `{filters}` and the insight left it open.
- */
-export type QueryScanFindingReason = 'in_or' | 'wrapped' | 'negated' | 'dynamic' | 'not_pruned' | 'filters'
+/** Where the change that fixes a finding goes. `insight_date_range` is the range a SQL insight takes through `{filters}`. */
+export type QueryScanFixLocation = 'query' | 'subquery' | 'view' | 'insight_date_range' | 'dashboard_date_filter'
/** One finding of a query's analysis. */
export interface QueryScanWarning {
kind: QueryScanFindingKind
- /** Only with `no_event_filter` and `no_start_date`. */
- reason?: QueryScanFindingReason
+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
+ cause?: string
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocation
/** Shown to the person: what happened and what to do. */
message: string
/** What "Fix with AI" and the assistant are told to do. */
fix: string
/** The one fact the finding rests on. */
evidence?: string
+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
+ actionable: boolean
}
/** The stored analysis of one query, kept for 30 days by cache key and put on every response for that query. */
export interface QueryScanAnalysis {
- /** Empty when the analysis found nothing to fix. */
+ /** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarning[]
/** How much of the project's events in the query's date range the query read, 0 to 1. */
range_share?: number
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index dbfe43ecd48f..a880281b715d 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -515,6 +515,8 @@ def _run_query_runner(
) -> dict | BaseModel | RawCachedQueryResponse:
if dashboard_filters:
query_runner.apply_dashboard_filters(dashboard_filters)
+ # A tag, so it reaches the async worker, which rebuilds the runner from the query alone.
+ tag_queries(dashboard_all_time=dashboard_filters.date_from == "all")
if variables_override:
query_runner.apply_variable_overrides(variables_override)
if pagination_cursor:
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index 785dcf899508..fab636853dad 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -51,7 +51,7 @@ from posthog.exceptions import APIQueriesBudgetExceeded, ClickHouseQueryTimeOut
from posthog.llm.completions import OpenAICompletion
from posthog.models import PersonalAPIKey
from posthog.models.utils import UUIDT, generate_random_token_personal, hash_key_value
-from posthog.query_scan.findings import build_warning
+from posthog.query_scan.findings import FindingCause, build_warning
from posthog.query_scan.flag import QueryScanFlag, QueryScanMode
from posthog.query_scan.test.slots import stored_slot
@@ -1361,7 +1361,13 @@ A_STORED_SCAN = stored_slot(
QueryScanAnalysis(
range_share=0.8,
project_share=0.25,
- findings=[build_warning(kind=QueryScanFindingKind.NO_EVENT_FILTER, query_kind="HogQLQuery")],
+ findings=[
+ build_warning(
+ kind=QueryScanFindingKind.NO_EVENT_FILTER,
+ cause=FindingCause.EVENT_FILTER_INSIDE_OR,
+ query_kind="HogQLQuery",
+ )
+ ],
)
)
A_CLAIMED_SCAN = json.dumps({"pending": True})
@@ -1389,7 +1395,7 @@ class TestQueryScan(APIBaseTest):
self.assertEqual(analysis["project_share"], 0.25)
self.assertEqual([finding["kind"] for finding in analysis["findings"]], ["no_event_filter"])
# "Fix with AI" sends this, so the endpoint builds it rather than the client.
- self.assertIn("- no_event_filter:", analysis["assistant_prompt"])
+ self.assertIn("- no_event_filter (in_or):", analysis["assistant_prompt"])
def test_answers_with_an_empty_body_while_the_job_runs(self):
# A client polls until an analysis arrives, so "not yet" has to differ from the 404 that
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index e84561f6e8b9..4f48b6443838 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -278,7 +278,7 @@ def _record_query_stats(client: Any, query_info_before: Any, execute_start_time:
return
# elapsed_ns is 0 on old protocol revisions; fall back to the client-side round trip.
duration_ms = summary.elapsed_ns / 1e6 if summary.elapsed_ns else (perf_counter() - execute_start_time) * 1000
- query_stats.record(rows_read=summary.rows, duration_ms=duration_ms)
+ query_stats.record(rows_read=summary.rows, duration_ms=duration_ms, lookup=get_query_tags().lookup is not None)
except Exception:
logger.warning("query_stats_record_failed", exc_info=True)
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index b899e7058f10..1b4529acac62 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -420,6 +420,7 @@ class QueryTags(BaseModel):
dashboard_id: Optional[int] = None
insight_id: Optional[int] = None
lookup: Optional[str] = None # a runner's internal lookup before its real query, e.g. "earliest_timestamp"
+ dashboard_all_time: Optional[bool] = None # the dashboard's date filter, not the insight's range, chose All time
scanner_id: Optional[str] = None # replay-vision scanner, for per-scanner read metering
exported_asset_id: Optional[int] = None
export_format: Optional[str] = None
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index b99f7dcb9e90..1a83a937f11a 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -67,7 +67,7 @@ from posthog.hogql.warehouse_warnings import record_warnings
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
-from posthog.clickhouse.query_tagging import get_query_tags, tag_queries
+from posthog.clickhouse.query_tagging import get_query_tag_value, get_query_tags, tag_queries
from posthog.dataclasses import frozen
from posthog.direct_query_cancellation import build_direct_query_cancellation_token
from posthog.errors import CHQueryErrorS3Error, CHQueryErrorS3FileChangedDuringRead, ExposedCHQueryError
@@ -121,6 +121,7 @@ class HogQLQueryExecutor:
clickhouse_prepared_ast: Optional[ast.AST] = None
clickhouse_context: Optional[HogQLContext] = None
clickhouse_sql: Optional[str] = None
+ clickhouse_settings: Optional[HogQLGlobalSettings] = None
direct_context: Optional[HogQLContext] = None
direct_sql: Optional[str] = None
direct_source_id: Optional[str] = None
@@ -627,6 +628,7 @@ class HogQLQueryExecutor:
@tracer.start_as_current_span("HogQLQueryExecutor._generate_clickhouse_sql")
def _generate_clickhouse_sql(self, *, include_settings: bool = True):
settings = get_default_hogql_global_settings(self.team.pk, self.settings)
+ self.clickhouse_settings = settings
if self.limit_context in (
LimitContext.EXPORT,
LimitContext.COHORT_CALCULATION,
@@ -835,6 +837,8 @@ class HogQLQueryExecutor:
tree=self.clickhouse_prepared_ast,
context=clickhouse_context,
rows_read=query_stats.last_rows_read(),
+ lookup=get_query_tag_value("lookup"),
+ settings=self.clickhouse_settings,
)
if self.debug and self.error is None:
diff --git a/posthog/hogql/query_stats.py b/posthog/hogql/query_stats.py
index 4bdc711fa00b..9ba9731b8ba1 100644
--- a/posthog/hogql/query_stats.py
+++ b/posthog/hogql/query_stats.py
@@ -21,16 +21,24 @@ from posthog.dataclasses import frozen
if TYPE_CHECKING:
from posthog.hogql import ast
+ from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.context import HogQLContext
@frozen
class RecordedExecution:
- """One ClickHouse execution inside a scope, held by reference for the job to explain later."""
+ """One ClickHouse execution inside a scope, held by reference for the job to explain later.
+
+ ``lookup`` is the ``QueryTags.lookup`` value the execution ran under, so a run's analysis can
+ leave out an internal lookup a runner made on the way to its real query. ``settings`` are the
+ ones the query was printed with, so the job plans it under the same ones.
+ """
tree: ast.Expr
context: HogQLContext
rows_read: int
+ lookup: str | None = None
+ settings: HogQLGlobalSettings | None = None
@frozen(frozen=False)
@@ -42,20 +50,37 @@ class QueryStats:
# How many ClickHouse queries the request ran. Zero means it never reached ClickHouse, for
# example a warehouse query over a direct connection, so there is nothing to report.
query_count: int = 0
+ # The part of the totals spent on lookups tagged ``QueryTags.lookup``, which run under a runner's
+ # scope without being the query the person wrote, so a reader can judge the run without them.
+ lookup_rows_read: int = 0
+ lookup_duration_ms: float = 0.0
# Runners that record from several threads share one QueryStats.
lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False)
# References only, filled by the executor, so the job can explain each execution without rerunning it.
executions: list[RecordedExecution] = field(default_factory=list, repr=False, compare=False)
- def add(self, *, rows_read: int, duration_ms: float) -> None:
+ def add(self, *, rows_read: int, duration_ms: float, lookup: bool = False) -> None:
with self.lock:
self.rows_read += rows_read
self.duration_ms += duration_ms
self.query_count += 1
-
- def record_execution(self, *, tree: ast.Expr, context: HogQLContext, rows_read: int) -> None:
+ if lookup:
+ self.lookup_rows_read += rows_read
+ self.lookup_duration_ms += duration_ms
+
+ def record_execution(
+ self,
+ *,
+ tree: ast.Expr,
+ context: HogQLContext,
+ rows_read: int,
+ lookup: str | None = None,
+ settings: HogQLGlobalSettings | None = None,
+ ) -> None:
with self.lock:
- self.executions.append(RecordedExecution(tree=tree, context=context, rows_read=rows_read))
+ self.executions.append(
+ RecordedExecution(tree=tree, context=context, rows_read=rows_read, lookup=lookup, settings=settings)
+ )
_accumulator: ContextVar[QueryStats | None] = ContextVar("query_stats_accumulator", default=None)
@@ -101,13 +126,13 @@ def use(stats: QueryStats | None) -> Iterator[None]:
_accumulator.reset(token)
-def record(*, rows_read: int, duration_ms: float) -> None:
+def record(*, rows_read: int, duration_ms: float, lookup: bool = False) -> None:
"""Add one ClickHouse query to the open scope. Does nothing without one."""
_last_rows_read.set(rows_read)
stats = _accumulator.get()
if stats is None:
return
- stats.add(rows_read=rows_read, duration_ms=duration_ms)
+ stats.add(rows_read=rows_read, duration_ms=duration_ms, lookup=lookup)
def reset_last_rows_read() -> None:
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index 957bcea4f960..33b94dcc872d 100644
--- a/posthog/hogql/test/test_query.py
+++ b/posthog/hogql/test/test_query.py
@@ -2402,6 +2402,8 @@ class TestQueryStatsRecording(BaseTest):
assert len(stats.executions) == 1
assert stats.executions[0].rows_read == 42
assert stats.executions[0].tree is not None
+ recorded_settings = stats.executions[0].settings
+ assert recorded_settings is not None and recorded_settings.max_ast_elements == 4_000_000
def killed(sql, values, **kwargs):
record(rows_read=90, duration_ms=1.0)
diff --git a/posthog/hogql/test/test_query_stats.py b/posthog/hogql/test/test_query_stats.py
index 8743e9ccb056..841c2942f71b 100644
--- a/posthog/hogql/test/test_query_stats.py
+++ b/posthog/hogql/test/test_query_stats.py
@@ -52,3 +52,12 @@ def test_the_last_rows_read_are_kept_per_thread():
assert last_rows_read() == 0
assert (stats.rows_read, stats.query_count) == (1003, 2)
+
+
+def test_a_lookup_counts_in_the_totals_and_is_kept_apart():
+ with query_stats_scope() as stats:
+ record(rows_read=1000, duration_ms=50.0, lookup=True)
+ record(rows_read=3, duration_ms=2.0)
+
+ assert (stats.rows_read, stats.duration_ms) == (1003, 52.0)
+ assert (stats.lookup_rows_read, stats.lookup_duration_ms) == (1000, 50.0)
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 7495ae35deae..c9390c0e1501 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -27,6 +27,7 @@ from posthog.schema import (
BounceRatePageViewMode,
CacheMissResponse,
CurrencyCode,
+ DashboardFilter,
DataTableNode,
DataVisualizationNode,
DateRange,
@@ -63,6 +64,7 @@ from posthog.hogql.errors import QueryError, ResolutionError
from posthog.hogql.parser import parse_select
from posthog.hogql.query_stats import get_active, record
+from posthog.api.services.query import _run_query_runner
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries
@@ -170,6 +172,7 @@ def setup_test_query_runner_class(base: type[QueryRunner] = QueryRunner):
_QUERY_SCAN_FLAG_SHOW = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)
+_KINDS_WITH_THE_TEST_KIND = frozenset({"TestQuery"})
_QUERY_SCAN_FLAG_LOG_ONLY = QueryScanFlag(
mode=QueryScanMode.LOG_ONLY, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5
)
@@ -339,6 +342,7 @@ class TestQueryRunner(BaseTest):
return_value=QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5),
),
mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis_client),
+ mock.patch("posthog.query_scan.trigger._KINDS_A_PERSON_BUILDS", _KINDS_WITH_THE_TEST_KIND),
mock.patch("posthog.query_scan.trigger.print_prepared_ast", return_value="SELECT 1"),
mock.patch("posthog.tasks.query_scan.analyze_query_scan.delay") as delay,
mock.patch.object(
@@ -383,6 +387,7 @@ class TestQueryRunner(BaseTest):
return_value=QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5),
),
mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis_client),
+ mock.patch("posthog.query_scan.trigger._KINDS_A_PERSON_BUILDS", _KINDS_WITH_THE_TEST_KIND),
mock.patch("posthog.tasks.query_scan.analyze_query_scan.delay") as delay,
mock.patch.object(
TestQueryRunner, "_calculate", autospec=True, side_effect=calculate_until_clickhouse_gives_up
@@ -399,6 +404,50 @@ class TestQueryRunner(BaseTest):
"analysis_requested": True,
}
+ @parameterized.expand([("all time", "all", True), ("a recent range", "-7d", False)])
+ def test_the_analysis_knows_when_the_dashboard_chose_all_time(self, _name, date_from, expected):
+ TestQueryRunner = self.setup_test_query_runner_class()
+
+ def calculate_over_the_floor(_self):
+ record(rows_read=90, duration_ms=4000.0)
+ active = get_active()
+ assert active is not None
+ active.record_execution(
+ tree=parse_select("select 1"), context=HogQLContext(team_id=self.team.pk), rows_read=90
+ )
+ return TheTestBasicQueryResponse(results=[])
+
+ redis_client = mock.Mock()
+ redis_client.get.return_value = None
+ redis_client.incr.return_value = 1
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
+ with (
+ mock.patch("posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=_QUERY_SCAN_FLAG_SHOW),
+ mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis_client),
+ mock.patch("posthog.query_scan.trigger._KINDS_A_PERSON_BUILDS", _KINDS_WITH_THE_TEST_KIND),
+ mock.patch("posthog.query_scan.trigger.print_prepared_ast", return_value="SELECT 1"),
+ mock.patch("posthog.tasks.query_scan.analyze_query_scan.delay") as delay,
+ mock.patch.object(TestQueryRunner, "_calculate", autospec=True, side_effect=calculate_over_the_floor),
+ ):
+ _run_query_runner(
+ runner,
+ dashboard_filters=DashboardFilter(date_from=date_from),
+ variables_override=None,
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ user=self.user,
+ query_id=None,
+ insight_id=None,
+ dashboard_id=None,
+ is_query_service=False,
+ cache_age_seconds=None,
+ pagination_cursor=None,
+ analytics_props=None,
+ allow_raw_results=False,
+ )
+
+ assert delay.call_count == 1
+ assert delay.call_args.kwargs["dashboard_all_time"] is expected
+
def test_calculate_runs_validators_before_calculation(self):
TestQueryRunner = self.setup_test_query_runner_class()
validation_rule = mock.MagicMock()
@@ -2088,6 +2137,7 @@ class TestQueryFailureCaching(BaseTest):
with (
mock.patch("posthoganalytics.feature_enabled", side_effect=_failure_caching_flag),
mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis_client),
+ mock.patch("posthog.query_scan.trigger._KINDS_A_PERSON_BUILDS", _KINDS_WITH_THE_TEST_KIND),
mock.patch.object(
runner_class, "_calculate", autospec=True, side_effect=calculate_until_clickhouse_gives_up
),
diff --git a/posthog/query_scan/analyze.py b/posthog/query_scan/analyze.py
index 2ab7b681b70e..2b1f34cf31dd 100644
--- a/posthog/query_scan/analyze.py
+++ b/posthog/query_scan/analyze.py
@@ -1,30 +1,62 @@
"""Turn ClickHouse's plans into findings and the two shares.
-Pure: no ClickHouse, Redis or Celery. A share is the outer read's granules over a denominator, the
-project's events in the query's date range or over all time.
+Pure: no ClickHouse, Redis or Celery. A share is a plan's largest events read over a denominator,
+the project's events in the plan's date range or over all time. The plan says what was read; the
+facts the trigger read off the tree say why. They give each finding its cause, whether it reads this
+much by design and where its fix goes, and those pick its wording and whether the person can act.
"""
-from posthog.schema import QueryScanFindingKind, QueryScanFindingReason, QueryScanWarning
+from posthog.schema import QueryScanFindingKind, QueryScanFixLocation, QueryScanWarning
from posthog.dataclasses import frozen
from posthog.query_scan.event_filter import EventFilterOutcome
from posthog.query_scan.explain import PlanIndex, PlanTableRead, QueryPlan
-from posthog.query_scan.findings import SQL_QUERY_KIND, build_warning, explain_evidence
+from posthog.query_scan.findings import SQL_QUERY_KIND, FindingCause, build_warning, explain_evidence, finding_label
from posthog.query_scan.flag import QueryScanFlag
+from posthog.query_scan.tree_facts import TreeFacts
-__all__ = ["PlanSet", "QueryScanResult", "analyze"]
+__all__ = ["ExplainedPlan", "PlanSet", "QueryScanResult", "RunFacts", "analyze"]
@frozen
-class PlanSet:
- """The plans one job produced. ``team_granules`` and ``range_granules`` are the denominators:
- the project's events over all time, and over the query's date range.
+class ExplainedPlan:
+ """One plan with what it is judged on, the same for the outer query and for a subquery.
+
+ ``range_granules`` is the project's events over the plan's own date range. ``event_filter`` is
+ the tree's verdict on the plan's reads folded with the plan's key use, and ``tree`` the other
+ facts the trigger read off those reads. Either is None when nothing shipped, and the plan alone
+ decides.
"""
- outer: QueryPlan | None
- subqueries: tuple[QueryPlan, ...] = ()
- team_granules: int | None = None
+ plan: QueryPlan
range_granules: int | None = None
+ event_filter: EventFilterOutcome | None = None
+ tree: TreeFacts | None = None
+
+
+@frozen
+class PlanSet:
+ """The plans one job produced, and the project's events over all time."""
+
+ outer: ExplainedPlan | None
+ subqueries: tuple[ExplainedPlan, ...] = ()
+ team_granules: int | None = None
+
+
+@frozen
+class RunFacts:
+ """What the trigger knew about the run that the plan cannot show.
+
+ ``all_time`` and ``dashboard_all_time`` say a picker chose All time, and where. The by-design
+ flags come from the insight's own settings: a first-time math has to read from the first event,
+ and an active-user count on All events has to read every event.
+ """
+
+ all_time: bool = False
+ dashboard_all_time: bool = False
+ all_history_by_design: bool = False
+ all_events_by_design: bool = False
+ open_filters_placeholder: bool = False
@frozen(eq=False)
@@ -37,128 +69,143 @@ class QueryScanResult:
def finding_kinds(self) -> list[str]:
return [str(finding.kind) for finding in self.findings]
+ def finding_labels(self) -> list[str]:
+ return [finding_label(finding) for finding in self.findings]
+
+ def actionable_finding_kinds(self) -> list[str]:
+ return [str(finding.kind) for finding in self.findings if finding.actionable]
+
+ def actionable_finding_labels(self) -> list[str]:
+ return [finding_label(finding) for finding in self.findings if finding.actionable]
+
def analyze(
plans: PlanSet,
flag: QueryScanFlag,
*,
query_kind: str,
- open_filters_placeholder: bool,
- event_filter: EventFilterOutcome | None = None,
+ run: RunFacts,
table_row_averages: dict[str, float] | None = None,
- all_time: bool = False,
- all_history_by_design: bool = False,
) -> QueryScanResult:
- """`open_filters_placeholder` is true when the query left its date range to a `{filters}`
- placeholder that expanded to no bound, so the fix is on the insight, not in the SQL.
-
- `event_filter` is the combined tree-and-plan verdict for the outer execution, from the job.
- None means no verdict shipped, so the outer read's no-event-filter gate falls back to the
- plan's keys alone. A subquery is never classified from the tree, so it always uses that
- fallback.
-
- `table_row_averages` is empty when the `system.parts` read failed; the persons gate then falls
+ """`table_row_averages` is empty when the `system.parts` read failed; the persons gate then falls
back to a raw granule comparison, so the analysis still runs without the metadata query.
-
- `all_history_by_design` is true when the insight has to read from the project's first event
- whatever its date range, so no start date is reported: there is nothing the person can change.
"""
averages = table_row_averages or {}
if plans.outer is None:
return QueryScanResult(findings=[], explain_ok=False)
- outer_events = plans.outer.heaviest_events_read()
- numerator = outer_events.selected_granules() if outer_events is not None else None
- range_share = _share(numerator, plans.range_granules)
- project_share = _share(numerator, plans.team_granules)
-
findings: list[QueryScanWarning] = []
- # Only the outer read has a range share; a subquery gates on the skip-step fallback.
- findings += _findings_for_plan(
- plans.outer,
- flag,
- query_kind=query_kind,
- open_filters_placeholder=open_filters_placeholder,
- all_time=all_time,
- all_history_by_design=all_history_by_design,
- range_share=range_share,
- subquery_index=None,
- table_row_averages=averages,
- event_filter=event_filter,
- )
- for index, subquery in enumerate(plans.subqueries):
+ for subquery_index, explained in [(None, plans.outer), *enumerate(plans.subqueries)]:
findings += _findings_for_plan(
- subquery,
+ explained,
flag,
query_kind=query_kind,
- open_filters_placeholder=open_filters_placeholder,
- all_time=all_time,
- all_history_by_design=all_history_by_design,
- range_share=None,
- subquery_index=index,
+ run=run,
+ team_granules=plans.team_granules,
+ subquery_index=subquery_index,
table_row_averages=averages,
- event_filter=None,
)
+ numerator = _read_granules(plans.outer)
return QueryScanResult(
findings=findings,
explain_ok=True,
- range_share=range_share,
- project_share=project_share,
+ range_share=_share(numerator, plans.outer.range_granules),
+ project_share=_share(numerator, plans.team_granules),
)
def _findings_for_plan(
- plan: QueryPlan,
+ explained: ExplainedPlan,
flag: QueryScanFlag,
*,
query_kind: str,
- open_filters_placeholder: bool,
- all_time: bool,
- all_history_by_design: bool,
- range_share: float | None,
+ run: RunFacts,
+ team_granules: int | None,
subquery_index: int | None,
table_row_averages: dict[str, float],
- event_filter: EventFilterOutcome | None,
) -> list[QueryScanWarning]:
# A plan that reads the events table more than once is judged on its largest read, except that
# any read with no start bound is enough for the start-date finding. A lighter read with no event
# filter goes unmentioned even when it is nearly as large, because gating each read on its own
# share would cost a denominator per read.
+ plan, tree, event_filter = explained.plan, explained.tree, explained.event_filter
heaviest = plan.heaviest_events_read()
# A plan that does not read the events table has no denominator and nothing to advise on.
if heaviest is None:
return []
+ is_sql = query_kind == SQL_QUERY_KIND
+ range_share = _share(_read_granules(explained), explained.range_granules)
+ view_name = tree.view_name if tree is not None else None
findings: list[QueryScanWarning] = []
# "All time" reaches the plan as a bound at the project's first event, so only the setting
- # says the person chose no start date; it applies to the outer query, not its subqueries.
- chose_all_time = all_time and subquery_index is None
- unbounded = next((read for read in plan.events_reads() if read.timestamp_bounds().lower is None), None)
- if (unbounded is not None or chose_all_time) and not all_history_by_design:
- reason = QueryScanFindingReason.FILTERS if open_filters_placeholder and query_kind == SQL_QUERY_KIND else None
+ # says the person chose no start date; it applies to the outer query, not its subqueries. It is
+ # one click to change, so it is reported at any size.
+ chose_all_time = run.all_time and subquery_index is None
+ unbounded = max(
+ (read for read in plan.events_reads() if read.timestamp_bounds().lower is None),
+ key=lambda read: read.selected_granules() or 0,
+ default=None,
+ )
+ if tree is not None and tree.start_date_hidden_from_plan:
+ unbounded = None
+ reads_all_history = chose_all_time or (
+ unbounded is not None and _passes_start_date_gate(unbounded, team_granules, flag.start_date_ratio)
+ )
+ no_event_filter, event_cause = _no_event_filter(heaviest, event_filter)
+ reads_all_events = no_event_filter and _passes_event_gate(heaviest, range_share, flag.event_ratio)
+ # All history of a few events, or every event of a short period, is an ordinary by-design read,
+ # so there the query's shape is believed. Every event of all history is the most expensive read
+ # there is, and the shape cannot tell intent, so there the finding stays a warning.
+ believe_shape = not (reads_all_history and reads_all_events)
+
+ if chose_all_time:
findings.append(
build_warning(
kind=QueryScanFindingKind.NO_START_DATE,
query_kind=query_kind,
- reason=reason,
+ by_design=_all_history_by_design(run, tree, believe_shape=believe_shape),
+ fix_location=_all_time_location(run, is_sql=is_sql),
evidence=(
- "The date range is set to All time, so the query starts at the project's first event."
- if chose_all_time
- else _evidence((unbounded if unbounded is not None else heaviest).min_max(), subquery_index)
+ "The dashboard's date filter is set to All time, so the query starts at the project's first event."
+ if run.dashboard_all_time
+ else "The date range is set to All time, so the query starts at the project's first event."
),
+ view_name=view_name,
+ )
+ )
+ elif unbounded is not None and reads_all_history:
+ by_design = _all_history_by_design(run, tree, believe_shape=believe_shape)
+ open_filters_location = _open_filters_location(run, is_sql=is_sql, subquery_index=subquery_index)
+ fixed_in_the_read = not by_design and open_filters_location is None
+ findings.append(
+ build_warning(
+ kind=QueryScanFindingKind.NO_START_DATE,
+ query_kind=query_kind,
+ cause=_unbounded_cause(tree) if fixed_in_the_read else None,
+ by_design=by_design,
+ fix_location=open_filters_location,
+ evidence=_evidence(unbounded.min_max(), subquery_index),
+ subquery_index=subquery_index,
+ view_name=view_name,
)
)
- no_event_filter, event_reason = _no_event_filter(heaviest, event_filter)
- if no_event_filter and _passes_event_gate(heaviest, range_share, flag.event_ratio):
+ if reads_all_events:
+ if event_cause is None:
+ sibling_uses_event_key = any(read is not heaviest and read.uses_event_key() for read in plan.events_reads())
+ event_cause = _unfiltered_cause(tree, is_sql=is_sql, sibling_uses_event_key=sibling_uses_event_key)
findings.append(
build_warning(
kind=QueryScanFindingKind.NO_EVENT_FILTER,
query_kind=query_kind,
- reason=event_reason,
+ cause=event_cause,
+ by_design=event_cause is None and _all_events_by_design(run, tree, believe_shape=believe_shape),
evidence=_evidence(heaviest.primary_key(), subquery_index),
+ subquery_index=subquery_index,
+ view_name=view_name,
)
)
@@ -169,27 +216,103 @@ def _findings_for_plan(
kind=QueryScanFindingKind.PERSONS_JOIN,
query_kind=query_kind,
evidence=_evidence(person_read.primary_key(), subquery_index),
+ subquery_index=subquery_index,
+ view_name=view_name,
)
)
return findings
+def _read_granules(explained: ExplainedPlan) -> int | None:
+ """The granules of the plan's largest events read, for its shares. None when the scan took a
+ filter on `event` or `timestamp` out before it asked for the plan, because the filter holds a
+ subquery that EXPLAIN would run: the plan's granules are then the read without that filter."""
+ hidden_event_filter = explained.event_filter is not None and explained.event_filter.hidden_from_plan
+ hidden_start_date = explained.tree is not None and explained.tree.start_date_hidden_from_plan
+ events_read = explained.plan.heaviest_events_read()
+ if events_read is None or hidden_event_filter or hidden_start_date:
+ return None
+ return events_read.selected_granules()
+
+
+def _all_history_by_design(run: RunFacts, tree: TreeFacts | None, *, believe_shape: bool) -> bool:
+ """Whether the read has to start at the project's first event. A first-time math says so in the
+ insight's settings, which is a choice the person made. A SQL query says so only by its shape."""
+ return run.all_history_by_design or (believe_shape and tree is not None and tree.all_history)
+
+
+def _all_time_location(run: RunFacts, *, is_sql: bool) -> QueryScanFixLocation | None:
+ """Where an All time range gets changed. The dashboard's date filter overrides the insight's
+ own range. A SQL insight takes All time through `{filters}`, so the fix is on the insight, not
+ in the SQL. None is an insight built from pickers, which holds its own range."""
+ if run.dashboard_all_time:
+ return QueryScanFixLocation.DASHBOARD_DATE_FILTER
+ return QueryScanFixLocation.INSIGHT_DATE_RANGE if is_sql else None
+
+
+def _open_filters_location(run: RunFacts, *, is_sql: bool, subquery_index: int | None) -> QueryScanFixLocation | None:
+ """Where a `{filters}` date range nobody set gets changed. None when the fix is in the read
+ itself: the query takes no date range through `{filters}`, or the read is a subquery's, because
+ nothing says which part of the SQL holds `{filters}`."""
+ if not (is_sql and run.open_filters_placeholder) or subquery_index is not None:
+ return None
+ if run.dashboard_all_time:
+ return QueryScanFixLocation.DASHBOARD_DATE_FILTER
+ return QueryScanFixLocation.INSIGHT_DATE_RANGE
+
+
+def _unbounded_cause(tree: TreeFacts | None) -> FindingCause | None:
+ """Why a read the plan could not bound has no start date. None is no bound at all, the plain
+ case. A bound the tree has but the plan does not is one ClickHouse could not use."""
+ return FindingCause.START_DATE_NOT_USED_BY_CLICKHOUSE if tree is not None and tree.timestamp_bound else None
+
+
+def _unfiltered_cause(tree: TreeFacts | None, *, is_sql: bool, sibling_uses_event_key: bool) -> FindingCause | None:
+ """Why a read with no event condition at all is unfiltered. An unfiltered helper read beside a
+ read that names events is the one to filter, even when it counts distinct actors; a property
+ condition stands in for an event name unless the query groups by event, whose answer is the
+ set of events itself. None is the plain case: nothing in the query says which events it is about.
+ """
+ # An insight's reads are PostHog's own code, so only a SQL author can add a filter to a helper read.
+ if is_sql and sibling_uses_event_key:
+ return FindingCause.UNFILTERED_HELPER_READ
+ if tree is not None and tree.property_filter and not tree.groups_by_event:
+ return FindingCause.PROPERTY_FILTER_WITHOUT_EVENT
+ return None
+
+
+def _all_events_by_design(run: RunFacts, tree: TreeFacts | None, *, believe_shape: bool) -> bool:
+ """Whether a read with no event condition and no cause has to read every event: the answer is
+ the set of events itself, or a count of people or sessions over any event. The insight's
+ settings say so as a choice the person made. A SQL query says so only by its shape."""
+ shape_says_so = tree is not None and (tree.groups_by_event or tree.counts_any_event)
+ return run.all_events_by_design or (believe_shape and shape_says_so)
+
+
def _no_event_filter(
heaviest: PlanTableRead, event_filter: EventFilterOutcome | None
-) -> tuple[bool, QueryScanFindingReason | None]:
- """Whether the heaviest read has no usable event filter, and the reason for the copy. The tree's
- verdict carries the reason when the job shipped one; the read's keys alone name none.
+) -> tuple[bool, FindingCause | None]:
+ """Whether the heaviest read has no usable event filter, and the cause for the copy. The tree's
+ verdict carries the cause when the job shipped one; the read's keys alone name none.
"""
if event_filter is not None:
- reason = QueryScanFindingReason(event_filter.reason) if event_filter.reason is not None else None
- return event_filter.classification != "usable", reason
+ cause = FindingCause(event_filter.reason) if event_filter.reason is not None else None
+ return event_filter.classification != "usable", cause
return not heaviest.uses_event_key(), None
+def _passes_start_date_gate(read: PlanTableRead, team_granules: int | None, start_date_ratio: float) -> bool:
+ """A small unbounded read, an event filter or a skip index having already pruned it to a sliver
+ of the project, is slow for another reason, so a start date is not the advice. Without the
+ denominator the size is unknown and the finding stands."""
+ share = _share(read.selected_granules(), team_granules)
+ return share is None or share >= start_date_ratio
+
+
def _passes_event_gate(read: PlanTableRead, range_share: float | None, event_ratio: float) -> bool:
- """With the range share known, gate on it. Without one (a subquery, or a failed denominator), a
- skip index that already pruned most of the read means an event filter would not help much.
+ """With the range share known, gate on it. Without one, because the denominator failed, a skip
+ index that already pruned most of the read means an event filter would not help much.
"""
if range_share is not None:
return range_share >= event_ratio
diff --git a/posthog/query_scan/event_filter.py b/posthog/query_scan/event_filter.py
index 6fb425f9e76d..b95b601e4f2c 100644
--- a/posthog/query_scan/event_filter.py
+++ b/posthog/query_scan/event_filter.py
@@ -48,22 +48,38 @@ _NOT_PRUNED_OPS = frozenset(
@frozen(eq=False)
class EventFilterOutcome:
+ """``hidden_from_plan`` marks a usable filter that compares ``event`` to a subquery. The scan
+ takes that comparison out before it asks for the plan, because EXPLAIN would run the subquery,
+ so the plan cannot say whether ClickHouse pruned on it and the tree's verdict stands.
+ """
+
classification: EventFilterClass
reason: EventFilterReason | None = None
+ hidden_from_plan: bool = False
+
+
+def _same_verdict(one: EventFilterOutcome, other: EventFilterOutcome) -> bool:
+ return (
+ one.classification == other.classification
+ and one.reason == other.reason
+ and one.hidden_from_plan == other.hidden_from_plan
+ )
-def classify_event_filter(tree: ast.AST) -> EventFilterOutcome | None:
+def classify_event_filter(tree: ast.AST, reads: list[EventsRead] | None = None) -> EventFilterOutcome | None:
"""The verdict the tree alone supports; ``usable`` when there is no events read. None when the
reads disagree: the tree cannot say which of them is the plan's heaviest read, the one the advice
- is about, so no verdict can be pinned to it.
+ is about, so no verdict can be pinned to it. ``reads`` narrows the verdict to the reads one plan
+ holds; None takes every read in the tree.
"""
- reads = find_events_reads(tree)
+ if reads is None:
+ reads = find_events_reads(tree)
if not reads:
return EventFilterOutcome(classification="usable")
outcomes = [_classify_read(read, collect_conditions(tree, read)) for read in reads]
first = outcomes[0]
- if any((other.classification, other.reason) != (first.classification, first.reason) for other in outcomes[1:]):
+ if any(not _same_verdict(other, first) for other in outcomes[1:]):
return None
return first
@@ -71,14 +87,15 @@ def classify_event_filter(tree: ast.AST) -> EventFilterOutcome | None:
def combine_event_filter(outcome: EventFilterOutcome, plan: QueryPlan | None) -> EventFilterOutcome:
"""Fold the plan's key use into the tree's verdict. The plan overrules the tree, except that a
negation enters the key condition yet prunes almost nothing, so ``negated`` stands. A key the plan
- did not use with a tree verdict of usable is ``not_pruned``. The plan's side is its heaviest events
- read, the one the advice is about.
+ did not use with a tree verdict of usable is ``not_pruned``, unless the filter is hidden from the
+ plan, where the plan has nothing to say. The plan's side is its heaviest events read, the one the
+ advice is about.
"""
heaviest = plan.heaviest_events_read() if plan is not None else None
key_used = heaviest.uses_event_key() if heaviest is not None else None
if key_used is True and outcome.reason != "negated":
return EventFilterOutcome(classification="usable")
- if key_used is False and outcome.classification == "usable":
+ if key_used is False and outcome.classification == "usable" and not outcome.hidden_from_plan:
return EventFilterOutcome(classification="not_used", reason="not_pruned")
return outcome
@@ -135,7 +152,8 @@ def _classify_or(term: ast.Or, read: EventsRead) -> EventFilterOutcome | None:
return None
if all(branch is not None and branch.classification == "usable" for branch in branches):
# Every branch names events, so the OR is still a list of event names.
- return EventFilterOutcome(classification="usable")
+ hidden = any(branch is not None and branch.hidden_from_plan for branch in branches)
+ return EventFilterOutcome(classification="usable", hidden_from_plan=hidden)
return EventFilterOutcome(classification="not_used", reason="in_or")
@@ -153,6 +171,9 @@ def _classify_event_compare(node: ast.CompareOperation, value_side: ast.Expr) ->
return EventFilterOutcome(classification="not_used", reason="negated")
if node.op in _EQUALITY_OPS and _is_constant(value_side):
return EventFilterOutcome(classification="usable")
+ if node.op in _EQUALITY_OPS and isinstance(strip_aliases(value_side), ast.SelectQuery | ast.SelectSetQuery):
+ # ClickHouse runs the subquery first and seeks on the names it returns, as it does on a written list.
+ return EventFilterOutcome(classification="usable", hidden_from_plan=True)
if node.op in _PATTERN_OPS and _is_constant(value_side):
pattern = next(_iter_string_constants(value_side), None)
if node.op in _PRUNABLE_PATTERN_OPS and pattern is not None and not pattern.startswith("%"):
@@ -160,19 +181,13 @@ def _classify_event_compare(node: ast.CompareOperation, value_side: ast.Expr) ->
# A leading wildcard leaves no prefix for the sort order to seek on, and an ILIKE pattern
# has no case-sensitive prefix at all.
return EventFilterOutcome(classification="not_used", reason="not_pruned")
- if node.op not in _NOT_PRUNED_OPS and _is_data(value_side):
- # `dynamic` tells the person their filter compares `event` to a column or a subquery, so
- # only that shape may take it.
+ if node.op not in _NOT_PRUNED_OPS and isinstance(strip_aliases(value_side), ast.Field):
+ # `dynamic` tells the person their filter compares `event` to a column, so only that shape
+ # may take it.
return EventFilterOutcome(classification="not_used", reason="dynamic")
return EventFilterOutcome(classification="not_used", reason="not_pruned")
-def _is_data(expr: ast.Expr) -> bool:
- """Whether the other side of the comparison is read from the data rather than written out."""
- expr = strip_aliases(expr)
- return isinstance(expr, ast.Field | ast.SelectQuery | ast.SelectSetQuery)
-
-
def _is_constant(expr: ast.Expr) -> bool:
expr = strip_aliases(expr)
if isinstance(expr, ast.Constant):
diff --git a/posthog/query_scan/explain.py b/posthog/query_scan/explain.py
index 018156dad7e4..746345fcd342 100644
--- a/posthog/query_scan/explain.py
+++ b/posthog/query_scan/explain.py
@@ -10,6 +10,8 @@ from typing import Any
from posthog.dataclasses import frozen
+EXPLAIN_MAX_SECONDS = 10
+
# Spelled out rather than imported, so this parser does not pull in the model layer.
_EVENTS_TABLE_NAMES = ("events", "events_json", "sharded_events", "sharded_events_json")
diff --git a/posthog/query_scan/findings.py b/posthog/query_scan/findings.py
index 1abd2c279244..bce70cbcb878 100644
--- a/posthog/query_scan/findings.py
+++ b/posthog/query_scan/findings.py
@@ -1,10 +1,15 @@
"""Turn an analysis outcome into the warning a person reads, and the prompt the assistant reads.
-A no-event-filter or no-start-date finding reads differently for raw SQL than for an insight built
-from pickers, so the query kind chooses which wording to use.
+A finding reads differently for raw SQL than for an insight built from pickers, so the query kind
+chooses which wording to use. Within a kind, three facts choose it: the cause, whether the query
+reads this much by design, and where the fix goes. The same facts decide whether the finding is
+actionable: whether the person can change the query so it reads less and still answers the same
+question. A by-design finding stays, worded as an explanation, and is never actionable.
"""
-from posthog.schema import QueryScanFindingKind, QueryScanFindingReason, QueryScanWarning
+from enum import StrEnum
+
+from posthog.schema import QueryScanFindingKind, QueryScanFixLocation, QueryScanWarning
from posthog.dataclasses import frozen
@@ -28,8 +33,44 @@ ASSISTANT_RULES = (
)
+class FindingCause(StrEnum):
+ """What in the query text kept ClickHouse from narrowing the read, when the analysis could tell.
+
+ The value picks the wording, and it is the label the `query scan analyzed` event and the
+ assistant's prompt carry. Nothing a person sees branches on it: surfaces read `actionable`.
+ """
+
+ EVENT_FILTER_INSIDE_OR = "in_or"
+ EVENT_WRAPPED_IN_FUNCTION = "wrapped"
+ EVENT_FILTER_ONLY_EXCLUDES = "negated"
+ EVENT_COMPARED_TO_COLUMN = "dynamic"
+ EVENT_FILTER_NOT_USED_BY_CLICKHOUSE = "not_pruned"
+ PROPERTY_FILTER_WITHOUT_EVENT = "property_filter"
+ UNFILTERED_HELPER_READ = "helper_read"
+ START_DATE_NOT_USED_BY_CLICKHOUSE = "bound_not_used"
+
+
+_FIXABLE_CAUSES: dict[QueryScanFindingKind, frozenset[FindingCause | None]] = {
+ QueryScanFindingKind.NO_EVENT_FILTER: frozenset(
+ {
+ FindingCause.EVENT_FILTER_INSIDE_OR,
+ FindingCause.EVENT_WRAPPED_IN_FUNCTION,
+ FindingCause.EVENT_FILTER_ONLY_EXCLUDES,
+ FindingCause.EVENT_FILTER_NOT_USED_BY_CLICKHOUSE,
+ FindingCause.PROPERTY_FILTER_WITHOUT_EVENT,
+ FindingCause.UNFILTERED_HELPER_READ,
+ }
+ ),
+ QueryScanFindingKind.NO_START_DATE: frozenset({None, FindingCause.START_DATE_NOT_USED_BY_CLICKHOUSE}),
+}
+
+# Fixed on the insight or the dashboard, so the assistant editing the query has nothing to change.
+_OUTSIDE_THE_QUERY = frozenset({QueryScanFixLocation.INSIGHT_DATE_RANGE, QueryScanFixLocation.DASHBOARD_DATE_FILTER})
+
+
@frozen
class _Copy:
+ # `{subject}` is the query, the insight, a subquery of it, or the view it reads.
lead: str
advice: str
fix: str
@@ -37,7 +78,7 @@ class _Copy:
_NO_EVENT_FILTER_SQL = _Copy(
lead=(
- "Queries are fastest when they name a fixed set of events. This query has no event filter, so it "
+ "Queries are fastest when they name a fixed set of events. {subject} has no event filter, so it "
"reads a large share of the events in its date range, which is slow."
),
advice="If the question is about specific events, add `WHERE event IN ('…')` naming them.",
@@ -53,19 +94,19 @@ _NO_EVENT_FILTER_SQL = _Copy(
_NO_EVENT_FILTER_INSIGHT = _Copy(
lead=(
- "Insights are fastest when they look at a fixed set of events. This insight looks at all events, so "
+ "Insights are fastest when they look at a fixed set of events. {subject} looks at all events, so "
"it reads a large share of the events in its date range, which is slow."
),
advice="Pick specific events if the question is about some of them.",
fix="Pick the events this insight is about instead of All events.",
)
-# A raw SQL query can name events yet leave ClickHouse unable to prune on them. The reason from the
+# A raw SQL query can name events yet leave ClickHouse unable to prune on them. The cause from the
# tree says which shape blocked it, so the copy names that shape and the specific fix.
-_NO_EVENT_FILTER_BY_REASON: dict[QueryScanFindingReason, _Copy] = {
- QueryScanFindingReason.IN_OR: _Copy(
+_NO_EVENT_FILTER_SQL_BY_CAUSE: dict[FindingCause, _Copy] = {
+ FindingCause.EVENT_FILTER_INSIDE_OR: _Copy(
lead=(
- "Queries are fastest when they name a fixed set of events. This query names events only inside an OR "
+ "Queries are fastest when they name a fixed set of events. {subject} names events only inside an OR "
"with another condition, so that filter cannot be used and it still reads a large share of the events "
"in its date range, which is slow."
),
@@ -79,9 +120,9 @@ _NO_EVENT_FILTER_BY_REASON: dict[QueryScanFindingReason, _Copy] = {
"help; propose the time bound only."
),
),
- QueryScanFindingReason.WRAPPED: _Copy(
+ FindingCause.EVENT_WRAPPED_IN_FUNCTION: _Copy(
lead=(
- "Queries are fastest when they compare `event` directly to fixed names. This query wraps `event` in a "
+ "Queries are fastest when they compare `event` directly to fixed names. {subject} wraps `event` in a "
"function, so that filter cannot be used and it still reads a large share of the events in its date "
"range, which is slow."
),
@@ -93,26 +134,27 @@ _NO_EVENT_FILTER_BY_REASON: dict[QueryScanFindingReason, _Copy] = {
"names could vary over time, say the rewrite may miss older spellings and ask."
),
),
- QueryScanFindingReason.NEGATED: _Copy(
+ FindingCause.EVENT_FILTER_ONLY_EXCLUDES: _Copy(
lead=(
- "Queries are fastest when they explicitly enumerate the events they want. This query only excludes "
+ "Queries are fastest when they explicitly enumerate the events they want. {subject} only excludes "
"events, so that filter cannot be used and it still reads most of the events in its date range, "
"which is slow."
),
advice="Explicitly enumerate the events you want instead.",
fix=(
- "The filter excludes events, and the index cannot use an exclusion, so it reads everything. "
- 'Exploration cannot reveal the intended set, because the query says "everything except". Ask whether '
- "the person can name the events they want. If they can, replace the exclusion with `event IN (...)`; "
- "if they cannot, keep the exclusion and add the time bound. Do not run exploratory queries for this "
- "finding."
+ "The filter excludes events, and the index cannot use an exclusion, so it reads everything. Run one "
+ "query for what the rest of the query matches: `SELECT event, count() FROM events WHERE <the query's "
+ "conditions, the exclusion included> AND timestamp >= now() - interval 7 day GROUP BY event ORDER BY "
+ "count() DESC LIMIT 20`. If that is a few events, replace the exclusion with `event IN (<those "
+ "events>)` and say the result then covers only those. If it is many events, ask which events the "
+ "person wants. If they cannot say, keep the exclusion and add the time bound."
),
),
- QueryScanFindingReason.DYNAMIC: _Copy(
+ FindingCause.EVENT_COMPARED_TO_COLUMN: _Copy(
lead=(
- "Queries are fastest when they compare `event` to fixed names. This query compares `event` to another "
- "column or a subquery, so that filter cannot be used and it still reads a large share of the events "
- "in its date range, which is slow."
+ "Queries are fastest when they compare `event` to fixed names. {subject} compares `event` to another "
+ "column, so that filter cannot be used and it still reads a large share of the events in its date "
+ "range, which is slow."
),
advice="Compare `event` to fixed names.",
fix=(
@@ -121,9 +163,9 @@ _NO_EVENT_FILTER_BY_REASON: dict[QueryScanFindingReason, _Copy] = {
"interval 7 day LIMIT 20` and enumerate; otherwise keep the condition and add the time bound."
),
),
- QueryScanFindingReason.NOT_PRUNED: _Copy(
+ FindingCause.EVENT_FILTER_NOT_USED_BY_CLICKHOUSE: _Copy(
lead=(
- "Queries are fastest when they compare `event` directly to fixed names. This query has an event "
+ "Queries are fastest when they compare `event` directly to fixed names. {subject} has an event "
"filter, but it could not be used, so it still read a large share of the events in its date range, "
"which is slow."
),
@@ -134,11 +176,92 @@ _NO_EVENT_FILTER_BY_REASON: dict[QueryScanFindingReason, _Copy] = {
"read."
),
),
+ FindingCause.PROPERTY_FILTER_WITHOUT_EVENT: _Copy(
+ lead=(
+ "Queries are fastest when they name a fixed set of events. {subject} narrows events by a property "
+ "but names no events, so it still reads a large share of the events in its date range, which is slow."
+ ),
+ advice=(
+ "If that property only appears on some events, add `WHERE event IN ('…')` naming them, for example "
+ "`$pageview` for a URL or path filter."
+ ),
+ fix=(
+ "The query filters on a property and names no events, so the index cannot prune. Run one query for "
+ "which events carry the property: `SELECT event, count() FROM events WHERE <the property condition> "
+ "AND timestamp >= now() - interval 7 day GROUP BY event ORDER BY count() DESC LIMIT 20`. If that is a "
+ "few events, add `event IN (<those events>)` and say the answer is the same; if the property is on "
+ "most events, say an event filter would change the answer and ask which events matter."
+ ),
+ ),
+ FindingCause.UNFILTERED_HELPER_READ: _Copy(
+ lead=(
+ "Queries are fastest when every read of the events table names a fixed set of events. {subject} "
+ "names events in one read, but its largest read of the events table has no event filter, which is slow."
+ ),
+ advice="Add an event filter, or at least the same start date, to the unfiltered read too.",
+ fix=(
+ "The query names events in one read of the events table and reads every event in another, a subquery "
+ "or CTE with no event condition, and that read is the large one. Add an event filter to the unfiltered "
+ "read: the events the other read names when it stands for the same people or sessions, otherwise the "
+ "events its own question is about. If nothing says which events, add the same time bound as the main "
+ "read and say the answer may change."
+ ),
+ ),
}
+_NO_EVENT_FILTER_INSIGHT_BY_CAUSE: dict[FindingCause, _Copy] = {
+ FindingCause.PROPERTY_FILTER_WITHOUT_EVENT: _Copy(
+ lead=(
+ "Insights are fastest when they look at a fixed set of events. {subject} looks at all events and "
+ "filters them by a property, so it still reads a large share of the events in its date range, which "
+ "is slow."
+ ),
+ advice=(
+ "Pick the events that carry that property instead of All events, for example `$pageview` for a URL "
+ "or path filter."
+ ),
+ fix=(
+ "The insight looks at All events with a property filter. Run one query for which events carry the "
+ "property: `SELECT event, count() FROM events WHERE <the property condition> AND timestamp >= now() - "
+ "interval 7 day GROUP BY event ORDER BY count() DESC LIMIT 20`. If that is a few events, pick them in "
+ "the series and say the answer is the same; otherwise say picking events would change the answer and "
+ "ask."
+ ),
+ ),
+}
+
+_ALL_EVENTS_SQL = _Copy(
+ lead=(
+ "{subject} reads all events by design: the answer is the set of events itself, or a count of people "
+ "or sessions over any event, so an event filter would change it. Reading a large share of the events "
+ "in its date range is what makes it slow."
+ ),
+ advice="There is no event filter to add unless the question is about specific events.",
+ fix=(
+ "The query reads all events by design: it groups by event, counts distinct people or sessions over "
+ "any event, or finds each person's last event. An event filter would change the answer, so do not "
+ "propose one. If the question could be about specific events, ask which; otherwise leave the event "
+ "set alone."
+ ),
+)
+
+_ALL_EVENTS_INSIGHT = _Copy(
+ lead=(
+ "{subject} looks at all events by design: the answer is a breakdown by event, or a count of people "
+ "or sessions over any event, so picking events would change it. Reading a large share of the events "
+ "in its date range is what makes it slow."
+ ),
+ advice="There are no events to pick unless the question is about specific ones.",
+ fix=(
+ "The insight breaks down by event or counts people or sessions over all events by design, so picking "
+ "events would change the answer. Do not propose one. Ask whether the question is about specific "
+ "events; otherwise leave the series on All events."
+ ),
+)
+
_NO_START_DATE_SQL = _Copy(
lead=(
- "Queries are fastest when they start from a recent date. This query has no start date, so it reads "
+ "Queries are fastest when they start from a recent date. {subject} has no start date, so it reads "
"all your data back to the beginning, which is slow."
),
advice="If you only need recent data, add `timestamp >= now() - interval 30 day` or the range you need.",
@@ -150,30 +273,103 @@ _NO_START_DATE_SQL = _Copy(
),
)
-_NO_START_DATE_FILTERS = _Copy(
+_DATE_RANGE_WITHOUT_START_SQL = _Copy(
lead=(
- "Queries are fastest when they start from a recent date. No date range is set on this insight or "
- "dashboard, so this query reads all your data back to the beginning, which is slow."
+ "Queries are fastest when they start from a recent date. The date range on this insight or dashboard "
+ "has no start date, so {subject_lower} reads all your data back to the beginning, which is slow."
),
- advice="Set a date range on the insight or the dashboard.",
+ advice="Set a date range with a start date on the insight or the dashboard.",
fix=(
- "The SQL takes its date range from the insight's or dashboard's filters and none is set. Do not edit "
- "the SQL; tell the person to set a date range on the insight or the dashboard."
+ "The SQL takes its date range from the insight's or dashboard's filters, and that range has no start "
+ "date: it is unset or set to All time. Do not edit the SQL; tell the person to set a date range on the "
+ "insight or the dashboard."
+ ),
+)
+
+_DASHBOARD_ALL_TIME_SQL = _Copy(
+ lead=(
+ "Queries are fastest when they start from a recent date. The dashboard's date filter is set to All "
+ "time, so {subject_lower} gets no start date and reads all your data back to the beginning, which is "
+ "slow."
+ ),
+ advice="Change the dashboard's date filter if you only need recent data.",
+ fix=(
+ "The SQL takes its date range from `{filters}` and the dashboard's date filter is All time. Do not "
+ "edit the SQL; tell the person to change the dashboard's date filter."
+ ),
+)
+
+_BOUND_NOT_USED_SQL = _Copy(
+ lead=(
+ "Queries are fastest when they start from a fixed recent date. {subject} has a start date, but it "
+ "could not be used to skip older data: it compares `timestamp` to another column, wraps it in a "
+ "function, or sits where the events read cannot see it, so the query still reads all your data back "
+ "to the beginning, which is slow."
+ ),
+ advice=(
+ "Keep it and add a fixed start date directly on the events read, for example "
+ "`AND timestamp >= now() - interval 30 day`."
+ ),
+ fix=(
+ "The query bounds `timestamp`, but ClickHouse could not skip data with the bound: it compares to "
+ "another column, wraps `timestamp` in a function, or sits in a CTE or subquery the events read does "
+ "not see. Keep that condition and add a fixed relative bound beside it on the events read, "
+ "`timestamp >= now() - interval N day`, with N from the question or 30 days. Never a calendar date. "
+ "No exploration needed."
+ ),
+)
+
+_ALL_HISTORY_SQL = _Copy(
+ lead=(
+ "{subject} finds a first event ever, so it reads all your data back to the beginning by design. A "
+ "start date would change the answer. Reading everything is what makes it slow."
+ ),
+ advice="There is no start date to add unless the question only needs recent history.",
+ fix=(
+ "The query finds a first event ever, with `min` or `argMin` over `timestamp` or a ranking window "
+ "ordered by it, and has no lower bound, so it reads all history by design and a start date would "
+ "change the answer. Do not propose a time bound for that read. If the question only needs people "
+ "first seen recently, ask before changing anything."
),
)
_NO_START_DATE_INSIGHT = _Copy(
lead=(
- "Insights are fastest when they start from a recent date. This insight has no start date, so it reads "
+ "Insights are fastest when they start from a recent date. {subject} has no start date, so it reads "
"all your data back to the beginning, which is slow."
),
advice="Set a date range if you only need recent data.",
fix="Set a date range on the insight instead of All time.",
)
+_DASHBOARD_ALL_TIME_INSIGHT = _Copy(
+ lead=(
+ "Insights are fastest when they start from a recent date. The dashboard's date filter is set to All "
+ "time, which overrides the date range on {subject_lower}, so it reads all your data back to the "
+ "beginning, which is slow."
+ ),
+ advice="Change the dashboard's date filter if you only need recent data.",
+ fix=(
+ "The insight's own date range is overridden by the dashboard's date filter, which is All time. Do not "
+ "change the insight's date range; tell the person to change the dashboard's date filter."
+ ),
+)
+
+_ALL_HISTORY_INSIGHT = _Copy(
+ lead=(
+ "{subject} finds each person's first event, so it reads all your data back to the beginning by "
+ "design. A date range would change the answer. Reading everything is what makes it slow."
+ ),
+ advice="There is no date range to set unless the question only needs recent history.",
+ fix=(
+ "The insight uses a first-time math or first-time retention, which reads from the project's first "
+ "event by design, so a date range would change the answer. Do not propose a date range change."
+ ),
+)
+
_PERSONS_JOIN = _Copy(
lead=(
- "Queries are fastest when they take person details from the events table. This query joins the "
+ "Queries are fastest when they take person details from the events table. {subject} joins the "
"persons table, and reading it costs about as much as reading the events, which is slow."
),
advice="Read person properties from the events table instead, for example `person.properties.email`.",
@@ -186,39 +382,147 @@ _PERSONS_JOIN = _Copy(
)
-def _copy_for(kind: QueryScanFindingKind, reason: QueryScanFindingReason | None, *, is_sql: bool) -> _Copy:
+# The option names are the ones on the project's "Person properties mode" setting.
+_PERSONS_JOIN_INSIGHT = _Copy(
+ lead="{subject} joins the persons table, which is slow.",
+ advice=(
+ 'The project\'s Person properties mode is set to "Use person properties as of running the query". '
+ 'PostHog recommends "Use person properties from the time of the event", which makes queries fast.'
+ ),
+ fix=(
+ "The insight joins the persons table because the project's Person properties mode reads person "
+ "properties as of running the query. Nothing in the insight changes that, so do not propose an edit "
+ "for it. Say that the mode is a project setting."
+ ),
+)
+
+
+def _by_cause(table: dict[FindingCause, _Copy], cause: FindingCause | None, default: _Copy) -> _Copy:
+ return default if cause is None else table.get(cause, default)
+
+
+def _copy_for(
+ kind: QueryScanFindingKind,
+ cause: FindingCause | None,
+ *,
+ is_sql: bool,
+ by_design: bool,
+ fix_location: QueryScanFixLocation,
+) -> _Copy:
if kind == QueryScanFindingKind.NO_EVENT_FILTER:
+ if by_design:
+ return _ALL_EVENTS_SQL if is_sql else _ALL_EVENTS_INSIGHT
if not is_sql:
- return _NO_EVENT_FILTER_INSIGHT
- if reason is not None and reason in _NO_EVENT_FILTER_BY_REASON:
- return _NO_EVENT_FILTER_BY_REASON[reason]
- return _NO_EVENT_FILTER_SQL
+ return _by_cause(_NO_EVENT_FILTER_INSIGHT_BY_CAUSE, cause, _NO_EVENT_FILTER_INSIGHT)
+ return _by_cause(_NO_EVENT_FILTER_SQL_BY_CAUSE, cause, _NO_EVENT_FILTER_SQL)
if kind == QueryScanFindingKind.NO_START_DATE:
+ if by_design:
+ return _ALL_HISTORY_SQL if is_sql else _ALL_HISTORY_INSIGHT
+ if fix_location == QueryScanFixLocation.DASHBOARD_DATE_FILTER:
+ return _DASHBOARD_ALL_TIME_SQL if is_sql else _DASHBOARD_ALL_TIME_INSIGHT
if not is_sql:
return _NO_START_DATE_INSIGHT
- return _NO_START_DATE_FILTERS if reason == QueryScanFindingReason.FILTERS else _NO_START_DATE_SQL
+ if fix_location == QueryScanFixLocation.INSIGHT_DATE_RANGE:
+ return _DATE_RANGE_WITHOUT_START_SQL
+ return _BOUND_NOT_USED_SQL if cause == FindingCause.START_DATE_NOT_USED_BY_CLICKHOUSE else _NO_START_DATE_SQL
if kind == QueryScanFindingKind.PERSONS_JOIN:
- return _PERSONS_JOIN
+ return _PERSONS_JOIN if is_sql else _PERSONS_JOIN_INSIGHT
raise ValueError(f"No copy for finding kind {kind}")
+def is_actionable(kind: QueryScanFindingKind, cause: FindingCause | None, *, is_sql: bool, by_design: bool) -> bool:
+ """Whether the person can change something so the query reads less and still answers the same
+ question. A read inside a saved view counts: the person can edit the view."""
+ if by_design:
+ return False
+ if kind == QueryScanFindingKind.PERSONS_JOIN:
+ # An insight joins the persons table because of the project's person properties mode, which
+ # nothing in the insight changes. A SQL author wrote the join and can take it out.
+ return is_sql
+ if kind == QueryScanFindingKind.NO_EVENT_FILTER and cause is None:
+ # An insight's All events series is a choice the person made in a picker. A SQL query that
+ # names no events may have left them out, and nothing in it tells which, so it is a warning.
+ return is_sql
+ return cause in _FIXABLE_CAUSES.get(kind, frozenset())
+
+
+def _read_location(*, subquery_index: int | None, view_name: str | None) -> QueryScanFixLocation:
+ if view_name is not None:
+ return QueryScanFixLocation.VIEW
+ if subquery_index is not None:
+ return QueryScanFixLocation.SUBQUERY
+ return QueryScanFixLocation.QUERY
+
+
+def _subject(*, is_sql: bool, subquery_index: int | None, view_name: str | None) -> str:
+ """Who the finding is about, so a person with a bounded main query is not told the query has no
+ start date when a subquery or a view is the one reading everything."""
+ noun = "query" if is_sql else "insight"
+ if view_name is not None:
+ return f"The view `{view_name}` inside this {noun}"
+ if subquery_index is not None:
+ return f"Subquery {subquery_index + 1} of this {noun}"
+ return f"This {noun}"
+
+
def build_warning(
*,
kind: QueryScanFindingKind,
query_kind: str,
- reason: QueryScanFindingReason | None = None,
+ cause: FindingCause | None = None,
+ by_design: bool = False,
+ fix_location: QueryScanFixLocation | None = None,
evidence: str | None = None,
+ subquery_index: int | None = None,
+ view_name: str | None = None,
) -> QueryScanWarning:
- copy = _copy_for(kind, reason, is_sql=query_kind == SQL_QUERY_KIND)
+ """``fix_location`` is for a fix that goes outside the query text, on the insight's date range or
+ the dashboard's date filter. None takes the location from the read: a view, a subquery, or the
+ query itself.
+ """
+ is_sql = query_kind == SQL_QUERY_KIND
+ location = fix_location or _read_location(subquery_index=subquery_index, view_name=view_name)
+ copy = _copy_for(kind, cause, is_sql=is_sql, by_design=by_design, fix_location=location)
+ subject = _subject(is_sql=is_sql, subquery_index=subquery_index, view_name=view_name)
+ lead = copy.lead.format(subject=subject, subject_lower=subject[0].lower() + subject[1:])
+ advice = copy.advice
+ fix = copy.fix
+ if view_name is not None:
+ advice = f"{advice} The events read is inside the view `{view_name}`, so the change goes in the view."
+ fix = (
+ f"{fix} The events read is inside the saved view `{view_name}`, and this query does not contain it. "
+ "Do not edit this query for it; tell the person the change belongs in the view."
+ )
+ elif subquery_index is not None:
+ fix = (
+ f"{fix} This is about subquery {subquery_index + 1}, an `IN (SELECT …)` of the query; change that subquery."
+ )
return QueryScanWarning(
kind=kind,
- reason=reason,
- message=f"{copy.lead} {copy.advice}",
- fix=copy.fix,
+ cause=cause.value if cause is not None else None,
+ by_design=by_design,
+ fix_location=location,
+ message=f"{lead} {advice}",
+ fix=fix,
evidence=evidence,
+ actionable=is_actionable(kind, cause, is_sql=is_sql, by_design=by_design),
)
+def finding_label(finding: QueryScanWarning) -> str:
+ """The kind, then whichever of the cause, `by_design` and a fix location other than the query
+ apply, joined by `/`. The `query scan analyzed` event splits findings by it, and the job uses
+ it to drop a finding that several executions of one run repeat."""
+ parts = [str(finding.kind)]
+ if finding.cause:
+ parts.append(finding.cause)
+ if finding.by_design:
+ parts.append("by_design")
+ if finding.fix_location is not None and finding.fix_location != QueryScanFixLocation.QUERY:
+ parts.append(str(finding.fix_location))
+ return "/".join(parts)
+
+
def explain_evidence(
keys: tuple[str, ...], *, before: int | None, after: int | None, subquery_index: int | None
) -> str:
@@ -246,14 +550,18 @@ def assistant_prompt(
fixable_only: bool = False,
) -> str | None:
"""What the assistant reads about a slow run: the goal, the run, one line per finding, and the
- standing rules. "Fix with AI" sends it as the person's message, and the in-app assistant and MCP
- get it above a slow run's results, so all of them read the same text.
+ standing rules. "Fix with AI" sends it as the person's message.
- ``fixable_only`` leaves out a finding that is fixed on the insight rather than in the query, since
- the assistant has nothing to change for it. None when no finding is left.
+ ``fixable_only`` is for "Fix with AI": without the findings fixed on the insight or the
+ dashboard rather than in the query, and None unless one of the rest is actionable. A by-design
+ finding stays, because its guidance tells the assistant what not to change.
"""
if fixable_only:
- findings = [finding for finding in findings if finding.reason != QueryScanFindingReason.FILTERS]
+ findings = [
+ finding for finding in findings if finding.by_design or finding.fix_location not in _OUTSIDE_THE_QUERY
+ ]
+ if not any(finding.actionable for finding in findings):
+ return None
if not findings:
return None
lines = [ASSISTANT_GOAL, ""]
@@ -279,7 +587,7 @@ def _run_line(rows_read: int, duration_ms: int, killed: bool) -> str:
def _finding_line(finding: QueryScanWarning) -> str:
- head = f"{finding.kind} ({finding.reason})" if finding.reason else str(finding.kind)
+ head = f"{finding.kind} ({finding.cause})" if finding.cause else str(finding.kind)
parts = [f"{head}:"]
if finding.evidence:
parts.append(finding.evidence)
diff --git a/posthog/query_scan/flag.py b/posthog/query_scan/flag.py
index b500e8a9ff6a..e0026493da7a 100644
--- a/posthog/query_scan/flag.py
+++ b/posthog/query_scan/flag.py
@@ -23,6 +23,7 @@ FLAG_KEY = "query-scan-warnings"
DEFAULT_FLOOR_MS = 1000
DEFAULT_EVENT_RATIO = 0.10
DEFAULT_PERSONS_RATIO = 0.5
+DEFAULT_START_DATE_RATIO = 0.01
class QueryScanMode(StrEnum):
@@ -49,11 +50,14 @@ class QueryScanFlag:
event_ratio: float
# A persons join is reported only when the persons read is at least this fraction of the events read.
persons_ratio: float
+ # No start date is reported unless the unbounded read is at least this share of the project's
+ # events over all time. "All time" chosen in a picker is reported at any size.
+ start_date_ratio: float = DEFAULT_START_DATE_RATIO
@property
def thresholds_fingerprint(self) -> str:
"""Names the gates an analysis ran under, so one stored under other gates is not served."""
- return f"{self.event_ratio!r}:{self.persons_ratio!r}"
+ return f"{self.event_ratio!r}:{self.persons_ratio!r}:{self.start_date_ratio!r}"
class InvalidPayload(ValueError):
@@ -115,6 +119,7 @@ def _parse(mode: QueryScanMode, payload: object) -> QueryScanFlag:
floor_ms=int(_number(values, "floor_ms", DEFAULT_FLOOR_MS)),
event_ratio=_number(values, "event_ratio", DEFAULT_EVENT_RATIO),
persons_ratio=_number(values, "persons_ratio", DEFAULT_PERSONS_RATIO),
+ start_date_ratio=_number(values, "start_date_ratio", DEFAULT_START_DATE_RATIO),
)
diff --git a/posthog/query_scan/job.py b/posthog/query_scan/job.py
index 64476a402024..7404f9d59884 100644
--- a/posthog/query_scan/job.py
+++ b/posthog/query_scan/job.py
@@ -22,23 +22,24 @@ from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
from posthog.ph_client import ph_scoped_capture
-from posthog.query_scan.analyze import PlanSet, QueryScanResult, analyze
+from posthog.query_scan.analyze import ExplainedPlan, PlanSet, QueryScanResult, RunFacts, analyze
from posthog.query_scan.event_filter import (
EventFilterClass,
EventFilterOutcome,
EventFilterReason,
combine_event_filter,
)
-from posthog.query_scan.explain import QueryPlan, TimestampBounds, parse_query_plan
+from posthog.query_scan.explain import EXPLAIN_MAX_SECONDS, QueryPlan, TimestampBounds, parse_query_plan
+from posthog.query_scan.findings import finding_label
from posthog.query_scan.flag import get_query_scan_flag
from posthog.query_scan.slot import (
clear as clear_slot,
set_done,
)
+from posthog.query_scan.tree_facts import TreeFacts
logger = structlog.get_logger(__name__)
-EXPLAIN_MAX_SECONDS = 10
TABLE_AVERAGES_MAX_SECONDS = 5
# The two events tables and the three persons tables the persons gate compares in rows.
@@ -56,26 +57,42 @@ _EVENT_FILTER_CLASSES = get_args(EventFilterClass)
_EVENT_FILTER_REASONS = get_args(EventFilterReason)
+@frozen
+class Subquery:
+ """One subquery of an execution, printed on its own, with the verdict and facts for its reads."""
+
+ sql: str
+ event_filter: dict[str, Any] | None = None
+ tree: dict[str, Any] | None = None
+
+ @classmethod
+ def from_payload(cls, payload: dict[str, Any]) -> Subquery:
+ return cls(sql=payload["sql"], event_filter=payload.get("event_filter"), tree=payload.get("tree"))
+
+
@frozen
class Execution:
"""One printed execution of the run, as the trigger enqueued it. ``event_filter`` is the tree
- verdict the trigger classified, or None when it shipped nothing.
+ verdict the trigger classified and ``tree`` the other facts it read off the tree; either is
+ None when it shipped nothing.
"""
stubbed_sql: str
- subqueries: tuple[str, ...]
+ subqueries: tuple[Subquery, ...]
values: dict[str, Any]
rows_read: int
event_filter: dict[str, Any] | None = None
+ tree: dict[str, Any] | None = None
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> Execution:
return cls(
stubbed_sql=payload["stubbed_sql"],
- subqueries=tuple(payload.get("subqueries") or ()),
+ subqueries=tuple(Subquery.from_payload(subquery) for subquery in payload.get("subqueries") or ()),
values=payload.get("values") or {},
rows_read=payload.get("rows_read") or 0,
event_filter=payload.get("event_filter"),
+ tree=payload.get("tree"),
)
@@ -96,7 +113,9 @@ class QueryScanJob:
killed: bool = False
error_type: str | None = None
all_time: bool = False
+ dashboard_all_time: bool = False
all_history_by_design: bool = False
+ all_events_by_design: bool = False
def run_query_scan(job: QueryScanJob) -> None:
@@ -127,24 +146,44 @@ def _run(job: QueryScanJob, started: float) -> None:
)
range_cache: dict[tuple[int | None, int | None], int | None] = {}
+ run = RunFacts(
+ all_time=job.all_time,
+ dashboard_all_time=job.dashboard_all_time,
+ all_history_by_design=job.all_history_by_design,
+ all_events_by_design=job.all_events_by_design,
+ open_filters_placeholder=job.open_filters_placeholder,
+ )
+
+ def explained(
+ sql: str, values: dict[str, Any], event_filter: dict[str, Any] | None, tree: dict[str, Any] | None
+ ) -> ExplainedPlan | None:
+ plan = _plan(sql, values, job.team.pk)
+ if plan is None:
+ return None
+ return ExplainedPlan(
+ plan=plan,
+ range_granules=_range_granules(job.team.pk, plan, team_granules, range_cache),
+ event_filter=_combined_event_filter(event_filter, plan),
+ tree=TreeFacts.from_payload(tree),
+ )
+
results: list[QueryScanResult] = []
for execution in job.executions:
- outer = _plan(execution.stubbed_sql, execution.values, job.team.pk)
- subqueries = tuple(
- plan
- for plan in (_plan(sql, execution.values, job.team.pk) for sql in execution.subqueries)
- if plan is not None
+ outer = explained(execution.stubbed_sql, execution.values, execution.event_filter, execution.tree)
+ subqueries = (
+ explained(subquery.sql, execution.values, subquery.event_filter, subquery.tree)
+ for subquery in execution.subqueries
)
- range_granules = _range_granules(job.team.pk, outer, team_granules, range_cache)
results.append(
analyze(
- PlanSet(outer=outer, subqueries=subqueries, team_granules=team_granules, range_granules=range_granules),
+ PlanSet(
+ outer=outer,
+ subqueries=tuple(subquery for subquery in subqueries if subquery is not None),
+ team_granules=team_granules,
+ ),
flag,
query_kind=job.query_kind or "",
- open_filters_placeholder=job.open_filters_placeholder,
- all_time=job.all_time,
- all_history_by_design=job.all_history_by_design,
- event_filter=_combined_event_filter(execution, outer),
+ run=run,
table_row_averages=table_row_averages,
)
)
@@ -180,11 +219,10 @@ def _plan(sql: str, values: dict[str, Any], team_id: int) -> QueryPlan | None:
return parse_query_plan(rows[0][0])
-def _combined_event_filter(execution: Execution, outer: QueryPlan | None) -> EventFilterOutcome | None:
- """The tree verdict the trigger shipped, folded with the outer plan's key use. None when it shipped
- none, so the plan alone decides.
+def _combined_event_filter(payload: dict[str, Any] | None, plan: QueryPlan) -> EventFilterOutcome | None:
+ """The tree verdict the trigger shipped for a plan, folded with the plan's key use. None when it
+ shipped none, so the plan alone decides.
"""
- payload = execution.event_filter
if not payload:
return None
classification = payload.get("classification")
@@ -194,20 +232,21 @@ def _combined_event_filter(execution: Execution, outer: QueryPlan | None) -> Eve
outcome = EventFilterOutcome(
classification=classification,
reason=reason if reason in _EVENT_FILTER_REASONS else None,
+ hidden_from_plan=payload.get("hidden_from_plan") is True,
)
- return combine_event_filter(outcome, outer)
+ return combine_event_filter(outcome, plan)
def _range_granules(
team_id: int,
- outer: QueryPlan | None,
+ plan: QueryPlan,
team_granules: int | None,
cache: dict[tuple[int | None, int | None], int | None],
) -> int | None:
- """The team's granules over the run's date range, cached per distinct bounds. With no bound the
+ """The team's granules over the plan's date range, cached per distinct bounds. With no bound the
range is all time, so it equals the team denominator.
"""
- events_read = outer.heaviest_events_read() if outer is not None else None
+ events_read = plan.heaviest_events_read()
bounds = events_read.timestamp_bounds() if events_read is not None else TimestampBounds(lower=None, upper=None)
if bounds.lower is None and bounds.upper is None:
return team_granules
@@ -283,15 +322,15 @@ def _explain(sql: str, values: dict[str, Any], team_id: int) -> list[Any] | None
def _merge(results: list[QueryScanResult], executions: tuple[Execution, ...]) -> QueryScanResult:
- """One result from the executions the job analyzed: findings deduplicated by kind and reason, and
- the shares from the execution that read the most rows."""
+ """One result from the executions the job analyzed: findings deduplicated by label, and the
+ shares from the execution that read the most rows."""
findings: list[QueryScanWarning] = []
- seen: set[tuple[str, str]] = set()
+ seen: set[str] = set()
for result in results:
for finding in result.findings:
- key = (str(finding.kind), str(finding.reason))
- if key not in seen:
- seen.add(key)
+ label = finding_label(finding)
+ if label not in seen:
+ seen.add(label)
findings.append(finding)
heaviest = _heaviest_result(results, executions)
@@ -328,6 +367,11 @@ def _report(job: QueryScanJob, merged: QueryScanResult, *, flag_event_ratio: flo
"event_ratio": flag_event_ratio,
"explain_ok": merged.explain_ok,
"finding_kinds": merged.finding_kinds(),
+ "finding_labels": merged.finding_labels(),
+ "actionable_finding_kinds": merged.actionable_finding_kinds(),
+ "actionable_finding_labels": merged.actionable_finding_labels(),
+ "actionable": bool(merged.actionable_finding_kinds()),
+ "all_time": job.all_time,
"killed": job.killed,
"error_type": job.error_type,
"job_ms": job_ms,
diff --git a/posthog/query_scan/slot.py b/posthog/query_scan/slot.py
index d641b3f46a1b..6d7ac7ca2df4 100644
--- a/posthog/query_scan/slot.py
+++ b/posthog/query_scan/slot.py
@@ -23,7 +23,7 @@ logger = structlog.get_logger(__name__)
# Bumped when a stored slot can no longer be read by this code. It is part of the key: a claim
# cannot replace an existing key, so an old slot left under the same key would block re-analysis
# for its whole TTL while reading as absent.
-SLOT_VERSION = 2
+SLOT_VERSION = 3
PENDING_TTL_SECONDS = 10 * 60
DONE_TTL_SECONDS = 30 * 24 * 60 * 60
diff --git a/posthog/query_scan/stub.py b/posthog/query_scan/stub.py
index 9ee2c2b8b965..06daf1f81da5 100644
--- a/posthog/query_scan/stub.py
+++ b/posthog/query_scan/stub.py
@@ -5,6 +5,10 @@ value: the right side of ``x IN (subquery)``, or a scalar ``(SELECT ...)`` in a
comparison, a function argument, or a column ``WITH`` alias. Each such run reads real data. The
constant keeps the outer query's shape, so the plan still shows how it reads the events table.
+One shape is lost. A comparison that holds a subquery folds to true, so when it filtered ``event``
+or ``timestamp`` the plan shows the read without that filter. For those the tree's verdict stands:
+see ``EventFilterOutcome.hidden_from_plan`` and ``TreeFacts.start_date_hidden_from_plan``.
+
A subquery that is a query source is kept, because the plan needs it: the root query, a ``FROM`` or
``JOIN`` table, a ``UNION`` member, and a subquery ``WITH`` body (``WITH a AS (SELECT ...)``). The
value subqueries taken out of the tree are collected so each can be explained on its own.
diff --git a/posthog/query_scan/test/test_analyze.py b/posthog/query_scan/test/test_analyze.py
index 8b202618a502..7d05c27998ec 100644
--- a/posthog/query_scan/test/test_analyze.py
+++ b/posthog/query_scan/test/test_analyze.py
@@ -2,13 +2,13 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.schema import QueryScanFindingReason
-
-from posthog.query_scan.analyze import PlanSet, QueryScanResult, analyze
+from posthog.query_scan.analyze import ExplainedPlan, PlanSet, QueryScanResult, RunFacts, analyze
from posthog.query_scan.event_filter import EventFilterOutcome
from posthog.query_scan.explain import QueryPlan, parse_query_plan
+from posthog.query_scan.findings import finding_label
from posthog.query_scan.flag import QueryScanFlag, QueryScanMode
from posthog.query_scan.test.test_explain import events_read_node, load_plan
+from posthog.query_scan.tree_facts import TreeFacts
_USABLE_EVENT_FILTER = EventFilterOutcome(classification="usable")
_END_DATE_ONLY = "(timestamp in (-Inf, 1800000000])"
@@ -18,6 +18,9 @@ _BOTH_BOUNDS = "and((timestamp in (-Inf, 1800000000]), (timestamp in [1700000000
_EVENT_KEY = ["team_id", "toDate(timestamp)", "event"]
+NO_START_DATE = "no_start_date"
+NO_EVENT_FILTER = "no_event_filter"
+
def plan(name: str) -> QueryPlan:
return parse_query_plan(load_plan(name))
@@ -31,10 +34,19 @@ def join_plan(*reads: dict[str, object]) -> QueryPlan:
return parse_query_plan([{"Plan": {"Node Type": "Join", "Plans": list(reads)}}])
+# A join whose heaviest read pruned on nothing while its lighter read pruned on `event`: an
+# unfiltered helper read beside a read that names events.
+_HELPER_READ_PLAN = join_plan(
+ events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=5000),
+ events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=10, primary_keys=_EVENT_KEY),
+)
+
+
def analyze_fixture(
outer: str | QueryPlan,
*,
subqueries: tuple[str, ...] = (),
+ subquery_range_granules: int | None = None,
team_granules: int | None = None,
range_granules: int | None = None,
persons_ratio: float = 0.5,
@@ -43,22 +55,34 @@ def analyze_fixture(
event_filter: EventFilterOutcome | None = None,
table_row_averages: dict[str, float] | None = None,
all_time: bool = False,
+ dashboard_all_time: bool = False,
all_history_by_design: bool = False,
+ all_events_by_design: bool = False,
+ tree: TreeFacts | None = None,
) -> QueryScanResult:
return analyze(
PlanSet(
- outer=plan(outer) if isinstance(outer, str) else outer,
- subqueries=tuple(plan(name) for name in subqueries),
+ outer=ExplainedPlan(
+ plan=plan(outer) if isinstance(outer, str) else outer,
+ range_granules=range_granules,
+ event_filter=event_filter,
+ tree=tree,
+ ),
+ subqueries=tuple(
+ ExplainedPlan(plan=plan(name), range_granules=subquery_range_granules) for name in subqueries
+ ),
team_granules=team_granules,
- range_granules=range_granules,
),
QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=persons_ratio),
query_kind=query_kind,
- open_filters_placeholder=open_filters_placeholder,
- event_filter=event_filter,
+ run=RunFacts(
+ all_time=all_time,
+ dashboard_all_time=dashboard_all_time,
+ all_history_by_design=all_history_by_design,
+ all_events_by_design=all_events_by_design,
+ open_filters_placeholder=open_filters_placeholder,
+ ),
table_row_averages=table_row_averages,
- all_time=all_time,
- all_history_by_design=all_history_by_design,
)
@@ -102,6 +126,33 @@ class TestAnalyze(SimpleTestCase):
{"event_filter": _USABLE_EVENT_FILTER},
["no_start_date"],
),
+ (
+ "a small unbounded read is not flagged",
+ join_plan(
+ events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=5000),
+ events_read_node("true", [], selected_granules=10),
+ ),
+ {"event_filter": _USABLE_EVENT_FILTER, "team_granules": 10_000},
+ [],
+ ),
+ (
+ "an unbounded read over the start-date ratio is flagged",
+ join_plan(
+ events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=5000),
+ events_read_node("true", [], selected_granules=10),
+ ),
+ {"event_filter": _USABLE_EVENT_FILTER, "team_granules": 500},
+ ["no_start_date"],
+ ),
+ (
+ "the largest unbounded read is the one sized, not the first",
+ join_plan(
+ events_read_node("true", [], selected_granules=10),
+ events_read_node("true", [], selected_granules=5000),
+ ),
+ {"event_filter": _USABLE_EVENT_FILTER, "team_granules": 10_000},
+ ["no_start_date"],
+ ),
# The event filter is judged on the larger read: a small read without one stays quiet, and
# a large read without one is flagged whatever the small read did.
(
@@ -115,29 +166,18 @@ class TestAnalyze(SimpleTestCase):
),
(
"the heaviest read with no event filter is flagged",
- join_plan(
- events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=5000),
- events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=10, primary_keys=_EVENT_KEY),
- ),
+ _HELPER_READ_PLAN,
{"range_granules": 10_000},
["no_event_filter"],
),
# An "All time" insight runs with a bound at the project's first event, so the plan alone
# would stay quiet; the setting is what says no start date was chosen.
(
- "all time insight is flagged despite the bound",
+ "all time insight is flagged despite the bound and whatever its size",
"plan_event_filter_used",
- {"query_kind": "TrendsQuery", "all_time": True},
+ {"query_kind": "TrendsQuery", "all_time": True, "team_granules": 100_000_000_000},
["no_start_date"],
),
- # First-time math has to read from the first event whatever the date range, so the
- # advice to set one could not be followed.
- (
- "an insight that reads all history by design gets no start-date advice",
- "plan_no_date_bound",
- {"query_kind": "TrendsQuery", "all_history_by_design": True},
- [],
- ),
# persons gate: the persons read dwarfs the events read
("persons join over the ratio", "plan_persons_join", {}, ["persons_join"]),
# persons gate the other way: raise the ratio past what the plan shows
@@ -158,9 +198,16 @@ class TestAnalyze(SimpleTestCase):
),
("object storage read yields nothing", "plan_object_storage_read", {}, []),
("a replay list query reads no events", "plan_replay_list_in_subqueries", {}, []),
- # a subquery whose events read pruned nothing is flagged through the skip-step fallback
+ # a subquery is gated on its share of its own date range, the way the outer query is
+ (
+ "a subquery that reads little of its date range is not flagged",
+ "plan_event_filter_used",
+ {"subqueries": ("plan_no_event_filter",), "subquery_range_granules": 40_000_000},
+ [],
+ ),
+ # without its denominator, a subquery falls back to the skip steps, as the outer query does
(
- "a subquery with no event filter is flagged",
+ "a subquery with no denominator and no pruning is flagged",
"plan_event_filter_used",
{"subqueries": ("plan_no_event_filter",)},
["no_event_filter"],
@@ -182,42 +229,231 @@ class TestAnalyze(SimpleTestCase):
self.assertTrue(result.explain_ok)
self.assertEqual(result.finding_kinds(), expected_kinds)
+ @parameterized.expand(
+ [
+ ("no bound at all", "plan_no_date_bound", {}, [("no_start_date", True)]),
+ (
+ "a bound clickhouse could not use",
+ "plan_no_date_bound",
+ {"tree": TreeFacts(timestamp_bound=True)},
+ [("no_start_date/bound_not_used", True)],
+ ),
+ (
+ "a start date the plan never saw",
+ "plan_no_date_bound",
+ {"tree": TreeFacts(timestamp_bound=True, start_date_hidden_from_plan=True)},
+ [],
+ ),
+ (
+ "a first-ever computation in sql",
+ "plan_no_date_bound",
+ {"tree": TreeFacts(all_history=True, timestamp_bound=True)},
+ [("no_start_date/by_design", False)],
+ ),
+ (
+ "a first-time math on all time",
+ "plan_event_filter_used",
+ {"query_kind": "TrendsQuery", "all_time": True, "all_history_by_design": True},
+ [("no_start_date/by_design", False)],
+ ),
+ (
+ "all time chosen on the insight",
+ "plan_event_filter_used",
+ {"query_kind": "TrendsQuery", "all_time": True},
+ [("no_start_date", True)],
+ ),
+ (
+ "all time forced by the dashboard",
+ "plan_event_filter_used",
+ {"query_kind": "TrendsQuery", "all_time": True, "dashboard_all_time": True},
+ [("no_start_date/dashboard_date_filter", True)],
+ ),
+ (
+ "all time reaching sql through filters",
+ "plan_no_date_bound",
+ {"all_time": True, "open_filters_placeholder": True},
+ [("no_start_date/insight_date_range", True)],
+ ),
+ (
+ "the dashboard's all time reaching sql through filters",
+ "plan_no_date_bound",
+ {"all_time": True, "open_filters_placeholder": True, "dashboard_all_time": True},
+ [("no_start_date/dashboard_date_filter", True)],
+ ),
+ (
+ "a read inside a saved view",
+ "plan_no_date_bound",
+ {"tree": TreeFacts(view_name="v_active")},
+ [("no_start_date/view", True)],
+ ),
+ (
+ "sql with no event condition at all",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000},
+ [("no_event_filter", True)],
+ ),
+ (
+ "an insight on all events",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "query_kind": "TrendsQuery"},
+ [("no_event_filter", False)],
+ ),
+ (
+ "a shape that reads every event of all history is not believed",
+ single_read_plan("true"),
+ {"tree": TreeFacts(all_history=True, counts_any_event=True)},
+ [("no_start_date", True), ("no_event_filter", True)],
+ ),
+ (
+ "an insight's settings are believed over every event of all history",
+ single_read_plan("true"),
+ {"query_kind": "TrendsQuery", "all_time": True, "all_history_by_design": True},
+ [("no_start_date/by_design", False), ("no_event_filter", False)],
+ ),
+ (
+ "a property filter standing in for an event name",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "tree": TreeFacts(property_filter=True)},
+ [("no_event_filter/property_filter", True)],
+ ),
+ (
+ "a property filter on an all events insight",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "query_kind": "TrendsQuery", "tree": TreeFacts(property_filter=True)},
+ [("no_event_filter/property_filter", True)],
+ ),
+ (
+ "grouping by event beside a property filter",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "tree": TreeFacts(groups_by_event=True, property_filter=True)},
+ [("no_event_filter/by_design", False)],
+ ),
+ (
+ "counting distinct people over any event",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "tree": TreeFacts(counts_any_event=True)},
+ [("no_event_filter/by_design", False)],
+ ),
+ (
+ "counting distinct people with a property filter",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "tree": TreeFacts(counts_any_event=True, property_filter=True)},
+ [("no_event_filter/property_filter", True)],
+ ),
+ (
+ "an active-user math on all events",
+ "plan_no_event_filter",
+ {"range_granules": 1_000_000, "query_kind": "TrendsQuery", "all_events_by_design": True},
+ [("no_event_filter/by_design", False)],
+ ),
+ (
+ "an unfiltered helper read in sql",
+ _HELPER_READ_PLAN,
+ {"range_granules": 10_000, "tree": TreeFacts(counts_any_event=True)},
+ [("no_event_filter/helper_read", True)],
+ ),
+ (
+ "an unfiltered helper read in an insight",
+ _HELPER_READ_PLAN,
+ {"range_granules": 10_000, "query_kind": "TrendsQuery"},
+ [("no_event_filter", False)],
+ ),
+ (
+ "an unfiltered subquery is worded like an unfiltered outer query",
+ "plan_event_filter_used",
+ {"subqueries": ("plan_no_event_filter",)},
+ [("no_event_filter/subquery", True)],
+ ),
+ (
+ "a negated event filter",
+ "plan_event_filter_negated",
+ {
+ "range_granules": 400_000,
+ "event_filter": EventFilterOutcome(classification="not_used", reason="negated"),
+ },
+ [("no_event_filter/negated", True)],
+ ),
+ (
+ "an event filter inside an or",
+ "plan_no_event_filter",
+ {
+ "range_granules": 1_000_000,
+ "event_filter": EventFilterOutcome(classification="not_used", reason="in_or"),
+ },
+ [("no_event_filter/in_or", True)],
+ ),
+ ]
+ )
+ def test_labels_and_actionability(
+ self,
+ _name: str,
+ outer: str | QueryPlan,
+ kwargs: dict[str, object],
+ expected: list[tuple[str, bool]],
+ ) -> None:
+ result = analyze_fixture(outer, **kwargs) # type: ignore[arg-type]
+
+ self.assertEqual([(finding_label(finding), finding.actionable) for finding in result.findings], expected)
+
def test_no_outer_plan_fails_closed(self) -> None:
result = analyze(
PlanSet(outer=None),
QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5),
query_kind="HogQLQuery",
- open_filters_placeholder=False,
+ run=RunFacts(),
)
self.assertFalse(result.explain_ok)
self.assertEqual(result.findings, [])
- def test_open_filters_placeholder_sets_the_filters_reason(self) -> None:
+ def test_open_filters_placeholder_puts_the_fix_on_the_insight(self) -> None:
result = analyze_fixture("plan_no_date_bound", open_filters_placeholder=True)
- self.assertEqual([finding.reason for finding in result.findings], [QueryScanFindingReason.FILTERS])
- self.assertIn("No date range is set on this insight or dashboard", result.findings[0].message)
+ self.assertEqual(result.finding_labels(), ["no_start_date/insight_date_range"])
+ self.assertIn("The date range on this insight or dashboard has no start date", result.findings[0].message)
def test_insight_kind_uses_the_insight_wording(self) -> None:
result = analyze_fixture("plan_no_date_bound", query_kind="TrendsQuery")
self.assertEqual(result.finding_kinds(), ["no_start_date"])
- self.assertIsNone(result.findings[0].reason)
+ self.assertIsNone(result.findings[0].cause)
self.assertIn("This insight has no start date", result.findings[0].message)
- def test_a_negated_event_filter_is_flagged_with_its_reason(self) -> None:
- # `event != x` lists `event` in the key yet keeps most of the range, so the plan alone
- # cannot flag it; the combined outcome the job ships carries the tree's `negated` reason.
- result = analyze_fixture(
- "plan_event_filter_negated",
- range_granules=400_000,
- event_filter=EventFilterOutcome(classification="not_used", reason="negated"),
- )
+ @parameterized.expand(
+ [
+ (
+ "the dashboard's date filter",
+ "plan_event_filter_used",
+ {"query_kind": "TrendsQuery", "all_time": True, "dashboard_all_time": True},
+ "The dashboard's date filter is set to All time",
+ ),
+ (
+ "the saved view the read sits in",
+ "plan_no_date_bound",
+ {"tree": TreeFacts(view_name="v_active")},
+ "The view `v_active` inside this query has no start date",
+ ),
+ (
+ "the subquery the read sits in",
+ "plan_event_filter_used",
+ {"subqueries": ("plan_no_date_bound",)},
+ "Subquery 1 of this query has no start date",
+ ),
+ (
+ "the subquery, not the insight's date range, when the query takes its dates from filters",
+ "plan_event_filter_used",
+ {"subqueries": ("plan_no_date_bound",), "open_filters_placeholder": True},
+ "Subquery 1 of this query has no start date",
+ ),
+ ]
+ )
+ def test_the_headline_names_the_cause(
+ self, _name: str, outer: str, kwargs: dict[str, object], expected_in_message: str
+ ) -> None:
+ result = analyze_fixture(outer, **kwargs) # type: ignore[arg-type]
- self.assertEqual(result.finding_kinds(), ["no_event_filter"])
- self.assertEqual(result.findings[0].reason, QueryScanFindingReason.NEGATED)
- self.assertIn("only excludes events", result.findings[0].message)
+ self.assertEqual(result.finding_kinds(), ["no_start_date"])
+ self.assertIn(expected_in_message, result.findings[0].message)
def test_shares_are_the_read_over_the_denominators(self) -> None:
result = analyze_fixture("plan_no_event_filter", team_granules=10_000_000, range_granules=1_000_000)
@@ -226,8 +462,19 @@ class TestAnalyze(SimpleTestCase):
self.assertAlmostEqual(result.range_share, 0.329267, places=5)
self.assertAlmostEqual(result.project_share, 0.0329267, places=6)
+ def test_a_filter_the_plan_never_saw_gets_no_share_and_no_finding(self) -> None:
+ result = analyze_fixture(
+ "plan_no_event_filter",
+ team_granules=10_000_000,
+ range_granules=1_000_000,
+ event_filter=EventFilterOutcome(classification="usable", hidden_from_plan=True),
+ )
+
+ self.assertEqual((result.range_share, result.project_share, result.findings), (None, None, []))
+
def test_a_subquery_finding_names_the_subquery(self) -> None:
result = analyze_fixture("plan_event_filter_used", subqueries=("plan_no_event_filter",))
assert result.findings[0].evidence is not None
self.assertIn("In subquery 1", result.findings[0].evidence)
+ self.assertIn("Subquery 1 of this query", result.findings[0].message)
diff --git a/posthog/query_scan/test/test_event_filter.py b/posthog/query_scan/test/test_event_filter.py
index 041ff59999b0..8aca1099790d 100644
--- a/posthog/query_scan/test/test_event_filter.py
+++ b/posthog/query_scan/test/test_event_filter.py
@@ -68,6 +68,19 @@ class TestClassifyEventFilter(BaseTest):
"not_used",
"dynamic",
),
+ (
+ "in a subquery",
+ "SELECT count() FROM events WHERE event IN (SELECT 'purchase')",
+ "usable",
+ None,
+ True,
+ ),
+ (
+ "not in a subquery",
+ "SELECT count() FROM events WHERE event NOT IN (SELECT 'purchase')",
+ "not_used",
+ "negated",
+ ),
# A property access prepares to a JSON-extract call, not a bare column, so it lands as a
# fixed comparison the sort order cannot seek on rather than a dynamic one.
(
@@ -93,7 +106,12 @@ class TestClassifyEventFilter(BaseTest):
]
)
def test_classification_reads_the_tree(
- self, _name: str, sql: str, expected_class: str | None, expected_reason: str | None
+ self,
+ _name: str,
+ sql: str,
+ expected_class: str | None,
+ expected_reason: str | None,
+ expected_hidden_from_plan: bool = False,
) -> None:
outcome = classify_event_filter(self.prepare(sql))
@@ -103,6 +121,7 @@ class TestClassifyEventFilter(BaseTest):
assert outcome is not None
self.assertEqual(outcome.classification, expected_class)
self.assertEqual(outcome.reason, expected_reason)
+ self.assertIs(outcome.hidden_from_plan, expected_hidden_from_plan)
class TestCombineEventFilter(SimpleTestCase):
@@ -132,6 +151,13 @@ class TestCombineEventFilter(SimpleTestCase):
"not_used",
"not_pruned",
),
+ (
+ "key unused does not fault a filter the plan never saw",
+ EventFilterOutcome(classification="usable", hidden_from_plan=True),
+ _KEY_UNUSED_PLAN,
+ "usable",
+ None,
+ ),
# The advice is about the heaviest read, so a lighter read that did not prune is no fault.
(
"the heaviest read's key use decides",
diff --git a/posthog/query_scan/test/test_findings.py b/posthog/query_scan/test/test_findings.py
index 3e0bafc8f603..678d1dc99a06 100644
--- a/posthog/query_scan/test/test_findings.py
+++ b/posthog/query_scan/test/test_findings.py
@@ -2,11 +2,12 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.schema import QueryScanFindingKind, QueryScanFindingReason
+from posthog.schema import QueryScanFindingKind, QueryScanFixLocation
from posthog.query_scan.findings import (
ASSISTANT_GOAL,
ASSISTANT_RULES,
+ FindingCause,
assistant_prompt,
build_warning,
explain_evidence,
@@ -22,100 +23,209 @@ class TestFindings(SimpleTestCase):
@parameterized.expand(
[
# The `message` is the human banner; the `fix` is the assistant-facing guidance. Each SQL
- # reason keeps its own guidance, including whether exploration helps and which query to run.
+ # cause keeps its own guidance, including whether exploration helps and which query to run.
(
QueryScanFindingKind.NO_EVENT_FILTER,
- None,
+ {},
"HogQLQuery",
"add `WHERE event IN",
"The query names no events",
),
(
QueryScanFindingKind.NO_EVENT_FILTER,
- QueryScanFindingReason.IN_OR,
+ {"cause": FindingCause.EVENT_FILTER_INSIDE_OR},
"HogQLQuery",
"names events only inside an OR",
"for what the other branch matches",
),
(
QueryScanFindingKind.NO_EVENT_FILTER,
- QueryScanFindingReason.WRAPPED,
+ {"cause": FindingCause.EVENT_WRAPPED_IN_FUNCTION},
"HogQLQuery",
"wraps `event` in a",
"SELECT DISTINCT event",
),
(
QueryScanFindingKind.NO_EVENT_FILTER,
- QueryScanFindingReason.NEGATED,
+ {"cause": FindingCause.EVENT_FILTER_ONLY_EXCLUDES},
"HogQLQuery",
"only excludes",
- "Do not run exploratory queries",
+ "replace the exclusion with `event IN",
),
(
QueryScanFindingKind.NO_EVENT_FILTER,
- QueryScanFindingReason.DYNAMIC,
+ {"cause": FindingCause.EVENT_COMPARED_TO_COLUMN},
"HogQLQuery",
"compares `event` to another",
"no fixed name to prune on",
),
(
QueryScanFindingKind.NO_EVENT_FILTER,
- QueryScanFindingReason.NOT_PRUNED,
+ {"cause": FindingCause.EVENT_FILTER_NOT_USED_BY_CLICKHOUSE},
"HogQLQuery",
"has an event filter",
"into the WHERE of the events read",
),
(
QueryScanFindingKind.NO_EVENT_FILTER,
- None,
+ {"cause": FindingCause.PROPERTY_FILTER_WITHOUT_EVENT},
+ "HogQLQuery",
+ "narrows events by a property but names no events",
+ "which events carry the property",
+ ),
+ (
+ QueryScanFindingKind.NO_EVENT_FILTER,
+ {"cause": FindingCause.UNFILTERED_HELPER_READ},
+ "HogQLQuery",
+ "its largest read of the events table has no event filter",
+ "Add an event filter to the unfiltered read",
+ ),
+ (
+ QueryScanFindingKind.NO_EVENT_FILTER,
+ {"by_design": True},
+ "HogQLQuery",
+ "reads all events by design",
+ "do not propose one",
+ ),
+ (
+ QueryScanFindingKind.NO_EVENT_FILTER,
+ {},
"TrendsQuery",
"This insight looks at all events",
"instead of All events",
),
+ (
+ QueryScanFindingKind.NO_EVENT_FILTER,
+ {"cause": FindingCause.PROPERTY_FILTER_WITHOUT_EVENT},
+ "TrendsQuery",
+ "looks at all events and filters them by a property",
+ "pick them in the series",
+ ),
+ (
+ QueryScanFindingKind.NO_EVENT_FILTER,
+ {"by_design": True},
+ "TrendsQuery",
+ "looks at all events by design",
+ "Do not propose one",
+ ),
(
QueryScanFindingKind.NO_START_DATE,
- None,
+ {},
"HogQLQuery",
"add `timestamp >= now()",
"relative time bound",
),
(
QueryScanFindingKind.NO_START_DATE,
- QueryScanFindingReason.FILTERS,
+ {"fix_location": QueryScanFixLocation.INSIGHT_DATE_RANGE},
"HogQLQuery",
- "No date range is set on this insight or dashboard",
+ "The date range on this insight or dashboard has no start date",
"Do not edit the SQL",
),
(
QueryScanFindingKind.NO_START_DATE,
- None,
+ {"fix_location": QueryScanFixLocation.DASHBOARD_DATE_FILTER},
+ "HogQLQuery",
+ "The dashboard's date filter is set to All time",
+ "change the dashboard's date filter",
+ ),
+ (
+ QueryScanFindingKind.NO_START_DATE,
+ {"cause": FindingCause.START_DATE_NOT_USED_BY_CLICKHOUSE},
+ "HogQLQuery",
+ "has a start date, but it could not be used",
+ "add a fixed relative bound beside it",
+ ),
+ (
+ QueryScanFindingKind.NO_START_DATE,
+ {"by_design": True},
+ "HogQLQuery",
+ "finds a first event ever",
+ "Do not propose a time bound",
+ ),
+ (
+ QueryScanFindingKind.NO_START_DATE,
+ {},
"TrendsQuery",
"This insight has no start date",
"instead of All time",
),
+ (
+ QueryScanFindingKind.NO_START_DATE,
+ {"fix_location": QueryScanFixLocation.DASHBOARD_DATE_FILTER},
+ "TrendsQuery",
+ "overrides the date range on this insight",
+ "tell the person to change the dashboard's date filter",
+ ),
+ (
+ QueryScanFindingKind.NO_START_DATE,
+ {"by_design": True},
+ "TrendsQuery",
+ "finds each person's first event",
+ "Do not propose a date range change",
+ ),
(
QueryScanFindingKind.PERSONS_JOIN,
- None,
+ {},
"HogQLQuery",
"joins the persons table",
"person.properties.x",
),
+ (
+ QueryScanFindingKind.PERSONS_JOIN,
+ {},
+ "TrendsQuery",
+ 'PostHog recommends "Use person properties from the time of the event"',
+ "do not propose an edit",
+ ),
]
)
def test_copy_switches_between_sql_and_insight_wording(
self,
kind: QueryScanFindingKind,
- reason: QueryScanFindingReason | None,
+ facts: dict[str, object],
query_kind: str,
message_contains: str,
fix_contains: str,
) -> None:
- warning = build_warning(kind=kind, reason=reason, query_kind=query_kind)
+ warning = build_warning(kind=kind, query_kind=query_kind, **facts) # type: ignore[arg-type]
self.assertEqual(warning.kind, kind)
self.assertIn(message_contains, warning.message)
self.assertIn(fix_contains, warning.fix)
+ @parameterized.expand(
+ [
+ (QueryScanFindingKind.NO_EVENT_FILTER, {}, True),
+ (QueryScanFindingKind.NO_EVENT_FILTER, {"query_kind": "TrendsQuery"}, False),
+ (QueryScanFindingKind.NO_EVENT_FILTER, {"cause": FindingCause.EVENT_FILTER_INSIDE_OR}, True),
+ (QueryScanFindingKind.NO_EVENT_FILTER, {"cause": FindingCause.EVENT_FILTER_ONLY_EXCLUDES}, True),
+ (QueryScanFindingKind.NO_EVENT_FILTER, {"cause": FindingCause.EVENT_COMPARED_TO_COLUMN}, False),
+ (QueryScanFindingKind.NO_EVENT_FILTER, {"by_design": True}, False),
+ (QueryScanFindingKind.NO_START_DATE, {}, True),
+ (QueryScanFindingKind.NO_START_DATE, {"by_design": True}, False),
+ (QueryScanFindingKind.NO_START_DATE, {"view_name": "v_active"}, True),
+ (QueryScanFindingKind.PERSONS_JOIN, {}, True),
+ (QueryScanFindingKind.PERSONS_JOIN, {"query_kind": "TrendsQuery"}, False),
+ ]
+ )
+ def test_actionable_follows_the_facts(
+ self, kind: QueryScanFindingKind, facts: dict[str, object], expected: bool
+ ) -> None:
+ warning = build_warning(**{"kind": kind, "query_kind": "HogQLQuery", **facts}) # type: ignore[arg-type]
+
+ self.assertIs(warning.actionable, expected)
+
+ def test_the_subject_names_the_subquery_or_the_view(self) -> None:
+ in_subquery = build_warning(kind=QueryScanFindingKind.NO_START_DATE, query_kind="HogQLQuery", subquery_index=1)
+ in_view = build_warning(kind=QueryScanFindingKind.NO_START_DATE, query_kind="HogQLQuery", view_name="v_active")
+
+ self.assertIn("Subquery 2 of this query has no start date", in_subquery.message)
+ self.assertIn("subquery 2", in_subquery.fix)
+ self.assertIn("The view `v_active` inside this query has no start date", in_view.message)
+ self.assertIn("the change goes in the view", in_view.message)
+ self.assertIn("Do not edit this query for it", in_view.fix)
+
@parameterized.expand(
[
(
@@ -160,7 +270,7 @@ class TestAssistantPrompt(SimpleTestCase):
def test_goal_first_then_the_run_each_finding_and_the_rules(self) -> None:
finding = build_warning(
kind=QueryScanFindingKind.NO_EVENT_FILTER,
- reason=QueryScanFindingReason.IN_OR,
+ cause=FindingCause.EVENT_FILTER_INSIDE_OR,
query_kind="HogQLQuery",
evidence="ClickHouse's index used team_id and kept 5 of 100 granules.",
)
@@ -200,16 +310,39 @@ class TestAssistantPrompt(SimpleTestCase):
# "Fix with AI" writes into the SQL, and a `{filters}` date range is set on the insight, so a
# prompt for that finding alone would send the assistant to change nothing.
on_insight = build_warning(
- kind=QueryScanFindingKind.NO_START_DATE, reason=QueryScanFindingReason.FILTERS, query_kind="HogQLQuery"
+ kind=QueryScanFindingKind.NO_START_DATE,
+ fix_location=QueryScanFixLocation.INSIGHT_DATE_RANGE,
+ query_kind="HogQLQuery",
)
- in_query = build_warning(kind=QueryScanFindingKind.NO_EVENT_FILTER, query_kind="HogQLQuery")
+ in_query = build_warning(
+ kind=QueryScanFindingKind.NO_EVENT_FILTER,
+ cause=FindingCause.EVENT_FILTER_INSIDE_OR,
+ query_kind="HogQLQuery",
+ )
+
+ by_design = build_warning(kind=QueryScanFindingKind.NO_EVENT_FILTER, by_design=True, query_kind="HogQLQuery")
self.assertIsNone(assistant_prompt([on_insight], fixable_only=True))
+ self.assertIsNone(assistant_prompt([on_insight, by_design], fixable_only=True))
fixable = assistant_prompt([on_insight, in_query], fixable_only=True)
assert fixable is not None
self.assertNotIn("no_start_date", fixable)
- self.assertIn("- no_event_filter:", fixable)
+ self.assertIn("- no_event_filter (in_or):", fixable)
# The assistant's own block keeps it, since the assistant can tell the person where to set the range.
full = assistant_prompt([on_insight])
assert full is not None
- self.assertIn("- no_start_date (filters):", full)
+ self.assertIn("- no_start_date:", full)
+
+ def test_fixable_only_needs_an_actionable_finding_and_keeps_the_by_design_guidance(self) -> None:
+ by_design = build_warning(kind=QueryScanFindingKind.NO_START_DATE, by_design=True, query_kind="HogQLQuery")
+ actionable = build_warning(
+ kind=QueryScanFindingKind.NO_EVENT_FILTER,
+ cause=FindingCause.EVENT_WRAPPED_IN_FUNCTION,
+ query_kind="HogQLQuery",
+ )
+
+ self.assertIsNone(assistant_prompt([by_design], fixable_only=True))
+ prompt = assistant_prompt([by_design, actionable], fixable_only=True)
+ assert prompt is not None
+ self.assertIn("- no_start_date:", prompt)
+ self.assertIn("- no_event_filter (wrapped):", prompt)
diff --git a/posthog/query_scan/test/test_flag.py b/posthog/query_scan/test/test_flag.py
index 618574f756c7..eef1ca31433c 100644
--- a/posthog/query_scan/test/test_flag.py
+++ b/posthog/query_scan/test/test_flag.py
@@ -14,6 +14,7 @@ from posthog.query_scan.flag import (
DEFAULT_EVENT_RATIO,
DEFAULT_FLOOR_MS,
DEFAULT_PERSONS_RATIO,
+ DEFAULT_START_DATE_RATIO,
QueryScanMode,
get_query_scan_flag,
)
@@ -34,7 +35,7 @@ TEAM = cast(
class TestQueryScanFlag(SimpleTestCase):
def test_evaluates_on_the_organization_and_the_project(self) -> None:
- payload = '{"floor_ms": 2000, "event_ratio": 0.2, "persons_ratio": 0.7}'
+ payload = '{"floor_ms": 2000, "event_ratio": 0.2, "persons_ratio": 0.7, "start_date_ratio": 0.05}'
with patch.object(flag.posthoganalytics, "get_feature_flag_result") as get_result:
get_result.return_value = SimpleNamespace(variant="show", payload=payload)
result = get_query_scan_flag(TEAM)
@@ -44,6 +45,7 @@ class TestQueryScanFlag(SimpleTestCase):
self.assertEqual(result.floor_ms, 2000)
self.assertEqual(result.event_ratio, 0.2)
self.assertEqual(result.persons_ratio, 0.7)
+ self.assertEqual(result.start_date_ratio, 0.05)
get_result.assert_called_once()
kwargs = get_result.call_args.kwargs
@@ -54,19 +56,27 @@ class TestQueryScanFlag(SimpleTestCase):
@parameterized.expand(
[
- ("no payload", None, (DEFAULT_FLOOR_MS, DEFAULT_EVENT_RATIO, DEFAULT_PERSONS_RATIO)),
- ("a float floor", {"floor_ms": 1500.0}, (1500, DEFAULT_EVENT_RATIO, DEFAULT_PERSONS_RATIO)),
+ (
+ "no payload",
+ None,
+ (DEFAULT_FLOOR_MS, DEFAULT_EVENT_RATIO, DEFAULT_PERSONS_RATIO, DEFAULT_START_DATE_RATIO),
+ ),
+ (
+ "a float floor",
+ {"floor_ms": 1500.0},
+ (1500, DEFAULT_EVENT_RATIO, DEFAULT_PERSONS_RATIO, DEFAULT_START_DATE_RATIO),
+ ),
]
)
def test_a_missing_threshold_falls_back_to_its_default(
- self, _name: str, payload: object, expected: tuple[int, float, float]
+ self, _name: str, payload: object, expected: tuple[int, float, float, float]
) -> None:
with patch.object(flag.posthoganalytics, "get_feature_flag_result") as get_result:
get_result.return_value = SimpleNamespace(variant="show", payload=payload)
result = get_query_scan_flag(TEAM)
assert result is not None
- self.assertEqual((result.floor_ms, result.event_ratio, result.persons_ratio), expected)
+ self.assertEqual((result.floor_ms, result.event_ratio, result.persons_ratio, result.start_date_ratio), expected)
@parameterized.expand(
[
diff --git a/posthog/query_scan/test/test_job.py b/posthog/query_scan/test/test_job.py
index 34570cd802e7..64f2d5c1005a 100644
--- a/posthog/query_scan/test/test_job.py
+++ b/posthog/query_scan/test/test_job.py
@@ -14,7 +14,7 @@ from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
from posthog.errors import InternalCHQueryError
from posthog.query_scan import slot
from posthog.query_scan.flag import QueryScanFlag, QueryScanMode
-from posthog.query_scan.job import Execution, QueryScanJob, run_query_scan
+from posthog.query_scan.job import Execution, QueryScanJob, Subquery, run_query_scan
from posthog.query_scan.stub import stub_in_subqueries
from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
@@ -64,10 +64,11 @@ class TestQueryScanJob(BaseTest):
self,
dispatch: dict[str, Any],
*,
- subqueries: tuple[str, ...] = (),
+ subqueries: tuple[str | Subquery, ...] = (),
team_denom: str = "plan_no_date_bound",
range_denom: str = "plan_no_event_filter",
averages_error: BaseException | None = None,
+ tree: dict[str, Any] | None = None,
) -> None:
def execute(query: str, arguments: Any = None, *args: Any, **kwargs: Any) -> Any:
self.calls.append((query, arguments or {}))
@@ -92,9 +93,13 @@ class TestQueryScanJob(BaseTest):
executions=(
Execution(
stubbed_sql="STUBBED_MARKER",
- subqueries=subqueries,
+ subqueries=tuple(
+ subquery if isinstance(subquery, Subquery) else Subquery(sql=subquery)
+ for subquery in subqueries
+ ),
values={},
rows_read=500_000,
+ tree=tree,
),
),
rows_read=500_000,
@@ -114,23 +119,54 @@ class TestQueryScanJob(BaseTest):
@parameterized.expand(
[
# The stubbed SQL plans, so the outer plan's finding is stored.
- ("the stubbed sql plans", {"STUBBED_MARKER": "plan_no_date_bound"}, (), ["no_start_date"], True),
+ (
+ "the stubbed sql plans",
+ {"STUBBED_MARKER": "plan_no_date_bound"},
+ (),
+ None,
+ ["no_start_date"],
+ ["no_start_date"],
+ True,
+ ),
+ (
+ "the tree's facts pick the label",
+ {"STUBBED_MARKER": "plan_no_date_bound"},
+ (),
+ {"timestamp_bound": True, "all_history": True},
+ ["no_start_date/by_design"],
+ [],
+ True,
+ ),
# A finding on a stubbed subquery is merged into the slot.
(
"a subquery finding is merged",
{"STUBBED_MARKER": "plan_event_filter_used", "SUB_MARKER": "plan_no_event_filter"},
("SUB_MARKER",),
+ None,
+ ["no_event_filter/subquery"],
+ ["no_event_filter"],
+ True,
+ ),
+ (
+ "a subquery gets the cause its own verdict names",
+ {"STUBBED_MARKER": "plan_event_filter_used", "SUB_MARKER": "plan_no_event_filter"},
+ (Subquery(sql="SUB_MARKER", event_filter={"classification": "not_used", "reason": "wrapped"}),),
+ None,
+ ["no_event_filter/wrapped/subquery"],
["no_event_filter"],
True,
),
# Any EXPLAIN error ends the analysis: a slot stored with no plan behind it would say
# "nothing to fix" for 30 days, so the claim goes and the next slow run analyzes again.
- ("an explain failure fails closed", {"STUBBED_MARKER": _OTHER_ERROR}, (), [], False),
+ ("an explain failure fails closed", {"STUBBED_MARKER": _OTHER_ERROR}, (), None, [], [], False),
]
)
- def test_analyzes_each_execution(self, _name, dispatch, subqueries, expected_kinds, expected_explain_ok) -> None:
- self._run(dispatch, subqueries=subqueries)
+ def test_analyzes_each_execution(
+ self, _name, dispatch, subqueries, tree, expected_labels, expected_actionable, expected_explain_ok
+ ) -> None:
+ self._run(dispatch, subqueries=subqueries, tree=tree)
+ expected_kinds = [label.split("/")[0] for label in expected_labels]
stored = slot.get(self.team.pk, "cache_key_1", thresholds=FLAG.thresholds_fingerprint)
if expected_explain_ok:
assert stored is not None and stored.analysis is not None
@@ -142,6 +178,9 @@ class TestQueryScanJob(BaseTest):
properties = self.capture.call_args.kwargs["properties"]
assert self.capture.call_args.kwargs["event"] == "query scan analyzed"
assert properties["finding_kinds"] == expected_kinds
+ assert properties["finding_labels"] == expected_labels
+ assert properties["actionable_finding_kinds"] == expected_actionable
+ assert properties["actionable"] is bool(expected_actionable)
assert properties["explain_ok"] is expected_explain_ok
# The rollout analysis groups the event by these, so they travel from the trigger to here.
assert (properties["insight_id"], properties["dashboard_id"]) == (7, 3)
@@ -226,7 +265,9 @@ class TestQueryScanJobOnClickhouse(ClickhouseTestMixin, BaseTest):
Execution(
stubbed_sql=print_prepared_ast(stub.stubbed, context, dialect="clickhouse"),
subqueries=tuple(
- print_prepared_ast(stub_in_subqueries(subquery).stubbed, context, dialect="clickhouse")
+ Subquery(
+ sql=print_prepared_ast(stub_in_subqueries(subquery).stubbed, context, dialect="clickhouse")
+ )
for subquery in stub.subqueries
),
values=context.values,
diff --git a/posthog/query_scan/test/test_serve.py b/posthog/query_scan/test/test_serve.py
index 1b18d86a6e2a..5c3064d972d6 100644
--- a/posthog/query_scan/test/test_serve.py
+++ b/posthog/query_scan/test/test_serve.py
@@ -25,6 +25,7 @@ STORED_ANALYSIS = json.dumps(
"kind": "no_event_filter",
"message": "This query read every event in its date range.",
"fix": "Add an event filter naming the events this question is about.",
+ "actionable": True,
}
],
},
diff --git a/posthog/query_scan/test/test_slot.py b/posthog/query_scan/test/test_slot.py
index 46058a27b236..40de7da40de7 100644
--- a/posthog/query_scan/test/test_slot.py
+++ b/posthog/query_scan/test/test_slot.py
@@ -39,6 +39,7 @@ class TestQueryScanSlotRoundTrip(SimpleTestCase):
kind=QueryScanFindingKind.NO_EVENT_FILTER,
message="This query read every event.",
fix="Add an event filter.",
+ actionable=True,
)
set_done(
1,
diff --git a/posthog/query_scan/test/test_tree_facts.py b/posthog/query_scan/test/test_tree_facts.py
new file mode 100644
index 000000000000..e3bc2c0f5496
--- /dev/null
+++ b/posthog/query_scan/test/test_tree_facts.py
@@ -0,0 +1,178 @@
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import HogQLQueryExecutor
+
+from posthog.query_scan.tree_facts import TreeFacts, tree_facts
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+
+_RECENT = "timestamp >= now() - interval 7 day"
+
+
+class TestTreeFacts(BaseTest):
+ def prepare(self, sql: str) -> ast.AST:
+ executor = HogQLQueryExecutor(
+ query=parse_select(sql),
+ team=self.team,
+ query_type="HogQLQuery",
+ limit_context=LimitContext.QUERY_ASYNC,
+ )
+ executor.generate_clickhouse_sql()
+ assert executor.clickhouse_prepared_ast is not None
+ return executor.clickhouse_prepared_ast
+
+ @parameterized.expand(
+ [
+ (
+ "a relative bound",
+ f"SELECT count() FROM events WHERE event = 'a' AND {_RECENT}",
+ TreeFacts(timestamp_bound=True),
+ ),
+ (
+ "a bound on another column",
+ "SELECT count() FROM events WHERE event = 'a' AND timestamp > toDateTime(properties.signup_time)",
+ TreeFacts(timestamp_bound=True),
+ ),
+ (
+ "a start from a subquery",
+ "SELECT count() FROM events WHERE event = 'a' AND timestamp >= (SELECT now() - interval 7 day)",
+ TreeFacts(timestamp_bound=True, start_date_hidden_from_plan=True),
+ ),
+ (
+ "an end from a subquery is not a start",
+ "SELECT count() FROM events WHERE event = 'a' AND timestamp < (SELECT now())",
+ TreeFacts(),
+ ),
+ (
+ "a bound on the wrapped timestamp",
+ "SELECT count() FROM events WHERE event = 'a' AND toDate(timestamp) >= today() - 7",
+ TreeFacts(timestamp_bound=True),
+ ),
+ (
+ "a bound with the timestamp on the right",
+ "SELECT count() FROM events WHERE event = 'a' AND now() - interval 7 day <= timestamp",
+ TreeFacts(timestamp_bound=True),
+ ),
+ ("an end date only", "SELECT count() FROM events WHERE event = 'a' AND timestamp < now()", TreeFacts()),
+ (
+ "a bound inside an OR",
+ f"SELECT count() FROM events WHERE event = 'a' AND ({_RECENT} OR properties.plan = 'pro')",
+ TreeFacts(),
+ ),
+ (
+ "two reads, one unbounded",
+ f"SELECT count() FROM events AS e JOIN (SELECT distinct_id FROM events WHERE event = 'b') AS s "
+ f"ON e.distinct_id = s.distinct_id WHERE e.event = 'a' AND e.{_RECENT}",
+ TreeFacts(),
+ ),
+ (
+ "a property standing in for an event",
+ f"SELECT count() FROM events WHERE properties.$current_url = 'https://example.com/x' AND {_RECENT}",
+ TreeFacts(timestamp_bound=True, property_filter=True),
+ ),
+ (
+ "a property beside an event condition",
+ f"SELECT count() FROM events WHERE event = 'a' AND properties.plan = 'pro' AND {_RECENT}",
+ TreeFacts(timestamp_bound=True),
+ ),
+ (
+ "a property inside an OR with the event",
+ f"SELECT count() FROM events WHERE (event = 'a' OR properties.plan = 'pro') AND {_RECENT}",
+ TreeFacts(timestamp_bound=True),
+ ),
+ (
+ "each person's first event",
+ "SELECT person_id, min(timestamp) FROM events GROUP BY person_id",
+ TreeFacts(all_history=True),
+ ),
+ (
+ "the value at each person's first event",
+ "SELECT person_id, argMin(properties.plan, timestamp) FROM events GROUP BY person_id",
+ TreeFacts(all_history=True),
+ ),
+ (
+ "a first-event window",
+ "SELECT person_id, row_number() OVER (PARTITION BY person_id ORDER BY timestamp ASC) AS n FROM events",
+ TreeFacts(all_history=True),
+ ),
+ (
+ "a first-event helper beside an unbounded main read",
+ "SELECT count() FROM events AS e JOIN (SELECT person_id, min(timestamp) AS first FROM events "
+ "GROUP BY person_id) AS f ON e.person_id = f.person_id WHERE e.event = 'a'",
+ TreeFacts(),
+ ),
+ (
+ "each person's first event in a range",
+ f"SELECT person_id, min(timestamp) FROM events WHERE {_RECENT} GROUP BY person_id",
+ TreeFacts(timestamp_bound=True),
+ ),
+ ("grouping by event", "SELECT event, count() FROM events GROUP BY event", TreeFacts(groups_by_event=True)),
+ (
+ "grouping by event position",
+ "SELECT event, count() FROM events GROUP BY 1",
+ TreeFacts(groups_by_event=True),
+ ),
+ (
+ "grouping by event with an event condition",
+ "SELECT event, count() FROM events WHERE event IN ('a', 'b') GROUP BY event",
+ TreeFacts(),
+ ),
+ (
+ "distinct people over any event",
+ f"SELECT count(DISTINCT person_id) FROM events WHERE {_RECENT}",
+ TreeFacts(timestamp_bound=True, counts_any_event=True),
+ ),
+ (
+ "unique sessions over any event",
+ f"SELECT uniq($session_id) FROM events WHERE {_RECENT}",
+ TreeFacts(timestamp_bound=True, counts_any_event=True),
+ ),
+ (
+ "distinct people over one event",
+ f"SELECT count(DISTINCT person_id) FROM events WHERE event = 'a' AND {_RECENT}",
+ TreeFacts(timestamp_bound=True),
+ ),
+ (
+ "each person's last event",
+ "SELECT person_id, max(timestamp) FROM events GROUP BY person_id",
+ TreeFacts(counts_any_event=True),
+ ),
+ (
+ "a last-event window",
+ "SELECT person_id, row_number() OVER (PARTITION BY person_id ORDER BY timestamp DESC) AS n FROM events",
+ TreeFacts(counts_any_event=True),
+ ),
+ ("the last event", "SELECT max(timestamp) FROM events", TreeFacts()),
+ ("a plain count", f"SELECT count() FROM events WHERE {_RECENT}", TreeFacts(timestamp_bound=True)),
+ ]
+ )
+ def test_reads_the_facts_off_the_tree(self, _name: str, sql: str, expected: TreeFacts) -> None:
+ self.assertEqual(tree_facts(self.prepare(sql)), expected)
+
+ def test_a_query_without_events_has_no_facts(self) -> None:
+ self.assertIsNone(tree_facts(self.prepare("SELECT 1")))
+
+ def test_a_read_inside_a_saved_view_names_the_view(self) -> None:
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="v_active",
+ query={"kind": "HogQLQuery", "query": "SELECT event, timestamp, person_id FROM events WHERE event = 'a'"},
+ columns={"event": "String", "timestamp": "DateTime64(6, 'UTC')", "person_id": "UUID"},
+ )
+
+ facts = tree_facts(self.prepare("SELECT count() FROM v_active"))
+
+ assert facts is not None
+ self.assertEqual(facts.view_name, "v_active")
+ mixed = tree_facts(
+ self.prepare(
+ "SELECT count() FROM events AS e JOIN v_active AS v ON e.person_id = v.person_id WHERE e.event = 'b'"
+ )
+ )
+ assert mixed is not None
+ self.assertIsNone(mixed.view_name)
diff --git a/posthog/query_scan/test/test_trigger.py b/posthog/query_scan/test/test_trigger.py
index 005f7e216acf..bf0b95e8a5b9 100644
--- a/posthog/query_scan/test/test_trigger.py
+++ b/posthog/query_scan/test/test_trigger.py
@@ -1,6 +1,7 @@
import json
from typing import Any
+from posthog.test.base import BaseTest
from unittest import mock
from django.test import SimpleTestCase
@@ -9,26 +10,38 @@ from parameterized import parameterized
from posthog.schema import (
BaseMathType,
+ Breakdown,
+ BreakdownFilter,
+ BreakdownType,
DateRange,
EventsNode,
+ EventsQuery,
FunnelMathType,
FunnelsQuery,
HogQLFilters,
HogQLQuery,
+ LifecycleQuery,
+ MultipleBreakdownType,
RetentionFilter,
RetentionQuery,
RetentionType,
TrendsQuery,
)
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.context import HogQLContext
from posthog.hogql.parser import parse_select
+from posthog.hogql.query import HogQLQueryExecutor
from posthog.hogql.query_stats import QueryStats, RecordedExecution
from posthog.clickhouse.query_tagging import AccessMethod, Feature, reset_query_tags, tag_queries
+from posthog.event_usage import EventSource
+from posthog.query_scan.explain import EXPLAIN_MAX_SECONDS
from posthog.query_scan.flag import QueryScanFlag, QueryScanMode
from posthog.query_scan.slot import slot_key
-from posthog.query_scan.trigger import MAX_EXECUTION_BYTES, _open_filters_placeholder, maybe_trigger_query_scan
+from posthog.query_scan.tree_facts import TreeFacts
+from posthog.query_scan.trigger import _open_filters_placeholder, maybe_trigger_query_scan
FLAG = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)
@@ -37,15 +50,35 @@ _QUERY_WITH_SUBQUERY = "select 1 from events where event in (select 'x')"
def _execution(
- sql: str = _QUERY_WITH_SUBQUERY, rows_read: int = 100, values: dict[str, Any] | None = None
+ sql: str = _QUERY_WITH_SUBQUERY,
+ rows_read: int = 100,
+ values: dict[str, Any] | None = None,
+ lookup: str | None = None,
+ settings: HogQLGlobalSettings | None = None,
) -> RecordedExecution:
return RecordedExecution(
- tree=parse_select(sql), context=HogQLContext(team_id=1, values=values or {}), rows_read=rows_read
+ tree=parse_select(sql),
+ context=HogQLContext(team_id=1, values=values or {}),
+ rows_read=rows_read,
+ lookup=lookup,
+ settings=settings,
)
-def _stats(*, duration_ms: float = 2000.0, executions: list[RecordedExecution] | None = None) -> QueryStats:
- stats = QueryStats(rows_read=10, duration_ms=duration_ms)
+def _stats(
+ *,
+ duration_ms: float = 2000.0,
+ rows_read: int = 10,
+ executions: list[RecordedExecution] | None = None,
+ lookup_rows_read: int = 0,
+ lookup_duration_ms: float = 0.0,
+) -> QueryStats:
+ stats = QueryStats(
+ rows_read=rows_read,
+ duration_ms=duration_ms,
+ lookup_rows_read=lookup_rows_read,
+ lookup_duration_ms=lookup_duration_ms,
+ )
stats.executions.extend(executions if executions is not None else [_execution()])
return stats
@@ -62,6 +95,14 @@ def _spend_the_enqueue_budget(test: "TestQueryScanTrigger") -> None:
test.redis.incr.return_value = 11
+def _tag_as_mcp_tool(test: "TestQueryScanTrigger") -> None:
+ tag_queries(access_method=AccessMethod.PERSONAL_API_KEY, feature=Feature.MCP)
+
+
+def _tag_as_mcp_server(test: "TestQueryScanTrigger") -> None:
+ tag_queries(access_method=AccessMethod.OAUTH, source=EventSource.MCP)
+
+
def _lose_the_slot_claim(test: "TestQueryScanTrigger") -> None:
test.redis.set.return_value = None
@@ -69,7 +110,7 @@ def _lose_the_slot_claim(test: "TestQueryScanTrigger") -> None:
def _printing(values: dict[str, Any]) -> Any:
"""A printer stand-in that adds to the context the values a real print would."""
- def print_with_values(node: Any, context: HogQLContext, dialect: str) -> str:
+ def print_with_values(node: Any, context: HogQLContext, dialect: str, settings: Any = None) -> str:
context.values.update(values)
return "SELECT 1"
@@ -118,6 +159,20 @@ class TestQueryScanTrigger(SimpleTestCase):
("flag off", {"flag": None}, None, "flag_off"),
("below the floor", {"stats": _stats(duration_ms=999.0)}, None, "below_floor"),
("api key run", {}, _tag_as_api_key, "api_key"),
+ ("an mcp tool on an api key", {}, _tag_as_mcp_tool, "mcp"),
+ ("the mcp server on oauth", {}, _tag_as_mcp_server, "mcp"),
+ (
+ "a kind from one of posthog's own screens",
+ {"query": EventsQuery(select=["*"])},
+ None,
+ "kind_not_analyzed",
+ ),
+ (
+ "sql from a screen that shows no advice",
+ {"insight_id": None, "dashboard_id": None},
+ None,
+ "sql_without_surface",
+ ),
(
"direct connection",
{"query": HogQLQuery(query="select 1", connectionId="connection_1")},
@@ -150,10 +205,46 @@ class TestQueryScanTrigger(SimpleTestCase):
assert self.delay.call_args.kwargs["killed"] is True
assert self.delay.call_args.kwargs["duration_ms"] == 999
- def test_an_mcp_run_is_analyzed_despite_its_api_key(self) -> None:
- tag_queries(access_method=AccessMethod.PERSONAL_API_KEY, feature=Feature.MCP)
+ @parameterized.expand(
+ [
+ ("still over the floor without it", 3000.0, None, 50, 1500),
+ ("under the floor without it", 2000.0, "below_floor", None, None),
+ ]
+ )
+ def test_a_runners_own_lookup_does_not_count_toward_the_run(
+ self, _name: str, total_ms: float, expected_reason: str | None, expected_rows: int | None, expected_ms
+ ) -> None:
+ lookup = _execution(rows_read=100, lookup="earliest_timestamp")
+ query = _execution(rows_read=50)
- result = self._trigger()
+ result = self._trigger(
+ stats=_stats(
+ duration_ms=total_ms,
+ rows_read=150,
+ lookup_rows_read=100,
+ lookup_duration_ms=1500.0,
+ executions=[lookup, query],
+ )
+ )
+
+ assert result == expected_reason
+ if expected_reason is not None:
+ self.delay.assert_not_called()
+ return
+ enqueued = self.delay.call_args.kwargs
+ assert (enqueued["rows_read"], enqueued["duration_ms"]) == (expected_rows, expected_ms)
+ assert [execution["rows_read"] for execution in enqueued["executions"]] == [50]
+
+ @parameterized.expand(
+ [
+ ("the sql editor", {"scene": "SQLEditor"}),
+ ("an unsaved insight", {"scene": "Insight"}),
+ ]
+ )
+ def test_sql_outside_an_insight_is_analyzed_where_its_advice_is_read(self, _name, tags) -> None:
+ tag_queries(**tags)
+
+ result = self._trigger(insight_id=None, dashboard_id=None)
assert result is None
assert self.delay.call_count == 1
@@ -203,31 +294,46 @@ class TestQueryScanTrigger(SimpleTestCase):
assert result == "enqueue_failed"
self.redis.delete.assert_called_once_with(slot_key(1, "cache_key_1", FLAG.thresholds_fingerprint))
- def test_the_payload_carries_the_event_filter_classification(self) -> None:
- # The job folds this verdict into the plan, so a payload that stopped carrying it would
- # drop the tree's reason for why the filter could not prune.
- result = self._trigger(trigger="killed", killed=True, error_type="ClickHouseQueryTimeOut")
+ def test_the_payload_carries_the_tree_verdicts(self) -> None:
+ facts = TreeFacts(
+ timestamp_bound=True,
+ property_filter=False,
+ all_history=False,
+ groups_by_event=False,
+ counts_any_event=False,
+ view_name="v_active",
+ )
+ with mock.patch("posthog.query_scan.trigger.tree_facts", return_value=facts):
+ result = self._trigger(trigger="killed", killed=True, error_type="ClickHouseQueryTimeOut")
assert result is None
enqueued = self.delay.call_args.kwargs["executions"]
- assert enqueued[0]["event_filter"] == {"classification": "usable", "reason": None}
+ assert enqueued[0]["event_filter"] == {
+ "classification": "usable",
+ "reason": None,
+ "hidden_from_plan": False,
+ }
+ assert enqueued[0]["tree"] == facts.to_payload()
# The job groups the analytics event by the error kind, so it travels on the payload.
assert self.delay.call_args.kwargs["error_type"] == "ClickHouseQueryTimeOut"
@parameterized.expand(
[
- # The values count because one large literal can outweigh the SQL around it.
- ("too large to ship", {"hogql_val_0": "x" * (MAX_EXECUTION_BYTES + 1)}, "too_large"),
- ("carrying a sensitive value", {"hogql_val_0_sensitive": "warehouse-secret"}, "sensitive_values"),
+ ("that will not print", RuntimeError("no printer for this node"), "print_failed"),
+ (
+ "carrying a sensitive value",
+ _printing({"hogql_val_0_sensitive": "warehouse-secret"}),
+ "sensitive_values",
+ ),
]
)
def test_an_unshippable_selected_execution_aborts_the_whole_scan(
- self, _name: str, printed_values: dict[str, Any], expected_reason: str
+ self, _name: str, print_outcome: Any, expected_reason: str
) -> None:
# A person reads the advice as if it covered the whole run, so a run with a selected
# execution that cannot ship is not analyzed in part. The claimed slot is dropped, so a
# later run can try again.
- self.print.side_effect = _printing(printed_values)
+ self.print.side_effect = print_outcome
result = self._trigger(stats=_stats(executions=[_execution(rows_read=100), _execution(rows_read=50)]))
@@ -235,6 +341,16 @@ class TestQueryScanTrigger(SimpleTestCase):
self.delay.assert_not_called()
self.redis.delete.assert_called_once_with(slot_key(1, "cache_key_1", FLAG.thresholds_fingerprint))
+ def test_the_sql_is_printed_under_the_settings_the_run_had(self) -> None:
+ run_settings = HogQLGlobalSettings(max_execution_time=600)
+
+ result = self._trigger(stats=_stats(executions=[_execution(settings=run_settings)]))
+
+ assert result is None
+ printed_under = self.print.call_args.kwargs["settings"]
+ assert printed_under.max_ast_elements == run_settings.max_ast_elements
+ assert printed_under.max_execution_time == EXPLAIN_MAX_SECONDS
+
def test_ships_several_printable_executions_heaviest_first(self) -> None:
# An insight fans out into several executions; the job explains the heaviest, so the payload
# carries them ordered by rows read.
@@ -247,7 +363,7 @@ class TestQueryScanTrigger(SimpleTestCase):
enqueued = self.delay.call_args.kwargs["executions"]
assert [execution["rows_read"] for execution in enqueued] == [100, 50]
assert enqueued[0]["stubbed_sql"] == "SELECT 1"
- assert enqueued[0]["subqueries"] == ["SELECT 1"]
+ assert [subquery["sql"] for subquery in enqueued[0]["subqueries"]] == ["SELECT 1"]
# A warehouse run's own values hold its source credentials, so only the job's print travels.
assert [execution["values"] for execution in enqueued] == [{}, {}]
@@ -279,10 +395,13 @@ class TestQueryScanTrigger(SimpleTestCase):
# A count left without a TTL would stand forever and cap the team for good.
self.redis.set.assert_any_call("query_scan:enqueues:1", 0, nx=True, ex=60)
- def test_the_payload_says_whether_all_time_was_chosen(self) -> None:
+ def test_the_payload_says_whether_all_time_was_chosen_and_by_which_picker(self) -> None:
+ tag_queries(dashboard_all_time=True)
+
self._trigger(query=TrendsQuery(series=[EventsNode(event="$pageview")], dateRange=DateRange(date_from="all")))
assert self.delay.call_args.kwargs["all_time"] is True
+ assert self.delay.call_args.kwargs["dashboard_all_time"] is True
@parameterized.expand(
[
@@ -314,6 +433,100 @@ class TestQueryScanTrigger(SimpleTestCase):
assert self.delay.call_args.kwargs["all_history_by_design"] is expected
+ @parameterized.expand(
+ [
+ ("active users on all events", TrendsQuery(series=[EventsNode(math=BaseMathType.DAU)]), True),
+ (
+ "monthly active on all events",
+ TrendsQuery(series=[EventsNode(math=BaseMathType.MONTHLY_ACTIVE)]),
+ True,
+ ),
+ ("unique sessions on all events", TrendsQuery(series=[EventsNode(math=BaseMathType.UNIQUE_SESSION)]), True),
+ ("lifecycle on all events", LifecycleQuery(series=[EventsNode()]), True),
+ (
+ "a breakdown by event name",
+ TrendsQuery(
+ series=[EventsNode()],
+ breakdownFilter=BreakdownFilter(breakdown="event", breakdown_type=BreakdownType.EVENT_METADATA),
+ ),
+ True,
+ ),
+ (
+ "a multiple breakdown by event name",
+ TrendsQuery(
+ series=[EventsNode()],
+ breakdownFilter=BreakdownFilter(
+ breakdowns=[Breakdown(property="event", type=MultipleBreakdownType.EVENT_METADATA)]
+ ),
+ ),
+ True,
+ ),
+ (
+ "active users on a named event",
+ TrendsQuery(series=[EventsNode(event="a", math=BaseMathType.DAU)]),
+ False,
+ ),
+ (
+ "a breakdown by event name on a named event",
+ TrendsQuery(
+ series=[EventsNode(event="a")],
+ breakdownFilter=BreakdownFilter(breakdown="event", breakdown_type=BreakdownType.EVENT_METADATA),
+ ),
+ False,
+ ),
+ ("a total on all events", TrendsQuery(series=[EventsNode(math=BaseMathType.TOTAL)]), False),
+ ]
+ )
+ def test_the_payload_says_whether_the_insight_reads_all_events_by_design(self, _name, query, expected) -> None:
+ self._trigger(query=query)
+
+ assert self.delay.call_args.kwargs["all_events_by_design"] is expected
+
+
+class TestSubqueryVerdicts(BaseTest):
+ def test_the_outer_query_and_a_subquery_are_each_judged_on_their_own_reads(self) -> None:
+ executor = HogQLQueryExecutor(
+ query=parse_select(
+ "select count() from events where event = '$pageview' and timestamp > now() - interval 7 day "
+ "and distinct_id in (select distinct_id from events "
+ "where lower(event) = 'signup' and timestamp > now() - interval 7 day)"
+ ),
+ team=self.team,
+ query_type="HogQLQuery",
+ limit_context=LimitContext.QUERY_ASYNC,
+ )
+ executor.generate_clickhouse_sql()
+ assert isinstance(executor.clickhouse_prepared_ast, ast.Expr) and executor.clickhouse_context is not None
+ execution = RecordedExecution(
+ tree=executor.clickhouse_prepared_ast, context=executor.clickhouse_context, rows_read=100
+ )
+ redis = mock.Mock()
+ redis.get.return_value = None
+ redis.incr.return_value = 1
+
+ with (
+ mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis),
+ mock.patch("posthog.tasks.query_scan.analyze_query_scan.delay") as delay,
+ ):
+ result = maybe_trigger_query_scan(
+ flag=FLAG,
+ stats=_stats(executions=[execution]),
+ team_id=self.team.pk,
+ cache_key="cache_key_1",
+ query=HogQLQuery(query="select 1"),
+ trigger="fresh",
+ cacheable=True,
+ insight_id=7,
+ )
+
+ assert result is None
+ shipped = delay.call_args.kwargs["executions"][0]
+ assert shipped["event_filter"]["classification"] == "usable"
+ assert [
+ (subquery["event_filter"]["classification"], subquery["event_filter"]["reason"])
+ for subquery in shipped["subqueries"]
+ ] == [("not_used", "wrapped")]
+
class TestOpenFiltersPlaceholder(SimpleTestCase):
@parameterized.expand(
diff --git a/posthog/query_scan/tree.py b/posthog/query_scan/tree.py
index 83f223864320..fd2fb4c59dcf 100644
--- a/posthog/query_scan/tree.py
+++ b/posthog/query_scan/tree.py
@@ -117,6 +117,9 @@ def resolve_to_table_columns(type_: ast.Type | None) -> list[tuple[ast.TableType
seen.add(id(current))
while isinstance(current, ast.FieldAliasType):
current = current.type
+ if isinstance(current, ast.PropertyType):
+ # `properties.plan` is a key inside the `properties` column, so the condition is on that column.
+ current = current.field_type
if not isinstance(current, ast.FieldType):
continue
table_type = _unwrap_table_alias(current.table_type)
diff --git a/posthog/query_scan/tree_facts.py b/posthog/query_scan/tree_facts.py
new file mode 100644
index 000000000000..90236d047323
--- /dev/null
+++ b/posthog/query_scan/tree_facts.py
@@ -0,0 +1,291 @@
+"""What the prepared tree says about its events reads, beyond the event filter.
+
+The plan reports an unfiltered read; it cannot say why. ``classify_event_filter`` reads the event
+condition off the tree, and this module reads the rest the advice needs: whether the read carries
+a start date at all, whether a property condition narrows it in place of an event name, whether
+the query's shape needs all history or all events by design, and whether the read sits inside a
+saved view. The trigger ships the facts with each execution and the job folds them into the plan.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.visitor import TraversingVisitor
+
+from posthog.dataclasses import frozen
+from posthog.query_scan.tree import (
+ EventsRead,
+ collect_conditions,
+ contains_column_of,
+ find_events_reads,
+ is_column_of,
+ resolve_to_table_columns,
+ strip_aliases,
+)
+
+_TIMESTAMP = "timestamp"
+_EVENT = "event"
+_PROPERTY_COLUMNS = ("properties", "person_properties")
+_ACTOR_COLUMNS = ("person_id", "distinct_id", "$session_id")
+
+_LOWER_BOUND_ON_LEFT = frozenset({ast.CompareOperationOp.Gt, ast.CompareOperationOp.GtEq, ast.CompareOperationOp.Eq})
+_LOWER_BOUND_ON_RIGHT = frozenset({ast.CompareOperationOp.Lt, ast.CompareOperationOp.LtEq, ast.CompareOperationOp.Eq})
+_FIRST_EVENT_AGGREGATES = frozenset({"min", "minIf", "argMin", "argMinIf"})
+_LAST_EVENT_AGGREGATES = frozenset({"max", "maxIf", "argMax", "argMaxIf"})
+_DISTINCT_COUNTS = frozenset(
+ {"uniq", "uniqIf", "uniqExact", "uniqExactIf", "uniqHLL12", "uniqCombined", "uniqCombined64", "uniqTheta"}
+)
+_RANKING_WINDOWS = frozenset({"row_number", "rank", "dense_rank"})
+
+
+@frozen
+class TreeFacts:
+ """Facts about the tree's events reads, for the job to fold into the plan.
+
+ The plan's finding is about one read and the tree cannot tell which, so each fact holds only
+ when every read the finding could be about agrees. A query that mixes a by-design read with a
+ plain one gets the plain wording, and the plan's evidence says which read it means.
+ """
+
+ # Every events read carries a lower bound on `timestamp`, so an unbounded read in the plan is
+ # a bound ClickHouse could not use.
+ timestamp_bound: bool = False
+ # Every events read with no event condition narrows itself by a property instead.
+ property_filter: bool = False
+ # Every unbounded events read finds a first event ever, with `min` or `argMin` over `timestamp`
+ # or a ranking window ordered by it: the answer needs all history.
+ all_history: bool = False
+ # Every events read with no event condition groups by `event`: the answer is the set of events.
+ groups_by_event: bool = False
+ # Every events read with no event condition counts distinct actors or sessions, or finds each
+ # actor's last event: the answer needs every event.
+ counts_any_event: bool = False
+ # The saved view every events read sits inside, when they all sit inside the same one.
+ view_name: str | None = None
+ # Every events read carries a lower bound and one of them compares `timestamp` to a subquery, so a
+ # read the plan shows with no start is that bound: the scan takes it out before it asks for the plan.
+ start_date_hidden_from_plan: bool = False
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "start_date_hidden_from_plan": self.start_date_hidden_from_plan,
+ "timestamp_bound": self.timestamp_bound,
+ "property_filter": self.property_filter,
+ "all_history": self.all_history,
+ "groups_by_event": self.groups_by_event,
+ "counts_any_event": self.counts_any_event,
+ "view_name": self.view_name,
+ }
+
+ @classmethod
+ def from_payload(cls, payload: object) -> TreeFacts | None:
+ """None for a payload that carries no facts, so the analysis treats the tree as unknown."""
+ if not isinstance(payload, dict):
+ return None
+ view_name = payload.get("view_name")
+ return cls(
+ timestamp_bound=payload.get("timestamp_bound") is True,
+ property_filter=payload.get("property_filter") is True,
+ all_history=payload.get("all_history") is True,
+ groups_by_event=payload.get("groups_by_event") is True,
+ counts_any_event=payload.get("counts_any_event") is True,
+ view_name=view_name if isinstance(view_name, str) and view_name else None,
+ start_date_hidden_from_plan=payload.get("start_date_hidden_from_plan") is True,
+ )
+
+
+@frozen
+class _ReadFacts:
+ timestamp_bound: bool
+ subquery_bound: bool
+ event_condition: bool
+ property_condition: bool
+ all_history: bool
+ groups_by_event: bool
+ counts_any_event: bool
+ view_name: str | None
+
+
+def tree_facts(tree: ast.AST, reads: list[EventsRead] | None = None) -> TreeFacts | None:
+ """The facts for ``tree``, or None when it reads no events. ``reads`` narrows the facts to the
+ reads one plan holds; None takes every read in the tree."""
+ if reads is None:
+ reads = find_events_reads(tree)
+ if not reads:
+ return None
+ parents = _ParentSelects()
+ parents.visit(tree)
+ facts = [_read_facts(read, collect_conditions(tree, read), parents) for read in reads]
+
+ unbounded = [read for read in facts if not read.timestamp_bound]
+ unfiltered = [read for read in facts if not read.event_condition]
+ view_names = {read.view_name for read in facts}
+ return TreeFacts(
+ timestamp_bound=not unbounded,
+ property_filter=bool(unfiltered) and all(read.property_condition for read in unfiltered),
+ all_history=bool(unbounded) and all(read.all_history for read in unbounded),
+ groups_by_event=bool(unfiltered) and all(read.groups_by_event for read in unfiltered),
+ counts_any_event=bool(unfiltered) and all(read.counts_any_event for read in unfiltered),
+ view_name=next(iter(view_names)) if len(view_names) == 1 else None,
+ start_date_hidden_from_plan=not unbounded and any(read.subquery_bound for read in facts),
+ )
+
+
+def _read_facts(read: EventsRead, conditions: list[ast.Expr], parents: _ParentSelects) -> _ReadFacts:
+ lower_bounds = [term for term in conditions if _is_lower_bound(term, read)]
+ timestamp_bound = bool(lower_bounds)
+ select = read.select
+ aggregates = _Aggregates(read)
+ aggregates.visit_exprs(select.select)
+ per_actor = any(_names_actor(expr, read) for expr in _group_by(select))
+ return _ReadFacts(
+ timestamp_bound=timestamp_bound,
+ subquery_bound=any(_holds_subquery(term) for term in lower_bounds),
+ event_condition=any(contains_column_of(term, read, _EVENT) for term in conditions),
+ property_condition=any(
+ contains_column_of(term, read, column) for term in conditions for column in _PROPERTY_COLUMNS
+ ),
+ all_history=not timestamp_bound and (aggregates.first_event or aggregates.first_by_window),
+ groups_by_event=any(is_column_of(expr, read, _EVENT) for expr in _group_by(select)),
+ counts_any_event=aggregates.distinct_actors
+ or (per_actor and aggregates.last_event)
+ or aggregates.last_by_window,
+ view_name=parents.view_of(select),
+ )
+
+
+def _is_lower_bound(term: ast.Expr, read: EventsRead) -> bool:
+ """Whether ``term`` puts a start on this read's ``timestamp``. The other side is not checked:
+ a bound on another column is still a bound in the tree, one the plan will show it could not
+ use, which is what tells that case from no bound at all.
+ """
+ term = strip_aliases(term)
+ if isinstance(term, ast.BetweenExpr):
+ return not term.negated and contains_column_of(term.expr, read, _TIMESTAMP)
+ if not isinstance(term, ast.CompareOperation):
+ return False
+ if term.op in _LOWER_BOUND_ON_LEFT and contains_column_of(term.left, read, _TIMESTAMP):
+ return True
+ return term.op in _LOWER_BOUND_ON_RIGHT and contains_column_of(term.right, read, _TIMESTAMP)
+
+
+def _holds_subquery(term: ast.Expr) -> bool:
+ finder = _SubqueryFinder()
+ finder.visit(term)
+ return finder.found
+
+
+def _group_by(select: ast.SelectQuery) -> list[ast.Expr]:
+ """The group-by expressions, with a positional `GROUP BY 1` resolved to the select column."""
+ resolved: list[ast.Expr] = []
+ for expr in select.group_by or []:
+ expr = strip_aliases(expr)
+ if isinstance(expr, ast.Constant) and isinstance(expr.value, int) and 1 <= expr.value <= len(select.select):
+ expr = strip_aliases(select.select[expr.value - 1])
+ resolved.append(expr)
+ return resolved
+
+
+def _names_actor(expr: ast.Expr, read: EventsRead) -> bool:
+ """Whether ``expr`` reads a person, distinct id or session column. `person_id` is a column of
+ the events read only in persons-on-events mode; otherwise the resolver reaches it through a
+ joined distinct-id subquery, so the column is judged by its resolved name on any table."""
+ finder = _ActorColumnFinder()
+ finder.visit(expr)
+ return finder.found
+
+
+class _Aggregates(TraversingVisitor):
+ """Finds the aggregates and windows over ``read`` in a select list, without entering a nested select."""
+
+ def __init__(self, read: EventsRead) -> None:
+ super().__init__()
+ self.read = read
+ self.first_event = False
+ self.last_event = False
+ self.distinct_actors = False
+ self.first_by_window = False
+ self.last_by_window = False
+
+ def visit_exprs(self, exprs: list[ast.Expr]) -> None:
+ for expr in exprs:
+ self.visit(expr)
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ return
+
+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:
+ return
+
+ def visit_call(self, node: ast.Call) -> None:
+ over_timestamp = any(contains_column_of(arg, self.read, _TIMESTAMP) for arg in node.args)
+ if node.name in _FIRST_EVENT_AGGREGATES and over_timestamp:
+ self.first_event = True
+ if node.name in _LAST_EVENT_AGGREGATES and over_timestamp:
+ self.last_event = True
+ counts_distinct = node.name in _DISTINCT_COUNTS or (node.name == "count" and node.distinct)
+ if counts_distinct and any(_names_actor(arg, self.read) for arg in node.args):
+ self.distinct_actors = True
+ super().visit_call(node)
+
+ def visit_window_function(self, node: ast.WindowFunction) -> None:
+ window = node.over_expr
+ if node.name in _RANKING_WINDOWS and window is not None:
+ for order in window.order_by or []:
+ if not contains_column_of(order.expr, self.read, _TIMESTAMP):
+ continue
+ if order.order == "ASC":
+ self.first_by_window = True
+ elif any(_names_actor(expr, self.read) for expr in window.partition_by or []):
+ self.last_by_window = True
+ super().visit_window_function(node)
+
+
+class _SubqueryFinder(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ self.found = True
+
+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:
+ self.found = True
+
+
+class _ActorColumnFinder(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_field(self, node: ast.Field) -> None:
+ if any(name in _ACTOR_COLUMNS for _, name in resolve_to_table_columns(node.type)):
+ self.found = True
+ super().visit_field(node)
+
+
+class _ParentSelects(TraversingVisitor):
+ """Maps each select to the one enclosing it, to find the saved view a read was inlined from."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._parent: dict[int, ast.SelectQuery] = {}
+ self._stack: list[ast.SelectQuery] = []
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if self._stack:
+ self._parent[id(node)] = self._stack[-1]
+ self._stack.append(node)
+ super().visit_select_query(node)
+ self._stack.pop()
+
+ def view_of(self, select: ast.SelectQuery) -> str | None:
+ """The nearest saved view ``select`` sits inside, the select itself included."""
+ current: ast.SelectQuery | None = select
+ while current is not None:
+ if current.view_name:
+ return current.view_name
+ current = self._parent.get(id(current))
+ return None
diff --git a/posthog/query_scan/trigger.py b/posthog/query_scan/trigger.py
index a8710b601026..75824124fbd0 100644
--- a/posthog/query_scan/trigger.py
+++ b/posthog/query_scan/trigger.py
@@ -8,13 +8,21 @@ the query result.
from __future__ import annotations
import copy
-import json
from typing import Any, Literal, TypeGuard
import structlog
from pydantic import BaseModel
-from posthog.schema import BaseMathType, FunnelMathType, GroupMathType, RetentionType
+from posthog.schema import (
+ BaseMathType,
+ BreakdownType,
+ EventsNode,
+ FunnelMathType,
+ GroupMathType,
+ LifecycleQuery,
+ NodeKind,
+ RetentionType,
+)
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
@@ -23,8 +31,10 @@ from posthog.hogql.printer import print_prepared_ast
from posthog.hogql.query_stats import QueryStats, RecordedExecution
from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, is_api_key_access_method
+from posthog.event_usage import EventSource
from posthog.models.user import User
from posthog.query_scan.event_filter import classify_event_filter
+from posthog.query_scan.explain import EXPLAIN_MAX_SECONDS
from posthog.query_scan.findings import SQL_QUERY_KIND
from posthog.query_scan.flag import QueryScanFlag
from posthog.query_scan.slot import (
@@ -34,13 +44,11 @@ from posthog.query_scan.slot import (
set_pending,
)
from posthog.query_scan.stub import stub_in_subqueries
+from posthog.query_scan.tree import EventsRead, find_events_reads
+from posthog.query_scan.tree_facts import tree_facts
logger = structlog.get_logger(__name__)
-# Above this an EXPLAIN is unlikely to plan and the payload is not worth shipping to the worker. The
-# cap covers the SQL and its parameter values together, since one large literal can outweigh the
-# SQL around it.
-MAX_EXECUTION_BYTES = 100 * 1024
# The runner can fan an insight out into many series; the heaviest handful explains the run.
MAX_EXECUTIONS = 5
# Each subquery is explained on its own, so the cap is across the whole run, not per execution.
@@ -59,10 +67,39 @@ _FIRST_TIME_MATHS: frozenset[str] = frozenset(
}
)
+# Math that counts people or sessions over whatever they did, so on an "All events" series the
+# answer needs every event and picking events would change it.
+_ANY_EVENT_MATHS: frozenset[str] = frozenset(
+ {
+ BaseMathType.DAU,
+ BaseMathType.WEEKLY_ACTIVE,
+ BaseMathType.MONTHLY_ACTIVE,
+ BaseMathType.UNIQUE_SESSION,
+ }
+)
+
+# Every other kind belongs to a PostHog screen that shows no advice and has nothing to edit.
+_KINDS_A_PERSON_BUILDS: frozenset[str] = frozenset(
+ {
+ NodeKind.HOG_QL_QUERY,
+ NodeKind.TRENDS_QUERY,
+ NodeKind.FUNNELS_QUERY,
+ NodeKind.RETENTION_QUERY,
+ NodeKind.LIFECYCLE_QUERY,
+ NodeKind.PATHS_QUERY,
+ NodeKind.STICKINESS_QUERY,
+ }
+)
+# PostHog's own screens run SQL too, so the kind alone does not say a person wrote it.
+_SQL_SCENES_WITH_ADVICE: frozenset[str] = frozenset({"SQLEditor", "Insight"})
+
SkipReason = Literal[
"flag_off",
"below_floor",
"api_key",
+ "mcp",
+ "kind_not_analyzed",
+ "sql_without_surface",
"no_principal",
"no_clickhouse_query",
"not_cacheable",
@@ -71,16 +108,22 @@ SkipReason = Literal[
"rate_limited",
"slot_exists",
"nothing_to_analyze",
- "too_large",
+ "print_failed",
"enqueue_failed",
]
def _is_mcp_run() -> bool:
- """An MCP agent authenticates with a personal API key, but it does read the findings in the
- block above its results, so the skip for API callers with nowhere to read advice leaves it
- out."""
- return get_query_tag_value("feature") == Feature.MCP
+ """Whether an MCP agent made the run. A PostHog AI tool the MCP server invokes carries the
+ feature. A call the server proxies to the query endpoint carries the source the request
+ middleware set, whichever key or token the agent authenticates with."""
+ return get_query_tag_value("feature") == Feature.MCP or get_query_tag_value("source") == EventSource.MCP
+
+
+def _sql_run_has_surface(insight_id: int | None, dashboard_id: int | None) -> bool:
+ if insight_id or dashboard_id:
+ return True
+ return get_query_tag_value("scene") in _SQL_SCENES_WITH_ADVICE
def is_analyzable_principal(user: object) -> TypeGuard[User]:
@@ -108,14 +151,29 @@ def maybe_trigger_query_scan(
if flag is None or stats is None:
return "flag_off"
- duration_ms = round(stats.duration_ms)
+ # A lookup a runner made on the way to its real query, such as the project's first event for
+ # an All time range, is not the query the person wrote, so it neither counts toward the floor
+ # nor gets analyzed in the query's place. The totals cover raw lookups too, which never reach
+ # the executor and so are never recorded as executions.
+ executions = [execution for execution in stats.executions if execution.lookup is None]
+ rows_read = max(0, stats.rows_read - stats.lookup_rows_read)
+ duration_ms = max(0, round(stats.duration_ms - stats.lookup_duration_ms))
# The floor leaves alone the runs nobody minded. Nobody gets a result from a run ClickHouse
# stopped, however fast it died, so a stopped run is analyzed at any duration.
if duration_ms < flag.floor_ms and not killed:
return "below_floor"
- if is_api_key_access_method(get_query_tag_value("access_method")) and not _is_mcp_run():
+ if _is_mcp_run():
+ # Nothing hands an agent the advice, so the analysis would only cost.
+ return "mcp"
+ if is_api_key_access_method(get_query_tag_value("access_method")):
# An API caller has no surface to read the advice on, so the analysis would only cost.
return "api_key"
+ kind = getattr(query, "kind", None)
+ query_kind = str(kind) if kind is not None else None
+ if query_kind not in _KINDS_A_PERSON_BUILDS:
+ return "kind_not_analyzed"
+ if query_kind == SQL_QUERY_KIND and not _sql_run_has_surface(insight_id, dashboard_id):
+ return "sql_without_surface"
if getattr(query, "connectionId", None):
# A direct connection reads the external warehouse instead of ClickHouse, so the job
# would park a pending slot for an analysis that cannot happen.
@@ -130,20 +188,17 @@ def maybe_trigger_query_scan(
# Another slow run of the same query claimed the slot between the read above and here.
return "slot_exists"
- executions = _print_executions(stats)
- if isinstance(executions, str):
+ printed = _print_executions(executions)
+ if isinstance(printed, str):
# A selected execution could not be shipped, so analyzing the rest would advise on a run the
# job never saw whole.
clear_slot(team_id, cache_key, thresholds=flag.thresholds_fingerprint)
- return executions
- if not executions:
+ return printed
+ if not printed:
# The run had no executions to print: it bypassed the executor, or fanned out into none.
clear_slot(team_id, cache_key, thresholds=flag.thresholds_fingerprint)
return "nothing_to_analyze"
- kind = getattr(query, "kind", None)
- query_kind = str(kind) if kind is not None else None
-
# A module-level import would close the runner, trigger, task, job, runner cycle.
from posthog.tasks.query_scan import analyze_query_scan # noqa: PLC0415
@@ -151,8 +206,8 @@ def maybe_trigger_query_scan(
analyze_query_scan.delay(
team_id=team_id,
cache_key=cache_key,
- executions=executions,
- rows_read=stats.rows_read,
+ executions=printed,
+ rows_read=rows_read,
duration_ms=duration_ms,
trigger=trigger,
insight_id=insight_id,
@@ -162,7 +217,9 @@ def maybe_trigger_query_scan(
query_kind=query_kind,
open_filters_placeholder=_open_filters_placeholder(query),
all_time=_all_time(query),
+ dashboard_all_time=get_query_tag_value("dashboard_all_time") is True,
all_history_by_design=_reads_all_history_by_design(query),
+ all_events_by_design=_reads_all_events_by_design(query),
)
except Exception:
# The broker can be down while ClickHouse is fine, and the result is not cached yet, so
@@ -174,13 +231,13 @@ def maybe_trigger_query_scan(
return None
-def _print_executions(stats: QueryStats) -> list[dict[str, Any]] | SkipReason:
+def _print_executions(executions: list[RecordedExecution]) -> list[dict[str, Any]] | SkipReason:
"""Print the heaviest executions for the job to EXPLAIN: each with its subqueries stubbed, and
each subquery on its own. The skip reason when any of the heaviest could not be shipped, so the
job never analyzes part of a run and advises as if it saw the whole. An empty list means the run
carried no executions to print.
"""
- heaviest = sorted(stats.executions, key=lambda execution: execution.rows_read, reverse=True)[:MAX_EXECUTIONS]
+ heaviest = sorted(executions, key=lambda execution: execution.rows_read, reverse=True)[:MAX_EXECUTIONS]
printed: list[dict[str, Any]] = []
subquery_budget = MAX_SUBQUERIES
for execution in heaviest:
@@ -199,11 +256,28 @@ def _print_execution(execution: RecordedExecution, subquery_budget: int) -> dict
context = copy.copy(execution.context)
context.values = {}
stub = stub_in_subqueries(execution.tree)
+ # A setting in the SQL overrides the one the job passes, so the EXPLAIN's time limit goes here.
+ settings = (
+ execution.settings.model_copy(update={"max_execution_time": EXPLAIN_MAX_SECONDS})
+ if execution.settings is not None
+ else None
+ )
+ # Each plan is judged on the reads it holds: a subquery's on its own, the outer query's
+ # without any of them. The tree is the run's, so the subqueries are the nodes inside it.
+ subquery_reads = [find_events_reads(subquery) for subquery in stub.subqueries]
+ in_a_subquery = {id(read.select) for reads in subquery_reads for read in reads}
+ outer_reads = [read for read in find_events_reads(execution.tree) if id(read.select) not in in_a_subquery]
entry = {
- "stubbed_sql": print_prepared_ast(stub.stubbed, context, dialect="clickhouse"),
+ "stubbed_sql": print_prepared_ast(stub.stubbed, context, dialect="clickhouse", settings=settings),
"subqueries": [
- print_prepared_ast(stub_in_subqueries(subquery).stubbed, context, dialect="clickhouse")
- for subquery in stub.subqueries[: max(subquery_budget, 0)]
+ {
+ "sql": print_prepared_ast(
+ stub_in_subqueries(subquery).stubbed, context, dialect="clickhouse", settings=settings
+ ),
+ "event_filter": _event_filter_verdict(execution.tree, reads),
+ "tree": _tree_facts_payload(execution.tree, reads),
+ }
+ for subquery, reads in zip(stub.subqueries[: max(subquery_budget, 0)], subquery_reads)
],
# The parameter values travel as they are: Celery's JSON serializer round-trips the
# datetimes, dates, UUIDs and decimals among them.
@@ -211,35 +285,49 @@ def _print_execution(execution: RecordedExecution, subquery_budget: int) -> dict
"rows_read": execution.rows_read,
# The plan says whether ClickHouse pruned on `event`; the tree says why it could not.
# Classify here, where the prepared tree is held; the job folds it into the plan.
- "event_filter": _event_filter_verdict(execution.tree),
+ "event_filter": _event_filter_verdict(execution.tree, outer_reads),
+ "tree": _tree_facts_payload(execution.tree, outer_reads),
}
if any(key.endswith("_sensitive") for key in context.values):
# The warehouse stub runs before the print, so this catches any other credential or access list.
return "sensitive_values"
- if len(json.dumps(entry, default=str).encode("utf-8")) > MAX_EXECUTION_BYTES:
- return "too_large"
return entry
except Exception:
# A tree that will not print is one the job could not EXPLAIN either. Dropping it drops the
# run's analysis, never the query result the person already waited for.
logger.warning("query_scan_print_failed", exc_info=True)
- return "too_large"
+ return "print_failed"
-def _event_filter_verdict(tree: ast.Expr) -> dict[str, str | None] | None:
+def _event_filter_verdict(tree: ast.Expr, reads: list[EventsRead]) -> dict[str, str | bool | None] | None:
"""The tree's event-filter classification, JSON-safe, for the job to combine with the plan.
A classifier failure ships None rather than dropping the execution, because the plan-only
fallback still produces a finding. Reads that disagree ship None for the same reason.
"""
try:
- outcome = classify_event_filter(tree)
+ outcome = classify_event_filter(tree, reads)
except Exception:
logger.warning("query_scan_classify_failed", exc_info=True)
return None
if outcome is None:
return None
- return {"classification": outcome.classification, "reason": outcome.reason}
+ return {
+ "classification": outcome.classification,
+ "reason": outcome.reason,
+ "hidden_from_plan": outcome.hidden_from_plan,
+ }
+
+
+def _tree_facts_payload(tree: ast.Expr, reads: list[EventsRead]) -> dict[str, Any] | None:
+ """What the tree says about its events reads, JSON-safe. A failure ships None rather than
+ dropping the execution: the plan alone still yields a finding, with the plain wording."""
+ try:
+ facts = tree_facts(tree, reads)
+ except Exception:
+ logger.warning("query_scan_tree_facts_failed", exc_info=True)
+ return None
+ return facts.to_payload() if facts is not None else None
def _source(query: BaseModel) -> BaseModel:
@@ -271,6 +359,35 @@ def _reads_all_history_by_design(query: BaseModel) -> bool:
return getattr(retention_filter, "retentionType", None) == RetentionType.RETENTION_FIRST_TIME
+def _reads_all_events_by_design(query: BaseModel) -> bool:
+ """Whether the insight has to read every event whatever its series: an active-user, unique-session
+ or lifecycle count on All events counts people over whatever they did, and a breakdown by event
+ name is a question about the set of events itself. Picking events would change the answer.
+ """
+ source = _source(query)
+ series = getattr(source, "series", None) or []
+ all_events = [item for item in series if isinstance(item, EventsNode) and item.event is None]
+ if not all_events:
+ return False
+ if any(getattr(item, "math", None) in _ANY_EVENT_MATHS for item in all_events):
+ return True
+ if isinstance(source, LifecycleQuery):
+ return True
+ breakdown_filter = getattr(source, "breakdownFilter", None)
+ if breakdown_filter is None:
+ return False
+ if (
+ getattr(breakdown_filter, "breakdown_type", None) == BreakdownType.EVENT_METADATA
+ and getattr(breakdown_filter, "breakdown", None) == "event"
+ ):
+ return True
+ return any(
+ getattr(breakdown, "type", None) == BreakdownType.EVENT_METADATA
+ and getattr(breakdown, "property", None) == "event"
+ for breakdown in getattr(breakdown_filter, "breakdowns", None) or []
+ )
+
+
def _open_filters_placeholder(query: BaseModel) -> bool:
"""Whether a HogQLQuery asks for a date range through ``{filters}`` and nobody supplied a start
date. Only the predicate forms count: ``{filters.interval(...)}`` and ``{filters.breakdown(...)}``
diff --git a/posthog/schema.py b/posthog/schema.py
index 61a6310ddd05..4651730c4f35 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -233,7 +233,7 @@ from posthog.schema_enums import (
PropertyType as PropertyType,
QueryIndexUsage as QueryIndexUsage,
QueryScanFindingKind as QueryScanFindingKind,
- QueryScanFindingReason as QueryScanFindingReason,
+ QueryScanFixLocation as QueryScanFixLocation,
QuickFilterContext as QuickFilterContext,
QuickFilterType as QuickFilterType,
RecordingOrder as RecordingOrder,
@@ -2678,13 +2678,35 @@ class QueryScanWarning(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ actionable: bool = Field(
+ ...,
+ description=(
+ "Whether the person can change the query so it reads less and still answers"
+ ' the same question. Surfaces show the full advice and "Fix with AI" only'
+ " when a finding is actionable."
+ ),
+ )
+ by_design: bool | None = Field(
+ default=None,
+ description=(
+ "True when the query reads this much on purpose, so reading less would change the answer. Absent means no."
+ ),
+ )
+ cause: str | None = Field(
+ default=None,
+ description=(
+ "A label for what in the query text kept the read wide, such as `in_or`."
+ " Only analytics and the assistant read it, and the labels can change."
+ ),
+ )
evidence: str | None = Field(default=None, description="The one fact the finding rests on.")
fix: str = Field(..., description='What "Fix with AI" and the assistant are told to do.')
+ fix_location: QueryScanFixLocation | None = Field(
+ default=None,
+ description="Where the change goes. Absent means the query itself.",
+ )
kind: QueryScanFindingKind
message: str = Field(..., description="Shown to the person: what happened and what to do.")
- reason: QueryScanFindingReason | None = Field(
- default=None, description="Only with `no_event_filter` and `no_start_date`."
- )
class QueryTiming(BaseModel):
@@ -6818,7 +6840,10 @@ class QueryScanAnalysis(BaseModel):
" finding can be fixed in the query."
),
)
- findings: list[QueryScanWarning] = Field(..., description="Empty when the analysis found nothing to fix.")
+ findings: list[QueryScanWarning] = Field(
+ ...,
+ description=("Every finding, fixable or not. Empty when the analysis found none."),
+ )
project_share: float | None = Field(
default=None,
description="How much of all the project's events the query read, 0 to 1.",
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index d18f6d795215..ff071d9ed8a6 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2555,13 +2555,12 @@ class QueryScanFindingKind(StrEnum):
PERSONS_JOIN = "persons_join"
-class QueryScanFindingReason(StrEnum):
- IN_OR = "in_or"
- WRAPPED = "wrapped"
- NEGATED = "negated"
- DYNAMIC = "dynamic"
- NOT_PRUNED = "not_pruned"
- FILTERS = "filters"
+class QueryScanFixLocation(StrEnum):
+ QUERY = "query"
+ SUBQUERY = "subquery"
+ VIEW = "view"
+ INSIGHT_DATE_RANGE = "insight_date_range"
+ DASHBOARD_DATE_FILTER = "dashboard_date_filter"
class QuickFilterContext(StrEnum):
diff --git a/posthog/tasks/query_scan.py b/posthog/tasks/query_scan.py
index e57c72c64a64..17b3656096a2 100644
--- a/posthog/tasks/query_scan.py
+++ b/posthog/tasks/query_scan.py
@@ -39,6 +39,8 @@ def analyze_query_scan(
error_type: str | None = None,
all_time: bool = False,
all_history_by_design: bool = False,
+ all_events_by_design: bool = False,
+ dashboard_all_time: bool = False,
) -> None:
team = Team.objects.select_related("organization").filter(pk=team_id).first()
if team is None:
@@ -59,7 +61,9 @@ def analyze_query_scan(
killed=killed,
error_type=error_type,
all_time=all_time,
+ dashboard_all_time=dashboard_all_time,
all_history_by_design=all_history_by_design,
+ all_events_by_design=all_events_by_design,
)
)
except SoftTimeLimitExceeded:
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index cc6ca788c34b..5f450b2b7039 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1601,6 +1601,16 @@ export interface ClickhouseQueryProgressApi {
time_elapsed: number
}
+export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
+
+export const QueryScanFixLocationApi = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+} as const
+
export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
export const QueryScanFindingKindApi = {
@@ -1609,33 +1619,28 @@ export const QueryScanFindingKindApi = {
PersonsJoin: 'persons_join',
} as const
-export type QueryScanFindingReasonApi = (typeof QueryScanFindingReasonApi)[keyof typeof QueryScanFindingReasonApi]
-
-export const QueryScanFindingReasonApi = {
- InOr: 'in_or',
- Wrapped: 'wrapped',
- Negated: 'negated',
- Dynamic: 'dynamic',
- NotPruned: 'not_pruned',
- Filters: 'filters',
-} as const
-
export interface QueryScanWarningApi {
+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
+ actionable: boolean
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null
+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
+ cause?: string | null
/** The one fact the finding rests on. */
evidence?: string | null
/** What "Fix with AI" and the assistant are told to do. */
fix: string
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocationApi | null
kind: QueryScanFindingKindApi
/** Shown to the person: what happened and what to do. */
message: string
- /** Only with `no_event_filter` and `no_start_date`. */
- reason?: QueryScanFindingReasonApi | null
}
export interface QueryScanAnalysisApi {
/** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
assistant_prompt?: string | null
- /** Empty when the analysis found nothing to fix. */
+ /** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarningApi[]
/** How much of all the project's events the query read, 0 to 1. */
project_share?: number | null
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 7ea0230bac57..580abbcf9149 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2004,6 +2004,16 @@ export interface ClickhouseQueryProgressApi {
time_elapsed: number
}
+export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
+
+export const QueryScanFixLocationApi = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+} as const
+
export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
export const QueryScanFindingKindApi = {
@@ -2012,33 +2022,28 @@ export const QueryScanFindingKindApi = {
PersonsJoin: 'persons_join',
} as const
-export type QueryScanFindingReasonApi = (typeof QueryScanFindingReasonApi)[keyof typeof QueryScanFindingReasonApi]
-
-export const QueryScanFindingReasonApi = {
- InOr: 'in_or',
- Wrapped: 'wrapped',
- Negated: 'negated',
- Dynamic: 'dynamic',
- NotPruned: 'not_pruned',
- Filters: 'filters',
-} as const
-
export interface QueryScanWarningApi {
+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
+ actionable: boolean
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null
+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
+ cause?: string | null
/** The one fact the finding rests on. */
evidence?: string | null
/** What "Fix with AI" and the assistant are told to do. */
fix: string
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocationApi | null
kind: QueryScanFindingKindApi
/** Shown to the person: what happened and what to do. */
message: string
- /** Only with `no_event_filter` and `no_start_date`. */
- reason?: QueryScanFindingReasonApi | null
}
export interface QueryScanAnalysisApi {
/** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
assistant_prompt?: string | null
- /** Empty when the analysis found nothing to fix. */
+ /** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarningApi[]
/** How much of all the project's events the query read, 0 to 1. */
project_share?: number | null
diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.ts
index 108b75329175..77b67591a162 100644
--- a/products/endpoints/frontend/generated/api.schemas.ts
+++ b/products/endpoints/frontend/generated/api.schemas.ts
@@ -1012,6 +1012,16 @@ export interface ClickhouseQueryProgressApi {
time_elapsed: number
}
+export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
+
+export const QueryScanFixLocationApi = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+} as const
+
export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
export const QueryScanFindingKindApi = {
@@ -1020,33 +1030,28 @@ export const QueryScanFindingKindApi = {
PersonsJoin: 'persons_join',
} as const
-export type QueryScanFindingReasonApi = (typeof QueryScanFindingReasonApi)[keyof typeof QueryScanFindingReasonApi]
-
-export const QueryScanFindingReasonApi = {
- InOr: 'in_or',
- Wrapped: 'wrapped',
- Negated: 'negated',
- Dynamic: 'dynamic',
- NotPruned: 'not_pruned',
- Filters: 'filters',
-} as const
-
export interface QueryScanWarningApi {
+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
+ actionable: boolean
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null
+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
+ cause?: string | null
/** The one fact the finding rests on. */
evidence?: string | null
/** What "Fix with AI" and the assistant are told to do. */
fix: string
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocationApi | null
kind: QueryScanFindingKindApi
/** Shown to the person: what happened and what to do. */
message: string
- /** Only with `no_event_filter` and `no_start_date`. */
- reason?: QueryScanFindingReasonApi | null
}
export interface QueryScanAnalysisApi {
/** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
assistant_prompt?: string | null
- /** Empty when the analysis found nothing to fix. */
+ /** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarningApi[]
/** How much of all the project's events the query read, 0 to 1. */
project_share?: number | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 1e426e13a14e..8b042a1f354f 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -964,6 +964,16 @@ export interface ClickhouseQueryProgressApi {
time_elapsed: number
}
+export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
+
+export const QueryScanFixLocationApi = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+} as const
+
export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
export const QueryScanFindingKindApi = {
@@ -972,33 +982,28 @@ export const QueryScanFindingKindApi = {
PersonsJoin: 'persons_join',
} as const
-export type QueryScanFindingReasonApi = (typeof QueryScanFindingReasonApi)[keyof typeof QueryScanFindingReasonApi]
-
-export const QueryScanFindingReasonApi = {
- InOr: 'in_or',
- Wrapped: 'wrapped',
- Negated: 'negated',
- Dynamic: 'dynamic',
- NotPruned: 'not_pruned',
- Filters: 'filters',
-} as const
-
export interface QueryScanWarningApi {
+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
+ actionable: boolean
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null
+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
+ cause?: string | null
/** The one fact the finding rests on. */
evidence?: string | null
/** What "Fix with AI" and the assistant are told to do. */
fix: string
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocationApi | null
kind: QueryScanFindingKindApi
/** Shown to the person: what happened and what to do. */
message: string
- /** Only with `no_event_filter` and `no_start_date`. */
- reason?: QueryScanFindingReasonApi | null
}
export interface QueryScanAnalysisApi {
/** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
assistant_prompt?: string | null
- /** Empty when the analysis found nothing to fix. */
+ /** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarningApi[]
/** How much of all the project's events the query read, 0 to 1. */
project_share?: number | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8a453aced875..f3b8c6380e03 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1398,6 +1398,17 @@ export namespace Schemas {
time_elapsed: number;
}
+ export type QueryScanFixLocation = typeof QueryScanFixLocation[keyof typeof QueryScanFixLocation];
+
+
+ export const QueryScanFixLocation = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+ } as const;
+
export type QueryScanFindingKind = typeof QueryScanFindingKind[keyof typeof QueryScanFindingKind];
@@ -1407,34 +1418,28 @@ export namespace Schemas {
PersonsJoin: 'persons_join',
} as const;
- export type QueryScanFindingReason = typeof QueryScanFindingReason[keyof typeof QueryScanFindingReason];
-
-
- export const QueryScanFindingReason = {
- InOr: 'in_or',
- Wrapped: 'wrapped',
- Negated: 'negated',
- Dynamic: 'dynamic',
- NotPruned: 'not_pruned',
- Filters: 'filters',
- } as const;
-
export interface QueryScanWarning {
+ /** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
+ actionable: boolean;
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null;
+ /** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
+ cause?: string | null;
/** The one fact the finding rests on. */
evidence?: string | null;
/** What "Fix with AI" and the assistant are told to do. */
fix: string;
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocation | null;
kind: QueryScanFindingKind;
/** Shown to the person: what happened and what to do. */
message: string;
- /** Only with `no_event_filter` and `no_start_date`. */
- reason?: QueryScanFindingReason | null;
}
export interface QueryScanAnalysis {
/** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
assistant_prompt?: string | null;
- /** Empty when the analysis found nothing to fix. */
+ /** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarning[];
/** How much of all the project's events the query read, 0 to 1. */
project_share?: number | null;