:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(query-scan): explain why a slow query was slow and how to fix it (#99428)
Sandy Spicerc568ba021bcf
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 284748c6a2c8..41cd4206e9b5 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -29,8 +29,8 @@ import {AggregatedSpanRow,AnyResponseType,DashboardFilter,- DataWarehouseManagedViewsetKind,DatabaseSerializedFieldType,+ DataWarehouseManagedViewsetKind,DomainConnectProviderName,EndpointLastExecutionTimesRequest,EndpointRequest,@@ -54,6 +54,7 @@ import {Node,NodeKind,QueryLogTags,+ QueryScanResponse,QuerySchema,QueryStatusResponse,RecordingsQuery,@@ -1746,6 +1747,10 @@ export class ApiRequest {return this.query(teamId).addPathComponent(queryId).addPathComponent('log')}+ public queryScan(cacheKey: string, teamId?: TeamType['id']): ApiRequest {+ return this.query(teamId).addPathComponent('scan').addPathComponent(cacheKey)+ }+public queryCancel(clientQueryId: string, teamId?: TeamType['id']): ApiRequest {return this.query(teamId).addPathComponent(clientQueryId)}@@ -6366,6 +6371,12 @@ const api = {},},+ queryScan: {+ async get(cacheKey: string): Promise<QueryScanResponse> {+ return await new ApiRequest().queryScan(cacheKey).get()+ },+ },+personalApiKeys: {async list(): Promise<PersonalAPIKeyType[]> {return await new ApiRequest().personalApiKeys().get()diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsxindex 14c3c3b2bc00..2fbf3b369f92 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx@@ -21,6 +21,7 @@ import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { LemonMenu } from 'lib/lemon-ui/LemonMenu'import { LemonTableLoader } from 'lib/lemon-ui/LemonTable/LemonTableLoader'+import { LemonTag } from 'lib/lemon-ui/LemonTag'import { Link } from 'lib/lemon-ui/Link'import { Popover } from 'lib/lemon-ui/Popover'import { Spinner } from 'lib/lemon-ui/Spinner'@@ -46,6 +47,7 @@ import { urls } from 'scenes/urls'import { dashboardsModel } from '~/models/dashboardsModel'import { insightsModel } from '~/models/insightsModel'+import { QueryScanTileTooltip } from '~/queries/nodes/DataNode/QueryScanTileTooltip'import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'import { Node, ProductKey } from '~/queries/schema/schema-general'import { isDataVisualizationNode, isDataVisualizationNodeWithHogQLQuery } from '~/queries/utils'@@ -244,6 +246,15 @@ export function InsightMeta({): true+ // 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} />+ ) : null+const showDashboardAlertsMenuItem = isUsedAsDashboardTile && !!dashboardId && !!insight.id && canViewInsightconst canCreateAlertForInsight = areAlertsSupportedForInsight(query, {metricsAlertsEnabled: !!featureFlags[FEATURE_FLAGS.METRICS],@@ -460,6 +471,7 @@ export function InsightMeta({compact={showCompactTile}showDescription={tile?.show_description !== false}dataRetentionWarning={dataRetentionWarning}+ queryScanTooltip={queryScanTooltip}infoPopover={showCompactTile ? (<CompactInfoPopover@@ -790,6 +802,7 @@ export function InsightMetaContent({showDescription,infoPopover,dataRetentionWarning,+ queryScanTooltip,}: {title: stringfallbackTitle?: string@@ -802,15 +815,28 @@ export function InsightMetaContent({showDescription?: booleaninfoPopover?: JSX.Element | nulldataRetentionWarning?: string | null+ queryScanTooltip?: JSX.Element | null}): JSX.Element {const dataRetentionIndicator = dataRetentionWarning ? (<Tooltip title={dataRetentionWarning}><IconWarning className="ml-1.5 text-base shrink-0 text-warning" /></Tooltip>) : 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>+ </Tooltip>+ ) : nullconst titleContent = (<>- <span className={clsx('text-primary', (infoPopover || dataRetentionIndicator) && 'truncate')}>+ <span+ className={clsx(+ 'text-primary',+ (infoPopover || dataRetentionIndicator || queryScanIndicator) && 'truncate'+ )}+ >{title || <i>{fallbackTitle || 'Untitled'}</i>}</span>{(loading || loadingQueued) && (@@ -826,7 +852,10 @@ export function InsightMetaContent({<h4title={!compact ? title : undefined}data-attr="insight-card-title"- className={clsx((infoPopover || dataRetentionIndicator) && 'inline-flex items-center overflow-visible')}+ className={clsx(+ (infoPopover || dataRetentionIndicator || queryScanIndicator) &&+ 'inline-flex items-center overflow-visible'+ )}>{link ? (<Link to={link} className="max-w-full truncate">@@ -836,6 +865,7 @@ export function InsightMetaContent({titleContent)}{dataRetentionIndicator}+ {queryScanIndicator}{infoPopover}</h4>)diff --git a/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsx b/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsxnew file mode 100644index 000000000000..fcb5e5dc5532--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/QueryScanBanner.test.tsx@@ -0,0 +1,70 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { Provider } from 'kea'++import { QueryScanSummary, QueryScanWarning } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { QueryScanBanner } from './QueryScanBanner'++const SUMMARY: QueryScanSummary = {+ rows_read: 8_400_000_000,+ duration_ms: 19_000,+ analysis_requested: true,+}++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.',+}++const INSIGHT_SIDE_FINDING: QueryScanWarning = {+ ...FINDING,+ kind: 'no_start_date',+ reason: 'filters',+ message: 'No date range is set for this insight or dashboard.',+ fix: 'Set a date range on the insight or the dashboard.',+}++describe('QueryScanBanner', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => cleanup())++ it.each([+ { label: 'nothing to advise', findings: [], assistantPrompt: null, advice: null, 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,+ fixer: true,+ },+ // The backend sends no prompt for a finding fixed on the insight, so there is nothing to hand the assistant.+ {+ label: 'a finding fixed on the insight',+ findings: [INSIGHT_SIDE_FINDING],+ assistantPrompt: null,+ advice: INSIGHT_SIDE_FINDING.message,+ fixer: false,+ },+ ])('keeps the stat line and shows $label', ({ findings, assistantPrompt, advice, fixer }) => {+ render(+ <Provider>+ <QueryScanBanner+ queryScan={{ summary: SUMMARY, findings, cacheKey: 'cache-key', assistantPrompt }}+ onFixWithAI={jest.fn()}+ />+ </Provider>+ )++ 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(!!screen.queryByText('Fix with AI')).toBe(fixer)+ })+})diff --git a/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsx b/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsxnew file mode 100644index 000000000000..d9e298600248--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/QueryScanBanner.tsx@@ -0,0 +1,48 @@+import clsx from 'clsx'++import { IconSparkles } from '@posthog/icons'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'++import { QueryScanState, queryScanStatLine } from './queryScan'+import { QueryScanFindingList } from './QueryScanFindingList'++export interface QueryScanBannerProps {+ queryScan: QueryScanState | null+ /** Opens the assistant on the findings. Left out where there is no editor to write into. */+ onFixWithAI?: () => void+ className?: string+}++export function QueryScanBanner({ queryScan, onFixWithAI, className }: QueryScanBannerProps): JSX.Element | null {+ if (!queryScan) {+ return null+ }++ const { summary, findings, assistantPrompt } = queryScan+ const showFindings = findings.length > 0++ 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 && (+ <LemonBanner type="warning">+ <QueryScanFindingList findings={findings} />+ {onFixWithAI && assistantPrompt && (+ <LemonButton+ className="mt-2"+ type="secondary"+ size="small"+ icon={<IconSparkles />}+ onClick={onFixWithAI}+ data-attr="query-scan-fix-with-ai"+ >+ Fix with AI+ </LemonButton>+ )}+ </LemonBanner>+ )}+ </div>+ )+}diff --git a/frontend/src/queries/nodes/DataNode/QueryScanFindingList.tsx b/frontend/src/queries/nodes/DataNode/QueryScanFindingList.tsxnew file mode 100644index 000000000000..d4aad3c780ec--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/QueryScanFindingList.tsx@@ -0,0 +1,24 @@+import { QueryScanWarning } from '~/queries/schema/schema-general'++/** A finding marks SQL with backticks, the way the assistant reads it. */+function withInlineCode(message: string): JSX.Element {+ return (+ <>+ {message+ .split('`')+ .map((part, index) =>+ index % 2 === 1 ? <code key={index}>{part}</code> : <span key={index}>{part}</span>+ )}+ </>+ )+}++export function QueryScanFindingList({ findings }: { findings: QueryScanWarning[] }): JSX.Element {+ return (+ <ul className="list-disc pl-5">+ {findings.map((finding, index) => (+ <li key={`${finding.kind}-${index}`}>{withInlineCode(finding.message)}</li>+ ))}+ </ul>+ )+}diff --git a/frontend/src/queries/nodes/DataNode/QueryScanTileTooltip.tsx b/frontend/src/queries/nodes/DataNode/QueryScanTileTooltip.tsxnew file mode 100644index 000000000000..a1bcef1c4d4a--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/QueryScanTileTooltip.tsx@@ -0,0 +1,18 @@+import { QueryScanSummary, QueryScanWarning } from '~/queries/schema/schema-general'++import { queryScanTileStatLine } from './queryScan'+import { QueryScanFindingList } from './QueryScanFindingList'++export interface QueryScanTileTooltipProps {+ summary: QueryScanSummary+ findings: QueryScanWarning[]+}++export function QueryScanTileTooltip({ summary, findings }: QueryScanTileTooltipProps): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <span>{queryScanTileStatLine(summary)}</span>+ <QueryScanFindingList findings={findings} />+ </div>+ )+}diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.tsindex e86d0e007ec3..68e57098f8af 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts@@ -1,11 +1,42 @@import { expectLogic, partial } from 'kea-test-utils'-import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { useMocks } from '~/mocks/jest'+import {+ QUERY_SCAN_POLL_DEADLINE_MS,+ QUERY_SCAN_POLL_DELAYS_MS,+ dataNodeLogic,+} from '~/queries/nodes/DataNode/dataNodeLogic'import { performQuery } from '~/queries/query'import { DashboardFilter, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'import { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'+const SCAN_ENDPOINT = '/api/environments/:team_id/query/scan/:cache_key/'+// The scan endpoint answers with an empty body while the job runs.+const PENDING_SCAN = {}+const DONE_SCAN = {+ analysis: {+ assistant_prompt: 'Help me get what this query is trying to find, as fast as possible.',+ findings: [+ {+ kind: 'no_event_filter',+ message: 'This query read every event in its date range.',+ fix: 'Add an event filter.',+ },+ ],+ range_share: 0.42,+ project_share: 0.1,+ },+}++function pendingScanResponse(cacheKey = 'cache-key'): Record<string, unknown> {+ return {+ results: [],+ cache_key: cacheKey,+ query_scan: { rows_read: 10, duration_ms: 2000, analysis_requested: true },+ }+}+jest.mock('~/queries/query', () => {return {__esModules: true,@@ -785,4 +816,141 @@ describe('dataNodeLogic', () => {undefined)})++ const mountWithPendingScan = (): void => {+ mockedQuery.mockResolvedValueOnce(pendingScanResponse())+ logic = dataNodeLogic({+ key: testUniqueKey,+ query: setLatestVersionsOnQuery({ kind: NodeKind.EventsQuery, select: ['*'] }),+ })+ logic.mount()+ }++ it('polls a slow run on a backoff and folds the finished scan into the response', async () => {+ jest.useFakeTimers()+ try {+ let scanCalls = 0+ useMocks({+ get: {+ [SCAN_ENDPOINT]: () => {+ scanCalls += 1+ return [200, scanCalls === 1 ? PENDING_SCAN : DONE_SCAN]+ },+ },+ })+ mountWithPendingScan()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.queryScan?.summary.analysis).toBeUndefined()++ await jest.advanceTimersByTimeAsync(QUERY_SCAN_POLL_DELAYS_MS[0])+ expect(scanCalls).toBe(1)+ expect(logic.values.queryScan?.summary.analysis).toBeUndefined()++ await jest.advanceTimersByTimeAsync(QUERY_SCAN_POLL_DELAYS_MS[1])+ expect(scanCalls).toBe(2)+ expect(logic.values.queryScan?.summary.analysis).not.toBeUndefined()+ expect(logic.values.queryScan?.summary.analysis?.range_share).toBe(0.42)+ expect(logic.values.queryScan?.findings).toHaveLength(1)+ expect(logic.values.queryScan?.assistantPrompt).toBe(DONE_SCAN.analysis.assistant_prompt)++ // The analysis is done, so no more asks go out.+ await jest.advanceTimersByTimeAsync(60000)+ expect(scanCalls).toBe(2)+ } finally {+ jest.useRealTimers()+ }+ })++ it('polls the analysis of a stopped run off its error', async () => {+ jest.useFakeTimers()+ try {+ let scanCalls = 0+ useMocks({+ get: {+ [SCAN_ENDPOINT]: () => {+ scanCalls += 1+ return [200, DONE_SCAN]+ },+ },+ })+ // A stopped run has no response, so the pointer to its analysis rides on the error.+ mockedQuery.mockRejectedValueOnce(+ Object.assign(new Error('Query was cancelled'), {+ data: {+ extra: {+ cache_key: 'cache-key',+ query_scan: { rows_read: 10, duration_ms: 2000, killed: true, analysis_requested: true },+ },+ },+ })+ )+ logic = dataNodeLogic({+ key: testUniqueKey,+ query: setLatestVersionsOnQuery({ kind: NodeKind.EventsQuery, select: ['*'] }),+ })+ logic.mount()++ await jest.advanceTimersByTimeAsync(QUERY_SCAN_POLL_DELAYS_MS[0])+ expect(scanCalls).toBe(1)+ expect(logic.values.queryScan?.summary.killed).toBe(true)+ expect(logic.values.queryScan?.findings).toHaveLength(1)+ expect(logic.values.queryScan?.assistantPrompt).toBe(DONE_SCAN.analysis.assistant_prompt)++ await jest.advanceTimersByTimeAsync(60000)+ expect(scanCalls).toBe(1)+ } finally {+ jest.useRealTimers()+ }+ })++ it('stops polling when the scan endpoint 404s', async () => {+ jest.useFakeTimers()+ try {+ let scanCalls = 0+ useMocks({+ get: {+ [SCAN_ENDPOINT]: () => {+ scanCalls += 1+ return [404, {}]+ },+ },+ })+ mountWithPendingScan()+ await jest.advanceTimersByTimeAsync(2000)+ expect(scanCalls).toBe(1)++ // A 404 is what a dead job looks like once its pending slot expires, so the poll ends.+ await jest.advanceTimersByTimeAsync(120000)+ expect(scanCalls).toBe(1)+ expect(logic.values.queryScan?.summary.analysis).toBeUndefined()+ } finally {+ jest.useRealTimers()+ }+ })++ it('stops polling once the run is too old to wait for', async () => {+ jest.useFakeTimers()+ try {+ let scanCalls = 0+ useMocks({+ get: {+ [SCAN_ENDPOINT]: () => {+ scanCalls += 1+ return [200, PENDING_SCAN]+ },+ },+ })+ mountWithPendingScan()++ await jest.advanceTimersByTimeAsync(QUERY_SCAN_POLL_DEADLINE_MS + 60000)+ const callsByDeadline = scanCalls+ // It kept asking on the repeating 30 s interval, past the fixed backoff steps.+ expect(callsByDeadline).toBeGreaterThan(QUERY_SCAN_POLL_DELAYS_MS.length)++ await jest.advanceTimersByTimeAsync(120000)+ expect(scanCalls).toBe(callsByDeadline)+ } finally {+ jest.useRealTimers()+ }+ })})diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.tsindex 39dc45fe9217..3bdb6ffd4aec 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts@@ -32,17 +32,18 @@ import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'import { DataNodeCollectionProps, dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'+import { QueryScanPollResult, QueryScanState, resolveQueryScan } from '~/queries/nodes/DataNode/queryScan'import { removeExpressionComment } from '~/queries/nodes/DataTable/utils'import { performQuery } from '~/queries/query'import {- ActorsQuery,- ActorsQueryResponse,- AnyResponseType,- DashboardFilter,AccountsQuery,AccountsQueryResponse,AccountsTableQuery,AccountsTableQueryResponse,+ ActorsQuery,+ ActorsQueryResponse,+ AnyResponseType,+ DashboardFilter,DataNode,DataVisualizationNode,ErrorTrackingQuery,@@ -60,6 +61,8 @@ import {MarketingAnalyticsTableQueryResponse,NodeKind,PersonsNode,+ QueryScanAnalysis,+ QueryScanResponse,QueryStatus,QueryTiming,RefreshType,@@ -146,6 +149,13 @@ export interface DataNodeLogicProps {export const AUTOLOAD_INTERVAL = 30000const LOAD_MORE_ROWS_LIMIT = 10000+// Backoff before each ask for a slow run's scan, holding at 30 s: the job starts with the run, so+// the early asks are close together.+export const QUERY_SCAN_POLL_DELAYS_MS = [2000, 4000, 8000, 15000, 30000]+// Stop asking this long after the run: a job that has not finished by then is not coming back, and+// its pending slot expires into a 404 around the same time.+export const QUERY_SCAN_POLL_DEADLINE_MS = 600000+// Loading and error states render the query id, so a random id per load// makes Storybook visual regression captures differ on every runconst STORYBOOK_QUERY_ID = '00000000-0000-4000-8000-000000000000'@@ -296,6 +306,8 @@ export interface dataNodeLogicValues {queryLog: HogQLQueryResponse | nullqueryLogLoading: booleanqueryLogQueryId: string | null+ queryScan: QueryScanState | null+ queryScanResult: QueryScanPollResult | nullresponse:| ErrorTrackingQueryResponse| HogQLAutocompleteResponse@@ -577,6 +589,9 @@ export interface dataNodeLogicActions {totalCount: number | nullpayload?: any}+ pollQueryScan: () => {+ value: true+ }resetLoadingTimer: () => {value: true}@@ -592,6 +607,13 @@ export interface dataNodeLogicActions {setQueryLogQueryId: (queryId: string) => {queryId: string}+ setQueryScanResult: (+ analysis: QueryScanAnalysis,+ cacheKey: string+ ) => {+ analysis: QueryScanAnalysis+ cacheKey: string+ }setResponse: (response: Exclude<AnyResponseType, undefined>) =>@@ -862,6 +884,25 @@ export interface dataNodeLogicMeta {hasActiveFilters: (query: DataNode<Record<string, any>>) => booleantotalCountQuery: (query: DataNode<Record<string, any>>) => DataNode | nullfilteredCountQuery: (query: DataNode<Record<string, any>>, hasActiveFilters: boolean) => DataNode | null+ queryScan: (+ response:+ | ErrorTrackingQueryResponse+ | HogQLAutocompleteResponse+ | HogQLMetadataResponse+ | HogQLQueryResponse<any[]>+ | HogQueryResponse+ | LogAttributesQueryResponse+ | LogValuesQueryResponse+ | MetricsQueryResponse+ | Record<string, any>+ | SessionsQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse+ | TraceSpansQueryResponse+ | null,+ responseErrorObject: Record<string, any> | null,+ queryScanResult: QueryScanPollResult | null+ ) => QueryScanState | null}}@@ -959,6 +1000,8 @@ export const dataNodeLogic = kea<dataNodeLogicType>([resetLoadingTimer: true,setQueryLogQueryId: (queryId: string) => ({ queryId }),loadFilteredCount: true,+ pollQueryScan: true,+ setQueryScanResult: (analysis: QueryScanAnalysis, cacheKey: string) => ({ analysis, cacheKey }),}),loaders(({ actions, cache, values, props }) => ({response: [@@ -1321,6 +1364,13 @@ export const dataNodeLogic = kea<dataNodeLogicType>([loadDataSuccess: () => null,},],+ queryScanResult: [+ null as QueryScanPollResult | null,+ {+ loadData: () => null,+ setQueryScanResult: (_, { analysis, cacheKey }) => ({ cacheKey, analysis }),+ },+ ],responseError: [null as string | null,{@@ -1984,6 +2034,28 @@ export const dataNodeLogic = kea<dataNodeLogicType>([return null},],+ queryScan: [+ (s) => [s.response, s.responseErrorObject, s.queryScanResult],+ (+ response:+ | ErrorTrackingQueryResponse+ | HogQLAutocompleteResponse+ | HogQLMetadataResponse+ | HogQLQueryResponse<any[]>+ | HogQueryResponse+ | LogAttributesQueryResponse+ | LogValuesQueryResponse+ | MetricsQueryResponse+ | Record<string, any>+ | SessionsQueryResponse+ | TraceSpansAggregationQueryResponse+ | TraceSpansAttributeBreakdownQueryResponse+ | TraceSpansQueryResponse+ | null,+ responseErrorObject: Record<string, any> | null,+ queryScanResult: QueryScanPollResult | null+ ): QueryScanState | null => resolveQueryScan(response, responseErrorObject, queryScanResult),+ ],})),listeners(({ actions, values, cache, props }) => ({abortAnyRunningQuery: () => {@@ -2014,9 +2086,43 @@ export const dataNodeLogic = kea<dataNodeLogicType>([if ('query' in props.query) {cache.localResults[JSON.stringify(props.query.query)] = response}+ actions.pollQueryScan()},loadDataFailure: () => {actions.collectionNodeLoadDataFailure(props.key)+ actions.pollQueryScan()+ },+ pollQueryScan: async (_, breakpoint) => {+ const scan = values.queryScan+ const cacheKey = scan?.cacheKey+ if (!scan || !cacheKey || !scan.summary.analysis_requested || scan.summary.analysis) {+ return+ }+ // The analysis lands after the response, and an error never carries one. Ask on a backoff+ // until it is stored, the run is too old to wait for, or a request fails: a 404 is what a+ // dead job looks like once its claim expires.+ const lastDelayMs = QUERY_SCAN_POLL_DELAYS_MS[QUERY_SCAN_POLL_DELAYS_MS.length - 1]+ let elapsedMs = 0+ for (let attempt = 0; ; attempt++) {+ const delayMs = QUERY_SCAN_POLL_DELAYS_MS[attempt] ?? lastDelayMs+ if (elapsedMs + delayMs > QUERY_SCAN_POLL_DEADLINE_MS) {+ return+ }+ elapsedMs += delayMs+ await breakpoint(delayMs)+ let stored: QueryScanResponse+ try {+ stored = await api.queryScan.get(cacheKey)+ } catch {+ // The analysis is advice, so a missing or failed scan leaves the run's numbers as they are.+ return+ }+ breakpoint()+ if (stored.analysis) {+ actions.setQueryScanResult(stored.analysis, cacheKey)+ return+ }+ }},loadNewDataSuccess: ({ response }) => {props.onData?.(response as Record<string, unknown> | null | undefined)diff --git a/frontend/src/queries/nodes/DataNode/queryScan.test.ts b/frontend/src/queries/nodes/DataNode/queryScan.test.tsnew file mode 100644index 000000000000..3cd5f38e3069--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/queryScan.test.ts@@ -0,0 +1,106 @@+import { QueryScanSummary, QueryScanWarning } from '~/queries/schema/schema-general'+import { DashboardTile, InsightShortId, QueryBasedInsightModel } from '~/types'++import {+ QueryScanPollResult,+ queryScanDashboardEntries,+ queryScanStatLine,+ queryScanTileStatLine,+ resolveQueryScan,+} from './queryScan'++const SUMMARY: QueryScanSummary = {+ rows_read: 8_400_000_000,+ duration_ms: 19_000,+ analysis_requested: true,+}++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.',+}++function tile(id: number, insight: Partial<QueryBasedInsightModel> | null): DashboardTile<QueryBasedInsightModel> {+ return { id, color: null, insight: insight ? (insight as QueryBasedInsightModel) : undefined }+}++function slowInsight(+ shortId: string,+ name: string,+ findings: number,+ summary: Partial<QueryScanSummary> = {}+): Partial<QueryBasedInsightModel> {+ return {+ short_id: shortId as InsightShortId,+ name,+ query_scan: { ...SUMMARY, ...summary, analysis: { findings: Array(findings).fill(FINDING) } },+ }+}++describe('queryScan', () => {+ it('reads no scan off a response that carries no summary', () => {+ expect(resolveQueryScan({ results: [] }, null, null)).toBeNull()+ })++ it('ignores a poll result for another run', () => {+ // A poll outlives the run that started it, so a result for another run must not decorate+ // this response with a share and advice measured somewhere else.+ const response = { query_scan: SUMMARY, cache_key: 'cache-key' }+ const polled: QueryScanPollResult = {+ cacheKey: 'another-cache-key',+ analysis: { findings: [FINDING], range_share: 0.9, project_share: 0.9 },+ }++ const state = resolveQueryScan(response, null, polled)++ expect(state?.summary.analysis).toBeUndefined()+ expect(state?.findings).toHaveLength(0)+ })++ it.each([+ ['a run that finished', {}, 'Read 8,400,000,000 rows in 19.0 s.'],+ [+ 'a run whose analysis measured the share of the date range it read',+ { analysis: { findings: [], range_share: 0.42 } },+ 'Read 8,400,000,000 rows in 19.0 s, about 42% of the events in this date range.',+ ],+ [+ 'a run ClickHouse stopped',+ { killed: true },+ 'ClickHouse stopped it after 19.0 s, having read 8,400,000,000 rows.',+ ],+ ] as [string, Partial<QueryScanSummary>, string][])('describes %s', (_label, summary, expected) => {+ expect(queryScanStatLine({ ...SUMMARY, ...summary })).toEqual(expected)+ })++ it.each([+ ['a run that finished', {}, 'This tile read 8,400,000,000 rows in 19.0 s on its last run.'],+ [+ 'a run ClickHouse stopped',+ { killed: true },+ "ClickHouse stopped this tile's last run after 19.0 s, having read 8,400,000,000 rows.",+ ],+ ] as [string, Partial<QueryScanSummary>, string][])('describes %s on a tile', (_label, summary, expected) => {+ expect(queryScanTileStatLine({ ...SUMMARY, ...summary })).toEqual(expected)+ })++ it('names only the insights whose last run has advice', () => {+ const entries = queryScanDashboardEntries([+ tile(1, null),+ tile(2, slowInsight('aaa', 'Active users', 2)),+ tile(3, slowInsight('bbb', 'Fast enough', 0)),+ tile(4, { short_id: 'ccc' as InsightShortId, name: 'Still analyzing', query_scan: SUMMARY }),+ tile(5, { ...slowInsight('ddd', 'Deleted', 1), 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)),+ ])++ 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 },+ ])+ })+})diff --git a/frontend/src/queries/nodes/DataNode/queryScan.ts b/frontend/src/queries/nodes/DataNode/queryScan.tsnew file mode 100644index 000000000000..b2817b4e6cba--- /dev/null+++ b/frontend/src/queries/nodes/DataNode/queryScan.ts@@ -0,0 +1,125 @@+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { QueryScanAnalysis, QueryScanSummary, QueryScanWarning } from '~/queries/schema/schema-general'+import { integer } from '~/queries/schema/type-utils'+import { DashboardTile, InsightShortId, QueryBasedInsightModel } from '~/types'++export interface QueryScanState {+ summary: QueryScanSummary+ findings: QueryScanWarning[]+ cacheKey: string | null+ /** The message "Fix with AI" sends, built by the backend. Null when nothing in the query can be fixed. */+ assistantPrompt: string | null+}++export interface QueryScanPollResult {+ cacheKey: string+ analysis: QueryScanAnalysis+}++interface ScanCarrier {+ query_scan?: QueryScanSummary+ cache_key?: string+}++function asObject(value: unknown): Record<string, unknown> | null {+ return value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : null+}++function asCarrier(value: unknown): ScanCarrier | null {+ const object = asObject(value)+ return object && asObject(object.query_scan) ? (object as ScanCarrier) : null+}++// A killed run has no response, so its scan rides on the error: on `extra` for a blocking run and+// on `query_status` for an async one.+function errorScanCarrier(responseErrorObject: unknown): ScanCarrier | null {+ const body = asObject(asObject(responseErrorObject)?.data)+ if (!body) {+ return null+ }+ return asCarrier(body.extra) ?? asCarrier(body.query_status)+}++export function resolveQueryScan(+ response: unknown,+ responseErrorObject: unknown,+ polled: QueryScanPollResult | null+): QueryScanState | null {+ const carrier = asCarrier(response) ?? errorScanCarrier(responseErrorObject)+ const stored = carrier?.query_scan+ if (!stored) {+ return null+ }+ const cacheKey = typeof carrier?.cache_key === 'string' ? carrier.cache_key : null+ // 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+ return {+ summary,+ findings: summary.analysis?.findings ?? [],+ cacheKey,+ assistantPrompt: summary.analysis?.assistant_prompt ?? null,+ }+}++function formatRows(rows: integer): string {+ return humanFriendlyNumber(rows)+}++function formatSeconds(durationMs: integer): string {+ return humanFriendlyNumber(durationMs / 1000, 1, 1)+}++export function queryScanStatLine(summary: QueryScanSummary): string {+ const rows = formatRows(summary.rows_read)+ const seconds = formatSeconds(summary.duration_ms)+ if (summary.killed) {+ return `ClickHouse stopped it after ${seconds} s, having read ${rows} rows.`+ }+ if (typeof summary.analysis?.range_share === 'number') {+ const percent = Math.round(summary.analysis.range_share * 100)+ return `Read ${rows} rows in ${seconds} s, about ${percent}% of the events in this date range.`+ }+ return `Read ${rows} rows in ${seconds} s.`+}++export function queryScanTileStatLine(summary: QueryScanSummary): string {+ const rows = formatRows(summary.rows_read)+ const seconds = formatSeconds(summary.duration_ms)+ if (summary.killed) {+ return `ClickHouse stopped this tile's last run after ${seconds} s, having read ${rows} rows.`+ }+ return `This tile read ${rows} rows in ${seconds} s on its last run.`+}++export interface QueryScanDashboardEntry {+ tileId: number+ shortId: InsightShortId+ name: string+ findingCount: number+}++/** The insights on a dashboard whose last fresh run has advice for the viewer. */+export function queryScanDashboardEntries(tiles: DashboardTile<QueryBasedInsightModel>[]): QueryScanDashboardEntry[] {+ const entries: QueryScanDashboardEntry[] = []+ for (const tile of tiles) {+ const insight = tile.insight+ if (!insight || insight.deleted) {+ continue+ }+ // 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+ if (findingCount === 0) {+ continue+ }+ entries.push({+ tileId: tile.id,+ shortId: insight.short_id,+ name: insight.name || insight.derived_name || 'Untitled',+ findingCount,+ })+ }+ return entries+}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 21671592d258..41c8504e5194 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -6573,6 +6573,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -6706,6 +6710,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -6810,6 +6818,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -6933,6 +6945,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7048,6 +7064,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7154,6 +7174,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7254,6 +7278,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7367,6 +7395,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7469,6 +7501,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7569,6 +7605,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7685,6 +7725,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7800,6 +7844,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -7915,6 +7963,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8052,6 +8104,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8195,6 +8251,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8304,6 +8364,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8418,6 +8482,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8526,6 +8594,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8633,6 +8705,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8761,6 +8837,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8884,6 +8964,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -8984,6 +9068,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9085,6 +9173,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9201,6 +9293,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9347,6 +9443,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9509,6 +9609,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9620,6 +9724,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9718,6 +9826,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9837,6 +9949,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -9932,6 +10048,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10036,6 +10156,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10141,6 +10265,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10241,6 +10369,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10341,6 +10473,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10441,6 +10577,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10541,6 +10681,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10641,6 +10785,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10741,6 +10889,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10841,6 +10993,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -10941,6 +11097,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11041,6 +11201,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11141,6 +11305,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11241,6 +11409,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11341,6 +11513,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11446,6 +11622,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11546,6 +11726,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11647,6 +11831,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11747,6 +11935,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -11871,6 +12063,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12007,6 +12203,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12139,6 +12339,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12266,6 +12470,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12376,6 +12584,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12483,6 +12695,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12565,6 +12781,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12665,6 +12885,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12762,6 +12986,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12869,6 +13097,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -12970,6 +13202,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13083,6 +13319,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13199,6 +13439,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13338,6 +13582,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13451,6 +13699,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13564,6 +13816,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13664,6 +13920,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13752,6 +14012,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13832,6 +14096,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -13933,6 +14201,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14013,6 +14285,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14120,6 +14396,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14227,6 +14507,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14340,6 +14624,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14439,6 +14727,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14548,6 +14840,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14663,6 +14959,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14774,6 +15074,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14874,6 +15178,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -14974,6 +15282,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15084,6 +15396,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15199,6 +15515,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15314,6 +15634,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15439,6 +15763,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15547,6 +15875,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15663,6 +15995,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15775,6 +16111,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -15899,6 +16239,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -16011,6 +16355,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -16113,6 +16461,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -28866,6 +29218,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -48910,6 +49266,108 @@}]},+ "QueryScanAnalysis": {+ "additionalProperties": false,+ "description": "The stored analysis of one query, kept for 30 days by cache key and put on every response for that query.",+ "properties": {+ "assistant_prompt": {+ "description": "The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query.",+ "type": "string"+ },+ "findings": {+ "description": "Empty when the analysis found nothing to fix.",+ "items": {+ "$ref": "#/definitions/QueryScanWarning"+ },+ "type": "array"+ },+ "project_share": {+ "description": "How much of all the project's events the query read, 0 to 1.",+ "type": "number"+ },+ "range_share": {+ "description": "How much of the project's events in the query's date range the query read, 0 to 1.",+ "type": "number"+ }+ },+ "required": ["findings"],+ "type": "object"+ },+ "QueryScanFindingKind": {+ "description": "`no_event_filter`: nothing narrows the query to particular events. `no_start_date`: nothing bounds where it starts reading. `persons_join`: the join to the persons tables reads as much as the events do.",+ "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"],+ "type": "string"+ },+ "QueryScanResponse": {+ "additionalProperties": false,+ "description": "From `GET /query/scan/{cache_key}`: the analysis once the job has stored it. Empty while the job runs, 404 when nothing is stored.",+ "properties": {+ "analysis": {+ "$ref": "#/definitions/QueryScanAnalysis"+ }+ },+ "type": "object"+ },+ "QueryScanSummary": {+ "additionalProperties": false,+ "description": "What a query cost and, once analyzed, why. Only on responses to a signed-in user of a team whose flag shows findings.",+ "properties": {+ "analysis": {+ "$ref": "#/definitions/QueryScanAnalysis",+ "description": "The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested."+ },+ "analysis_requested": {+ "description": "True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it.",+ "type": "boolean"+ },+ "duration_ms": {+ "$ref": "#/definitions/integer",+ "description": "ClickHouse time for the last fresh run, summed over its ClickHouse queries."+ },+ "killed": {+ "description": "True when ClickHouse stopped the run instead of finishing it.",+ "type": "boolean"+ },+ "rows_read": {+ "$ref": "#/definitions/integer",+ "description": "Rows ClickHouse read for the last fresh run, all tables included."+ }+ },+ "required": ["rows_read", "duration_ms"],+ "type": "object"+ },+ "QueryScanWarning": {+ "additionalProperties": false,+ "description": "One finding of a query's analysis.",+ "properties": {+ "evidence": {+ "description": "The one fact the finding rests on.",+ "type": "string"+ },+ "fix": {+ "description": "What \"Fix with AI\" and the assistant are told to do.",+ "type": "string"+ },+ "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"],+ "type": "object"+ },"QuerySchema": {"discriminator": {"propertyName": "kind"@@ -49234,6 +49692,10 @@"bytes_read": {"$ref": "#/definitions/integer"},+ "cache_key": {+ "description": "Cache key of the run that failed, so clients can ask for its query scan.",+ "type": "string"+ },"complete": {"default": false,"description": "Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set.",@@ -49291,6 +49753,9 @@"query_progress": {"$ref": "#/definitions/ClickhouseQueryProgress"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary"+ },"results": {},"start_time": {"description": "When was query execution task enqueued.",@@ -53754,6 +54219,10 @@"query_metadata": {"type": "object"},+ "query_scan": {+ "$ref": "#/definitions/QueryScanSummary",+ "description": "The rows and time of the run that produced these results, with its analysis once it is stored."+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 0b2c722b792a..5724cff27ead 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -586,6 +586,64 @@ export interface AccessControlFilterWarning {message: string}+/**+ * `no_event_filter`: nothing narrows the query to particular events. `no_start_date`: nothing bounds+ * where it starts reading. `persons_join`: the join to the persons tables reads as much as the events do.+ */+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'++/** One finding of a query's analysis. */+export interface QueryScanWarning {+ kind: QueryScanFindingKind+ /** Only with `no_event_filter` and `no_start_date`. */+ reason?: QueryScanFindingReason+ /** 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+}++/** 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. */+ findings: QueryScanWarning[]+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number+ /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */+ assistant_prompt?: string+}++/** What a query cost and, once analyzed, why. Only on responses to a signed-in user of a team whose flag shows findings. */+export interface QueryScanSummary {+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: integer+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: integer+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysis+}++/** From `GET /query/scan/{cache_key}`: the analysis once the job has stored it. Empty while the job runs, 404 when nothing is stored. */+export interface QueryScanResponse {+ analysis?: QueryScanAnalysis+}+export interface HogQLQueryResponse<T = any[]> extends AnalyticsQueryResponseBase {results: T/** Input query string */@@ -2715,6 +2773,8 @@ interface CachedQueryResponseMixin {/** What triggered the calculation of the query, leave empty if user/immediate */calculation_trigger?: stringquery_metadata?: object+ /** The rows and time of the run that produced these results, with its analysis once it is stored. */+ query_scan?: QueryScanSummary}type CachedQueryResponse<T> = T & CachedQueryResponseMixin@@ -2797,6 +2857,9 @@ export type QueryStatus = {labels?: string[]bytes_read?: integerbudget_remaining_bytes?: integer+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string+ query_scan?: QueryScanSummary}export interface LifecycleQueryResponse extends AnalyticsQueryResponseBase {diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsxindex 3994255f0016..4cfa1963c62d 100644--- a/frontend/src/scenes/dashboard/Dashboard.tsx+++ b/frontend/src/scenes/dashboard/Dashboard.tsx@@ -30,6 +30,7 @@ import { AddInsightToDashboardModal } from './addInsightToDashboardModal/AddInsiimport { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'import { DashboardHeader } from './DashboardHeader'import { DashboardPublicAccessBanner } from './DashboardPublicAccessBanner'+import { DashboardQueryScanBanner } from './DashboardQueryScanBanner'import { DashboardRetentionBanner } from './DashboardRetentionBanner'import { dashboardSubscribeNudgeLogic } from './dashboardSubscribeNudgeLogic'import { DashboardZoomControl } from './DashboardZoomControl'@@ -188,6 +189,7 @@ function DashboardScene({})}><DashboardRetentionBanner />+ <DashboardQueryScanBanner /><SceneStickyBar showBorderBottom={false} className="flex gap-2 space-y-0"><DashboardFilterBar backTo={backTo} />diff --git a/frontend/src/scenes/dashboard/DashboardQueryScanBanner.tsx b/frontend/src/scenes/dashboard/DashboardQueryScanBanner.tsxnew file mode 100644index 000000000000..6d7c1085ed97--- /dev/null+++ b/frontend/src/scenes/dashboard/DashboardQueryScanBanner.tsx@@ -0,0 +1,38 @@+import { useValues } from 'kea'+import { Fragment } from 'react'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { Link } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import { queryScanDashboardEntries } from '~/queries/nodes/DataNode/queryScan'++import { dashboardLogic } from './dashboardLogic'++export function DashboardQueryScanBanner(): JSX.Element | null {+ const { dashboard, insightTiles, canEditDashboard } = useValues(dashboardLogic)+ if (!dashboard || !canEditDashboard) {+ return null+ }++ const entries = queryScanDashboardEntries(insightTiles)+ if (entries.length === 0) {+ return null+ }++ const single = entries.length === 1+ return (+ <LemonBanner type="warning" className="mt-4 mb-2">+ {single+ ? '1 insight on this dashboard reads a large number of events, which can slow down dashboard loads: '+ : `${entries.length} insights on this dashboard read a large number of events, which can slow down dashboard loads: `}+ {entries.map((entry, index) => (+ <Fragment key={entry.tileId}>+ {index > 0 ? ', ' : ''}+ <Link to={urls.insightView(entry.shortId)}>{entry.name}</Link>+ </Fragment>+ ))}+ {single ? '. Open it to see the advice.' : '. Open an insight to see the advice.'}+ </LemonBanner>+ )+}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex d32fa7a72761..baa7ee046908 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -2223,6 +2223,7 @@ export const dashboardLogic = kea<dashboardLogicType>([last_refresh: item.last_refresh ?? existing.last_refresh,columns: item.columns ?? existing.columns,types: item.types ?? existing.types,+ query_scan: item.query_scan ?? existing.query_scan,},}diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsxindex 7f55f13ec412..9ef50fe0d0b7 100644--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx@@ -93,6 +93,7 @@ import {copyTableToJson,copyTableToMarkdown,} from '../../../queries/nodes/DataTable/clipboardUtils'+import { EditorQueryScanBanner } from './components/EditorQueryScanBanner'import { FixErrorButton } from './components/FixErrorButton'import { QueryIndexUsageBar } from './output-pane-tabs/QueryIndexUsageBar'import { OutputTab, outputPaneLogic } from './outputPaneLogic'@@ -1190,6 +1191,7 @@ const ErrorState = ({ responseError, sourceQuery, queryCancelled, response }: an<FixErrorButton contentOverride="Fix error with AI" type="primary" source="query-error" />}/>+ <EditorQueryScanBanner /></div></div>)@@ -1319,6 +1321,7 @@ const Content = ({return (<div className="absolute inset-0 flex flex-col border-t overflow-hidden"><QueryWarningsBanner warnings={response?.warnings} />+ <EditorQueryScanBanner /><div className="flex flex-col flex-1 min-h-0 hide-scrollbar overflow-auto"><InternalDataTableVisualizationuniqueKey={vizKey}@@ -1390,6 +1393,7 @@ const Content = ({return (<div className="flex flex-col flex-1 min-h-0 w-full overflow-hidden"><QueryWarningsBanner warnings={response?.warnings} />+ <EditorQueryScanBanner />{rows.length === 0 ? (<EmptyResultsState />) : (diff --git a/frontend/src/scenes/data-warehouse/editor/components/EditorQueryScanBanner.tsx b/frontend/src/scenes/data-warehouse/editor/components/EditorQueryScanBanner.tsxnew file mode 100644index 000000000000..691fefb262e0--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/components/EditorQueryScanBanner.tsx@@ -0,0 +1,24 @@+import { useActions, useValues } from 'kea'++import { autoRunMaxPrompt } from 'scenes/max/maxPrompt'++import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { QueryScanBanner } from '~/queries/nodes/DataNode/QueryScanBanner'+import { SidePanelTab } from '~/types'++export function EditorQueryScanBanner(): JSX.Element | null {+ const { queryScan } = useValues(dataNodeLogic)+ const { openSidePanel } = useActions(sidePanelStateLogic)++ // The editor registers the `execute_sql` tool with the current query, so the assistant reads the+ // query from there and writes its proposal back through the same tool.+ const askAssistant = (): void => {+ if (!queryScan?.assistantPrompt) {+ return+ }+ openSidePanel(SidePanelTab.Max, autoRunMaxPrompt(queryScan.assistantPrompt))+ }++ return <QueryScanBanner className="m-2" queryScan={queryScan} onFixWithAI={askAssistant} />+}diff --git a/frontend/src/scenes/insights/InsightAsScene.tsx b/frontend/src/scenes/insights/InsightAsScene.tsxindex 1b1cd0fc8973..d01a6a494f1f 100644--- a/frontend/src/scenes/insights/InsightAsScene.tsx+++ b/frontend/src/scenes/insights/InsightAsScene.tsx@@ -18,6 +18,7 @@ import { teamLogic } from '../teamLogic'import { InsightRetentionBanner } from './dataRetention/InsightRetentionBanner'import { insightDataLogic } from './insightDataLogic'import { insightLogic } from './insightLogic'+import { InsightQueryScanBanner } from './InsightQueryScanBanner'import { InsightSceneHeader } from './InsightSceneHeader'import { insightVizDataLogic } from './insightVizDataLogic'import { SqlInsightFilters } from './SqlInsightFilters'@@ -92,6 +93,8 @@ export function InsightAsScene({ insightId, attachTo }: InsightAsSceneProps): JS<InsightRetentionBanner insightProps={insightProps} />+ <InsightQueryScanBanner insightProps={insightProps} />+<SqlInsightFilters query={query} setQuery={setQuery}>{isDataVisualizationNode(query) && insightLoading ? (// Avoid painting the stale chart type during a reload (the query re-syncs in insightDataLogic).diff --git a/frontend/src/scenes/insights/InsightQueryScanBanner.tsx b/frontend/src/scenes/insights/InsightQueryScanBanner.tsxnew file mode 100644index 000000000000..dd1fbc1384a9--- /dev/null+++ b/frontend/src/scenes/insights/InsightQueryScanBanner.tsx@@ -0,0 +1,12 @@+import { useValues } from 'kea'++import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { QueryScanBanner } from '~/queries/nodes/DataNode/QueryScanBanner'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'+import { InsightLogicProps } from '~/types'++export function InsightQueryScanBanner({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element {+ const { queryScan } = useValues(dataNodeLogic({ key: insightVizDataNodeKey(insightProps) } as DataNodeLogicProps))++ return <QueryScanBanner queryScan={queryScan} />+}diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsxindex 43392632197c..f2e8035aeb36 100644--- a/frontend/src/scenes/insights/insightDataLogic.tsx+++ b/frontend/src/scenes/insights/insightDataLogic.tsx@@ -301,6 +301,7 @@ export interface insightDataLogicActions {next_allowed_client_refresh?: string | null | undefinedorder: number | nullquery: Node<Record<string, any>> | null+ query_scan?: import('~/queries/schema/schema-general').QueryScanSummary | undefinedquery_status?: QueryStatus | undefinedresolved_date_range?: ResolvedDateRangeResponse | null | undefinedresult: any@@ -350,6 +351,7 @@ export interface insightDataLogicActions {next_allowed_client_refresh?: string | null | undefinedorder: number | nullquery: Node<Record<string, any>> | null+ query_scan?: import('~/queries/schema/schema-general').QueryScanSummary | undefinedquery_status?: QueryStatus | undefinedresolved_date_range?: ResolvedDateRangeResponse | null | undefinedresult: anydiff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex 09d77d69a776..3168d7de15bf 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -82,6 +82,7 @@ import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'import type { ProductIntentProperties } from '../../lib/utils/product-intents'import type { Noun } from '../../models/groupsModel'import type { QueryStatus, ResolvedDateRangeResponse } from '../../queries/schema/schema-general'+import type { QueryScanSummary } from '../../queries/schema/schema-general'import type { CohortType, DashboardTileBasicType, TeamPublicType, TeamType, UserBasicType, UserType } from '../../types'import { teamLogic } from '../teamLogic'import { insightDataLogic, isInsightSceneInstance } from './insightDataLogic'@@ -212,6 +213,7 @@ export interface insightLogicActions {next_allowed_client_refresh?: string | null | undefinedorder: number | nullquery: Node<Record<string, any>> | null+ query_scan?: QueryScanSummary | undefinedquery_status?: QueryStatus | undefinedresolved_date_range?: ResolvedDateRangeResponse | null | undefinedresult: any@@ -259,6 +261,7 @@ export interface insightLogicActions {next_allowed_client_refresh?: string | null | undefinedorder: number | nullquery: Node<Record<string, any>> | null+ query_scan?: QueryScanSummary | undefinedquery_status?: QueryStatus | undefinedresolved_date_range?: ResolvedDateRangeResponse | null | undefinedresult: any@@ -383,6 +386,7 @@ export interface insightLogicActions {next_allowed_client_refresh?: string | null | undefinedorder?: number | null | undefinedquery?: Node<Record<string, any>> | null | undefined+ query_scan?: QueryScanSummary | undefinedquery_status?: QueryStatus | undefinedresolved_date_range?: ResolvedDateRangeResponse | null | undefinedresult?: any@@ -429,6 +433,7 @@ export interface insightLogicActions {next_allowed_client_refresh?: string | null | undefinedorder?: number | null | undefinedquery?: Node<Record<string, any>> | null | undefined+ query_scan?: QueryScanSummary | undefinedquery_status?: QueryStatus | undefinedresolved_date_range?: ResolvedDateRangeResponse | null | undefinedresult?: anydiff --git a/frontend/src/scenes/saved-insights/activityDescriptions.tsx b/frontend/src/scenes/saved-insights/activityDescriptions.tsxindex f269d7402114..5f82f3ff5dc1 100644--- a/frontend/src/scenes/saved-insights/activityDescriptions.tsx+++ b/frontend/src/scenes/saved-insights/activityDescriptions.tsx@@ -250,6 +250,7 @@ const insightActionsMapping: Record<disable_baseline: () => null,dashboard_tiles: () => null,query_status: () => null,+ query_scan: () => null,user_access_level: () => null,_create_in_folder: () => null,last_viewed_at: () => null,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 056f099ab1a0..4362f2b3bc33 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -66,6 +66,7 @@ import type {NodeKind,ProductItemCategory,ProductKey,+ QueryScanSummary,QuerySchema,QueryStatus,QuickFilterContext,@@ -2653,6 +2654,7 @@ export interface InsightModel extends Cacheable, WithAccessControl {alerts?: AlertType[]query?: Node | nullquery_status?: QueryStatus+ query_scan?: QueryScanSummaryis_cached?: booleanfilter_override_context?: InsightFilterOverrideContextApi | nullresolved_date_range?: ResolvedDateRangeResponse | nulldiff --git a/posthog/api/query.py b/posthog/api/query.pyindex 419f6764b989..71ff0a51042a 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -1,6 +1,6 @@import refrom time import perf_counter-from typing import NoReturn+from typing import Any, NoReturnfrom django.core.cache import cachefrom django.http import JsonResponse@@ -14,7 +14,7 @@ from opentelemetry import tracefrom prometheus_client import Counterfrom pydantic import BaseModelfrom rest_framework import status, viewsets-from rest_framework.exceptions import APIException, NotAuthenticated, Throttled, ValidationError+from rest_framework.exceptions import APIException, NotAuthenticated, NotFound, Throttled, ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -24,6 +24,7 @@ from posthog.schema import (LimitContext as SchemaLimitContext,QueryRequest,QueryResponseAlternative,+ QueryScanResponse,QueryStatusResponse,QueryUpgradeRequest,QueryUpgradeResponse,@@ -59,6 +60,9 @@ from posthog.hogql_queries.query_failure_handling import captured_elsewherefrom posthog.hogql_queries.query_runner import ExecutionMode, execution_mode_from_refreshfrom posthog.models.user import Userfrom posthog.models.utils import uuid7+from posthog.query_scan import slot as query_scan_slot+from posthog.query_scan.flag import QueryScanMode, get_query_scan_flag+from posthog.query_scan.serve import analysis_with_promptfrom posthog.rate_limit import (AIBurstRateThrottle,AISustainedRateThrottle,@@ -104,6 +108,11 @@ def _add_query_cost_headers(response: HttpResponseBase, bytes_read: int, remainiresponse["X-PostHog-Query-Budget-Remaining-Bytes"] = str(remaining_bytes)+def _scan_extra(error: Exception) -> dict[str, Any]:+ """The scan a stopped run left on the exception, for the error body's ``extra``."""+ return {key: value for key in ("cache_key", "query_scan") if (value := getattr(error, key, None)) is not None}++def _extract_validation_code(error: ValidationError) -> str:validation_codes = error.get_codes()if isinstance(validation_codes, list):@@ -376,6 +385,11 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)if isinstance(e, ExposedHogQLError):request_user = request.user if isinstance(request.user, User) else Nonedetail, extra = enrich_hogql_validation_error(query, self.team, request_user, detail)+ # A run ClickHouse stopped carries its scan, so the client can show the advice under+ # the error.+ scan_extra = _scan_extra(e)+ if scan_extra:+ extra = {**(extra or {}), **scan_extra}validation_error = ValidationError(detail, getattr(e, "code_name", None))if extra is not None:validation_error.extra = extra # type: ignore[attr-defined]@@ -383,7 +397,11 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)except InternalCHQueryError as e:self.handle_column_ch_error(e)capture_exception(e)- raise APIException("ClickHouse error while executing query.")+ replacement = APIException("ClickHouse error while executing query.")+ scan_extra = _scan_extra(e)+ if scan_extra:+ replacement.extra = scan_extra # type: ignore[attr-defined]+ raise replacementexcept UserAccessControlError as e:raise ValidationError(str(e))except ResolutionError as e:@@ -404,6 +422,11 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)except Exception as e:if not captured_elsewhere(e):capture_exception(e)+ # The timeout and memory-limit classes land here, which are the runs the scan+ # exists for.+ scan_extra = _scan_extra(e)+ if scan_extra:+ e.extra = {**(getattr(e, "extra", None) or {}), **scan_extra} # type: ignore[attr-defined]raise@extend_schema(@@ -537,6 +560,37 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)capture_exception(e)raise+ @extend_schema(+ description=(+ "Get the query scan for a cache key: the analysis of the last slow run of that query. The body "+ "is empty while the analysis runs. 404 when the query has not been analyzed."+ ),+ responses={+ 200: QueryScanResponse,+ 404: OpenApiResponse(description="No query scan exists for this cache key."),+ },+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path=r"scan/(?P<cache_key>[^/]+)",+ required_scopes=["query:read"],+ )+ def get_query_scan(self, request: Request, cache_key: str, *args, **kwargs) -> Response:+ # `log_only` collects the analysis without showing it to anyone, and with the flag off+ # there is no current configuration to hold a stored analysis to.+ flag = get_query_scan_flag(self.team)+ if flag is None or flag.mode != QueryScanMode.SHOW:+ raise NotFound("There is no query scan for this cache key.")+ slot = query_scan_slot.get(self.team_id, cache_key, thresholds=flag.thresholds_fingerprint)+ if slot is None:+ raise NotFound("There is no query scan for this cache key.")+ if slot.analysis is None:+ return Response({}, status=status.HTTP_200_OK)+ # Nothing here knows the run that asked, so the prompt carries the findings without a run line.+ scan = QueryScanResponse(analysis=analysis_with_prompt(slot.analysis))+ return Response(scan.model_dump(by_alias=True, exclude_none=True), status=status.HTTP_200_OK)+def handle_column_ch_error(self, error):if getattr(error, "message", None):match = re.search(r"There's no column.*in table", error.message)diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 0412f3142227..8f40c146660c 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -3044,6 +3044,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):},"resolved_date_range": ANY,"query_status": None,+ "query_scan": None,"result": None,"saved": True,"short_id": ANY,diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex 9cce7763f243..785dcf899508 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -29,6 +29,8 @@ from posthog.schema import (HogQLQuery,PersonPropertyFilter,PropertyOperator,+ QueryScanAnalysis,+ QueryScanFindingKind,QueryStatus,)@@ -43,11 +45,15 @@ from posthog.api.services.query import process_query_dict, process_query_modelfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Product, QueryTags+from posthog.errors import InternalCHQueryErrorfrom posthog.event_usage import EventSourcefrom posthog.exceptions import APIQueriesBudgetExceeded, ClickHouseQueryTimeOutfrom posthog.llm.completions import OpenAICompletionfrom posthog.models import PersonalAPIKeyfrom posthog.models.utils import UUIDT, generate_random_token_personal, hash_key_value+from posthog.query_scan.findings import build_warning+from posthog.query_scan.flag import QueryScanFlag, QueryScanMode+from posthog.query_scan.test.slots import stored_slotfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyTypefrom products.managed_warehouse.backend.facade.query_labels import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX@@ -94,6 +100,28 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, ClickHouseQueryTimeOut.status_code)self.assertEqual(mock_capture.called, expect_capture)+ @parameterized.expand(+ [+ ("timeout", ClickHouseQueryTimeOut("query timed out"), ClickHouseQueryTimeOut.status_code),+ ("internal clickhouse error", InternalCHQueryError("too many rows", code=158), 500),+ ]+ )+ def test_a_killed_run_puts_its_scan_on_the_error_body(self, _name, error, expected_status):+ error.cache_key = "cache_key_1"+ error.query_scan = {"rows_read": 41_200, "duration_ms": 19_000, "killed": True, "analysis_requested": True}++ with patch("posthog.api.query.process_query_model", side_effect=error):+ response = self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {"query": HogQLQuery(query="select 1").model_dump()},+ )++ self.assertEqual(response.status_code, expected_status)+ # Without the cache key on the failure the caller cannot read the stored analysis.+ extra = response.json()["extra"]+ self.assertEqual(extra["cache_key"], "cache_key_1")+ self.assertEqual(extra["query_scan"]["killed"], True)+@snapshot_clickhouse_queriesdef test_select_hogql_expressions(self):with time_machine.travel("2020-01-10 12:00:00", tick=False):@@ -1016,6 +1044,8 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):"dashboard_id": mock.ANY,"query_progress": None,"labels": None,+ "cache_key": None,+ "query_scan": None,}},)@@ -1324,6 +1354,71 @@ class TestQueryRetrieve(APIBaseTest):self.assertEqual(self.redis_client_mock.delete.call_count, 2)+SHOW_FLAG = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)+LOG_ONLY_FLAG = QueryScanFlag(mode=QueryScanMode.LOG_ONLY, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)++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")],+ )+)+A_CLAIMED_SCAN = json.dumps({"pending": True})+++class TestQueryScan(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.redis_client_mock = mock.Mock()+ patcher = mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=self.redis_client_mock)+ patcher.start()+ self.addCleanup(patcher.stop)+ flag_patcher = mock.patch("posthog.api.query.get_query_scan_flag", return_value=SHOW_FLAG)+ self.flag_mock = flag_patcher.start()+ self.addCleanup(flag_patcher.stop)++ def test_returns_the_stored_scan(self):+ self.redis_client_mock.get.return_value = A_STORED_SCAN++ response = self.client.get(f"/api/environments/{self.team.id}/query/scan/cache_key_1/")++ self.assertEqual(response.status_code, 200, response.content)+ analysis = response.json()["analysis"]+ self.assertEqual(analysis["range_share"], 0.8)+ 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"])++ 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+ # ends the poll.+ self.redis_client_mock.get.return_value = A_CLAIMED_SCAN++ response = self.client.get(f"/api/environments/{self.team.id}/query/scan/cache_key_1/")++ self.assertEqual(response.status_code, 200, response.content)+ self.assertEqual(response.json(), {})++ @parameterized.expand(+ [+ ("the query was never analyzed", None, SHOW_FLAG),+ # `log_only` collects the analysis without showing it to anyone, so the endpoint that+ # serves it to a client has to stay closed on that mode.+ ("the team is in log-only mode", A_STORED_SCAN, LOG_ONLY_FLAG),+ ("the flag is off", A_STORED_SCAN, None),+ ]+ )+ def test_returns_404_when(self, _name, stored, flag):+ self.redis_client_mock.get.return_value = stored+ self.flag_mock.return_value = flag++ response = self.client.get(f"/api/environments/{self.team.id}/query/scan/cache_key_1/")++ self.assertEqual(response.status_code, 404)++class TestQueryDraftSql(APIBaseTest):@patch("posthog.hogql.ai.hit_openai",diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.pyindex cf21828c433a..7f12b21be336 100644--- a/posthog/caching/calculate_results.py+++ b/posthog/caching/calculate_results.py@@ -172,6 +172,7 @@ def calculate_for_query_based_insight(hogql=getattr(process_response, "hogql", None),types=getattr(process_response, "types", None),resolved_date_range=_model_field_as_dict(process_response, "resolved_date_range"),+ query_scan=_model_field_as_dict(process_response, "query_scan"),)response = process_response@@ -194,4 +195,5 @@ def calculate_for_query_based_insight(hogql=response.get("hogql"),types=response.get("types"),resolved_date_range=response.get("resolved_date_range"),+ query_scan=response.get("query_scan"),)diff --git a/posthog/caching/insight_result.py b/posthog/caching/insight_result.pyindex 1612d34863ae..1cb05b0478f5 100644--- a/posthog/caching/insight_result.py+++ b/posthog/caching/insight_result.py@@ -22,6 +22,8 @@ class InsightResult:types: Optional[list] = None# A ResolvedDateRangeResponse-shaped dict — the field carries model_dump outputresolved_date_range: Optional[dict] = None+ # A QueryScanSummary dict. The insight serializer puts the stored analysis on it.+ query_scan: Optional[dict] = None@dataclass(frozen=True)diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 4e87937d1a18..ac07a4593260 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -189,9 +189,45 @@ def get_clickhouse_creds(user: ClickHouseUser) -> ClickHouseCredentials:return __user_dict[ClickHouseUser.DEFAULT]+@frozen+class QuerySummary:+ """What one ClickHouse query read."""++ rows: int = 0+ elapsed_ns: int = 0+++class ClickHouseClient(SyncClient):+ """Keeps the progress of a query the server stopped.++ The driver forgets its last query when it reconnects after an error, but a stopped query has+ already read rows, and the query scan reports them. The record is kept here until read once.+ """++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ # Set before the base constructor, which calls reset_last_query.+ self.last_query_before_reset: Any = None+ super().__init__(*args, **kwargs)++ def reset_last_query(self) -> None:+ last_query = getattr(self, "last_query", None)+ # A second disconnect must not drop what the first one stashed.+ if last_query is not None:+ self.last_query_before_reset = last_query+ super().reset_last_query()++ def take_last_query_before_reset(self) -> Any:+ """Return the stashed query info and forget it, so one execution is never counted twice."""+ stashed = self.last_query_before_reset+ self.last_query_before_reset = None+ return stashed++class ProxyClient:def __init__(self, client: "HttpClient"):self._client = client+ # The HTTP client has no last_query, so it reports what it read here instead.+ self.last_query_summary: QuerySummary | None = Nonedef execute(self,@@ -204,11 +240,16 @@ class ProxyClient:types_check=False,columnar=False,):+ self.last_query_summary = Noneif query_id:if settings is None:settings = {}settings["query_id"] = query_idresult = self._client.query(query=query, parameters=params, settings=settings, column_oriented=columnar)+ self.last_query_summary = QuerySummary(+ rows=int(result.summary.get("read_rows", 0)),+ elapsed_ns=int(result.summary.get("elapsed_ns", 0)),+ )# we must play with result summary herewritten_rows = int(result.summary.get("written_rows", 0))@@ -386,7 +427,7 @@ def default_client(password overrides the static CLICKHOUSE_PASSWORD, for example with a resolved file-backed token.send_receive_timeout bounds each socket read and write; None keeps the driver default."""- return SyncClient(+ return ClickHouseClient(host=host,**({"send_receive_timeout": send_receive_timeout} if send_receive_timeout is not None else {}),# We set "system" here as we don't necessarily have a "default" database,@@ -404,7 +445,21 @@ def default_client()-class RefreshingChPool(ChPool):+class ClickHouseChPool(ChPool):+ """A pool of ClickHouseClient. ``ChPool._connect`` hardcodes the driver's client class, so it is+ repeated here with ours."""++ def _connect(self, key: str | None = None) -> ClickHouseClient:+ client = ClickHouseClient(**self.connection_args)+ if key is not None:+ self._used[key] = client+ self._rused[id(client)] = key+ else:+ self._pool.append(client)+ return client+++class RefreshingChPool(ClickHouseChPool):"""ChPool that stamps the current credential onto every pulled client.The pool is keyed on identity rather than the credential, so one pool survives credential@@ -452,7 +507,7 @@ def _make_ch_pool(# kwargs["password"] is only the lazy seed here; RefreshingChPool re-stamps every pulled client.return RefreshingChPool(credential_provider=credential_provider, **kwargs)- return ChPool(**kwargs)+ return ClickHouseChPool(**kwargs)make_ch_pool = cache(_make_ch_pool)diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex d118a56a554c..0084dc875ed3 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -19,9 +19,12 @@ from clickhouse_driver import Client as SyncClientfrom opentelemetry import tracefrom prometheus_client import Counter+from posthog.hogql import query_stats+from posthog.api_queries_budget import API_QUERIES_BUDGET_ERRORS_COUNTER, QueryCost, debit, record_request_query_costfrom posthog.clickhouse.client.connection import (ClickHouseUser,+ QuerySummary,Workload,get_client_from_pool,get_default_clickhouse_workload_type,@@ -242,6 +245,44 @@ def _chargeable_query_info(client: Any, query_info_before: Any) -> Optional[Any]return query_info+def _query_stats_summary(client: Any, query_info_before: Any) -> Optional[QuerySummary]:+ """What the query that just ran on `client` read, or None when nothing was recorded.++ A stopped query's record is taken from the stash, because the reconnect after the error cleared+ it. A record unchanged since before the call belongs to an earlier query on the same pooled client.+ """+ if not hasattr(client, "last_query"):+ return getattr(client, "last_query_summary", None)+ query_info = client.last_query+ if query_info is None:+ take_stashed = getattr(client, "take_last_query_before_reset", None)+ query_info = take_stashed() if take_stashed is not None else None+ if query_info is None or query_info is query_info_before or not query_info.progress:+ return None+ progress = query_info.progress+ return QuerySummary(+ rows=int(progress.rows or 0),+ elapsed_ns=int(progress.elapsed_ns or 0),+ )+++def _record_query_stats(client: Any, query_info_before: Any, execute_start_time: float) -> None:+ """Add what this query read to the request's totals.++ Also runs after a failure, since a stopped query has still read rows. Never raises: the totals+ are advisory.+ """+ try:+ summary = _query_stats_summary(client, query_info_before)+ if summary is None:+ 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)+ except Exception:+ logger.warning("query_stats_record_failed", exc_info=True)++def kill_switch_overrides(team_id: Optional[int], ch_user: ClickHouseUser = ClickHouseUser.DEFAULT) -> dict[str, int]:"""The ClickHouse setting ceilings the kill switch imposes right now, empty when it is off.@@ -547,6 +588,9 @@ def sync_execute(sync_client or get_client_from_pool(workload, team_id, readonly, ch_user) as client,):query_info_before = getattr(client, "last_query", None)+ # Taken after the concurrency slot and the pool checkout, so the fallback does not count+ # the queue wait.+ execute_start_time = perf_counter()try:result = client.execute(prepared_sql,@@ -562,6 +606,7 @@ def sync_execute(# in the outer finally, once the connection is back in the pool.if tags.chargeable and tags.team_id:chargeable_query_info = _chargeable_query_info(client, query_info_before)+ _record_query_stats(client, query_info_before, execute_start_time)if ("INSERT INTO" in prepared_sqland hasattr(client, "last_query")diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex 9db6d5dd05ea..8f74447694ba 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -9,7 +9,7 @@ from prometheus_client import Histogramfrom pydantic import BaseModelfrom rest_framework.exceptions import APIException, NotFound-from posthog.schema import ClickhouseQueryProgress, QueryStatus+from posthog.schema import ClickhouseQueryProgress, QueryScanSummary, QueryStatusfrom posthog.hogql.constants import LimitContextfrom posthog.hogql.errors import ExposedHogQLError@@ -206,6 +206,17 @@ def _shared_link_user_for(sharing_configuration_id: int, team: "Team") -> Optionreturn cast("User", SharedLinkUser(sharing_configuration))+def _query_scan_from_error(err: Exception) -> Optional[QueryScanSummary]:+ """The scan summary the query runner put on a killed run, if this failure carries one."""+ summary = getattr(err, "query_scan", None)+ if summary is None:+ return None+ try:+ return QueryScanSummary.model_validate(summary)+ except Exception:+ return None++def execute_process_query(team_id: int,user_id: Optional[int],@@ -301,6 +312,11 @@ def execute_process_query(is_user_safe_error = isinstance(err, APIException | ExposedHogQLError | ExposedCHQueryError | UserAccessControlError)+ # A stopped run's scan rides on the status so a dead tile can show the advice, with the cache key+ # for polling. Only for a real user: a shared link must not see the project's data volume.+ if user_id:+ query_status.cache_key = getattr(err, "cache_key", None)+ query_status.query_scan = _query_scan_from_error(err)if is_user_safe_error or is_staff_user:# We can only expose the error message if it's a known safe error OR if the user is PostHog staffquery_status.error_message = str(err)diff --git a/posthog/clickhouse/client/test/test_connection.py b/posthog/clickhouse/client/test/test_connection.pyindex 2e1bdbe2039e..c7c124bf8154 100644--- a/posthog/clickhouse/client/test/test_connection.py+++ b/posthog/clickhouse/client/test/test_connection.py@@ -1,10 +1,9 @@import pytestfrom unittest.mock import patch-from clickhouse_pool import ChPool-from posthog.clickhouse.client import connectionfrom posthog.clickhouse.client.connection import (+ ClickHouseChPool,ClickHouseCredentials,ClickHouseUser,RefreshingChPool,@@ -45,7 +44,7 @@ def test_connection_pool_creation_without_offline_cluster(settings):settings.CLICKHOUSE_OFFLINE_CLUSTER_HOST = Noneonline_pool = get_pool(Workload.ONLINE)- assert type(online_pool) is ChPool # a user with no password file keeps a plain, non-refreshing pool+ assert type(online_pool) is ClickHouseChPool # a user with no password file keeps a non-refreshing poolassert get_pool(Workload.ONLINE) is online_poolassert get_pool(Workload.OFFLINE) is online_poolassert get_pool(Workload.DEFAULT) is online_pooldiff --git a/posthog/clickhouse/client/test/test_execute.py b/posthog/clickhouse/client/test/test_execute.pyindex e1f488c4cded..16189c5a0c4a 100644--- a/posthog/clickhouse/client/test/test_execute.py+++ b/posthog/clickhouse/client/test/test_execute.py@@ -1,9 +1,13 @@from ipaddress import IPv4Address, IPv6Address+from types import SimpleNamespace+from typing import Anyimport pytestfrom unittest.mock import MagicMock, patch-from posthog.clickhouse.client.connection import ClickHouseUser, Workload+from posthog.hogql.query_stats import query_stats_scope++from posthog.clickhouse.client.connection import ClickHouseClient, ClickHouseUser, ProxyClient, Workloadfrom posthog.clickhouse.client.execute import query_with_columns, sync_executefrom posthog.clickhouse.client.limit import ConcurrencySlot, RateLimit, get_llm_analytics_rate_limiterfrom posthog.clickhouse.query_tagging import AccessMethod, Product, tags_context@@ -109,6 +113,62 @@ def test_llm_analytics_queries_take_a_concurrency_slot(client_from_pool, llm_anaassert llm_analytics_slots.call_count == expected_slots+def _fake_query_info(rows: int, elapsed_ns: int) -> SimpleNamespace:+ return SimpleNamespace(progress=SimpleNamespace(rows=rows, elapsed_ns=elapsed_ns))+++class _FakeNativeClient(ClickHouseClient):+ # Nothing here connects, so disconnect() only clears last_query.+ def __init__(self, fails: str | None = None, last_query: SimpleNamespace | None = None) -> None:+ super().__init__(host="localhost")+ self.last_query = last_query+ self._fails = fails++ def execute(self, *args: Any, **kwargs: Any) -> list[tuple[int]]:+ if self._fails == "connect":+ self.disconnect()+ raise ValueError("Connection refused")+ self.last_query = _fake_query_info(rows=7, elapsed_ns=3_000_000)+ if self._fails == "kill":+ self.disconnect()+ raise ValueError("Memory limit (for query) exceeded")+ return [(1,)]+++def _proxy_client() -> ProxyClient:+ summary = {"read_rows": "7", "elapsed_ns": "3000000"}+ http_client = SimpleNamespace(query=lambda **kwargs: SimpleNamespace(summary=summary, result_set=[(1,)]))+ return ProxyClient(http_client) # type: ignore[arg-type]+++ "make_client,raises,expected",+ [+ (_FakeNativeClient, False, (7, 3.0)),+ (lambda: _FakeNativeClient(fails="kill"), True, (7, 3.0)),+ # Counting the previous query's progress would charge this query with another query's rows.+ (+ lambda: _FakeNativeClient(fails="connect", last_query=_fake_query_info(rows=99, elapsed_ns=1)),+ True,+ (0, 0.0),+ ),+ (_proxy_client, False, (7, 3.0)),+ ],+ ids=["ok", "killed_by_the_server", "connect_failed", "http_client"],+)+def test_sync_execute_records_what_clickhouse_read(make_client, raises, expected):+ with patch("posthog.clickhouse.client.execute.get_client_from_pool") as pool:+ pool.return_value.__enter__.return_value = make_client()+ with query_stats_scope() as stats:+ if raises:+ with pytest.raises(ValueError):+ sync_execute("SELECT 1", flush=False)+ else:+ sync_execute("SELECT 1", flush=False)++ assert (stats.rows_read, stats.duration_ms) == expected++@pytest.mark.parametrize("types,row,expected",[diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.pyindex 2f5dc07bd058..ff0107e8cbde 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -308,6 +308,43 @@ class TestExecuteProcessQuery(TestCase):else:assert user is None+ @parameterized.expand(+ [+ ("a real user", True, True),+ # A shared link is read from outside the project, and the scan reports how much data+ # the project holds, so neither it nor the key that addresses it may be stored.+ ("a shared link viewer", False, False),+ ]+ )+ @patch("posthog.clickhouse.client.execute_async.redis.get_client")+ @patch("posthog.api.services.query.process_query_dict")+ def test_a_killed_run_stores_its_scan_only_for_a_real_user(+ self, _name, real_user, expect_scan, mock_process_query_dict, mock_redis_client+ ):+ mock_redis = MagicMock()+ mock_redis.get.return_value = json.dumps(+ {"id": self.query_id, "team_id": self.team.id, "complete": False, "error": False}+ ).encode()+ mock_redis_client.return_value = mock_redis+ error = ExposedCHQueryError("query timed out")+ error.cache_key = "cache_key_1"+ error.query_scan = {"rows_read": 41_200, "duration_ms": 19_000, "killed": True, "analysis_requested": True}+ mock_process_query_dict.side_effect = error+ sharing_configuration = None if real_user else SharingConfiguration.objects.create(team=self.team, enabled=True)++ execute_process_query(+ self.team.id,+ self.user.id if real_user else None,+ self.query_id,+ self.query_json,+ self.limit_context,+ sharing_configuration_id=sharing_configuration.id if sharing_configuration else None,+ )++ stored = json.loads(mock_redis.set.call_args.args[1])+ assert (stored.get("cache_key") == "cache_key_1") is expect_scan+ assert (stored.get("query_scan") is not None) is expect_scan+class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):def setUp(self):diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 4ecc85c2cd71..603898e3463d 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -139,6 +139,8 @@ class Feature(StrEnum):ENDPOINT_LAST_EXECUTION = "endpoint_last_execution" # Usage tab query_log lookupPOSTHOG_AI = "posthog_ai"MCP = "mcp"+ # The offline analysis of a slow query: a handful of EXPLAINs per scan slot, not per request.+ QUERY_SCAN = "query_scan"SEMANTIC_SEARCH = "semantic_search"# A 30 day aggregate that runs on every AI observability dashboard mount and trace view, so its# load is worth attributing separately from the tab queries it sits alongside.diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.pyindex b2af55c40dfb..4987941e4002 100644--- a/posthog/hogql/placeholders.py+++ b/posthog/hogql/placeholders.py@@ -31,6 +31,9 @@ class FindPlaceholders(TraversingVisitor):def __init__(self):super().__init__()self.has_filters = False # Legacy fallback: treat filters as before+ # The filters forms that expand into a predicate, so a date range can bound the query+ # through them. The dotted call forms substitute a value and cannot add one.+ self.has_date_filters = Falseself.placeholder_fields: list[list[str | int]] = [] # Did we find simple fieldsself.placeholder_expressions: list[ast.Expr] = [] # Did we find complex expressions@@ -41,12 +44,14 @@ class FindPlaceholders(TraversingVisitor):if chain := node.chain:if chain[0] == "filters":self.has_filters = True+ self.has_date_filters = Trueelse:self.placeholder_fields.append(chain)elif isinstance(node.expr, ast.Call) and node.expr.name == "filters":# The column-bound form {filters(expr AS key, ...)} is resolved by replace_filters;# classifying it as a generic expression placeholder would send it to the Hog VM instead.self.has_filters = True+ self.has_date_filters = Trueelif (isinstance(node.expr, ast.ExprCall)and isinstance(node.expr.expr, ast.Field)diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex 093e9d84eb11..f36426111755 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -15,7 +15,7 @@ from posthog.schema import (HogQLVariable,)-from posthog.hogql import ast+from posthog.hogql import ast, query_statsfrom posthog.hogql.constants import (HogQLDialect,HogQLGlobalSettings,@@ -807,6 +807,10 @@ class HogQLQueryExecutor:external_tables=list(clickhouse_context.external_tables.values()) or None,)+ stats = query_stats.get_active()+ # The rows are read back per thread after the run, so a run ClickHouse stops is still+ # recorded with what it read, and a series running in another thread is not charged here.+ query_stats.reset_last_rows_read()try:try:self.results, self.types = run_clickhouse_query()@@ -823,6 +827,13 @@ class HogQLQueryExecutor:self.error = "Unknown error"else:raise+ finally:+ if stats is not None and isinstance(self.clickhouse_prepared_ast, ast.Expr):+ stats.record_execution(+ tree=self.clickhouse_prepared_ast,+ context=clickhouse_context,+ rows_read=query_stats.last_rows_read(),+ )if self.debug and self.error is None:with self.timings.measure("explain"):diff --git a/posthog/hogql/query_stats.py b/posthog/hogql/query_stats.pynew file mode 100644index 000000000000..4bdc711fa00b--- /dev/null+++ b/posthog/hogql/query_stats.py@@ -0,0 +1,120 @@+"""Add up the rows and time ClickHouse spent on one query request.++One request can run several ClickHouse queries (a trends insight runs one per series). The runner+opens ``query_stats_scope()`` around the run, ``sync_execute`` calls ``record()`` after each query,+and the runner reads the totals at the end. With no scope open, ``record()`` does nothing.++A new thread does not see the scope its parent opened, so a runner that runs its queries in threads+reads the totals with ``get_active()`` and installs them in each thread with ``use()``.+"""++from __future__ import annotations++import threading+import contextlib+from collections.abc import Iterator+from contextvars import ContextVar+from dataclasses import field+from typing import TYPE_CHECKING++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ from posthog.hogql import ast+ from posthog.hogql.context import HogQLContext+++@frozen+class RecordedExecution:+ """One ClickHouse execution inside a scope, held by reference for the job to explain later."""++ tree: ast.Expr+ context: HogQLContext+ rows_read: int+++@frozen(frozen=False)+class QueryStats:+ """The totals for one request."""++ rows_read: int = 0+ duration_ms: float = 0.0+ # 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+ # 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:+ 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:+ with self.lock:+ self.executions.append(RecordedExecution(tree=tree, context=context, rows_read=rows_read))+++_accumulator: ContextVar[QueryStats | None] = ContextVar("query_stats_accumulator", default=None)++# The rows of the last query recorded in the current thread, for the executor to attribute to the+# tree it just ran. Kept per thread rather than read off the shared totals, because runners that+# fan out over threads share one QueryStats, and a change in its total would charge one thread with+# rows another read at the same time.+_last_rows_read: ContextVar[int] = ContextVar("query_stats_last_rows_read", default=0)+++def query_stats_scope() -> Iterator[QueryStats]:+ """Add up every ClickHouse query run inside this block. Nested in another scope, it adds to that one."""+ outer = _accumulator.get()+ if outer is not None:+ yield outer+ return+ stats = QueryStats()+ token = _accumulator.set(stats)+ try:+ yield stats+ finally:+ _accumulator.reset(token)+++def get_active() -> QueryStats | None:+ """The totals of the open scope, or None when none is open."""+ return _accumulator.get()+++def use(stats: QueryStats | None) -> Iterator[None]:+ """Record into ``stats`` inside this block, for a thread that does not see its parent's scope.+ Does nothing for None."""+ if stats is None:+ yield+ return+ token = _accumulator.set(stats)+ try:+ yield+ finally:+ _accumulator.reset(token)+++def record(*, rows_read: int, duration_ms: float) -> 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)+++def reset_last_rows_read() -> None:+ """Forget the last query's rows in this thread, before a run that must not inherit them."""+ _last_rows_read.set(0)+++def last_rows_read() -> int:+ """The rows of the last query recorded in this thread since the reset, or 0."""+ return _last_rows_read.get()diff --git a/posthog/hogql/test/test_placeholders.py b/posthog/hogql/test/test_placeholders.pyindex 84e983704c15..6259b4244649 100644--- a/posthog/hogql/test/test_placeholders.py+++ b/posthog/hogql/test/test_placeholders.py@@ -29,15 +29,23 @@ class TestParser(BaseTest):expr = parse_expr("{filters(a AS timestamp, b AS 'plan')} and {foo} and {1 + 2}")finder = find_placeholders(expr)self.assertTrue(finder.has_filters)+ self.assertTrue(finder.has_date_filters)self.assertEqual(finder.placeholder_fields, [["foo"]])self.assertEqual(len(finder.placeholder_expressions), 1)+ def test_find_placeholders_chain_filters(self):+ finder = find_placeholders(parse_select("select 1 from events where {filters}"))+ self.assertTrue(finder.has_filters)+ self.assertTrue(finder.has_date_filters)+def test_find_placeholders_dotted_filters_calls(self):# The dotted call forms must count as filters usage too; the Hog VM has no `filters` global.# A dotted call on anything else stays an expression placeholder.expr = parse_expr("{filters.interval('week')} and {filters.breakdown(a AS 'plan')} and {other.call(1)}")finder = find_placeholders(expr)self.assertTrue(finder.has_filters)+ # They substitute a value rather than a predicate, so no date range reaches the query.+ self.assertFalse(finder.has_date_filters)self.assertEqual(finder.placeholder_fields, [])self.assertEqual(len(finder.placeholder_expressions), 1)diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.pyindex 6225edddd810..957bcea4f960 100644--- a/posthog/hogql/test/test_query.py+++ b/posthog/hogql/test/test_query.py@@ -8,12 +8,14 @@ import pytestimport time_machinefrom posthog.test.base import (APIBaseTest,+ BaseTest,ClickhouseTestMixin,NewEventsSchemaSnapshotExtension,_create_event,_create_person,flush_persons_and_events,)+from unittest import mockfrom unittest.mock import patchfrom django.conf import settings@@ -39,6 +41,7 @@ from posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.printer import prepare_ast_for_printing as unmocked_prepare_ast_for_printingfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import HogQLQueryExecutor, execute_hogql_query+from posthog.hogql.query_stats import query_stats_scope, recordfrom posthog.hogql.test.utils import (execute_hogql_query_with_timings,pretty_print_in_tests,@@ -48,6 +51,7 @@ from posthog.hogql.test.utils import (from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE, ADHOC_EVENTS_DELETION_TABLE_SQLfrom posthog.clickhouse.client import sync_executefrom posthog.errors import CHQueryErrorS3Error, InternalCHQueryError+from posthog.exceptions import ClickHouseQueryMemoryLimitExceededfrom posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODESfrom posthog.models.team import Teamfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary@@ -2382,3 +2386,30 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):self.assertEqual(mock_sync_execute.call_count, 1)mock_sleep.assert_not_called()+++class TestQueryStatsRecording(BaseTest):+ def test_the_executor_records_each_execution_including_a_killed_run(self) -> None:+ # The trigger reads the run's executions off the scope, so the executor must record one for+ # every ClickHouse call, and a run ClickHouse kills has to be recorded with what it read.+ def ok(sql, values, **kwargs):+ record(rows_read=42, duration_ms=1.0)+ return ([[0]], [("count()", "UInt64")])++ with query_stats_scope() as stats:+ with mock.patch("posthog.hogql.query.sync_execute", side_effect=ok):+ execute_hogql_query("select count() from events", team=self.team, query_type="test")+ assert len(stats.executions) == 1+ assert stats.executions[0].rows_read == 42+ assert stats.executions[0].tree is not None++ def killed(sql, values, **kwargs):+ record(rows_read=90, duration_ms=1.0)+ raise ClickHouseQueryMemoryLimitExceeded()++ with query_stats_scope() as killed_stats:+ with self.assertRaises(ClickHouseQueryMemoryLimitExceeded):+ with mock.patch("posthog.hogql.query.sync_execute", side_effect=killed):+ execute_hogql_query("select count() from events", team=self.team, query_type="test")+ assert len(killed_stats.executions) == 1+ assert killed_stats.executions[0].rows_read == 90diff --git a/posthog/hogql/test/test_query_stats.py b/posthog/hogql/test/test_query_stats.pynew file mode 100644index 000000000000..8743e9ccb056--- /dev/null+++ b/posthog/hogql/test/test_query_stats.py@@ -0,0 +1,54 @@+import threading++from posthog.hogql.query_stats import get_active, last_rows_read, query_stats_scope, record, reset_last_rows_read, use+++def test_scope_sums_nested_records_and_ignores_what_was_recorded_outside_it():+ record(rows_read=5, duration_ms=9.0)++ with query_stats_scope() as outer:+ record(rows_read=1, duration_ms=5.0)+ with query_stats_scope() as inner:+ assert inner is outer+ record(rows_read=2, duration_ms=7.0)+ record(rows_read=4, duration_ms=1.0)++ assert (outer.rows_read, outer.duration_ms) == (7, 13.0)+++def test_use_installs_the_accumulator_in_another_thread():+ with query_stats_scope() as stats:+ handed_over = get_active()++ def worker() -> None:+ with use(handed_over):+ record(rows_read=3, duration_ms=2.0)++ thread = threading.Thread(target=worker)+ thread.start()+ thread.join()++ assert (stats.rows_read, stats.duration_ms) == (3, 2.0)+++def test_the_last_rows_read_are_kept_per_thread():+ # Runners fan series out over threads that share one QueryStats, so the executor takes each+ # execution's rows from its own thread rather than from a change in the shared total.+ with query_stats_scope() as stats:+ handed_over = get_active()+ reset_last_rows_read()++ def worker() -> None:+ with use(handed_over):+ record(rows_read=1000, duration_ms=1.0)++ thread = threading.Thread(target=worker)+ thread.start()+ thread.join()+ record(rows_read=3, duration_ms=2.0)++ assert last_rows_read() == 3+ reset_last_rows_read()+ assert last_rows_read() == 0++ assert (stats.rows_read, stats.query_count) == (1003, 2)diff --git a/posthog/hogql_queries/query_failure_handling.py b/posthog/hogql_queries/query_failure_handling.pyindex d7bd26aff6d7..2cbafd8ba912 100644--- a/posthog/hogql_queries/query_failure_handling.py+++ b/posthog/hogql_queries/query_failure_handling.py@@ -159,10 +159,11 @@ def _approximate_wait(open_until: datetime) -> str:return f"{hours} hour{'s' if hours != 1 else ''}"-def build_failure_exception(record: QueryFailureRecord) -> APIException:+def build_failure_exception(record: QueryFailureRecord, *, with_scan: bool = False) -> APIException:"""Rebuild the remembered failure with its original exception class, so status codes andfrontend error handling stay identical to a fresh failure. The original message leads and- the breaker context follows it."""+ the breaker context follows it. ``with_scan`` puts the first failure's query scan pointer on+ the copy, for a reader allowed to see it."""sentences = [record.detail]if record.consecutive_failures == 1:sentences.append("This query failed in a way that will repeat, so it was not run again.")@@ -174,4 +175,7 @@ def build_failure_exception(record: QueryFailureRecord) -> APIException:sentences.append(f"It can run again in about {_approximate_wait(record.open_until)}.")error = FAILURE_KIND_EXCEPTIONS[record.kind](detail=" ".join(sentences))error.served_from_query_failure_cache = True # type: ignore[attr-defined]+ if with_scan and record.query_scan is not None:+ error.cache_key = record.cache_key # type: ignore[attr-defined]+ error.query_scan = record.query_scan # type: ignore[attr-defined]return errordiff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 57b7b5b529b3..e351034af164 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -1,6 +1,7 @@import threadingfrom abc import ABC, abstractmethodfrom collections.abc import Callable, Sequence+from contextlib import AbstractContextManager, nullcontextfrom datetime import UTC, datetime, timedeltafrom enum import StrEnumfrom functools import cache, cached_property@@ -108,6 +109,7 @@ from posthog.hogql.database.database import Databasefrom posthog.hogql.modifiers import create_default_modifiers_for_userfrom posthog.hogql.printer import prepare_and_print_ast, to_printed_hogqlfrom posthog.hogql.query import create_default_modifiers_for_team+from posthog.hogql.query_stats import QueryStats, query_stats_scopefrom posthog.hogql.timings import HogQLTimingsfrom posthog.hogql.warehouse_warnings import accumulator_scope@@ -175,6 +177,13 @@ from posthog.query_cache.single_flight import (FlightWait,QuerySingleFlight,)+from posthog.query_scan.flag import QueryScanFlag, QueryScanMode, get_query_scan_flag+from posthog.query_scan.serve import hydrate_response_scan+from posthog.query_scan.trigger import (+ SkipReason as QueryScanSkipReason,+ is_analyzable_principal,+ maybe_trigger_query_scan,+)from posthog.schema_helpers import to_dictfrom posthog.scopes import APIScopeObjectfrom posthog.shared_link_user import SharedLinkUser@@ -2007,7 +2016,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,):- self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED)+ self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED, user)# We're allowed to calculate, but we'll do it asynchronously and attach the query statuscached_response.query_status = self.enqueue_async_calculation(cache_manager=cache_manager, user=user, refresh_requested=True, analytics_props=analytics_props@@ -2017,7 +2026,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):# We're allowed to calculate if the lazy check fails, but we'll do it asynchronouslyassert isinstance(cached_response, CachedResponse)if self._is_stale_for_request(last_refresh=last_refresh_from_cached_result(cached_response), lazy=True):- self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED)+ self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED, user)cached_response.query_status = self.enqueue_async_calculation(cache_manager=cache_manager, user=user, analytics_props=analytics_props)@@ -2037,7 +2046,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,ExecutionMode.EXTENDED_CACHE_CALCULATE_ASYNC_IF_STALE,):- self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED)+ self._raise_if_failure_fresh_for(failure, BUDGET_EXTENDED, user)# We're allowed to calculate, but we'll do it asynchronouslycached_response.query_status = self.enqueue_async_calculation(cache_manager=cache_manager, user=user, analytics_props=analytics_props@@ -2080,13 +2089,27 @@ class QueryRunner(ABC, Generic[Q, R, CR]):except Exception:return False- def _raise_if_failure_fresh_for(self, failure: Optional[QueryFailureRecord], budget: Budget) -> None:+ def _scan_replay_visible(self, failure: QueryFailureRecord, user: Optional[User]) -> bool:+ """Whether a replay may carry the first failure's scan pointer. The reader gate is the fresh+ path's. The flag is read again because the pointer was stored under the flag of the first+ failure, and the error body renders it as scan UI, so a flag since turned off or moved to+ log_only must hide it the way it hides a fresh summary."""+ if failure.query_scan is None or not is_analyzable_principal(user):+ return False+ flag = get_query_scan_flag(self.team)+ return flag is not None and flag.mode == QueryScanMode.SHOW++ def _raise_if_failure_fresh_for(+ self, failure: Optional[QueryFailureRecord], budget: Budget, user: Optional[User]+ ) -> None:"""The one breaker rule: a failure outcome that is fresh for the given execution budget- substitutes for the execution it would forbid."""+ substitutes for the execution it would forbid. The replay carries the first failure's+ pointer to its stored analysis, for the same readers the first failure had, under the+ flag as it is now."""if failure is None or not failure.forbids(budget):returnQUERY_FAILURE_CACHE_COUNTER.labels(action="served_error", kind=failure.kind).inc()- raise build_failure_exception(failure)+ raise build_failure_exception(failure, with_scan=self._scan_replay_visible(failure, user))def _call_with_rate_limits(self, *, dashboard_id: Optional[int]) -> tuple[R, float]:"""Execute calculate() with all rate limiters applied.@@ -2275,7 +2298,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):# enqueued job runs under the async budget, so only failures that cover# that budget forbid it.if self._query_failure_caching_enabled:- self._raise_if_failure_fresh_for(cache_manager.open_failure(), BUDGET_EXTENDED)+ self._raise_if_failure_fresh_for(cache_manager.open_failure(), BUDGET_EXTENDED, user)# We should always kick off async calculation and disregard the cache.# cache_hit is left unset on this path because the cache wasn't consulted.slo.tag(execution_path="async_dispatched")@@ -2312,7 +2335,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):# cache_hit is left unset on this path: either the caller passed# CALCULATE_BLOCKING_ALWAYS (cache skipped) or the cache returned nothing.slo.tag(execution_path="blocking", calculation_trigger=trigger)- return self._execute_and_cache_blocking(+ fresh_response = self._execute_and_cache_blocking(cache_key=cache_key,cache_manager=cache_manager,execution_mode=execution_mode,@@ -2323,6 +2346,10 @@ class QueryRunner(ABC, Generic[Q, R, CR]):start_time=start_time,analytics_props=analytics_props,)+ # A fresh run of a query analyzed earlier still has a done slot, so this is+ # where its findings reach the recomputed response.+ self._serve_query_scan(fresh_response, user)+ return fresh_responseexcept Exception as exc:if getattr(exc, "served_from_query_failure_cache", False):# ClickHouse was never touched; the original failure was already@@ -2367,7 +2394,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):) -> CR:# The single gate for all blocking execution, forced refreshes included: an open# breaker that covers this run's execution budget forbids touching ClickHouse.- self._raise_if_breaker_forbids(cache_manager)+ self._raise_if_breaker_forbids(cache_manager, user)flight: Optional[QuerySingleFlight] = Noneif self._joins_single_flight():@@ -2427,10 +2454,12 @@ class QueryRunner(ABC, Generic[Q, R, CR]):and self.limit_context != LimitContext.EXPORT)- def _raise_if_breaker_forbids(self, cache_manager: QueryCache) -> None:+ def _raise_if_breaker_forbids(self, cache_manager: QueryCache, user: Optional[User]) -> None:if not self._query_failure_caching_enabled:return- self._raise_if_failure_fresh_for(cache_manager.open_failure(), budget_for_limit_context(self.limit_context))+ self._raise_if_failure_fresh_for(+ cache_manager.open_failure(), budget_for_limit_context(self.limit_context), user+ )def _record_breaker_failure(self, cache_manager: QueryCache, exc: Exception) -> None:if not self._query_failure_caching_enabled:@@ -2438,7 +2467,13 @@ class QueryRunner(ABC, Generic[Q, R, CR]):# Transient error classes classify to None and are never recorded.failure_kind = classify_failure(exc, self.team.pk)if failure_kind is not None:- cache_manager.record_failure(failure_kind, str(exc), budget=budget_for_limit_context(self.limit_context))+ cache_manager.record_failure(+ failure_kind,+ str(exc),+ budget=budget_for_limit_context(self.limit_context),+ cache_key=getattr(exc, "cache_key", None),+ query_scan=getattr(exc, "query_scan", None),+ )def _serve_flight_outcome(self,@@ -2507,6 +2542,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):execution_path: str = "cache_hit",) -> None:cache_tracking_props: dict[str, Any] = {}+ # The numbers describe the fresh run that filled the cache, not this hit. Read before serving,+ # which can take the field off the response.+ cached_query_scan = getattr(results, "query_scan", None)if isinstance(results, self.cached_response_type):if (not trigger or not trigger.startswith("warming")) and results.query_metadata:log_event_usage_from_query_metadata(@@ -2525,6 +2563,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"last_refresh": last_refresh.isoformat() if last_refresh else None,}tag_current_slo(execution_path=execution_path, cache_hit=True, **cache_tracking_props)+ self._serve_query_scan(results, user)else:tag_current_slo(execution_path="cache_miss", cache_hit=False)@@ -2537,6 +2576,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"cache_hit": isinstance(results, self.cached_response_type),"cache_age_override": self._cache_age_override,"response_time_ms": round((perf_counter() - start_time) * 1000, 2),+ "clickhouse_rows_read": cached_query_scan.rows_read if cached_query_scan else None,+ "clickhouse_duration_ms": cached_query_scan.duration_ms if cached_query_scan else None,**cache_tracking_props,}report_user_or_team_action(@@ -2573,10 +2614,15 @@ class QueryRunner(ABC, Generic[Q, R, CR]):self.modifiers = create_default_modifiers_for_user(user, self.team, self.modifiers)self.modifiers.useMaterializedViews = True+ query_scan_flag = get_query_scan_flag(self.team)+ query_stats_context: AbstractContextManager[QueryStats | None] = (+ query_stats_scope() if query_scan_flag is not None else nullcontext(None)+ )+# Capture data warehouse sync warnings from every HogQL execution that contributes to this# response. Nested calls (one runner invoking another) see the parent's accumulator via# ContextVar and contribute to it; the outermost scope is the one that attaches and resets.- with accumulator_scope() as warnings_accumulator:+ with accumulator_scope() as warnings_accumulator, query_stats_context as query_stats:query_type = getattr(self.query, "kind", "Other")survey_query_metric_labels = get_survey_query_metric_labels(self.query)query_start = perf_counter()@@ -2605,6 +2651,21 @@ class QueryRunner(ABC, Generic[Q, R, CR]):category=classify_query_error(e),error_type=clickhouse_error_type(e),).inc()+ if (+ query_scan_flag is not None+ and classify_query_error(e) == QueryErrorCategory.QUERY_PERFORMANCE_ERROR+ ):+ # Every retry of a query ClickHouse stops dies the same way, so this is the+ # only run that can ever carry the advice to the person.+ self._analyze_killed_run(+ e,+ flag=query_scan_flag,+ stats=query_stats,+ cache_key=cache_key,+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ user=user,+ )raisefinally:query_duration_seconds = perf_counter() - query_start@@ -2664,7 +2725,45 @@ class QueryRunner(ABC, Generic[Q, R, CR]):# Don't cache debug queries with errors and export querieserrors: Optional[list[Any]] = fresh_response_dict.get("error", None)has_error = errors is not None and len(errors) > 0- if not has_error and self.limit_context != LimitContext.EXPORT:+ cacheable = not has_error and self.limit_context != LimitContext.EXPORT++ # Stored with the results, so a cache hit carries the numbers of the run that produced+ # them.+ scan_skip: QueryScanSkipReason | None = "flag_off"+ if query_scan_flag is not None and query_stats is not None:+ if not is_analyzable_principal(user):+ # The summary describes the project's data volume, which a shared-link viewer+ # reads from outside the project, so it stays off their response.+ scan_skip = "no_principal"+ elif query_stats.query_count == 0:+ # A warehouse query over a direct connection never reaches ClickHouse, so a+ # summary would only report a run that read nothing in no time.+ scan_skip = "no_clickhouse_query"+ else:+ query_scan: dict[str, Any] = {+ "rows_read": query_stats.rows_read,+ "duration_ms": round(query_stats.duration_ms),+ }+ fresh_response_dict["query_scan"] = query_scan+ scan_skip = maybe_trigger_query_scan(+ flag=query_scan_flag,+ stats=query_stats,+ team_id=self.team.pk,+ # Dashboard and tile overrides are already applied here, so the cache key+ # is the right identity for the analysis.+ cache_key=cache_key,+ query=self.query,+ trigger="fresh",+ cacheable=cacheable,+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ )+ if scan_skip in (None, "slot_exists"):+ # Says only that there is an analysis to look up, never its state: the+ # cached copy is not rewritten when the job finishes.+ query_scan["analysis_requested"] = True++ if cacheable:stored = cache_manager.store_result(response=fresh_response_dict,# This would be a possible place to decide to not ever keep this cache warm@@ -2693,6 +2792,10 @@ class QueryRunner(ABC, Generic[Q, R, CR]):"response_time_ms": round((perf_counter() - start_time) * 1000, 2),"query_duration_ms": query_duration_ms,"has_error": has_error,+ "clickhouse_rows_read": query_stats.rows_read if query_stats else None,+ "clickhouse_duration_ms": round(query_stats.duration_ms) if query_stats else None,+ "query_scan_triggered": scan_skip is None,+ "query_scan_skipped_reason": scan_skip,}report_user_or_team_action("query executed",@@ -2705,6 +2808,65 @@ class QueryRunner(ABC, Generic[Q, R, CR]):return CachedResponse(**fresh_response_dict)+ def _serve_query_scan(self, response: Any, user: Optional[User]) -> None:+ """Put the stored analysis on a response, or take the field off for a shared-link viewer, who+ must not see the project's data volume from the cache.+ """+ if is_analyzable_principal(user):+ hydrate_response_scan(self.team, response)+ elif getattr(response, "query_scan", None) is not None:+ response.query_scan = None++ def _analyze_killed_run(+ self,+ error: Exception,+ *,+ flag: QueryScanFlag,+ stats: Optional[QueryStats],+ cache_key: str,+ insight_id: Optional[int],+ dashboard_id: Optional[int],+ user: Optional[User],+ ) -> None:+ """Enqueue the analysis for a run ClickHouse stopped and put the summary on the exception. The+ error is re-raised unchanged; nothing here may replace it.+ """+ if not is_analyzable_principal(user):+ # Same gate as the fresh path: the summary must not ride out on an error body a+ # shared link renders.+ return+ if stats is None:+ # No stats scope was open, so nothing about the run was recorded to analyze.+ return+ try:+ skip = maybe_trigger_query_scan(+ flag=flag,+ stats=stats,+ team_id=self.team.pk,+ cache_key=cache_key,+ query=self.query,+ trigger="killed",+ # A killed run has no result to cache, so only the export exclusion applies.+ cacheable=self.limit_context != LimitContext.EXPORT,+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ killed=True,+ error_type=clickhouse_error_type(error),+ )+ if flag.mode != QueryScanMode.SHOW or skip not in (None, "slot_exists"):+ # Under `log_only` the analysis runs and nobody sees it, and with no slot behind+ # this cache key the scan endpoint answers 404.+ return+ error.query_scan = { # type: ignore[attr-defined]+ "rows_read": stats.rows_read,+ "duration_ms": round(stats.duration_ms),+ "killed": True,+ "analysis_requested": True,+ }+ error.cache_key = cache_key # type: ignore[attr-defined]+ except Exception as scan_error:+ capture_exception(scan_error, {"team_id": self.team.pk, "context": "query_scan_killed_run"})+def get_api_queries_concurrency_limit(self):""":return: None - no feature, 1,3,<other> for actual concurrency limitdiff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex 442b21d14acf..f786d10ccfb2 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -1,7 +1,8 @@+import jsonimport timeimport threadingfrom datetime import UTC, datetime, timedelta-from typing import Any, Literal, Optional+from typing import Any, Literal, Optional, castfrom zoneinfo import ZoneInfoimport pytest@@ -56,8 +57,11 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import LimitContext+from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.errors import QueryError, ResolutionError+from posthog.hogql.parser import parse_select+from posthog.hogql.query_stats import get_active, recordfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded@@ -104,6 +108,7 @@ from posthog.query_cache.failures import ()from posthog.query_cache.single_flight import QUERY_SINGLE_FLIGHT_FLAG, FlightWait, QuerySingleFlight, SharedFailurefrom posthog.query_cache.storage import entry_redis_key+from posthog.query_scan.flag import QueryScanFlag, QueryScanModefrom posthog.shared_link_user import SharedLinkUserfrom posthog.slo.types import SloOutcome@@ -164,6 +169,28 @@ def setup_test_query_runner_class(base: type[QueryRunner] = QueryRunner):return TestQueryRunner+_QUERY_SCAN_FLAG_SHOW = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)+_QUERY_SCAN_FLAG_LOG_ONLY = QueryScanFlag(+ mode=QueryScanMode.LOG_ONLY, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5+)+++def _calculate_recording_clickhouse_stats(_self):+ record(rows_read=12, duration_ms=34.0)+ return TheTestBasicQueryResponse(results=[])+++def _calculate_without_clickhouse(_self):+ return TheTestBasicQueryResponse(results=[])+++def _shared_link_user(team: Team) -> User:+ # The share link is its authorization, so the query runs, but there is no user row the worker+ # could resolve back.+ configuration = SharingConfiguration.objects.create(team=team, enabled=True)+ return cast("User", SharedLinkUser(configuration))++def _chain(exc: Exception, cause: Exception) -> Exception:exc.__cause__ = causereturn exc@@ -213,6 +240,165 @@ class TestQueryRunner(BaseTest):assert any(w.get("table_name") == "paid_bills" for w in warnings)assert any(w.get("resources") == ["insight"] for w in warnings)+ @parameterized.expand(+ [+ ("flag on for a real user", _QUERY_SCAN_FLAG_SHOW, True, True, True),+ ("flag off", None, True, True, False),+ # The worker resolves no user for a shared-link viewer, and the summary describes the+ # project's data volume to someone outside it.+ ("flag on for a shared link viewer", _QUERY_SCAN_FLAG_SHOW, False, True, False),+ # A warehouse query over a direct connection never reaches ClickHouse, and a summary of+ # zeros would tell the person it read nothing in no time.+ ("a run that never reached clickhouse", _QUERY_SCAN_FLAG_SHOW, True, False, False),+ ]+ )+ def test_query_scan_summary_attached_only_for_a_flagged_team_and_a_real_user(+ self, _name, flag, real_user, reached_clickhouse, expect_summary+ ):+ TestQueryRunner = self.setup_test_query_runner_class()+ user = self.user if real_user else _shared_link_user(self.team)+ calculate = _calculate_recording_clickhouse_stats if reached_clickhouse else _calculate_without_clickhouse++ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)+ with (+ mock.patch("posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=flag),+ # The serving side re-reads the flag to correct a summary cached under an older one.+ mock.patch("posthog.query_scan.serve.get_query_scan_flag", return_value=flag),+ mock.patch.object(TestQueryRunner, "_calculate", autospec=True, side_effect=calculate),+ ):+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=user)++ if not expect_summary:+ assert response.query_scan is None+ else:+ assert response.query_scan is not None+ assert (response.query_scan.rows_read, response.query_scan.duration_ms) == (12, 34)++ @parameterized.expand(+ [+ ("flag turned off", None),+ # `log_only` collects the analysis without showing it to anyone.+ ("mode narrowed", _QUERY_SCAN_FLAG_LOG_ONLY),+ ]+ )+ def test_a_cache_hit_drops_the_summary_once_the_flag_stops_showing_it(self, _name, flag_at_read):+ TestQueryRunner = self.setup_test_query_runner_class()+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)+ with (+ time_machine.travel(datetime(2023, 2, 4, 13, 37, 42), tick=False),+ mock.patch.object(+ TestQueryRunner, "_calculate", autospec=True, side_effect=_calculate_recording_clickhouse_stats+ ),+ ):+ with (+ mock.patch(+ "posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=_QUERY_SCAN_FLAG_SHOW+ ),+ mock.patch("posthog.query_scan.serve.get_query_scan_flag", return_value=_QUERY_SCAN_FLAG_SHOW),+ ):+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE, user=self.user)+ with (+ mock.patch("posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=flag_at_read),+ mock.patch("posthog.query_scan.serve.get_query_scan_flag", return_value=flag_at_read),+ ):+ response = runner.run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE, user=self.user+ )++ assert response.is_cached+ assert response.query_scan is None++ @parameterized.expand(+ [+ ("a real user", True, True),+ ("a shared link viewer", False, False),+ ]+ )+ def test_a_killed_run_is_analyzed_only_for_a_real_user(self, _name, real_user, expect_scan):+ TestQueryRunner = self.setup_test_query_runner_class()+ user = self.user if real_user else _shared_link_user(self.team)++ def calculate_until_clickhouse_gives_up(_self):+ # 400 ms is under the flag's 1000 ms floor: a stopped run is analyzed at any duration.+ record(rows_read=90, duration_ms=400.0)+ # The executor records this before the kill; the fake runner stands in for it here.+ 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+ )+ raise ClickHouseQueryMemoryLimitExceeded()++ 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=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.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_until_clickhouse_gives_up+ ),+ self.assertRaises(ClickHouseQueryMemoryLimitExceeded) as raised,+ ):+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=user)++ if not expect_scan:+ delay.assert_not_called()+ assert getattr(raised.exception, "query_scan", None) is None+ assert getattr(raised.exception, "cache_key", None) is None+ return+ assert delay.call_count == 1+ assert delay.call_args.kwargs["killed"] is True+ assert len(delay.call_args.kwargs["executions"]) == 1+ assert getattr(raised.exception, "cache_key", None) == runner.get_cache_key()+ assert getattr(raised.exception, "query_scan", None) == {+ "rows_read": 90,+ "duration_ms": 400,+ "killed": True,+ "analysis_requested": True,+ }++ def test_a_killed_run_points_at_the_analysis_another_run_owns(self):+ # A retry of a killed query has the same cache key, so the second kill finds the first+ # one's analysis still running, and says so without reading it.+ TestQueryRunner = self.setup_test_query_runner_class()++ def calculate_until_clickhouse_gives_up(_self):+ record(rows_read=90, duration_ms=4000.0)+ raise ClickHouseQueryMemoryLimitExceeded()++ redis_client = mock.Mock()+ redis_client.get.return_value = json.dumps({"pending": True})+ 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=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.tasks.query_scan.analyze_query_scan.delay") as delay,+ mock.patch.object(+ TestQueryRunner, "_calculate", autospec=True, side_effect=calculate_until_clickhouse_gives_up+ ),+ self.assertRaises(ClickHouseQueryMemoryLimitExceeded) as raised,+ ):+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=self.user)++ delay.assert_not_called()+ assert getattr(raised.exception, "query_scan", None) == {+ "rows_read": 90,+ "duration_ms": 4000,+ "killed": True,+ "analysis_requested": True,+ }+def test_calculate_runs_validators_before_calculation(self):TestQueryRunner = self.setup_test_query_runner_class()validation_rule = mock.MagicMock()@@ -1863,6 +2049,54 @@ class TestQueryFailureCaching(BaseTest):assert mock_calculate.call_count == 1assert getattr(ctx.exception, "served_from_query_failure_cache", False)+ @parameterized.expand(+ [+ ("the flag still shows", _QUERY_SCAN_FLAG_SHOW, True, True),+ ("the flag moved to log_only", _QUERY_SCAN_FLAG_LOG_ONLY, True, False),+ ("the flag is off", None, True, False),+ ("a shared link viewer replays it", _QUERY_SCAN_FLAG_SHOW, False, False),+ ]+ )+ def test_a_replayed_failure_carries_the_scan_pointer_under_the_flag_as_it_is_now(+ self, _name, flag_at_replay, real_user, expect_pointer+ ):+ # The pointer was stored under the flag of the first failure. The error body renders it as+ # scan UI, so a flag since turned off must hide it the way it hides a fresh summary.+ runner_class = setup_test_query_runner_class()+ runner = runner_class(query={"some_attr": "bla"}, team=self.team)++ def calculate_until_clickhouse_gives_up(_self):+ record(rows_read=90, duration_ms=4000.0)+ raise _per_query_memory_error()++ redis_client = mock.Mock()+ redis_client.get.return_value = json.dumps({"pending": True})+ 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.object(+ runner_class, "_calculate", autospec=True, side_effect=calculate_until_clickhouse_gives_up+ ),+ ):+ with (+ mock.patch(+ "posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=_QUERY_SCAN_FLAG_SHOW+ ),+ self.assertRaises(ClickHouseQueryMemoryLimitExceeded),+ ):+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=self.user)+ with (+ mock.patch("posthog.hogql_queries.query_runner.get_query_scan_flag", return_value=flag_at_replay),+ self.assertRaises(ClickHouseQueryMemoryLimitExceeded) as replayed,+ ):+ runner.run(+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ user=self.user if real_user else _shared_link_user(self.team),+ )++ assert getattr(replayed.exception, "served_from_query_failure_cache", False)+ assert (getattr(replayed.exception, "query_scan", None) is not None) is expect_pointer+def test_forced_blocking_run_respects_open_breaker(self):runner_class = setup_test_query_runner_class()runner = runner_class(query={"some_attr": "bla"}, team=self.team)diff --git a/posthog/query_cache/cache.py b/posthog/query_cache/cache.pyindex 356464f177b5..8e5152b8aef4 100644--- a/posthog/query_cache/cache.py+++ b/posthog/query_cache/cache.py@@ -1,6 +1,6 @@from dataclasses import dataclassfrom datetime import datetime-from typing import Optional+from typing import Any, Optionalfrom django.conf import settings@@ -87,8 +87,18 @@ class QueryCache:"""The open breaker record alone, for paths that skip the result cache entirely."""return QueryFailureCache(self.cache_key).get_open()- def record_failure(self, kind: FailureKind, detail: str, *, budget: Budget) -> Optional[QueryFailureRecord]:- return QueryFailureCache(self.cache_key).record_failure(kind, detail, budget=budget)+ def record_failure(+ self,+ kind: FailureKind,+ detail: str,+ *,+ budget: Budget,+ cache_key: Optional[str] = None,+ query_scan: Optional[dict[str, Any]] = None,+ ) -> Optional[QueryFailureRecord]:+ return QueryFailureCache(self.cache_key).record_failure(+ kind, detail, budget=budget, cache_key=cache_key, query_scan=query_scan+ )def clear_failure(self) -> None:QueryFailureCache(self.cache_key).clear()diff --git a/posthog/query_cache/failures.py b/posthog/query_cache/failures.pyindex 38df4bd823fa..116971a325d7 100644--- a/posthog/query_cache/failures.py+++ b/posthog/query_cache/failures.py@@ -54,6 +54,10 @@ class QueryFailureRecord:last_failed_at: datetimeopen_until: Optional[datetime]budget: Budget = BUDGET_INTERACTIVE+ # The pointer to the stored query scan the runner put on the original failure, so a replay+ # carries it the way the first failure did.+ cache_key: Optional[str] = None+ query_scan: Optional[dict[str, Any]] = None@propertydef is_open(self) -> bool:@@ -86,7 +90,13 @@ class QueryFailureCache:return record if record is not None and record.is_open else Nonedef record_failure(- self, kind: FailureKind, detail: str, budget: Budget = BUDGET_INTERACTIVE+ self,+ kind: FailureKind,+ detail: str,+ budget: Budget = BUDGET_INTERACTIVE,+ *,+ cache_key: Optional[str] = None,+ query_scan: Optional[dict[str, Any]] = None,) -> Optional[QueryFailureRecord]:"""Count a deterministic failure. The detail is shown to users verbatim when theremembered failure is served, so callers must only ever pass user-safe copy."""@@ -117,6 +127,8 @@ class QueryFailureCache:last_failed_at=datetime.now(UTC),open_until=open_until,budget=record_budget,+ cache_key=cache_key,+ query_scan=query_scan,)caches[QUERY_CACHE_ALIAS].set(self.key, self._serialize(record), RECORD_TTL.total_seconds())QUERY_FAILURE_CACHE_COUNTER.labels(action="opened" if open_until else "recorded", kind=kind).inc()@@ -148,6 +160,8 @@ class QueryFailureCache:last_failed_at=datetime.fromisoformat(data["last_failed_at"]),open_until=datetime.fromisoformat(data["open_until"]) if data["open_until"] else None,budget=data.get("budget", BUDGET_INTERACTIVE),+ cache_key=data.get("cache_key"),+ query_scan=data.get("query_scan"),)except Exception:logger.exception("query_failure_cache_read_failed", key=self.key)@@ -162,4 +176,6 @@ class QueryFailureCache:"last_failed_at": record.last_failed_at.isoformat(),"open_until": record.open_until.isoformat() if record.open_until else None,"budget": record.budget,+ "cache_key": record.cache_key,+ "query_scan": record.query_scan,}diff --git a/posthog/query_scan/__init__.py b/posthog/query_scan/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/query_scan/analyze.py b/posthog/query_scan/analyze.pynew file mode 100644index 000000000000..2ab7b681b70e--- /dev/null+++ b/posthog/query_scan/analyze.py@@ -0,0 +1,251 @@+"""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.+"""++from posthog.schema import QueryScanFindingKind, QueryScanFindingReason, 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.flag import QueryScanFlag++__all__ = ["PlanSet", "QueryScanResult", "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.+ """++ outer: QueryPlan | None+ subqueries: tuple[QueryPlan, ...] = ()+ team_granules: int | None = None+ range_granules: int | None = None+++@frozen(eq=False)+class QueryScanResult:+ findings: list[QueryScanWarning]+ explain_ok: bool+ range_share: float | None = None+ project_share: float | None = None++ def finding_kinds(self) -> list[str]:+ return [str(finding.kind) for finding in self.findings]+++def analyze(+ plans: PlanSet,+ flag: QueryScanFlag,+ *,+ query_kind: str,+ open_filters_placeholder: bool,+ event_filter: EventFilterOutcome | None = None,+ 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+ 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):+ findings += _findings_for_plan(+ subquery,+ 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,+ table_row_averages=averages,+ event_filter=None,+ )++ return QueryScanResult(+ findings=findings,+ explain_ok=True,+ range_share=range_share,+ project_share=project_share,+ )+++def _findings_for_plan(+ plan: QueryPlan,+ flag: QueryScanFlag,+ *,+ query_kind: str,+ open_filters_placeholder: bool,+ all_time: bool,+ all_history_by_design: bool,+ range_share: float | 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.+ 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 []++ 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+ findings.append(+ build_warning(+ kind=QueryScanFindingKind.NO_START_DATE,+ query_kind=query_kind,+ reason=reason,+ 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)+ ),+ )+ )++ 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):+ findings.append(+ build_warning(+ kind=QueryScanFindingKind.NO_EVENT_FILTER,+ query_kind=query_kind,+ reason=event_reason,+ evidence=_evidence(heaviest.primary_key(), subquery_index),+ )+ )++ person_read = _persons_join_read(plan, heaviest, flag.persons_ratio, table_row_averages)+ if person_read is not None:+ findings.append(+ build_warning(+ kind=QueryScanFindingKind.PERSONS_JOIN,+ query_kind=query_kind,+ evidence=_evidence(person_read.primary_key(), subquery_index),+ )+ )++ return findings+++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.+ """+ 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+ return not heaviest.uses_event_key(), None+++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.+ """+ if range_share is not None:+ return range_share >= event_ratio+ return not _any_skip_pruned_half(read)+++def _any_skip_pruned_half(read: PlanTableRead) -> bool:+ for skip in read.skip_steps():+ if (+ skip.initial_granules is not None+ and skip.initial_granules > 0+ and skip.selected_granules is not None+ and skip.selected_granules < 0.5 * skip.initial_granules+ ):+ return True+ return False+++def _persons_join_read(+ plan: QueryPlan,+ events_read: PlanTableRead,+ persons_ratio: float,+ table_row_averages: dict[str, float],+) -> PlanTableRead | None:+ events_granules = events_read.selected_granules()+ if events_granules is None:+ return None+ events_rows = _estimated_rows(events_read, events_granules, table_row_averages)+ for read in plan.person_reads():+ person_granules = read.selected_granules()+ if person_granules is None:+ continue+ person_rows = _estimated_rows(read, person_granules, table_row_averages)+ # A granule holds several times more rows in the persons tables than in events, so a raw+ # granule ratio under-fires the gate; scale each side to rows when both averages are known.+ if events_rows is not None and person_rows is not None:+ if person_rows >= persons_ratio * events_rows:+ return read+ elif person_granules >= persons_ratio * events_granules:+ return read+ return None+++def _estimated_rows(read: PlanTableRead, granules: int, table_row_averages: dict[str, float]) -> float | None:+ average = read.average_rows_per_granule(table_row_averages)+ return granules * average if average is not None else None+++def _evidence(step: PlanIndex | None, subquery_index: int | None) -> str:+ keys = step.keys if step is not None else ()+ before = step.initial_granules if step is not None else None+ after = step.selected_granules if step is not None else None+ return explain_evidence(keys, before=before, after=after, subquery_index=subquery_index)+++def _share(numerator: int | None, denominator: int | None) -> float | None:+ if numerator is None or denominator is None or denominator <= 0:+ return None+ return min(1.0, max(0.0, numerator / denominator))diff --git a/posthog/query_scan/event_filter.py b/posthog/query_scan/event_filter.pynew file mode 100644index 000000000000..6fb425f9e76d--- /dev/null+++ b/posthog/query_scan/event_filter.py@@ -0,0 +1,182 @@+"""Decide whether a query's event filter lets ClickHouse prune the events table.++The table is sorted by ``(team_id, toDate(timestamp), event, …)``, so only a comparison of ``event``+to fixed names skips granules; a query can look filtered and still read every event.+``classify_event_filter`` reads the tree and says why a filter could not prune.+``combine_event_filter`` folds in the plan, which says whether ClickHouse pruned on ``event`` at all.+"""++from typing import Literal++from posthog.hogql import ast+from posthog.hogql.feature_extractor import _iter_string_constants++from posthog.dataclasses import frozen+from posthog.query_scan.explain import QueryPlan+from posthog.query_scan.tree import (+ EventsRead,+ collect_conditions,+ contains_column_of,+ find_events_reads,+ is_column_of,+ strip_aliases,+)++EventFilterClass = Literal["usable", "not_used", "none"]+EventFilterReason = Literal["in_or", "wrapped", "negated", "dynamic", "not_pruned"]++_EVENT_COLUMN = "event"++_NEGATED_OPS = frozenset(ast.NEGATED_COMPARE_OPS)+_EQUALITY_OPS = frozenset({ast.CompareOperationOp.Eq, ast.CompareOperationOp.In, ast.CompareOperationOp.GlobalIn})+_PATTERN_OPS = frozenset({ast.CompareOperationOp.Like, ast.CompareOperationOp.ILike})+# The sort order is case-sensitive, so only a case-sensitive pattern can seek in it.+_PRUNABLE_PATTERN_OPS = frozenset({ast.CompareOperationOp.Like})+# A fixed comparison the sort order cannot seek on: a regular expression has no prefix to seek+# with, and a range over event names spans the whole table in practice.+_NOT_PRUNED_OPS = frozenset(+ {+ ast.CompareOperationOp.Regex,+ ast.CompareOperationOp.IRegex,+ ast.CompareOperationOp.Gt,+ ast.CompareOperationOp.GtEq,+ ast.CompareOperationOp.Lt,+ ast.CompareOperationOp.LtEq,+ }+)+++@frozen(eq=False)+class EventFilterOutcome:+ classification: EventFilterClass+ reason: EventFilterReason | None = None+++def classify_event_filter(tree: ast.AST) -> 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.+ """+ 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:]):+ return None+ return first+++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.+ """+ 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":+ return EventFilterOutcome(classification="not_used", reason="not_pruned")+ return outcome+++def _classify_read(read: EventsRead, conditions: list[ast.Expr]) -> EventFilterOutcome:+ matched = _classify_from_tree(read, conditions)+ return matched if matched is not None else EventFilterOutcome(classification="none")+++def _classify_from_tree(read: EventsRead, conditions: list[ast.Expr]) -> EventFilterOutcome | None:+ """``None`` when nothing in ``conditions`` names this read's ``event`` column. A conjunction is+ classified like the whole list, so an OR branch that never names the column stays unrelated.+ """+ best: EventFilterOutcome | None = None+ for term in conditions:+ classified = _classify_term(term, read)+ if classified is None:+ continue+ if classified.classification == "usable":+ return classified+ if best is None:+ best = classified+ return best+++def _classify_term(term: ast.Expr, read: EventsRead) -> EventFilterOutcome | None:+ """``None`` when the term says nothing about this read's ``event`` column."""+ term = strip_aliases(term)++ if isinstance(term, ast.And):+ return _classify_from_tree(read, [strip_aliases(child) for child in term.exprs])++ if isinstance(term, ast.Or):+ return _classify_or(term, read)++ if isinstance(term, ast.Not):+ inner = _classify_term(term.expr, read)+ if inner is None:+ return None+ return EventFilterOutcome(classification="not_used", reason="negated")++ if isinstance(term, ast.CompareOperation):+ return _classify_compare(term, read)++ if contains_column_of(term, read, _EVENT_COLUMN):+ # A bare call over `event`, for example `match(event, '…')`.+ return EventFilterOutcome(classification="not_used", reason="wrapped")+ return None+++def _classify_or(term: ast.Or, read: EventsRead) -> EventFilterOutcome | None:+ branches = [_classify_term(branch, read) for branch in term.exprs]+ if all(branch is None for branch in branches):+ 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")+ return EventFilterOutcome(classification="not_used", reason="in_or")+++def _classify_compare(node: ast.CompareOperation, read: EventsRead) -> EventFilterOutcome | None:+ for field_side, value_side in ((node.left, node.right), (node.right, node.left)):+ if is_column_of(field_side, read, _EVENT_COLUMN):+ return _classify_event_compare(node, value_side)+ if contains_column_of(field_side, read, _EVENT_COLUMN):+ return EventFilterOutcome(classification="not_used", reason="wrapped")+ return None+++def _classify_event_compare(node: ast.CompareOperation, value_side: ast.Expr) -> EventFilterOutcome:+ if node.op in _NEGATED_OPS:+ 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 _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("%"):+ return EventFilterOutcome(classification="usable")+ # 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.+ 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):+ return True+ if isinstance(expr, ast.Tuple | ast.Array):+ return all(_is_constant(item) for item in expr.exprs)+ return Falsediff --git a/posthog/query_scan/explain.py b/posthog/query_scan/explain.pynew file mode 100644index 000000000000..130e06496454--- /dev/null+++ b/posthog/query_scan/explain.py@@ -0,0 +1,209 @@+"""Read the JSON that ``EXPLAIN indexes = 1, json = 1`` returns.++ClickHouse reads a table in granules, blocks of rows it reads or skips whole, so the granules a+read kept say how much of the table it touched. The plan reports that per table and per index step.+"""++import re+import json+from typing import Any++from posthog.dataclasses import frozen++# 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")++_PERSON_TABLE_NAMES = ("person", "person_distinct_id2", "person_distinct_id_overrides")++_MIN_MAX_TYPE = "Min-Max"+_PRIMARY_KEY_TYPE = "PrimaryKey"+_SKIP_TYPE = "Skip"+_MERGE_TREE_READ = "ReadFromMergeTree"++# ClickHouse prints each timestamp clause of the Min-Max condition as `timestamp in [A, +Inf)`,+# `timestamp in (-Inf, B]` or `timestamp in [A, B]`. A bound is unix seconds: bare for a DateTime+# constant, single-quoted for a DateTime64 constant, with a fractional part when the constant is+# now64, as in `['1788818422.100868', +Inf)`. HogQL prints now() as now64 and every date literal as+# toDateTime64, so the quoted form is what every insight and SQL-editor query produces. A range with+# a start and an end comes as two clauses under `and(...)`, the end first, so every clause is read.+_SECONDS = r"'?(-?\d+(?:\.\d+)?)'?"+_INFINITY = r"[-+]Inf"+_BOUND_RE = re.compile(rf"in\s*[\[\(]\s*(?:{_INFINITY}|{_SECONDS})\s*,\s*(?:{_INFINITY}|{_SECONDS})\s*[\]\)]")+++@frozen+class TimestampBounds:+ """The timestamp range the Min-Max step could bound, in unix seconds. None means unbounded."""++ lower: int | None+ upper: int | None+++@frozen+class PlanIndex:+ """One entry of a read node's ``Indexes`` list."""++ type: str+ keys: tuple[str, ...]+ condition: str | None+ initial_granules: int | None+ selected_granules: int | None+++@frozen+class PlanTableRead:+ """One ``ReadFromMergeTree`` node. ``table`` is the node's Description."""++ table: str+ indexes: tuple[PlanIndex, ...]++ def reads_events(self) -> bool:+ return self._matches(_EVENTS_TABLE_NAMES)++ def reads_persons(self) -> bool:+ return self._matches(_PERSON_TABLE_NAMES)++ def _matches(self, names: tuple[str, ...]) -> bool:+ # The database qualifier is optional; a longer name that only ends in one of these is another table.+ return any(self.table == name or self.table.endswith(f".{name}") for name in names)++ def average_rows_per_granule(self, averages: dict[str, float]) -> float | None:+ # The map is keyed by bare table name, and the plan's Description keeps the database qualifier.+ return next((average for name, average in averages.items() if self._matches((name,))), None)++ def primary_key(self) -> PlanIndex | None:+ return self._first(_PRIMARY_KEY_TYPE)++ def uses_event_key(self) -> bool:+ """Whether the primary key lists `event`. The plan side of the event-filter verdict, and the fallback+ when no tree verdict shipped.+ """+ primary_key = self.primary_key()+ return primary_key is not None and "event" in primary_key.keys++ def min_max(self) -> PlanIndex | None:+ return self._first(_MIN_MAX_TYPE)++ def _first(self, index_type: str) -> PlanIndex | None:+ for index in self.indexes:+ if index.type == index_type:+ return index+ return None++ def skip_steps(self) -> tuple[PlanIndex, ...]:+ return tuple(index for index in self.indexes if index.type == _SKIP_TYPE)++ def selected_granules(self) -> int | None:+ """The granules the read kept after its last index step."""+ for index in reversed(self.indexes):+ if index.selected_granules is not None:+ return index.selected_granules+ return None++ def timestamp_bounds(self) -> TimestampBounds:+ step = self.min_max()+ if step is None or step.condition is None or not any("timestamp" in key for key in step.keys):+ return TimestampBounds(lower=None, upper=None)+ return _parse_timestamp_bounds(step.condition)+++@frozen+class QueryPlan:+ reads: tuple[PlanTableRead, ...]++ def events_reads(self) -> tuple[PlanTableRead, ...]:+ return tuple(read for read in self.reads if read.reads_events())++ def heaviest_events_read(self) -> PlanTableRead | None:+ """The events read that kept the most granules. A query can read the events table more than+ once, through a join or a union, and the largest read is the one that made it slow.+ """+ reads = self.events_reads()+ if not reads:+ return None+ return max(reads, key=lambda read: read.selected_granules() or 0)++ def person_reads(self) -> tuple[PlanTableRead, ...]:+ return tuple(read for read in self.reads if read.reads_persons())+++def parse_query_plan(payload: object) -> QueryPlan:+ """Never raises: an unexpected shape yields a plan with no reads."""+ if isinstance(payload, str | bytes | bytearray):+ try:+ payload = json.loads(payload)+ except (ValueError, TypeError):+ return QueryPlan(reads=())++ reads: list[PlanTableRead] = []+ _collect_reads(payload, reads)+ return QueryPlan(reads=tuple(reads))+++def _collect_reads(node: object, reads: list[PlanTableRead]) -> None:+ """Append every MergeTree read under ``node`` to ``reads``, in plan order."""+ if isinstance(node, list):+ for item in node:+ _collect_reads(item, reads)+ return+ if not isinstance(node, dict):+ return+ _collect_reads(node.get("Plan"), reads)+ if node.get("Node Type") == _MERGE_TREE_READ:+ read = _parse_read(node)+ if read is not None:+ reads.append(read)+ _collect_reads(node.get("Plans"), reads)+++def _parse_read(node: dict[str, Any]) -> PlanTableRead | None:+ table = node.get("Description")+ if not isinstance(table, str):+ return None+ indexes = node.get("Indexes")+ parsed_indexes: list[PlanIndex] = []+ if isinstance(indexes, list):+ for entry in indexes:+ parsed = _parse_index(entry)+ if parsed is not None:+ parsed_indexes.append(parsed)+ return PlanTableRead(table=table, indexes=tuple(parsed_indexes))+++def _parse_index(entry: object) -> PlanIndex | None:+ if not isinstance(entry, dict):+ return None+ index_type = entry.get("Type")+ if not isinstance(index_type, str):+ return None+ keys = entry.get("Keys")+ condition = entry.get("Condition")+ return PlanIndex(+ type=index_type,+ keys=tuple(key for key in keys if isinstance(key, str)) if isinstance(keys, list) else (),+ condition=condition if isinstance(condition, str) else None,+ initial_granules=_as_int(entry.get("Initial Granules")),+ selected_granules=_as_int(entry.get("Selected Granules")),+ )+++def _parse_timestamp_bounds(condition: str) -> TimestampBounds:+ lowers: list[int] = []+ uppers: list[int] = []+ for match in _BOUND_RE.finditer(condition):+ lower, upper = match.groups()+ if lower is not None:+ lowers.append(_whole_seconds(lower))+ if upper is not None:+ uppers.append(_whole_seconds(upper))+ # The clauses are ANDed, so the range they describe is their intersection.+ return TimestampBounds(lower=max(lowers, default=None), upper=min(uppers, default=None))+++def _whole_seconds(seconds: str) -> int:+ # The fraction is dropped because the range denominator re-runs the bound through toDateTime.+ return int(float(seconds))+++def _as_int(value: object) -> int | None:+ return value if isinstance(value, int) and not isinstance(value, bool) else Nonediff --git a/posthog/query_scan/findings.py b/posthog/query_scan/findings.pynew file mode 100644index 000000000000..1abd2c279244--- /dev/null+++ b/posthog/query_scan/findings.py@@ -0,0 +1,301 @@+"""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.+"""++from posthog.schema import QueryScanFindingKind, QueryScanFindingReason, QueryScanWarning++from posthog.dataclasses import frozen++# Raw SQL gets a clause to add; an insight built from pickers gets the name of its picker.+SQL_QUERY_KIND = "HogQLQuery"++ASSISTANT_GOAL = (+ "Help me get what this query is trying to find, as fast as possible. Start by saying in one sentence what "+ "you think the query is trying to find. If you cannot tell, or if a faster version would answer a different "+ "question, ask me before rewriting. Otherwise propose the rewrite."+)++ASSISTANT_RULES = (+ "The events table is sorted by project, day and event name, so a query is fast when it bounds `timestamp` "+ "and names events; property filters and persons joins do not narrow the read. Use relative time bounds, "+ "never a calendar date. Never invent event names, property values or dates; use only names seen in results "+ "or given by the person. Run at most the one exploration query a finding's guidance names, always with a "+ "recent time bound and a LIMIT, and none when the guidance says none. Propose the rewritten query and label "+ "every change as same answer, narrower, or different. When a change would alter the answer and it is unclear "+ "whether that is acceptable, ask instead of choosing."+)+++@frozen+class _Copy:+ lead: str+ advice: str+ fix: str+++_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 "+ "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.",+ fix=(+ "The query names no events. If its other conditions imply specific events, run one query: "+ "`SELECT event, count() FROM events WHERE <the other conditions> AND timestamp >= now() - interval 7 day "+ "GROUP BY event ORDER BY count() DESC LIMIT 20`, then propose `event IN (...)` with the names seen and "+ "say the result then covers only those. If the query is about the set of events itself, grouping or "+ "counting by event with no other condition, an event filter would change the answer: do not add one, "+ "propose the time bound, and ask which events matter if a narrower question would do."+ ),+)++_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 "+ "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+# 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(+ lead=(+ "Queries are fastest when they name a fixed set of events. This query 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."+ ),+ advice="Put the event filter outside the OR: `WHERE event IN ('…') AND (… OR …)`.",+ fix=(+ "The event condition is one branch of an OR, so the index cannot use it. Run one query for what the "+ "other branch matches: `SELECT event, count() FROM events WHERE <the other branch> AND timestamp >= "+ "now() - interval 7 day GROUP BY event ORDER BY count() DESC LIMIT 20`. If that is a few events, "+ "rewrite as `event IN (<the named events>, <those found>)`, keeping the other branch's own condition "+ "where the answer needs it, and say what changes. If it matches most events, an event filter cannot "+ "help; propose the time bound only."+ ),+ ),+ QueryScanFindingReason.WRAPPED: _Copy(+ lead=(+ "Queries are fastest when they compare `event` directly to fixed names. This query 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."+ ),+ advice="Compare `event` directly to the names.",+ fix=(+ "The condition applies a function to `event`, which the index cannot see through. Run one query to "+ "learn the exact stored names: `SELECT DISTINCT event FROM events WHERE <the wrapped condition> AND "+ "timestamp >= now() - interval 7 day LIMIT 20`, then compare `event` directly to those names. If the "+ "names could vary over time, say the rewrite may miss older spellings and ask."+ ),+ ),+ QueryScanFindingReason.NEGATED: _Copy(+ lead=(+ "Queries are fastest when they explicitly enumerate the events they want. This query 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."+ ),+ ),+ QueryScanFindingReason.DYNAMIC: _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."+ ),+ advice="Compare `event` to fixed names.",+ fix=(+ "`event` is compared to another column or expression, so there is no fixed name to prune on. If that "+ "column has few values, run `SELECT DISTINCT <the column> FROM events WHERE timestamp >= now() - "+ "interval 7 day LIMIT 20` and enumerate; otherwise keep the condition and add the time bound."+ ),+ ),+ QueryScanFindingReason.NOT_PRUNED: _Copy(+ lead=(+ "Queries are fastest when they compare `event` directly to fixed names. This query 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."+ ),+ advice="Compare `event` directly to fixed names, outside any OR.",+ fix=(+ "The query names events, but the condition sits where ClickHouse cannot apply it to the events read, "+ "after a join, in HAVING, or on a subquery's output. Move it, unchanged, into the WHERE of the events "+ "read."+ ),+ ),+}++_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 "+ "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.",+ fix=(+ "Add a relative time bound on `timestamp` in the events read, `timestamp >= now() - interval N day`. "+ "Take N from the question if it states a period. If the question implies all history, a lifetime total "+ "or a first-ever date, say the bound would change the answer and ask how far back is needed. Otherwise "+ "propose 30 days and say it can be widened. No exploration needed."+ ),+)++_NO_START_DATE_FILTERS = _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."+ ),+ advice="Set a date range 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."+ ),+)++_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 "+ "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.",+)++_PERSONS_JOIN = _Copy(+ lead=(+ "Queries are fastest when they take person details from the events table. This query 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`.",+ fix=(+ "The query reads the persons table and that read is as large as the events read. If it filters or "+ "selects a person property, use the copy stored on the event (`person.properties.x`) instead of "+ "joining; if the join only resolves identity, drop it. Say what changes. If unsure whether the person "+ "needs current or at-event property values, ask."+ ),+)+++def _copy_for(kind: QueryScanFindingKind, reason: QueryScanFindingReason | None, *, is_sql: bool) -> _Copy:+ if kind == QueryScanFindingKind.NO_EVENT_FILTER:+ 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+ if kind == QueryScanFindingKind.NO_START_DATE:+ if not is_sql:+ return _NO_START_DATE_INSIGHT+ return _NO_START_DATE_FILTERS if reason == QueryScanFindingReason.FILTERS else _NO_START_DATE_SQL+ if kind == QueryScanFindingKind.PERSONS_JOIN:+ return _PERSONS_JOIN+ raise ValueError(f"No copy for finding kind {kind}")+++def build_warning(+ *,+ kind: QueryScanFindingKind,+ query_kind: str,+ reason: QueryScanFindingReason | None = None,+ evidence: str | None = None,+) -> QueryScanWarning:+ copy = _copy_for(kind, reason, is_sql=query_kind == SQL_QUERY_KIND)+ return QueryScanWarning(+ kind=kind,+ reason=reason,+ message=f"{copy.lead} {copy.advice}",+ fix=copy.fix,+ evidence=evidence,+ )+++def explain_evidence(+ keys: tuple[str, ...], *, before: int | None, after: int | None, subquery_index: int | None+) -> str:+ """What the deciding index step reported, for the person to check. ``before`` and ``after`` are+ the granules it read and kept; ``subquery_index`` says which ``IN`` subquery, when it is one.+ """+ used = ", ".join(keys) if keys else "no columns"+ if before is None or after is None:+ evidence = f"ClickHouse's index used {used}."+ else:+ evidence = f"ClickHouse's index used {used} and kept {after:,} of {before:,} granules."+ if subquery_index is not None:+ return f"In subquery {subquery_index + 1}: {evidence}"+ return evidence+++def assistant_prompt(+ findings: list[QueryScanWarning],+ *,+ rows_read: int | None = None,+ duration_ms: int | None = None,+ range_share: float | None = None,+ project_share: float | None = None,+ killed: bool = False,+ 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.++ ``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.+ """+ if fixable_only:+ findings = [finding for finding in findings if finding.reason != QueryScanFindingReason.FILTERS]+ if not findings:+ return None+ lines = [ASSISTANT_GOAL, ""]+ if rows_read is not None and duration_ms is not None:+ lines.append(_run_line(rows_read, duration_ms, killed))+ elif killed:+ lines.append("ClickHouse stopped this query before it finished.")+ if range_share is not None:+ lines.append(f"It read about {round(range_share * 100)}% of the events in this date range.")+ if project_share is not None:+ lines.append(f"It read about {round(project_share * 100)}% of the project's events.")+ lines.extend(_finding_line(finding) for finding in findings)+ lines.extend(["", ASSISTANT_RULES])+ return "\n".join(lines)+++def _run_line(rows_read: int, duration_ms: int, killed: bool) -> str:+ rows = format_rows(rows_read)+ seconds = format_seconds(duration_ms)+ if killed:+ return f"ClickHouse stopped this query after {seconds} s, having read {rows} rows."+ return f"This query read {rows} rows in {seconds} s."+++def _finding_line(finding: QueryScanWarning) -> str:+ head = f"{finding.kind} ({finding.reason})" if finding.reason else str(finding.kind)+ parts = [f"{head}:"]+ if finding.evidence:+ parts.append(finding.evidence)+ parts.append(finding.fix)+ return "- " + " ".join(parts)+++def format_rows(rows: int) -> str:+ if rows >= 1_000_000_000_000:+ return f"{rows / 1_000_000_000_000:.1f} trillion"+ if rows >= 1_000_000_000:+ return f"{rows / 1_000_000_000:.1f} billion"+ if rows >= 1_000_000:+ return f"{rows / 1_000_000:.1f} million"+ return f"{rows:,}"+++def format_seconds(duration_ms: int) -> str:+ return f"{duration_ms / 1000:.1f}"diff --git a/posthog/query_scan/flag.py b/posthog/query_scan/flag.pynew file mode 100644index 000000000000..b500e8a9ff6a--- /dev/null+++ b/posthog/query_scan/flag.py@@ -0,0 +1,126 @@+"""The `query-scan-warnings` flag: whether a team gets slow query advice, and the thresholds to use."""++from __future__ import annotations++import json+import math+from enum import StrEnum+from typing import TYPE_CHECKING++import structlog+import posthoganalytics++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception++if TYPE_CHECKING:+ from posthog.models.team.team import Team++logger = structlog.get_logger(__name__)++FLAG_KEY = "query-scan-warnings"++DEFAULT_FLOOR_MS = 1000+DEFAULT_EVENT_RATIO = 0.10+DEFAULT_PERSONS_RATIO = 0.5+++class QueryScanMode(StrEnum):+ """Variant of the flag. `log_only`: analyze and show nothing, to calibrate the thresholds. `show`:+ findings are served. Never sent to a client, which sees a summary only under `show`."""++ LOG_ONLY = "log_only"+ SHOW = "show"+++_MODES = {mode.value for mode in QueryScanMode}+++@frozen+class QueryScanFlag:+ """The flag's variant for a team, and the thresholds from its payload."""++ # `log_only` analyzes but shows nothing; `show` lets clients show findings.+ mode: QueryScanMode+ # A finished run is analyzed only when its ClickHouse time reaches this. A run ClickHouse+ # stopped is analyzed at any duration.+ floor_ms: int+ # No event filter is reported unless the query read at least this share of its date range's events.+ 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++ @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}"+++class InvalidPayload(ValueError):+ pass+++def get_query_scan_flag(team: Team) -> QueryScanFlag | None:+ """The flag for `team`, or None when off. Evaluated locally on the organization and the project.++ Nothing here raises: the runner calls this on every query, so a flag outage or a bad payload+ reads as off.+ """+ try:+ result = posthoganalytics.get_feature_flag_result(+ FLAG_KEY,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {+ "id": str(team.id),+ "created_at": team.created_at.isoformat() if team.created_at else None,+ "uuid": str(team.uuid),+ },+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ if result is None or result.variant not in _MODES:+ return None+ return _parse(QueryScanMode(result.variant), result.payload)+ except InvalidPayload as error:+ # The thresholds are typed by hand into the flag, which only checks that they are JSON. A+ # value the code cannot use turns the feature off and is reported, so the person who set+ # it hears about it.+ capture_exception(error, {"flag": FLAG_KEY, "team_id": team.id})+ logger.exception("query_scan_flag_payload_invalid", team_id=team.id, error=str(error))+ return None+ except Exception:+ logger.warning("query_scan_flag_evaluation_failed", team_id=team.id, exc_info=True)+ return None+++def _parse(mode: QueryScanMode, payload: object) -> QueryScanFlag:+ """A missing threshold falls back to its default; one that is present but not a finite number is an error."""+ if isinstance(payload, str):+ try:+ payload = json.loads(payload)+ except ValueError as error:+ raise InvalidPayload("payload is not JSON") from error+ if payload is None:+ values: dict[str, object] = {}+ elif isinstance(payload, dict):+ values = payload+ else:+ raise InvalidPayload(f"payload must be an object, got {payload!r}")+ return QueryScanFlag(+ mode=mode,+ 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),+ )+++def _number(values: dict[str, object], key: str, default: float) -> float:+ value = values.get(key, default)+ # bool is an int in Python, and true/false is a typo here, not a threshold.+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):+ raise InvalidPayload(f"{key} must be a finite number, got {value!r}")+ return valuediff --git a/posthog/query_scan/job.py b/posthog/query_scan/job.pynew file mode 100644index 000000000000..64476a402024--- /dev/null+++ b/posthog/query_scan/job.py@@ -0,0 +1,343 @@+"""The query scan job, kept out of Celery so a test can call it directly.++It asks ClickHouse how it planned the run's SQL, reads findings and shares off the plan, and stores+the result in the scan slot. It runs EXPLAINs only, on the offline pool.+"""++from __future__ import annotations++from time import perf_counter+from typing import Any, get_args++import structlog+from celery.exceptions import SoftTimeLimitExceeded++from posthog.schema import QueryScanAnalysis, QueryScanWarning++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.dataclasses import frozen+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.event_filter import (+ EventFilterClass,+ EventFilterOutcome,+ EventFilterReason,+ combine_event_filter,+)+from posthog.query_scan.explain import QueryPlan, TimestampBounds, parse_query_plan+from posthog.query_scan.flag import get_query_scan_flag+from posthog.query_scan.slot import (+ clear as clear_slot,+ set_done,+)++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.+_ROW_AVERAGE_TABLES = (+ "sharded_events",+ "sharded_events_json",+ "person",+ "person_distinct_id2",+ "person_distinct_id_overrides",+)++# The tree verdict the trigger ships per execution. A payload outside these leaves the event filter+# to the plan alone, the same as a payload that carried no verdict.+_EVENT_FILTER_CLASSES = get_args(EventFilterClass)+_EVENT_FILTER_REASONS = get_args(EventFilterReason)+++@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.+ """++ stubbed_sql: str+ subqueries: tuple[str, ...]+ values: dict[str, Any]+ rows_read: int+ event_filter: 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 ()),+ values=payload.get("values") or {},+ rows_read=payload.get("rows_read") or 0,+ event_filter=payload.get("event_filter"),+ )+++@frozen+class QueryScanJob:+ """One run to analyze, as the trigger printed it."""++ team: Team+ cache_key: str+ executions: tuple[Execution, ...]+ rows_read: int+ duration_ms: int+ trigger: str+ query_kind: str | None+ open_filters_placeholder: bool+ insight_id: int | None = None+ dashboard_id: int | None = None+ killed: bool = False+ error_type: str | None = None+ all_time: bool = False+ all_history_by_design: bool = False+++def run_query_scan(job: QueryScanJob) -> None:+ """Analyze one run and store the result. Never raises, and never retries: the next slow+ run of the same query enqueues a new job."""+ started = perf_counter()+ try:+ _run(job, started)+ except SoftTimeLimitExceeded:+ # The task handles its own timeout; letting it propagate leaves the pending slot to expire.+ raise+ except Exception as error:+ capture_exception(error, {"team_id": job.team.pk, "cache_key": job.cache_key, "context": "query_scan_job"})+++def _run(job: QueryScanJob, started: float) -> None:+ flag = get_query_scan_flag(job.team)+ if flag is None:+ # The flag went off between the enqueue and now. Leave the pending slot to expire.+ return++ # Read once per run: the average is a table-wide property, the same for every execution.+ table_row_averages = _table_row_averages(job.team.pk)++ # The team's whole data on the initiator shard, run once for every execution's share.+ team_granules = _denominator_granules(+ _explain("SELECT uuid FROM events WHERE team_id = %(scan_team_id)s", {"scan_team_id": job.team.pk}, job.team.pk)+ )+ range_cache: dict[tuple[int | None, int | None], int | None] = {}++ 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+ )+ 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),+ 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),+ table_row_averages=table_row_averages,+ )+ )++ merged = _merge(results, job.executions)+ # Stored under the flag in force now. A pending claim left under other thresholds expires on its+ # own key.+ if merged.explain_ok:+ set_done(+ job.team.pk,+ job.cache_key,+ thresholds=flag.thresholds_fingerprint,+ analysis=QueryScanAnalysis(+ findings=list(merged.findings), range_share=merged.range_share, project_share=merged.project_share+ ),+ )+ else:+ # 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.+ clear_slot(job.team.pk, job.cache_key, thresholds=flag.thresholds_fingerprint)+ _report(job, merged, flag_event_ratio=flag.event_ratio, job_ms=round((perf_counter() - started) * 1000))+++def _plan(sql: str, values: dict[str, Any], team_id: int) -> QueryPlan | None:+ """The plan for one stubbed query, or None when its EXPLAIN did not return one.++ Only stubbed SQL reaches EXPLAIN, because it runs every IN subquery it is given. A rows cap+ cannot guard the exact SQL, since ClickHouse checks it against the planned read's own estimate.+ """+ rows = _explain(sql, values, team_id)+ if rows is None:+ return 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.+ """+ payload = execution.event_filter+ if not payload:+ return None+ classification = payload.get("classification")+ if classification is None or classification not in _EVENT_FILTER_CLASSES:+ return None+ reason = payload.get("reason")+ outcome = EventFilterOutcome(+ classification=classification,+ reason=reason if reason in _EVENT_FILTER_REASONS else None,+ )+ return combine_event_filter(outcome, outer)+++def _range_granules(+ team_id: int,+ outer: QueryPlan | None,+ 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+ range is all time, so it equals the team denominator.+ """+ events_read = outer.heaviest_events_read() if outer is not None else None+ 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+ key = (bounds.lower, bounds.upper)+ if key not in cache:+ cache[key] = _denominator_granules(_explain_range(team_id, bounds))+ return cache[key]+++def _explain_range(team_id: int, bounds: TimestampBounds) -> list[Any] | None:+ conditions = ["team_id = %(scan_team_id)s"]+ values: dict[str, Any] = {"scan_team_id": team_id}+ if bounds.lower is not None:+ conditions.append("timestamp >= toDateTime(%(scan_lower)s)")+ values["scan_lower"] = bounds.lower+ if bounds.upper is not None:+ conditions.append("timestamp < toDateTime(%(scan_upper)s)")+ values["scan_upper"] = bounds.upper+ # A bare count() can be answered from a count projection with no table read in the plan, so the+ # denominator selects a column; EXPLAIN reads nothing either way.+ return _explain("SELECT uuid FROM events WHERE " + " AND ".join(conditions), values, team_id)+++def _denominator_granules(rows: list[Any] | None) -> int | None:+ if rows is None:+ return None+ events_read = parse_query_plan(rows[0][0]).heaviest_events_read()+ return events_read.selected_granules() if events_read is not None else None+++def _table_row_averages(team_id: int) -> dict[str, float]:+ """Average rows per granule per table, from `system.parts` metadata. A failure yields an empty map+ rather than failing the analysis: the persons gate then falls back to raw granules.+ """+ try:+ with tags_context(product=Product.PRODUCT_ANALYTICS, feature=Feature.QUERY_SCAN):+ rows = sync_execute(+ "SELECT table, sum(rows) / sum(marks) FROM system.parts WHERE active AND table IN %(tables)s GROUP BY table",+ {"tables": list(_ROW_AVERAGE_TABLES)},+ settings={"max_execution_time": TABLE_AVERAGES_MAX_SECONDS},+ workload=Workload.OFFLINE,+ team_id=team_id,+ readonly=True,+ )+ except SoftTimeLimitExceeded:+ raise+ except Exception:+ logger.warning("query_scan_table_averages_failed", team_id=team_id, exc_info=True)+ return {}+ return {table: float(average) for table, average in rows if average is not None and float(average) > 0}+++def _explain(sql: str, values: dict[str, Any], team_id: int) -> list[Any] | None:+ """EXPLAIN on the offline pool. None on any failure, which fails that plan closed."""+ try:+ with tags_context(product=Product.PRODUCT_ANALYTICS, feature=Feature.QUERY_SCAN):+ # nosemgrep: clickhouse-fstring-param-audit - sql is compiled from the HogQL AST by the printer, and its values stay parameterized+ rows = sync_execute(+ f"EXPLAIN indexes = 1, json = 1 {sql}",+ values,+ settings={"max_execution_time": EXPLAIN_MAX_SECONDS},+ workload=Workload.OFFLINE,+ team_id=team_id,+ readonly=True,+ )+ return rows+ except SoftTimeLimitExceeded:+ # Never swallow the task's timeout as an explain failure; the task leaves the slot pending.+ raise+ except Exception:+ logger.warning("query_scan_explain_failed", team_id=team_id, exc_info=True)+ return 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."""+ findings: list[QueryScanWarning] = []+ seen: set[tuple[str, 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)+ findings.append(finding)++ heaviest = _heaviest_result(results, executions)+ return QueryScanResult(+ findings=findings,+ # A person reads the advice as if it covered the whole run, so one unplanned execution+ # fails the run, the way the trigger drops a run with one execution it cannot ship.+ explain_ok=all(result.explain_ok for result in results),+ range_share=heaviest.range_share if heaviest is not None else None,+ project_share=heaviest.project_share if heaviest is not None else None,+ )+++def _heaviest_result(results: list[QueryScanResult], executions: tuple[Execution, ...]) -> QueryScanResult | None:+ if not results:+ return None+ return max(zip(results, executions), key=lambda pair: pair[1].rows_read)[0]+++def _report(job: QueryScanJob, merged: QueryScanResult, *, flag_event_ratio: float, job_ms: int) -> None:+ """Send `query scan analyzed`, findings or not: a run with no findings is what says which check to+ write next.+ """+ properties = {+ "cache_key": job.cache_key,+ "insight_id": job.insight_id,+ "dashboard_id": job.dashboard_id,+ "query_kind": job.query_kind,+ "trigger": job.trigger,+ "rows_read": job.rows_read,+ "duration_ms": job.duration_ms,+ "range_share": merged.range_share,+ "project_share": merged.project_share,+ "event_ratio": flag_event_ratio,+ "explain_ok": merged.explain_ok,+ "finding_kinds": merged.finding_kinds(),+ "killed": job.killed,+ "error_type": job.error_type,+ "job_ms": job_ms,+ }+ # A Celery worker can exit before the global client's background flush runs, so this event+ # needs a client that is flushed here.+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=str(job.team.uuid),+ event="query scan analyzed",+ properties=properties,+ groups=groups(job.team.organization, job.team),+ )diff --git a/posthog/query_scan/serve.py b/posthog/query_scan/serve.pynew file mode 100644index 000000000000..115d190895b5--- /dev/null+++ b/posthog/query_scan/serve.py@@ -0,0 +1,79 @@+"""Put the stored analysis on a summary, on a cache hit and on a fresh run alike.++A summary that asked for an analysis says so, and that alone decides whether the slot is read; the+cached copy of the summary is never rewritten. A Redis failure drops the advice, never the results.+"""++from __future__ import annotations++from typing import Any++import structlog++from posthog.schema import QueryScanAnalysis, QueryScanSummary++from posthog.models.team.team import Team+from posthog.query_scan.findings import assistant_prompt+from posthog.query_scan.flag import QueryScanMode, get_query_scan_flag+from posthog.query_scan.slot import get as get_slot++logger = structlog.get_logger(__name__)+++def hydrate_response_scan(team: Team, response: Any) -> None:+ """Put the stored analysis on an outgoing query response, or take the summary off when the flag no+ longer shows findings."""+ try:+ summary = getattr(response, "query_scan", None)+ if summary is None:+ return+ response.query_scan = hydrate(team, summary, getattr(response, "cache_key", None))+ except Exception:+ logger.warning("query_scan_hydrate_failed", team_id=team.pk, exc_info=True)+++def hydrate_scan_summary(team: Team, summary: dict[str, Any], cache_key: str | None) -> dict[str, Any] | None:+ """The same for a surface of plain dicts, such as an insight's stored result. None when the flag no+ longer shows findings, and when the summary cannot be read."""+ try:+ hydrated = hydrate(team, QueryScanSummary.model_validate(summary), cache_key)+ if hydrated is None:+ return None+ return hydrated.model_dump(mode="json", by_alias=True, exclude_none=True)+ except Exception:+ logger.warning("query_scan_hydrate_failed", team_id=team.pk, exc_info=True)+ return None+++def hydrate(team: Team, summary: QueryScanSummary, cache_key: str | None) -> QueryScanSummary | None:+ """``summary`` with its stored analysis on it, or None when the flag no longer shows findings. The+ flag is evaluated locally, so a summary that asked for nothing costs no round trip."""+ flag = get_query_scan_flag(team)+ if flag is None or flag.mode != QueryScanMode.SHOW:+ return None+ if not summary.analysis_requested or cache_key is None:+ return summary+ slot = get_slot(team.pk, cache_key, thresholds=flag.thresholds_fingerprint)+ if slot is None or slot.analysis is None:+ return summary+ summary.analysis = analysis_with_prompt(+ slot.analysis, rows_read=summary.rows_read, duration_ms=summary.duration_ms, killed=bool(summary.killed)+ )+ return summary+++def analysis_with_prompt(+ analysis: QueryScanAnalysis, *, rows_read: int | None = None, duration_ms: int | None = None, killed: bool = False+) -> QueryScanAnalysis:+ """The analysis with the message "Fix with AI" sends, built here so no client keeps its own copy.+ The run facts describe the run being served, not the run the analysis came from."""+ prompt = assistant_prompt(+ list(analysis.findings),+ rows_read=rows_read,+ duration_ms=duration_ms,+ range_share=analysis.range_share,+ project_share=analysis.project_share,+ killed=killed,+ fixable_only=True,+ )+ return analysis.model_copy(update={"assistant_prompt": prompt})diff --git a/posthog/query_scan/slot.py b/posthog/query_scan/slot.pynew file mode 100644index 000000000000..d641b3f46a1b--- /dev/null+++ b/posthog/query_scan/slot.py@@ -0,0 +1,127 @@+"""The scan slot: one query's analysis, keyed by its cache key and the flag's thresholds.++Claimed by the trigger, written once by the job, read by every response for that cache key, in the+query cache's Redis. The thresholds and the slot version ride in the key, so an analysis run under+other gates, or written by older code, lives under another key and expires on its own instead of+blocking the claim. A read returns None on any Redis or JSON failure, and a write logs and swallows.+"""++from __future__ import annotations++import json+from typing import Any++import structlog++from posthog.schema import QueryScanAnalysis++from posthog.dataclasses import frozen+from posthog.query_cache.storage import query_cache_raw_client++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++PENDING_TTL_SECONDS = 10 * 60+DONE_TTL_SECONDS = 30 * 24 * 60 * 60++# The job runs on a queue sized to protect ClickHouse, so one project whose dashboards are all+# slow must not be able to fill it.+ENQUEUE_CAP_PER_WINDOW = 10+ENQUEUE_WINDOW_SECONDS = 60+++@frozen+class QueryScanSlot:+ """One query's slot: the analysis once the job stored it, None while the job runs."""++ analysis: QueryScanAnalysis | None = None+++def slot_key(team_id: int, cache_key: str, thresholds: str) -> str:+ return f"query_scan:v{SLOT_VERSION}:{team_id}:{cache_key}:{thresholds}"+++def enqueue_counter_key(team_id: int) -> str:+ return f"query_scan:enqueues:{team_id}"+++def get(team_id: int, cache_key: str, *, thresholds: str) -> QueryScanSlot | None:+ """The stored slot for these thresholds, or None. An analysis run under other gates lives under+ another key, so the next slow run analyzes again instead of serving it.+ """+ try:+ # The primary, not the read replica the query cache reads through. The response that+ # enqueues a scan reads the slot back in the same request, so a replica behind the write+ # would miss it.+ raw = query_cache_raw_client().get(slot_key(team_id, cache_key, thresholds))+ if raw is None:+ return None+ return _deserialize(json.loads(raw))+ except Exception:+ logger.warning("query_scan_slot_read_failed", team_id=team_id, exc_info=True)+ return None+++def set_pending(team_id: int, cache_key: str, *, thresholds: str) -> bool:+ """Claim the slot for one job. The write is conditional, so two slow runs of one query enqueue one job."""+ return _write(team_id, cache_key, {"pending": True}, PENDING_TTL_SECONDS, thresholds=thresholds, nx=True)+++def set_done(team_id: int, cache_key: str, *, thresholds: str, analysis: QueryScanAnalysis) -> None:+ value = {"analysis": analysis.model_dump(by_alias=True, exclude_none=True)}+ _write(team_id, cache_key, value, DONE_TTL_SECONDS, thresholds=thresholds)+++def clear(team_id: int, cache_key: str, *, thresholds: str) -> None:+ """Drop the slot, for a claim no job will fill; a pending slot nobody answers reads as in flight+ for its whole TTL.+ """+ try:+ query_cache_raw_client().delete(slot_key(team_id, cache_key, thresholds))+ except Exception:+ logger.warning("query_scan_slot_clear_failed", team_id=team_id, exc_info=True)+++def claim_enqueue_budget(team_id: int) -> bool:+ """Whether this project may enqueue another scan in the window. One dashboard refresh can produce+ hundreds of slow queries. A Redis failure allows the enqueue; the slot claim that follows stops+ there instead.+ """+ try:+ client = query_cache_raw_client()+ key = enqueue_counter_key(team_id)+ # An `INCR` that creates the key and a later `EXPIRE` can be split by a worker that dies,+ # and the counter left behind has no TTL, so the project stays capped for good.+ client.set(key, 0, nx=True, ex=ENQUEUE_WINDOW_SECONDS)+ count = client.incr(key)+ return count <= ENQUEUE_CAP_PER_WINDOW+ except Exception:+ logger.warning("query_scan_enqueue_budget_failed", team_id=team_id, exc_info=True)+ return True+++def _write(+ team_id: int, cache_key: str, value: dict[str, Any], ttl_seconds: int, *, thresholds: str, nx: bool = False+) -> bool:+ try:+ payload = json.dumps(value)+ key = slot_key(team_id, cache_key, thresholds)+ return bool(query_cache_raw_client().set(key, payload, ex=ttl_seconds, nx=nx))+ except Exception:+ logger.warning("query_scan_slot_write_failed", team_id=team_id, exc_info=True)+ return False+++def _deserialize(value: Any) -> QueryScanSlot | None:+ if not isinstance(value, dict):+ return None+ analysis = value.get("analysis")+ if isinstance(analysis, dict):+ return QueryScanSlot(analysis=QueryScanAnalysis.model_validate(analysis))+ if value.get("pending"):+ return QueryScanSlot()+ return Nonediff --git a/posthog/query_scan/stub.py b/posthog/query_scan/stub.pynew file mode 100644index 000000000000..9ee2c2b8b965--- /dev/null+++ b/posthog/query_scan/stub.py@@ -0,0 +1,156 @@+"""Replace every subquery used as a value with a constant before asking ClickHouse for the plan.++``EXPLAIN`` runs a subquery to completion before it plans whenever the subquery stands in for a+value: the right side of ``x IN (subquery)``, or a scalar ``(SELECT ...)`` in a select list, 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.++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.++A warehouse table is swapped for a stand-in with its columns and no rows. The real one prints as+``s3(url, key, secret, ...)``, which puts the source's credentials in the printed values, and+EXPLAIN lists the bucket to plan it. The stand-in keeps the join's shape around the events read,+which is all the plan is read for.+"""++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.s3_table import DataWarehouseTable+from posthog.hogql.visitor import CloningVisitor++from posthog.dataclasses import frozen+++def _always_true() -> ast.Constant:+ return ast.Constant(value=1, type=ast.IntegerType(nullable=False))+++def _stubbed_value() -> ast.Constant:+ # A value never decides which granules the outer read plans, so any constant stands in. NULL is+ # accepted wherever a stand-in can land (``toStartOfDay(NULL)``, ``concat('a', NULL)``), and+ # the ClickHouse printer inlines a ``None`` constant as ``NULL`` without a type.+ return ast.Constant(value=None)+++class EmptyWarehouseTable(DataWarehouseTable):+ """A warehouse table's stand-in for the plan: ``null(structure)`` is an empty table with the+ same columns. Subclassing keeps the printer's warehouse-table handling, such as the subquery+ wrap around a joined table, so the printed shape matches the real query's.+ """++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return f"null({context.add_value(self.structure)})"+++def _stand_in_join_type(join_type: ast.Type | None) -> ast.TableType | ast.TableAliasType | None:+ """The join's type with its warehouse table swapped for the stand-in, or None to leave it."""+ if isinstance(join_type, ast.TableAliasType):+ inner = _stand_in_table_type(join_type.table_type)+ return None if inner is None else ast.TableAliasType(alias=join_type.alias, table_type=inner)+ if isinstance(join_type, ast.TableType):+ return _stand_in_table_type(join_type)+ return None+++def _stand_in_table_type(table_type: ast.TableType | ast.LazyTableType) -> ast.TableType | None:+ if not isinstance(table_type, ast.TableType):+ return None+ table = table_type.table+ if not isinstance(table, DataWarehouseTable) or isinstance(table, EmptyWarehouseTable) or not table.structure:+ return None+ stand_in = EmptyWarehouseTable(+ name=table.name, url="", format=table.format, structure=table.structure, fields=table.fields+ )+ return ast.TableType(table=stand_in)+++@frozen+class StubResult:+ """The stubbed tree and the subqueries taken out of it, in the order they were visited."""++ stubbed: ast.Expr+ subqueries: tuple[ast.SelectQuery | ast.SelectSetQuery, ...]+++def stub_in_subqueries(node: ast.Expr) -> StubResult:+ visitor = _StubVisitor()+ visitor.mark_source(node)+ stubbed = visitor.visit(node)+ return StubResult(stubbed=stubbed, subqueries=tuple(visitor.subqueries))+++class _StubVisitor(CloningVisitor):+ def __init__(self) -> None:+ # The stubbed tree is printed as ClickHouse SQL, and the printer refuses a FROM clause+ # whose types were cleared, so the clone keeps the resolved types.+ super().__init__(clear_types=False)+ self.subqueries: list[ast.SelectQuery | ast.SelectSetQuery] = []+ # ``id()`` of each subquery that is a query source. A parent marks its source children before+ # ``super()`` recurses into them.+ self._source_ids: set[int] = set()++ def mark_source(self, node: ast.Expr) -> None:+ self._source_ids.add(id(node))++ def visit_select_query(self, node: ast.SelectQuery) -> ast.Expr:+ if id(node) not in self._source_ids:+ self.subqueries.append(node)+ return _stubbed_value()+ return super().visit_select_query(node)++ def visit_select_set_query(self, node: ast.SelectSetQuery) -> ast.Expr:+ if id(node) not in self._source_ids:+ self.subqueries.append(node)+ return _stubbed_value()+ self.mark_source(node.initial_select_query)+ for member in node.subsequent_select_queries:+ self.mark_source(member.select_query)+ return super().visit_select_set_query(node)++ def visit_join_expr(self, node: ast.JoinExpr) -> ast.JoinExpr:+ # ``super()`` passes this same table node to ``self.visit``, so marking it here is enough.+ if isinstance(node.table, (ast.SelectQuery, ast.SelectSetQuery)):+ self.mark_source(node.table)+ cloned = super().visit_join_expr(node)+ # The clone shares its type with the run's tree, so the swap builds a new one rather than editing it.+ stand_in = _stand_in_join_type(cloned.type)+ if stand_in is not None:+ cloned.type = stand_in+ return cloned++ def visit_cte(self, node: ast.CTE) -> ast.CTE:+ # A column CTE (``WITH (SELECT ...) AS a``) is a value, so it falls through to the value stub.+ if node.cte_type == "subquery" and isinstance(node.expr, (ast.SelectQuery, ast.SelectSetQuery)):+ self.mark_source(node.expr)+ return super().visit_cte(node)++ def visit_compare_operation(self, node: ast.CompareOperation) -> ast.Expr:+ # A stub value left inside a comparison (``timestamp >= NULL``) would change which granules+ # the key condition plans, so the whole comparison folds to true, whatever the operator.+ before = len(self.subqueries)+ cloned = super().visit_compare_operation(node)+ if len(self.subqueries) > before:+ return _always_true()+ return cloned++ def visit_not(self, node: ast.Not) -> ast.Expr:+ # Fold the whole ``NOT``: stubbing only the inner comparison leaves ``NOT 1``, which the key+ # condition reads as always false, so the plan would report zero granules.+ before = len(self.subqueries)+ cloned = super().visit_not(node)+ if len(self.subqueries) > before:+ return _always_true()+ return cloned++ def visit_call(self, node: ast.Call) -> ast.Expr:+ # The parser emits ``NOT (...)`` as a ``not(...)`` call rather than an ``ast.Not``. Fold it+ # whole for the same reason as ``visit_not``.+ if node.name.lower() == "not" and len(node.args) == 1:+ before = len(self.subqueries)+ cloned = super().visit_call(node)+ if len(self.subqueries) > before:+ return _always_true()+ return cloned+ return super().visit_call(node)diff --git a/posthog/query_scan/test/__init__.py b/posthog/query_scan/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/query_scan/test/fixtures/plan_event_filter_in_or.json b/posthog/query_scan/test/fixtures/plan_event_filter_in_or.jsonnew file mode 100644index 000000000000..fd879b2cea06--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_event_filter_in_or.json@@ -0,0 +1,120 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_75",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_71",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_65",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_48",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_47",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_76",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_44",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "timestamp"+ ],+ "Condition": "(timestamp in [1788461220, +Inf))",+ "Initial Parts": 3564,+ "Selected Parts": 115,+ "Initial Granules": 270833110,+ "Selected Granules": 5538857+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(timestamp)"+ ],+ "Condition": "(toYYYYMM(timestamp) in [202609, +Inf))",+ "Initial Parts": 115,+ "Selected Parts": 115,+ "Initial Granules": 5538857,+ "Selected Granules": 5538857+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "toDate(timestamp)",+ "event",+ "cityHash64(distinct_id)"+ ],+ "Condition": "and(or((cityHash64(distinct_id) in [11760547678682620745, 11760547678682620745]), (event in ['$pageview', '$pageview'])), and((toDate(timestamp) in [20699, +Inf)), (team_id in [2, 2])))",+ "Search Algorithm": "generic exclusion search",+ "Initial Parts": 115,+ "Selected Parts": 74,+ "Initial Granules": 5538857,+ "Selected Granules": 25745+ },+ {+ "Type": "Skip",+ "Name": "minmax_sharded_events_timestamp",+ "Description": "minmax GRANULARITY 1",+ "Condition": "(timestamp in [1788461220, +Inf))",+ "Initial Parts": 74,+ "Selected Parts": 70,+ "Initial Granules": 25745,+ "Selected Granules": 23018+ },+ {+ "Type": "Skip",+ "Name": "bloom_filter_distinct_id",+ "Description": "bloom_filter GRANULARITY 1",+ "Initial Parts": 70,+ "Selected Parts": 70,+ "Initial Granules": 23018,+ "Selected Granules": 23018+ },+ {+ "Type": "Skip",+ "Name": "<Combined skip indexes>",+ "Description": "Final set of granules after AND/OR processing",+ "Initial Parts": 70,+ "Selected Parts": 74,+ "Initial Granules": 23018,+ "Selected Granules": 23018+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_64",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_event_filter_negated.json b/posthog/query_scan/test/fixtures/plan_event_filter_negated.jsonnew file mode 100644index 000000000000..bec9c0dcaa49--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_event_filter_negated.json@@ -0,0 +1,101 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_75",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_71",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_65",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_48",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_47",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_76",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_44",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "timestamp"+ ],+ "Condition": "(timestamp in [1788499982, +Inf))",+ "Initial Parts": 3542,+ "Selected Parts": 97,+ "Initial Granules": 271158937,+ "Selected Granules": 5583026+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(timestamp)"+ ],+ "Condition": "(toYYYYMM(timestamp) in [202609, +Inf))",+ "Initial Parts": 97,+ "Selected Parts": 97,+ "Initial Granules": 5583026,+ "Selected Granules": 5583026+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "toDate(timestamp)",+ "event"+ ],+ "Condition": "and((event not in ['$pageview', '$pageview']), and((toDate(timestamp) in [20700, +Inf)), (team_id in [2, 2])))",+ "Search Algorithm": "generic exclusion search",+ "Initial Parts": 97,+ "Selected Parts": 56,+ "Initial Granules": 5583026,+ "Selected Granules": 326023+ },+ {+ "Type": "Skip",+ "Name": "minmax_sharded_events_timestamp",+ "Description": "minmax GRANULARITY 1",+ "Condition": "(timestamp in [1788499982, +Inf))",+ "Initial Parts": 56,+ "Selected Parts": 52,+ "Initial Granules": 326023,+ "Selected Granules": 324229+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_64",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_event_filter_used.json b/posthog/query_scan/test/fixtures/plan_event_filter_used.jsonnew file mode 100644index 000000000000..83fbdc93ae1d--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_event_filter_used.json@@ -0,0 +1,101 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_75",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_71",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_65",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_48",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_47",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_76",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_44",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "timestamp"+ ],+ "Condition": "(timestamp in [1788461182, +Inf))",+ "Initial Parts": 3573,+ "Selected Parts": 108,+ "Initial Granules": 270832618,+ "Selected Granules": 5538361+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(timestamp)"+ ],+ "Condition": "(toYYYYMM(timestamp) in [202609, +Inf))",+ "Initial Parts": 108,+ "Selected Parts": 108,+ "Initial Granules": 5538361,+ "Selected Granules": 5538361+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "toDate(timestamp)",+ "event"+ ],+ "Condition": "and((event in ['$pageview', '$pageview']), and((toDate(timestamp) in [20699, +Inf)), (team_id in [2, 2])))",+ "Search Algorithm": "generic exclusion search",+ "Initial Parts": 108,+ "Selected Parts": 67,+ "Initial Granules": 5538361,+ "Selected Granules": 9613+ },+ {+ "Type": "Skip",+ "Name": "minmax_sharded_events_timestamp",+ "Description": "minmax GRANULARITY 1",+ "Condition": "(timestamp in [1788461182, +Inf))",+ "Initial Parts": 67,+ "Selected Parts": 63,+ "Initial Granules": 9613,+ "Selected Granules": 8567+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_64",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_no_date_bound.json b/posthog/query_scan/test/fixtures/plan_no_date_bound.jsonnew file mode 100644index 000000000000..c14590d94262--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_no_date_bound.json@@ -0,0 +1,84 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_75",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_71",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_65",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_23",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_22",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_76",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_19",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Condition": "true",+ "Initial Parts": 3511,+ "Selected Parts": 3511,+ "Initial Granules": 265491928,+ "Selected Granules": 265491928+ },+ {+ "Type": "Partition",+ "Condition": "true",+ "Initial Parts": 3511,+ "Selected Parts": 3511,+ "Initial Granules": 265491928,+ "Selected Granules": 265491928+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "event"+ ],+ "Condition": "and((event in ['$pageview', '$pageview']), (team_id in [2, 2]))",+ "Search Algorithm": "generic exclusion search",+ "Initial Parts": 3511,+ "Selected Parts": 1659,+ "Initial Granules": 265491928,+ "Selected Granules": 412056+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_64",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_no_event_filter.json b/posthog/query_scan/test/fixtures/plan_no_event_filter.jsonnew file mode 100644index 000000000000..6b8a32bea98b--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_no_event_filter.json@@ -0,0 +1,100 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_75",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_71",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_65",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_23",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_22",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_76",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_19",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "timestamp"+ ],+ "Condition": "(timestamp in [1788461215, +Inf))",+ "Initial Parts": 3508,+ "Selected Parts": 66,+ "Initial Granules": 265491898,+ "Selected Granules": 5582406+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(timestamp)"+ ],+ "Condition": "(toYYYYMM(timestamp) in [202609, +Inf))",+ "Initial Parts": 66,+ "Selected Parts": 66,+ "Initial Granules": 5582406,+ "Selected Granules": 5582406+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "toDate(timestamp)"+ ],+ "Condition": "and((toDate(timestamp) in [20699, +Inf)), (team_id in [2, 2]))",+ "Search Algorithm": "binary search",+ "Initial Parts": 66,+ "Selected Parts": 60,+ "Initial Granules": 5582406,+ "Selected Granules": 362907+ },+ {+ "Type": "Skip",+ "Name": "minmax_sharded_events_timestamp",+ "Description": "minmax GRANULARITY 1",+ "Condition": "(timestamp in [1788461215, +Inf))",+ "Initial Parts": 60,+ "Selected Parts": 56,+ "Initial Granules": 362907,+ "Selected Granules": 329267+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_64",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_object_storage_read.json b/posthog/query_scan/test/fixtures/plan_object_storage_read.jsonnew file mode 100644index 000000000000..9660420525ae--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_object_storage_read.json@@ -0,0 +1,106 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_30",+ "Description": "Project names",+ "Plans": [+ {+ "Node Type": "Limit",+ "Node Id": "Limit_29",+ "Description": "preliminary LIMIT",+ "Plans": [+ {+ "Node Type": "Sorting",+ "Node Id": "Sorting_28",+ "Description": "Sorting for ORDER BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_51",+ "Description": "(Before ORDER BY + Projection)",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_25",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_47",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_49",+ "Description": "(Before GROUP BY + (Change column names to column identifiers + (Conversion before UNION + (Project names + Projection))))",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_7",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_6",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Filter",+ "Node Id": "Filter_34",+ "Description": "(WHERE + (Change column names to column identifiers + (Project names + (Projection + Change column names to column identifiers))))",+ "Plans": [+ {+ "Node Type": "ReadFromObjectStorage",+ "Node Id": "ReadFromObjectStorage_0"+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "Expression",+ "Node Id": "Expression_50",+ "Description": "(Before GROUP BY + (Change column names to column identifiers + (Conversion before UNION + (Project names + Projection))))",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_17",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_16",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Filter",+ "Node Id": "Filter_40",+ "Description": "(WHERE + (Change column names to column identifiers + (Project names + (Projection + Change column names to column identifiers))))",+ "Plans": [+ {+ "Node Type": "ReadFromObjectStorage",+ "Node Id": "ReadFromObjectStorage_10"+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_persons_join.json b/posthog/query_scan/test/fixtures/plan_persons_join.jsonnew file mode 100644index 000000000000..bac5c3b0862e--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_persons_join.json@@ -0,0 +1,153 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_144",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_134",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_125",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_67",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_152",+ "Plans": [+ {+ "Node Type": "Join",+ "Node Id": "Join_150",+ "Description": "JOIN FillRightFirst",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_148",+ "Description": "Left Pre Join Actions",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_155",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_58",+ "Description": "posthog.person",+ "Indexes": [+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id"+ ],+ "Condition": "(team_id in [2, 2])",+ "Search Algorithm": "binary search",+ "Initial Parts": 86,+ "Selected Parts": 86,+ "Initial Granules": 9366597,+ "Selected Granules": 79160+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "Expression",+ "Node Id": "Expression_149",+ "Description": "Right Pre Join Actions",+ "Plans": [+ {+ "Node Type": "BuildRuntimeFilter",+ "Node Id": "BuildRuntimeFilter_146",+ "Description": "Build runtime join filter on __table1.person_id",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_156",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_56",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "timestamp"+ ],+ "Condition": "(timestamp in [1788461223, +Inf))",+ "Initial Parts": 2938,+ "Selected Parts": 50,+ "Initial Granules": 291514662,+ "Selected Granules": 5515706+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(timestamp)"+ ],+ "Condition": "(toYYYYMM(timestamp) in [202609, +Inf))",+ "Initial Parts": 50,+ "Selected Parts": 50,+ "Initial Granules": 5515706,+ "Selected Granules": 5515706+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "toDate(timestamp)",+ "event"+ ],+ "Condition": "and((event in ['$pageview', '$pageview']), and((toDate(timestamp) in [20699, +Inf)), (team_id in [2, 2])))",+ "Search Algorithm": "generic exclusion search",+ "Initial Parts": 50,+ "Selected Parts": 45,+ "Initial Granules": 5515706,+ "Selected Granules": 8832+ },+ {+ "Type": "Skip",+ "Name": "minmax_sharded_events_timestamp",+ "Description": "minmax GRANULARITY 1",+ "Condition": "(timestamp in [1788461223, +Inf))",+ "Initial Parts": 45,+ "Selected Parts": 44,+ "Initial Granules": 8832,+ "Selected Granules": 8285+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_124",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_replay_list_in_subqueries.json b/posthog/query_scan/test/fixtures/plan_replay_list_in_subqueries.jsonnew file mode 100644index 000000000000..ea2c9dfb68eb--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_replay_list_in_subqueries.json@@ -0,0 +1,126 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_568",+ "Description": "(Project names + (Before ORDER BY + Projection) [lifted up part])",+ "Plans": [+ {+ "Node Type": "Limit",+ "Node Id": "Limit_562",+ "Description": "preliminary LIMIT",+ "Plans": [+ {+ "Node Type": "Sorting",+ "Node Id": "Sorting_561",+ "Description": "Sorting for ORDER BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_566",+ "Description": "(Before ORDER BY + Projection)",+ "Plans": [+ {+ "Node Type": "Filter",+ "Node Id": "Filter_558",+ "Description": "HAVING",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_557",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_551",+ "Plans": [+ {+ "Node Type": "CreatingSets",+ "Node Id": "CreatingSets_579",+ "Description": "Create sets before main query execution",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_511",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_510",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Filter",+ "Node Id": "Filter_578",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_507",+ "Description": "posthog.sharded_session_replay_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "min_first_timestamp"+ ],+ "Condition": "and((min_first_timestamp in (-Inf, '1789058701.088805']), (min_first_timestamp in ['1788418800', +Inf)))",+ "Initial Parts": 217,+ "Selected Parts": 26,+ "Initial Granules": 2164629,+ "Selected Granules": 59554+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(min_first_timestamp)"+ ],+ "Condition": "and((toYYYYMM(min_first_timestamp) in (-Inf, 202609]), (toYYYYMM(min_first_timestamp) in [202609, +Inf)))",+ "Initial Parts": 26,+ "Selected Parts": 26,+ "Initial Granules": 59554,+ "Selected Granules": 59554+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "toDate(min_first_timestamp)",+ "team_id",+ "session_id"+ ],+ "Condition": "and((session_id notIn 49327-element set), and(and((session_id in 197773-element set), (session_id in 61-element set)), and((toDate(min_first_timestamp) in (-Inf, 20706]), and((toDate(min_first_timestamp) in [20699, +Inf)), (team_id in [2, 2])))))",+ "Search Algorithm": "generic exclusion search",+ "Initial Parts": 26,+ "Selected Parts": 26,+ "Initial Granules": 59554,+ "Selected Granules": 163+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_550",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/fixtures/plan_skip_index_pruned.json b/posthog/query_scan/test/fixtures/plan_skip_index_pruned.jsonnew file mode 100644index 000000000000..1554f8a7d718--- /dev/null+++ b/posthog/query_scan/test/fixtures/plan_skip_index_pruned.json@@ -0,0 +1,110 @@+[+ {+ "Plan": {+ "Node Type": "Expression",+ "Node Id": "Expression_75",+ "Description": "(Project names + Projection)",+ "Plans": [+ {+ "Node Type": "MergingAggregated",+ "Node Id": "MergingAggregated_71",+ "Plans": [+ {+ "Node Type": "Union",+ "Node Id": "Union_65",+ "Plans": [+ {+ "Node Type": "Aggregating",+ "Node Id": "Aggregating_63",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_62",+ "Description": "Before GROUP BY",+ "Plans": [+ {+ "Node Type": "Expression",+ "Node Id": "Expression_76",+ "Description": "(WHERE + Change column names to column identifiers)",+ "Plans": [+ {+ "Node Type": "ReadFromMergeTree",+ "Node Id": "ReadFromMergeTree_59",+ "Description": "posthog.sharded_events",+ "Indexes": [+ {+ "Type": "Min-Max",+ "Keys": [+ "timestamp"+ ],+ "Condition": "(timestamp in [1788461227, +Inf))",+ "Initial Parts": 2929,+ "Selected Parts": 91,+ "Initial Granules": 280507871,+ "Selected Granules": 5525235+ },+ {+ "Type": "Partition",+ "Keys": [+ "toYYYYMM(timestamp)"+ ],+ "Condition": "(toYYYYMM(timestamp) in [202609, +Inf))",+ "Initial Parts": 91,+ "Selected Parts": 91,+ "Initial Granules": 5525235,+ "Selected Granules": 5525235+ },+ {+ "Type": "PrimaryKey",+ "Keys": [+ "team_id",+ "toDate(timestamp)"+ ],+ "Condition": "and((toDate(timestamp) in [20699, +Inf)), (team_id in [2, 2]))",+ "Search Algorithm": "binary search",+ "Initial Parts": 91,+ "Selected Parts": 53,+ "Initial Granules": 5525235,+ "Selected Granules": 349931+ },+ {+ "Type": "Skip",+ "Name": "minmax_$session_id",+ "Description": "minmax GRANULARITY 1",+ "Condition": "($session_id in ['019a0000-0000-7000-8000-000000000000', '019a0000-0000-7000-8000-000000000000'])",+ "Initial Parts": 53,+ "Selected Parts": 53,+ "Initial Granules": 349931,+ "Selected Granules": 117977+ },+ {+ "Type": "Skip",+ "Name": "minmax_sharded_events_timestamp",+ "Description": "minmax GRANULARITY 1",+ "Condition": "(timestamp in [1788461227, +Inf))",+ "Initial Parts": 53,+ "Selected Parts": 52,+ "Initial Granules": 117977,+ "Selected Granules": 103415+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "Node Type": "ReadFromRemote",+ "Node Id": "ReadFromRemote_64",+ "Description": "Read from remote replica"+ }+ ]+ }+ ]+ }+ ]+ }+ }+]\ No newline at end of filediff --git a/posthog/query_scan/test/slots.py b/posthog/query_scan/test/slots.pynew file mode 100644index 000000000000..46d0db072cfa--- /dev/null+++ b/posthog/query_scan/test/slots.py@@ -0,0 +1,13 @@+from unittest import mock++from posthog.schema import QueryScanAnalysis++from posthog.query_scan.slot import set_done+++def stored_slot(analysis: QueryScanAnalysis) -> str:+ """What Redis holds for ``analysis``, as the job writes it, for a test that mocks the read side."""+ client = mock.Mock()+ with mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=client):+ set_done(0, "cache_key", thresholds="0.1:0.5", analysis=analysis)+ return client.set.call_args.args[1]diff --git a/posthog/query_scan/test/test_analyze.py b/posthog/query_scan/test/test_analyze.pynew file mode 100644index 000000000000..8b202618a502--- /dev/null+++ b/posthog/query_scan/test/test_analyze.py@@ -0,0 +1,233 @@+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.event_filter import EventFilterOutcome+from posthog.query_scan.explain import QueryPlan, parse_query_plan+from posthog.query_scan.flag import QueryScanFlag, QueryScanMode+from posthog.query_scan.test.test_explain import events_read_node, load_plan++_USABLE_EVENT_FILTER = EventFilterOutcome(classification="usable")+_END_DATE_ONLY = "(timestamp in (-Inf, 1800000000])"+# A start and an end date, in the two-clause form ClickHouse prints them in.+_BOTH_BOUNDS = "and((timestamp in (-Inf, 1800000000]), (timestamp in [1700000000, +Inf)))"+++_EVENT_KEY = ["team_id", "toDate(timestamp)", "event"]+++def plan(name: str) -> QueryPlan:+ return parse_query_plan(load_plan(name))+++def single_read_plan(condition: str) -> QueryPlan:+ return parse_query_plan([{"Plan": events_read_node(condition, ["timestamp"] if condition != "true" else [])}])+++def join_plan(*reads: dict[str, object]) -> QueryPlan:+ return parse_query_plan([{"Plan": {"Node Type": "Join", "Plans": list(reads)}}])+++def analyze_fixture(+ outer: str | QueryPlan,+ *,+ subqueries: tuple[str, ...] = (),+ team_granules: int | None = None,+ range_granules: int | None = None,+ persons_ratio: float = 0.5,+ query_kind: str = "HogQLQuery",+ open_filters_placeholder: bool = False,+ event_filter: EventFilterOutcome | None = None,+ table_row_averages: dict[str, float] | None = None,+ all_time: bool = False,+ all_history_by_design: bool = False,+) -> QueryScanResult:+ return analyze(+ PlanSet(+ outer=plan(outer) if isinstance(outer, str) else outer,+ subqueries=tuple(plan(name) 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,+ table_row_averages=table_row_averages,+ all_time=all_time,+ all_history_by_design=all_history_by_design,+ )+++class TestAnalyze(SimpleTestCase):+ @parameterized.expand(+ [+ # event gate: the read is a large share of the range, so the missing event filter is flagged+ (+ "no event filter, over the ratio",+ "plan_no_event_filter",+ {"range_granules": 1_000_000},+ ["no_event_filter"],+ ),+ # event gate the other way: the read is a small share, so nothing is flagged+ ("no event filter, under the ratio", "plan_no_event_filter", {"range_granules": 100_000_000}, []),+ ("event filter in the key stays quiet", "plan_event_filter_used", {}, []),+ ("event filter inside an OR still used", "plan_event_filter_in_or", {}, []),+ ("no date bound is flagged", "plan_no_date_bound", {}, ["no_start_date"]),+ # A date range with a start and an end is bounded, whatever order ClickHouse lists the two+ # clauses in; an end date on its own leaves the start open.+ (+ "a start and an end date are bounded",+ single_read_plan(_BOTH_BOUNDS),+ {"event_filter": _USABLE_EVENT_FILTER},+ [],+ ),+ (+ "an end date alone is no start date",+ single_read_plan(_END_DATE_ONLY),+ {"event_filter": _USABLE_EVENT_FILTER},+ ["no_start_date"],+ ),+ # A join reads the events table twice; the small unbounded read is the one to flag even+ # though the bounded read is the larger one and the one the shares are taken from.+ (+ "any events read with no start date 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},+ ["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.+ (+ "a lighter read with no event filter is not flagged",+ join_plan(+ events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=5000, primary_keys=_EVENT_KEY),+ events_read_node(_BOTH_BOUNDS, ["timestamp"], selected_granules=10),+ ),+ {"range_granules": 10_000},+ [],+ ),+ (+ "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),+ ),+ {"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",+ "plan_event_filter_used",+ {"query_kind": "TrendsQuery", "all_time": True},+ ["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+ ("persons join under the ratio", "plan_persons_join", {"persons_ratio": 10.0}, []),+ # At ratio 20 the raw granule counts miss (9.6x), but scaling both sides to rows (51x) fires.+ (+ "persons join fires once granules are scaled to rows",+ "plan_persons_join",+ {"persons_ratio": 20.0, "table_row_averages": {"sharded_events": 740.0, "person": 3955.0}},+ ["persons_join"],+ ),+ # Same granules and ratio, but averages that make the events side heavier keep it quiet.+ (+ "persons join stays quiet when rows do not clear the ratio",+ "plan_persons_join",+ {"persons_ratio": 20.0, "table_row_averages": {"sharded_events": 4000.0, "person": 740.0}},+ [],+ ),+ ("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 with no event filter is flagged",+ "plan_event_filter_used",+ {"subqueries": ("plan_no_event_filter",)},+ ["no_event_filter"],+ ),+ # a subquery a skip index already pruned is not flagged+ (+ "a subquery a skip index pruned is not flagged",+ "plan_event_filter_used",+ {"subqueries": ("plan_skip_index_pruned",)},+ [],+ ),+ ]+ )+ def test_findings_per_gate(+ self, _name: str, outer: str | QueryPlan, kwargs: dict[str, object], expected_kinds: list[str]+ ) -> None:+ result = analyze_fixture(outer, **kwargs) # type: ignore[arg-type]++ self.assertTrue(result.explain_ok)+ self.assertEqual(result.finding_kinds(), expected_kinds)++ 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,+ )++ self.assertFalse(result.explain_ok)+ self.assertEqual(result.findings, [])++ def test_open_filters_placeholder_sets_the_filters_reason(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)++ 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.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"),+ )++ 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)++ 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)++ assert result.range_share is not None and result.project_share is not None+ self.assertAlmostEqual(result.range_share, 0.329267, places=5)+ self.assertAlmostEqual(result.project_share, 0.0329267, places=6)++ 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)diff --git a/posthog/query_scan/test/test_event_filter.py b/posthog/query_scan/test/test_event_filter.pynew file mode 100644index 000000000000..041ff59999b0--- /dev/null+++ b/posthog/query_scan/test/test_event_filter.py@@ -0,0 +1,164 @@+from posthog.test.base import BaseTest++from django.test import SimpleTestCase++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.event_filter import EventFilterOutcome, classify_event_filter, combine_event_filter+from posthog.query_scan.explain import QueryPlan, parse_query_plan+from posthog.query_scan.test.test_explain import events_read_node, load_plan++_KEY_USED_PLAN = parse_query_plan(load_plan("plan_event_filter_used"))+_KEY_UNUSED_PLAN = parse_query_plan(load_plan("plan_no_event_filter"))+_EVENT_KEY = ["team_id", "toDate(timestamp)", "event"]+# A join whose large read pruned on `event` while its small one did not.+_HEAVIEST_PRUNED_PLAN = parse_query_plan(+ [+ {+ "Plan": {+ "Node Type": "Join",+ "Plans": [+ events_read_node("true", [], selected_granules=5000, primary_keys=_EVENT_KEY),+ events_read_node("true", [], selected_granules=10),+ ],+ }+ }+ ]+)+++class TestClassifyEventFilter(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(+ [+ ("plain equality", "SELECT count() FROM events WHERE event = 'purchase'", "usable", None),+ ("in a list", "SELECT count() FROM events WHERE event IN ('a', 'b')", "usable", None),+ (+ "inside an or with another condition",+ "SELECT count() FROM events WHERE properties.plan = 'pro' OR event = 'upgrade'",+ "not_used",+ "in_or",+ ),+ (+ "wrapped in a function",+ "SELECT count() FROM events WHERE lower(event) = 'purchase'",+ "not_used",+ "wrapped",+ ),+ ("not equal", "SELECT count() FROM events WHERE event != 'purchase'", "not_used", "negated"),+ ("not in a list", "SELECT count() FROM events WHERE event NOT IN ('$pageview')", "not_used", "negated"),+ (+ "compared to another column",+ "SELECT count() FROM events WHERE event = distinct_id",+ "not_used",+ "dynamic",+ ),+ # 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.+ (+ "compared to a property",+ "SELECT count() FROM events WHERE event = properties.plan",+ "not_used",+ "not_pruned",+ ),+ ("no event condition at all", "SELECT count() FROM events", "none", None),+ (+ "reads that agree",+ "SELECT count() FROM events WHERE event = 'a' UNION ALL SELECT count() FROM events WHERE event = 'b'",+ "usable",+ None,+ ),+ # The tree cannot say which read is the plan's heaviest, so no verdict is pinned to it.+ (+ "reads that disagree",+ "SELECT count() FROM events WHERE event = 'a' UNION ALL SELECT count() FROM events",+ None,+ None,+ ),+ ]+ )+ def test_classification_reads_the_tree(+ self, _name: str, sql: str, expected_class: str | None, expected_reason: str | None+ ) -> None:+ outcome = classify_event_filter(self.prepare(sql))++ if expected_class is None:+ self.assertIsNone(outcome)+ return+ assert outcome is not None+ self.assertEqual(outcome.classification, expected_class)+ self.assertEqual(outcome.reason, expected_reason)+++class TestCombineEventFilter(SimpleTestCase):+ @parameterized.expand(+ [+ # A used key overrules a tree fault that is not a negation.+ (+ "key used excuses a wrapped tree",+ EventFilterOutcome(classification="not_used", reason="wrapped"),+ _KEY_USED_PLAN,+ "usable",+ None,+ ),+ # A negation lists `event` in the key yet prunes almost nothing, so the tree stands.+ (+ "key used does not excuse a negated tree",+ EventFilterOutcome(classification="not_used", reason="negated"),+ _KEY_USED_PLAN,+ "not_used",+ "negated",+ ),+ # The plan says no key use while the tree read as usable, so the filter did not prune.+ (+ "key unused faults a usable tree",+ EventFilterOutcome(classification="usable"),+ _KEY_UNUSED_PLAN,+ "not_used",+ "not_pruned",+ ),+ # 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",+ EventFilterOutcome(classification="usable"),+ _HEAVIEST_PRUNED_PLAN,+ "usable",+ None,+ ),+ # No plan (EXPLAIN failed) leaves the tree verdict untouched.+ (+ "no plan leaves the tree verdict",+ EventFilterOutcome(classification="not_used", reason="in_or"),+ None,+ "not_used",+ "in_or",+ ),+ ]+ )+ def test_the_plan_folds_into_the_tree_verdict(+ self,+ _name: str,+ outcome: EventFilterOutcome,+ plan: QueryPlan | None,+ expected_class: str,+ expected_reason: str | None,+ ) -> None:+ combined = combine_event_filter(outcome, plan)++ self.assertEqual(combined.classification, expected_class)+ self.assertEqual(combined.reason, expected_reason)diff --git a/posthog/query_scan/test/test_explain.py b/posthog/query_scan/test/test_explain.pynew file mode 100644index 000000000000..1f3ad6638229--- /dev/null+++ b/posthog/query_scan/test/test_explain.py@@ -0,0 +1,214 @@+import json+from pathlib import Path++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.query_scan.explain import parse_query_plan++FIXTURES = Path(__file__).parent / "fixtures"+++def load_plan(name: str) -> object:+ return json.loads((FIXTURES / f"{name}.json").read_text())+++def events_read_node(+ condition: str, keys: list[str], *, selected_granules: int = 1000, primary_keys: list[str] | None = None+) -> dict[str, object]:+ indexes: list[dict[str, object]] = [+ {+ "Type": "Min-Max",+ "Keys": keys,+ "Condition": condition,+ "Initial Granules": 1000,+ "Selected Granules": selected_granules,+ }+ ]+ if primary_keys is not None:+ indexes.append(+ {+ "Type": "PrimaryKey",+ "Keys": primary_keys,+ "Condition": condition,+ "Initial Granules": selected_granules,+ "Selected Granules": selected_granules,+ }+ )+ return {"Node Type": "ReadFromMergeTree", "Description": "posthog.sharded_events", "Indexes": indexes}+++def min_max_read(condition: str, keys: list[str]) -> list[dict[str, object]]:+ return [{"Plan": events_read_node(condition, keys)}]+++class TestExplainParsing(SimpleTestCase):+ @parameterized.expand(+ [+ # fixture, primary key columns, event in the key, granules after the last step, the+ # lower unix bound the Min-Max step could apply+ ("plan_event_filter_used", ("team_id", "toDate(timestamp)", "event"), True, 8567, 1788461182),+ ("plan_no_event_filter", ("team_id", "toDate(timestamp)"), False, 329267, 1788461215),+ ("plan_no_date_bound", ("team_id", "event"), True, 412056, None),+ (+ "plan_event_filter_in_or",+ ("team_id", "toDate(timestamp)", "event", "cityHash64(distinct_id)"),+ True,+ 23018,+ 1788461220,+ ),+ ("plan_skip_index_pruned", ("team_id", "toDate(timestamp)"), False, 103415, 1788461227),+ ]+ )+ def test_events_read_reports_table_keys_granules_and_bounds(+ self,+ fixture: str,+ expected_keys: tuple[str, ...],+ event_in_key: bool,+ final_granules: int,+ lower_bound: int | None,+ ) -> None:+ plan = parse_query_plan(load_plan(fixture))++ read = plan.heaviest_events_read()+ assert read is not None+ self.assertEqual(read.table, "posthog.sharded_events")+ primary_key = read.primary_key()+ assert primary_key is not None+ self.assertEqual(primary_key.keys, expected_keys)+ self.assertEqual("event" in primary_key.keys, event_in_key)+ self.assertEqual(read.selected_granules(), final_granules)+ bounds = read.timestamp_bounds()+ self.assertEqual(bounds.lower, lower_bound)+ self.assertIsNone(bounds.upper)++ def test_steps_are_kept_in_plan_order(self) -> None:+ read = parse_query_plan(load_plan("plan_skip_index_pruned")).heaviest_events_read()+ assert read is not None++ self.assertEqual([step.type for step in read.indexes], ["Min-Max", "Partition", "PrimaryKey", "Skip", "Skip"])+ self.assertEqual(len(read.skip_steps()), 2)++ @parameterized.expand(+ [+ ("lower bound only", "(timestamp in [1700000000, +Inf))", ["timestamp"], 1700000000, None),+ ("upper bound only", "(timestamp in (-Inf, 1800000000])", ["timestamp"], None, 1800000000),+ # ClickHouse prints a range with a start and an end as two clauses, the end first, so a+ # parser that stopped at the first clause would report every bounded query as unbounded.+ (+ "both bounds, as ClickHouse prints them",+ "and((timestamp in (-Inf, 1800000000]), (timestamp in [1700000000, +Inf)))",+ ["timestamp"],+ 1700000000,+ 1800000000,+ ),+ # HogQL prints now() as now64 and date literals as toDateTime64, and ClickHouse prints a+ # DateTime64 bound quoted, with a fractional part for now64.+ (+ "DateTime64 lower bound, as HogQL's now() renders",+ "(timestamp in ['1788818422.100868', +Inf))",+ ["timestamp"],+ 1788818422,+ None,+ ),+ (+ "DateTime64 range, as HogQL date literals render",+ "and((timestamp in (-Inf, '1789344000')), (timestamp in ['1788739200', +Inf)))",+ ["timestamp"],+ 1788739200,+ 1789344000,+ ),+ ("no timestamp key", "true", [], None, None),+ ]+ )+ def test_timestamp_bounds_parse_the_canonical_forms(+ self, _name: str, condition: str, keys: list[str], lower: int | None, upper: int | None+ ) -> None:+ read = parse_query_plan(min_max_read(condition, keys)).heaviest_events_read()+ assert read is not None++ bounds = read.timestamp_bounds()+ self.assertEqual(bounds.lower, lower)+ self.assertEqual(bounds.upper, upper)++ def test_the_largest_of_several_events_reads_is_the_one_judged(self) -> None:+ # A join or a union reads the events table more than once, and the read that kept the most+ # granules is the one that made the query slow, whatever order ClickHouse lists them in.+ plan = parse_query_plan(+ [+ {+ "Plan": {+ "Node Type": "Join",+ "Plans": [+ events_read_node("(timestamp in [1700000000, +Inf))", ["timestamp"], selected_granules=10),+ events_read_node("true", [], selected_granules=5000),+ ],+ }+ }+ ]+ )++ heaviest = plan.heaviest_events_read()+ assert heaviest is not None+ self.assertEqual(heaviest.selected_granules(), 5000)+ self.assertEqual(len(plan.events_reads()), 2)++ def test_persons_join_plan_names_both_reads(self) -> None:+ plan = parse_query_plan(load_plan("plan_persons_join"))++ events_read = plan.heaviest_events_read()+ assert events_read is not None+ self.assertEqual(events_read.table, "posthog.sharded_events")+ self.assertEqual([read.table for read in plan.person_reads()], ["posthog.person"])++ @parameterized.expand(+ [+ ("object storage read has no events read", "plan_object_storage_read"),+ ("a replay list reads its own table, not events", "plan_replay_list_in_subqueries"),+ ]+ )+ def test_plans_without_an_events_read(self, _name: str, fixture: str) -> None:+ plan = parse_query_plan(load_plan(fixture))++ self.assertIsNone(plan.heaviest_events_read())++ @parameterized.expand(+ [+ ("the events table with no database qualifier", "events", True, False),+ ("the native-JSON table", "posthog.sharded_events_json", True, False),+ ("another table whose name ends in events", "posthog.ai_events", False, False),+ ("the persons table", "posthog.person", False, True),+ ("a person override table", "posthog.person_distinct_id_overrides", False, True),+ ]+ )+ def test_table_names_are_classified_by_the_description(+ self, _name: str, description: str, reads_events: bool, reads_persons: bool+ ) -> None:+ plan = parse_query_plan(+ [{"Plan": {"Node Type": "ReadFromMergeTree", "Description": description, "Indexes": []}}]+ )++ read = plan.reads[0]+ self.assertEqual(read.reads_events(), reads_events)+ self.assertEqual(read.reads_persons(), reads_persons)++ @parameterized.expand(+ [+ ("nothing at all", None),+ ("unparseable text", "not json at all"),+ ("a read without a description", [{"Plan": {"Node Type": "ReadFromMergeTree", "Indexes": []}}]),+ ]+ )+ def test_unexpected_shape_reports_no_events_read(self, _name: str, payload: object) -> None:+ plan = parse_query_plan(payload)++ self.assertEqual(plan.reads, ())+ self.assertIsNone(plan.heaviest_events_read())++ def test_json_text_is_accepted(self) -> None:+ raw = (FIXTURES / "plan_event_filter_used.json").read_text()++ read = parse_query_plan(raw).heaviest_events_read()+ assert read is not None+ self.assertEqual(read.table, "posthog.sharded_events")diff --git a/posthog/query_scan/test/test_findings.py b/posthog/query_scan/test/test_findings.pynew file mode 100644index 000000000000..3e0bafc8f603--- /dev/null+++ b/posthog/query_scan/test/test_findings.py@@ -0,0 +1,215 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.schema import QueryScanFindingKind, QueryScanFindingReason++from posthog.query_scan.findings import (+ ASSISTANT_GOAL,+ ASSISTANT_RULES,+ assistant_prompt,+ build_warning,+ explain_evidence,+ format_rows,+)+++class TestFindings(SimpleTestCase):+ @parameterized.expand([("8.4 billion", 8_400_000_000), ("12,345", 12_345)])+ def test_row_counts_read_as_words_above_a_million(self, expected: str, rows: int) -> None:+ self.assertEqual(format_rows(rows), expected)++ @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.+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ None,+ "HogQLQuery",+ "add `WHERE event IN",+ "The query names no events",+ ),+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ QueryScanFindingReason.IN_OR,+ "HogQLQuery",+ "names events only inside an OR",+ "for what the other branch matches",+ ),+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ QueryScanFindingReason.WRAPPED,+ "HogQLQuery",+ "wraps `event` in a",+ "SELECT DISTINCT event",+ ),+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ QueryScanFindingReason.NEGATED,+ "HogQLQuery",+ "only excludes",+ "Do not run exploratory queries",+ ),+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ QueryScanFindingReason.DYNAMIC,+ "HogQLQuery",+ "compares `event` to another",+ "no fixed name to prune on",+ ),+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ QueryScanFindingReason.NOT_PRUNED,+ "HogQLQuery",+ "has an event filter",+ "into the WHERE of the events read",+ ),+ (+ QueryScanFindingKind.NO_EVENT_FILTER,+ None,+ "TrendsQuery",+ "This insight looks at all events",+ "instead of All events",+ ),+ (+ QueryScanFindingKind.NO_START_DATE,+ None,+ "HogQLQuery",+ "add `timestamp >= now()",+ "relative time bound",+ ),+ (+ QueryScanFindingKind.NO_START_DATE,+ QueryScanFindingReason.FILTERS,+ "HogQLQuery",+ "No date range is set on this insight or dashboard",+ "Do not edit the SQL",+ ),+ (+ QueryScanFindingKind.NO_START_DATE,+ None,+ "TrendsQuery",+ "This insight has no start date",+ "instead of All time",+ ),+ (+ QueryScanFindingKind.PERSONS_JOIN,+ None,+ "HogQLQuery",+ "joins the persons table",+ "person.properties.x",+ ),+ ]+ )+ def test_copy_switches_between_sql_and_insight_wording(+ self,+ kind: QueryScanFindingKind,+ reason: QueryScanFindingReason | None,+ query_kind: str,+ message_contains: str,+ fix_contains: str,+ ) -> None:+ warning = build_warning(kind=kind, reason=reason, query_kind=query_kind)++ self.assertEqual(warning.kind, kind)+ self.assertIn(message_contains, warning.message)+ self.assertIn(fix_contains, warning.fix)++ @parameterized.expand(+ [+ (+ "keys and granule counts",+ ("team_id", "toDate(timestamp)"),+ 5_582_406,+ 362_907,+ None,+ "ClickHouse's index used team_id, toDate(timestamp) and kept 362,907 of 5,582,406 granules.",+ ),+ (+ "no columns used",+ (),+ 100,+ 100,+ None,+ "ClickHouse's index used no columns and kept 100 of 100 granules.",+ ),+ (+ "a subquery finding names the subquery",+ ("team_id",),+ 9_366_597,+ 79_160,+ 0,+ "In subquery 1: ClickHouse's index used team_id and kept 79,160 of 9,366,597 granules.",+ ),+ ]+ )+ def test_evidence_renders_keys_and_granule_counts(+ self,+ _name: str,+ keys: tuple[str, ...],+ before: int | None,+ after: int | None,+ subquery_index: int | None,+ expected: str,+ ) -> None:+ self.assertEqual(explain_evidence(keys, before=before, after=after, subquery_index=subquery_index), expected)+++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,+ query_kind="HogQLQuery",+ evidence="ClickHouse's index used team_id and kept 5 of 100 granules.",+ )++ prompt = assistant_prompt(+ [finding], rows_read=8_400_000_000, duration_ms=19_000, range_share=0.42, project_share=0.07+ )++ assert prompt is not None+ lines = prompt.splitlines()+ self.assertEqual(lines[0], ASSISTANT_GOAL)+ self.assertIn("This query read 8.4 billion rows in 19.0 s.", lines)+ self.assertIn("It read about 42% of the events in this date range.", lines)+ self.assertIn("It read about 7% of the project's events.", lines)+ self.assertIn(f"- no_event_filter (in_or): {finding.evidence} {finding.fix}", lines)+ self.assertEqual(lines[-1], ASSISTANT_RULES)++ @parameterized.expand(+ [+ ("with the run's numbers", 90, 400, "ClickHouse stopped this query after 0.4 s, having read 90 rows."),+ # The scan endpoint has no numbers for the run, only that it was stopped.+ ("without them", None, None, "ClickHouse stopped this query before it finished."),+ ]+ )+ def test_a_stopped_run_says_so(+ self, _name: str, rows_read: int | None, duration_ms: int | None, expected_line: str+ ) -> None:+ finding = build_warning(kind=QueryScanFindingKind.NO_START_DATE, query_kind="HogQLQuery")++ prompt = assistant_prompt([finding], rows_read=rows_read, duration_ms=duration_ms, killed=True)++ assert prompt is not None+ self.assertIn(expected_line, prompt.splitlines())+ self.assertNotIn("of the events in this date range", prompt)++ def test_fixable_only_leaves_out_a_finding_fixed_on_the_insight(self) -> None:+ # "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"+ )+ in_query = build_warning(kind=QueryScanFindingKind.NO_EVENT_FILTER, query_kind="HogQLQuery")++ self.assertIsNone(assistant_prompt([on_insight], 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)+ # 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)diff --git a/posthog/query_scan/test/test_flag.py b/posthog/query_scan/test/test_flag.pynew file mode 100644index 000000000000..618574f756c7--- /dev/null+++ b/posthog/query_scan/test/test_flag.py@@ -0,0 +1,96 @@+import uuid+from datetime import UTC, datetime+from types import SimpleNamespace+from typing import TYPE_CHECKING, cast++from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.query_scan import flag+from posthog.query_scan.flag import (+ DEFAULT_EVENT_RATIO,+ DEFAULT_FLOOR_MS,+ DEFAULT_PERSONS_RATIO,+ QueryScanMode,+ get_query_scan_flag,+)++if TYPE_CHECKING:+ from posthog.models.team.team import Team++TEAM = cast(+ "Team",+ SimpleNamespace(+ id=42,+ uuid=uuid.UUID("00000000-0000-0000-0000-0000000000ff"),+ created_at=datetime(2026, 1, 1, tzinfo=UTC),+ organization_id=uuid.UUID("00000000-0000-0000-0000-00000000000a"),+ ),+)+++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}'+ 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.mode, QueryScanMode.SHOW)+ self.assertEqual(result.floor_ms, 2000)+ self.assertEqual(result.event_ratio, 0.2)+ self.assertEqual(result.persons_ratio, 0.7)++ get_result.assert_called_once()+ kwargs = get_result.call_args.kwargs+ self.assertEqual(kwargs["groups"]["organization"], str(TEAM.organization_id))+ self.assertEqual(kwargs["group_properties"]["organization"]["id"], str(TEAM.organization_id))+ self.assertEqual(kwargs["groups"]["project"], str(TEAM.id))+ self.assertEqual(kwargs["group_properties"]["project"]["id"], str(TEAM.id))++ @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)),+ ]+ )+ def test_a_missing_threshold_falls_back_to_its_default(+ self, _name: str, payload: object, expected: tuple[int, 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)++ @parameterized.expand(+ [+ ("not json", "not json"),+ ("a boolean", {"floor_ms": True}),+ ("a string", {"event_ratio": "0.2"}),+ # The flag stores whatever json.loads accepts, and int() of either of these raises, so+ # without the guard one typo in the payload would fail every query on the team.+ ("not a number", {"floor_ms": float("nan")}),+ ("infinite", {"floor_ms": float("inf")}),+ ]+ )+ def test_a_bad_threshold_turns_the_feature_off_and_is_reported(self, _name: str, payload: object) -> None:+ with (+ patch.object(flag.posthoganalytics, "get_feature_flag_result") as get_result,+ patch.object(flag, "capture_exception") as capture,+ ):+ get_result.return_value = SimpleNamespace(variant="show", payload=payload)+ result = get_query_scan_flag(TEAM)++ self.assertIsNone(result)+ capture.assert_called_once()++ def test_a_boolean_flag_reads_as_off(self) -> None:+ with patch.object(flag.posthoganalytics, "get_feature_flag_result") as get_result:+ get_result.return_value = SimpleNamespace(variant="on", payload=None)+ self.assertIsNone(get_query_scan_flag(TEAM))diff --git a/posthog/query_scan/test/test_job.py b/posthog/query_scan/test/test_job.pynew file mode 100644index 000000000000..34570cd802e7--- /dev/null+++ b/posthog/query_scan/test/test_job.py@@ -0,0 +1,251 @@+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any++from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person+from unittest import mock++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+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.stub import stub_in_subqueries++from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable++FIXTURES = Path(__file__).parent / "fixtures"+FLAG = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)++_OTHER_ERROR = InternalCHQueryError("Estimated execution time too long", code=160)++# The `system.parts` metadata query returns average rows per granule per table.+_ROW_AVERAGES = [+ ["sharded_events", 740.0],+ ["person", 3955.0],+ ["person_distinct_id2", 512.0],+ ["person_distinct_id_overrides", 512.0],+]+++def _plan(name: str) -> str:+ return (FIXTURES / f"{name}.json").read_text()+++def _fake_job_boundaries(test: BaseTest, stored: dict[str, Any], flag: QueryScanFlag = FLAG) -> mock.Mock:+ redis = mock.Mock()+ redis.get.side_effect = lambda key: stored.get(key)+ redis.set.side_effect = lambda key, value, ex=None, nx=False: stored.__setitem__(key, value)+ redis.delete.side_effect = lambda key: stored.pop(key, None)+ redis_patcher = mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis)+ flag_patcher = mock.patch("posthog.query_scan.job.get_query_scan_flag", return_value=flag)+ capture_patcher = mock.patch("posthog.query_scan.job.ph_scoped_capture")+ for patcher in (redis_patcher, flag_patcher):+ patcher.start()+ test.addCleanup(patcher.stop)+ capture = capture_patcher.start().return_value.__enter__.return_value+ test.addCleanup(capture_patcher.stop)+ return capture+++class TestQueryScanJob(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.calls: list[tuple[str, dict[str, Any]]] = []+ self.stored: dict[str, Any] = {}+ self.capture = _fake_job_boundaries(self, self.stored)++ def _run(+ self,+ dispatch: dict[str, Any],+ *,+ subqueries: tuple[str, ...] = (),+ team_denom: str = "plan_no_date_bound",+ range_denom: str = "plan_no_event_filter",+ averages_error: BaseException | None = None,+ ) -> None:+ def execute(query: str, arguments: Any = None, *args: Any, **kwargs: Any) -> Any:+ self.calls.append((query, arguments or {}))+ if "system.parts" in query:+ if averages_error is not None:+ raise averages_error+ return _ROW_AVERAGES+ if "timestamp >=" in query or "timestamp <" in query:+ return [[_plan(range_denom)]]+ if "%(scan_team_id)s" in query:+ return [[_plan(team_denom)]]+ for marker, behavior in dispatch.items():+ if marker in query:+ if isinstance(behavior, BaseException):+ raise behavior+ return [[_plan(behavior)]]+ raise AssertionError(f"unexpected EXPLAIN: {query}")++ job = QueryScanJob(+ team=self.team,+ cache_key="cache_key_1",+ executions=(+ Execution(+ stubbed_sql="STUBBED_MARKER",+ subqueries=subqueries,+ values={},+ rows_read=500_000,+ ),+ ),+ rows_read=500_000,+ duration_ms=19_000,+ trigger="fresh",+ query_kind="HogQLQuery",+ open_filters_placeholder=False,+ insight_id=7,+ dashboard_id=3,+ )+ with mock.patch("posthog.query_scan.job.sync_execute", side_effect=execute):+ run_query_scan(job)++ def _explained(self) -> list[str]:+ return [query for query, _ in self.calls]++ @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),+ # 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",),+ ["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),+ ]+ )+ def test_analyzes_each_execution(self, _name, dispatch, subqueries, expected_kinds, expected_explain_ok) -> None:+ self._run(dispatch, subqueries=subqueries)++ 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+ assert [str(finding.kind) for finding in stored.analysis.findings] == expected_kinds+ else:+ assert stored is None++ assert self.capture.call_count == 1+ 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["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)++ def test_runs_both_denominators_and_stores_the_shares(self) -> None:+ # plan_no_event_filter has a lower timestamp bound, so the range denominator runs with that+ # bound, and both shares reach the slot.+ self._run({"STUBBED_MARKER": "plan_no_event_filter"})++ stored = slot.get(self.team.pk, "cache_key_1", thresholds=FLAG.thresholds_fingerprint)+ assert stored is not None+ assert stored.analysis is not None+ assert stored.analysis.range_share is not None+ assert stored.analysis.project_share is not None+ # The team denominator runs once, unbounded.+ assert any("%(scan_team_id)s" in query and "timestamp" not in query for query, _ in self.calls)+ # The range denominator carries the lower bound the plan's Min-Max step reported.+ range_call = next((args for query, args in self.calls if "timestamp >=" in query), None)+ assert range_call is not None+ assert range_call["scan_lower"] == 1788461215++ def test_reads_the_row_averages_once_and_survives_their_failure(self) -> None:+ # The average is a table-wide property, so the query runs once, not per execution or EXPLAIN.+ self._run({"STUBBED_MARKER": "plan_persons_join"})+ assert len([query for query in self._explained() if "system.parts" in query]) == 1+ stored = slot.get(self.team.pk, "cache_key_1", thresholds=FLAG.thresholds_fingerprint)+ assert stored is not None and stored.analysis is not None+ assert [str(finding.kind) for finding in stored.analysis.findings] == ["persons_join"]++ # A failed metadata query must not fail the analysis: the gate falls back to raw granules.+ self.calls.clear()+ self.stored.clear()+ self._run({"STUBBED_MARKER": "plan_persons_join"}, averages_error=_OTHER_ERROR)+ stored = slot.get(self.team.pk, "cache_key_1", thresholds=FLAG.thresholds_fingerprint)+ assert stored is not None and stored.analysis is not None+ assert [str(finding.kind) for finding in stored.analysis.findings] == ["persons_join"]+++class TestQueryScanJobOnClickhouse(ClickhouseTestMixin, BaseTest):+ def setUp(self) -> None:+ super().setUp()+ # Any persons read fires the gate, so the test checks that the plan names the table, not the+ # row arithmetic the fixture tests cover.+ self.flag = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.0)+ self.capture = _fake_job_boundaries(self, {}, flag=self.flag)++ def test_the_real_plan_carries_everything_the_analysis_reads(self) -> None:+ # A saved plan freezes both the printer's and ClickHouse's format, so only a real EXPLAIN of+ # a printed query catches either side changing what the parser reads: the read nodes and+ # their table names, the Min-Max bounds, the primary key's columns and the granule counts.+ _create_person(team=self.team, distinct_ids=["user_1"])+ _create_event(+ team=self.team, event="$pageview", distinct_id="user_1", timestamp=datetime.now(UTC) - timedelta(days=1)+ )+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="key", access_secret="secret")+ DataWarehouseTable.objects.create(+ team=self.team,+ name="customers",+ format="Parquet",+ url_pattern="http://localhost/customers/*.parquet",+ credential=credential,+ columns={"id": "String"},+ )+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ tree = prepare_ast_for_printing(+ parse_select(+ "SELECT count() FROM events AS e JOIN persons AS p ON e.person_id = p.id "+ "JOIN customers AS c ON e.distinct_id = c.id "+ "WHERE e.event = '$pageview' AND e.timestamp >= now() - interval 7 day AND e.timestamp < now() "+ "AND e.distinct_id IN (SELECT distinct_id FROM events "+ "WHERE event = '$pageview' AND timestamp >= now() - interval 7 day)"+ ),+ context,+ dialect="clickhouse",+ )+ assert tree is not None+ stub = stub_in_subqueries(tree)+ job = QueryScanJob(+ team=self.team,+ cache_key="cache_key_1",+ executions=(+ Execution(+ stubbed_sql=print_prepared_ast(stub.stubbed, context, dialect="clickhouse"),+ subqueries=tuple(+ print_prepared_ast(stub_in_subqueries(subquery).stubbed, context, dialect="clickhouse")+ for subquery in stub.subqueries+ ),+ values=context.values,+ rows_read=500_000,+ ),+ ),+ rows_read=500_000,+ duration_ms=19_000,+ trigger="fresh",+ query_kind="HogQLQuery",+ open_filters_placeholder=False,+ )++ run_query_scan(job)++ stored = slot.get(self.team.pk, "cache_key_1", thresholds=self.flag.thresholds_fingerprint)+ assert stored is not None and stored.analysis is not None+ assert self.capture.call_args.kwargs["properties"]["explain_ok"] is True+ # A share proves the events read and its bounds were found. The only finding is the persons+ # join: the outer read has a start date and an event filter, and so does the subquery.+ assert stored.analysis.range_share is not None+ assert [str(finding.kind) for finding in stored.analysis.findings] == ["persons_join"]diff --git a/posthog/query_scan/test/test_serve.py b/posthog/query_scan/test/test_serve.pynew file mode 100644index 000000000000..1b18d86a6e2a--- /dev/null+++ b/posthog/query_scan/test/test_serve.py@@ -0,0 +1,109 @@+import json+from types import SimpleNamespace+from typing import Any++from posthog.test.base import BaseTest+from unittest import mock++from parameterized import parameterized++from posthog.schema import QueryScanSummary++from posthog.query_scan.flag import QueryScanFlag, QueryScanMode+from posthog.query_scan.serve import hydrate_response_scan, hydrate_scan_summary++SHOW = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)+LOG_ONLY = QueryScanFlag(mode=QueryScanMode.LOG_ONLY, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)++STORED_ANALYSIS = json.dumps(+ {+ "analysis": {+ "range_share": 0.8,+ "project_share": 0.25,+ "findings": [+ {+ "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.",+ }+ ],+ },+ }+)+PENDING = json.dumps({"pending": True})+++class TestHydrateScanSummary(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.redis = mock.Mock()+ self.redis.get.return_value = STORED_ANALYSIS+ patcher = mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=self.redis)+ patcher.start()+ self.addCleanup(patcher.stop)++ def _cached_summary(self, **overrides: Any) -> dict[str, Any]:+ # What a slow run stored with its result.+ return {"rows_read": 41_200, "duration_ms": 19_000, "analysis_requested": True, **overrides}++ def _cached_response(self, **overrides: Any) -> SimpleNamespace:+ return SimpleNamespace(+ query_scan=QueryScanSummary(**self._cached_summary(**overrides)), cache_key="cache_key_1"+ )++ @parameterized.expand(+ [+ ("the flag went off", None, None),+ # `log_only` collects the analysis without showing it to anyone.+ ("the mode was downgraded", LOG_ONLY, None),+ ("nothing moved", SHOW, ["no_event_filter"]),+ ]+ )+ def test_a_cached_summary_is_served_under_the_live_flag(self, _name, flag, expected_kinds) -> None:+ response = self._cached_response()++ with mock.patch("posthog.query_scan.serve.get_query_scan_flag", return_value=flag):+ hydrate_response_scan(self.team, response)+ folded = hydrate_scan_summary(self.team, self._cached_summary(), "cache_key_1")++ if expected_kinds is None:+ assert response.query_scan is None+ assert folded is None+ return+ assert [finding.kind for finding in response.query_scan.analysis.findings] == expected_kinds+ assert folded is not None+ assert [finding["kind"] for finding in folded["analysis"]["findings"]] == expected_kinds+ assert (response.query_scan.analysis.range_share, folded["analysis"]["project_share"]) == (0.8, 0.25)+ # The findings come with the message "Fix with AI" sends, built here so no client keeps its own copy.+ assert "- no_event_filter:" in response.query_scan.analysis.assistant_prompt++ @parameterized.expand(+ [+ # A run that asked for nothing costs no Redis read, however long it took.+ ("no analysis was requested", {"analysis_requested": False}, STORED_ANALYSIS, 0),+ ("the job is still running", {}, PENDING, 1),+ ("the slot expired", {}, None, 1),+ ]+ )+ def test_a_summary_without_a_stored_analysis_is_served_as_it_is(+ self, _name, overrides: dict[str, Any], stored: str | None, redis_reads: int+ ) -> None:+ self.redis.get.return_value = stored+ response = self._cached_response(**overrides)++ with mock.patch("posthog.query_scan.serve.get_query_scan_flag", return_value=SHOW):+ hydrate_response_scan(self.team, response)++ assert response.query_scan is not None+ assert response.query_scan.analysis is None+ assert self.redis.get.call_count == redis_reads++ def test_the_prompt_describes_the_run_being_served(self) -> None:+ # The slot can hold the analysis of a run that finished while this one was stopped, and the+ # other way round, so the prompt's run line follows the summary.+ response = self._cached_response(killed=True)++ with mock.patch("posthog.query_scan.serve.get_query_scan_flag", return_value=SHOW):+ hydrate_response_scan(self.team, response)++ assert "ClickHouse stopped this query after" in response.query_scan.analysis.assistant_promptdiff --git a/posthog/query_scan/test/test_slot.py b/posthog/query_scan/test/test_slot.pynew file mode 100644index 000000000000..46058a27b236--- /dev/null+++ b/posthog/query_scan/test/test_slot.py@@ -0,0 +1,64 @@+from typing import Any++from unittest import mock++from django.test import SimpleTestCase++from posthog.schema import QueryScanAnalysis, QueryScanFindingKind, QueryScanWarning++from posthog.query_scan.slot import (+ get as get_slot,+ set_done,+ set_pending,+)+++class TestQueryScanSlotRoundTrip(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.stored: dict[str, Any] = {}+ redis = mock.Mock()+ redis.get.side_effect = lambda key: self.stored.get(key)++ def set_unless_claimed(key: str, value: str, ex: int | None = None, nx: bool = False) -> bool | None:+ # Redis answers a conditional write that lost with None and any other write with True.+ if nx and key in self.stored:+ return None+ self.stored[key] = value+ return True++ redis.set.side_effect = set_unless_claimed+ patcher = mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis)+ patcher.start()+ self.addCleanup(patcher.stop)++ def test_a_stored_analysis_round_trips_its_shares_and_findings(self) -> None:+ # The shares and findings are what a served response and the scan endpoint read back, so a+ # write that dropped them on the way through Redis would show a blank analysis.+ finding = QueryScanWarning(+ kind=QueryScanFindingKind.NO_EVENT_FILTER,+ message="This query read every event.",+ fix="Add an event filter.",+ )+ set_done(+ 1,+ "cache_key_1",+ thresholds="0.1:0.5",+ analysis=QueryScanAnalysis(findings=[finding], range_share=0.42, project_share=0.13),+ )++ stored = get_slot(1, "cache_key_1", thresholds="0.1:0.5")++ assert stored is not None and stored.analysis is not None+ assert (stored.analysis.range_share, stored.analysis.project_share) == (0.42, 0.13)+ assert [str(finding.kind) for finding in stored.analysis.findings] == ["no_event_filter"]++ def test_a_claim_reads_back_as_a_slot_with_no_analysis(self) -> None:+ # The scan endpoint tells "not yet" from "nothing stored" by this, so a claim must read+ # back as a slot rather than as nothing.+ assert set_pending(1, "cache_key_1", thresholds="0.1:0.5") is True++ stored = get_slot(1, "cache_key_1", thresholds="0.1:0.5")++ assert stored is not None+ assert stored.analysis is Nonediff --git a/posthog/query_scan/test/test_stub.py b/posthog/query_scan/test/test_stub.pynew file mode 100644index 000000000000..71165416e39d--- /dev/null+++ b/posthog/query_scan/test/test_stub.py@@ -0,0 +1,196 @@+from posthog.test.base import BaseTest++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import HogQLPrinter+from posthog.hogql.printer.utils import prepare_ast_for_printing, print_prepared_ast++from posthog.query_scan.stub import stub_in_subqueries++from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable+++def print_hogql(node: ast.Expr) -> str:+ # HogQLPrinter serializes a parsed tree with no database, so the stub can be checked without one.+ return HogQLPrinter(context=HogQLContext(team_id=0)).visit(node)+++class TestStubInSubqueries(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "IN a subquery",+ "SELECT count() FROM events WHERE event IN (SELECT event FROM events)",+ "SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "NOT IN a subquery",+ "SELECT count() FROM events WHERE event NOT IN (SELECT event FROM events)",+ "SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "NOT wrapping an IN subquery folds whole, never NOT 1",+ "SELECT count() FROM events WHERE NOT (event IN (SELECT event FROM events))",+ "SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "an IN subquery inside a JOIN subquery",+ "SELECT count() FROM events e "+ "JOIN (SELECT id FROM persons WHERE id IN (SELECT id FROM cohortpeople)) p ON e.person_id = p.id",+ "SELECT count() FROM events e JOIN (SELECT id FROM persons WHERE 1) p ON e.person_id = p.id",+ 1,+ ),+ (+ "an IN subquery in the select list",+ "SELECT event IN (SELECT event FROM events) FROM events",+ "SELECT 1 FROM events",+ 1,+ ),+ (+ "a scalar subquery in the select list",+ "SELECT (SELECT count() FROM events) AS total FROM events",+ "SELECT NULL AS total FROM events",+ 1,+ ),+ (+ "a scalar subquery compared with a non-IN operator",+ "SELECT count() FROM events WHERE timestamp >= (SELECT min(timestamp) FROM events)",+ "SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "a scalar subquery nested in a function inside a comparison",+ "SELECT count() FROM events WHERE toDate(timestamp) >= toDate((SELECT min(timestamp) FROM events))",+ "SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "NOT wrapping a scalar comparison folds whole",+ "SELECT count() FROM events WHERE NOT (timestamp >= (SELECT min(timestamp) FROM events))",+ "SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "a scalar subquery inside a JOIN subquery is stubbed while the JOIN subquery stays",+ "SELECT count() FROM events e "+ "JOIN (SELECT id FROM persons WHERE created_at >= (SELECT max(created_at) FROM persons)) p "+ "ON e.person_id = p.id",+ "SELECT count() FROM events e JOIN (SELECT id FROM persons WHERE 1) p ON e.person_id = p.id",+ 1,+ ),+ (+ "a UNION ALL root keeps both members",+ "SELECT count() FROM events WHERE event IN (SELECT event FROM events) "+ "UNION ALL SELECT count() FROM events",+ "SELECT count() FROM events WHERE 1 UNION ALL SELECT count() FROM events",+ 1,+ ),+ (+ "a subquery CTE body survives",+ "WITH c AS (SELECT distinct_id FROM events) "+ "SELECT count() FROM events WHERE distinct_id IN (SELECT distinct_id FROM c)",+ "WITH c AS (SELECT distinct_id FROM events) SELECT count() FROM events WHERE 1",+ 1,+ ),+ (+ "a column CTE is a scalar and is stubbed",+ "WITH (SELECT max(timestamp) FROM events) AS latest "+ "SELECT count() FROM events WHERE timestamp = latest",+ "WITH NULL AS latest SELECT count() FROM events WHERE timestamp = latest",+ 1,+ ),+ (+ "a literal IN list survives",+ "SELECT count() FROM events WHERE event IN ('$pageview', '$autocapture')",+ "SELECT count() FROM events WHERE event IN ('$pageview', '$autocapture')",+ 0,+ ),+ ]+ )+ def test_stub_replaces_subqueries_used_as_values_and_keeps_literal_lists(+ self, _name: str, source: str, expected: str, expected_subqueries: int+ ) -> None:+ result = stub_in_subqueries(parse_select(source))++ self.assertEqual(print_hogql(result.stubbed), print_hogql(parse_select(expected)))+ self.assertEqual(len(result.subqueries), expected_subqueries)++ def test_global_in_is_stubbed_too(self) -> None:+ # HogQL has no GLOBAL IN syntax, so build the op the tree carries once it is lowered for a+ # distributed query.+ node = parse_select("SELECT count() FROM events WHERE event IN (SELECT event FROM events)")+ assert isinstance(node, ast.SelectQuery) and isinstance(node.where, ast.CompareOperation)+ node.where.op = ast.CompareOperationOp.GlobalIn++ result = stub_in_subqueries(node)++ self.assertEqual(len(result.subqueries), 1)+ self.assertEqual(print_hogql(result.stubbed), print_hogql(parse_select("SELECT count() FROM events WHERE 1")))++ def test_collector_returns_subqueries_in_visit_order(self) -> None:+ source = (+ "SELECT count() FROM events "+ "WHERE event IN (SELECT 'first' FROM events) AND event IN (SELECT 'second' FROM events)"+ )++ result = stub_in_subqueries(parse_select(source))++ self.assertEqual(len(result.subqueries), 2)+ printed = [print_hogql(subquery) for subquery in result.subqueries]+ self.assertIn("'first'", printed[0])+ self.assertIn("'second'", printed[1])+++class TestStubPrintsAsClickHouse(BaseTest):+ def test_the_stubbed_tree_and_its_subqueries_print_in_the_clickhouse_dialect(self) -> None:+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ prepared = prepare_ast_for_printing(+ node=parse_select(+ "SELECT count() FROM events "+ "WHERE distinct_id IN (SELECT distinct_id FROM events WHERE event = 'x') "+ "AND timestamp >= (SELECT min(timestamp) FROM events)"+ ),+ context=context,+ dialect="clickhouse",+ )++ assert prepared is not None+ stub = stub_in_subqueries(prepared)+ sql = print_prepared_ast(stub.stubbed, context, dialect="clickhouse")+ subquery_sql = print_prepared_ast(stub_in_subqueries(stub.subqueries[0]).stubbed, context, dialect="clickhouse")++ assert "(SELECT" not in sql.replace("\n", " ")+ assert len(stub.subqueries) == 2+ assert "events" in subquery_sql and "IN (SELECT" not in subquery_sql++ def test_a_warehouse_table_prints_as_an_empty_table_without_its_credentials(self) -> None:+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="key", access_secret="secret")+ DataWarehouseTable.objects.create(+ team=self.team,+ name="customers",+ format="Parquet",+ url_pattern="http://localhost/customers/*.parquet",+ credential=credential,+ columns={"id": "String", "plan": "String"},+ )+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ prepared = prepare_ast_for_printing(+ node=parse_select("SELECT count() FROM events AS e JOIN customers AS c ON e.distinct_id = c.id"),+ context=context,+ dialect="clickhouse",+ )+ assert prepared is not None++ sql = print_prepared_ast(stub_in_subqueries(prepared).stubbed, context, dialect="clickhouse")++ assert "null(" in sql and "s3(" not in sql+ assert "`id` String, `plan` String" in context.values.values()+ assert not any(key.endswith("_sensitive") for key in context.values)diff --git a/posthog/query_scan/test/test_trigger.py b/posthog/query_scan/test/test_trigger.pynew file mode 100644index 000000000000..005f7e216acf--- /dev/null+++ b/posthog/query_scan/test/test_trigger.py@@ -0,0 +1,361 @@+import json+from typing import Any++from unittest import mock++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.schema import (+ BaseMathType,+ DateRange,+ EventsNode,+ FunnelMathType,+ FunnelsQuery,+ HogQLFilters,+ HogQLQuery,+ RetentionFilter,+ RetentionQuery,+ RetentionType,+ TrendsQuery,+)++from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.query_stats import QueryStats, RecordedExecution++from posthog.clickhouse.query_tagging import AccessMethod, Feature, reset_query_tags, tag_queries+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++FLAG = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)++# A query with one `IN` subquery, so the stub collects exactly one subquery to print.+_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+) -> RecordedExecution:+ return RecordedExecution(+ tree=parse_select(sql), context=HogQLContext(team_id=1, values=values or {}), rows_read=rows_read+ )+++def _stats(*, duration_ms: float = 2000.0, executions: list[RecordedExecution] | None = None) -> QueryStats:+ stats = QueryStats(rows_read=10, duration_ms=duration_ms)+ stats.executions.extend(executions if executions is not None else [_execution()])+ return stats+++def _tag_as_api_key(test: "TestQueryScanTrigger") -> None:+ tag_queries(access_method=AccessMethod.PERSONAL_API_KEY)+++def _store_a_slot(test: "TestQueryScanTrigger") -> None:+ test.redis.get.return_value = json.dumps({"analysis": {"findings": []}})+++def _spend_the_enqueue_budget(test: "TestQueryScanTrigger") -> None:+ test.redis.incr.return_value = 11+++def _lose_the_slot_claim(test: "TestQueryScanTrigger") -> None:+ test.redis.set.return_value = 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:+ context.values.update(values)+ return "SELECT 1"++ return print_with_values+++class TestQueryScanTrigger(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.redis = mock.Mock()+ self.redis.get.return_value = None+ self.redis.incr.return_value = 1+ patcher = mock.patch("posthog.query_scan.slot.query_cache_raw_client", return_value=self.redis)+ patcher.start()+ self.addCleanup(patcher.stop)+ delay_patcher = mock.patch("posthog.tasks.query_scan.analyze_query_scan.delay")+ self.delay = delay_patcher.start()+ self.addCleanup(delay_patcher.stop)+ # The prepared tree is not printable in a unit test, so control the printed SQL directly.+ print_patcher = mock.patch("posthog.query_scan.trigger.print_prepared_ast", return_value="SELECT 1")+ self.print = print_patcher.start()+ self.addCleanup(print_patcher.stop)+ self.addCleanup(reset_query_tags)++ def _assert_no_slot_was_claimed(self) -> None:+ key = slot_key(1, "cache_key_1", FLAG.thresholds_fingerprint)+ slot_writes = [call for call in self.redis.set.call_args_list if call.args[0] == key]+ assert slot_writes == []++ def _trigger(self, **overrides: Any):+ arguments: dict[str, Any] = {+ "flag": FLAG,+ "stats": _stats(),+ "team_id": 1,+ "cache_key": "cache_key_1",+ "query": HogQLQuery(query="select 1"),+ "trigger": "fresh",+ "cacheable": True,+ "insight_id": 7,+ "dashboard_id": 3,+ }+ return maybe_trigger_query_scan(**{**arguments, **overrides})++ @parameterized.expand(+ [+ ("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"),+ (+ "direct connection",+ {"query": HogQLQuery(query="select 1", connectionId="connection_1")},+ None,+ "direct_connection",+ ),+ ("result not cacheable", {"cacheable": False}, None, "not_cacheable"),+ ("slot already exists", {}, _store_a_slot, "slot_exists"),+ ("over the enqueues a team gets in a minute", {}, _spend_the_enqueue_budget, "rate_limited"),+ ]+ )+ def test_skips_with_a_reason(self, _name, overrides, prepare, expected_reason) -> None:+ if prepare is not None:+ prepare(self)++ result = self._trigger(**overrides)++ assert result == expected_reason+ self.delay.assert_not_called()+ self._assert_no_slot_was_claimed()++ def test_a_killed_run_is_analyzed_below_the_floor(self) -> None:+ # A memory-limit kill can die in under a second, and nobody gets a result from it, so the+ # floor must not keep it from the one analysis that can ever advise the person.+ result = self._trigger(+ stats=_stats(duration_ms=999.0), killed=True, error_type="ClickHouseQueryMemoryLimitExceeded"+ )++ assert result is None+ 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)++ result = self._trigger()++ assert result is None+ assert self.delay.call_count == 1++ def test_a_lost_slot_claim_does_not_enqueue_a_second_job(self) -> None:+ # Two slow runs of the same query can both find no slot, so the conditional write is what+ # keeps one job per slot; without it the loser would enqueue a duplicate analysis.+ _lose_the_slot_claim(self)++ result = self._trigger()++ assert result == "slot_exists"+ self.delay.assert_not_called()++ def test_a_threshold_change_reanalyzes_under_the_new_key(self) -> None:+ # A done slot from other thresholds sits under its own key, so a run under the current+ # thresholds still claims a fresh slot and enqueues, instead of reading the old slot as in+ # place and never analyzing until it expires.+ other = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.2, persons_ratio=0.5)+ other_key = slot_key(1, "cache_key_1", other.thresholds_fingerprint)+ new_key = slot_key(1, "cache_key_1", FLAG.thresholds_fingerprint)+ stored = {other_key: json.dumps({"analysis": {"findings": []}})}+ self.redis.get.side_effect = lambda key: stored.get(key)++ def claim(key: str, value: Any, ex: int | None = None, nx: bool = False) -> bool | None:+ if nx and key in stored:+ return None+ stored[key] = value+ return True++ self.redis.set.side_effect = claim++ result = self._trigger()++ assert result is None+ assert self.delay.call_count == 1+ assert new_key in stored+ assert json.loads(stored[new_key])["pending"] is True++ def test_a_broker_failure_does_not_fail_the_query(self) -> None:+ # ClickHouse has already done the work and the result is not cached yet, so an optional+ # side effect must not take a successful query down with it.+ self.delay.side_effect = Exception("broker unavailable")++ result = self._trigger()++ 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")++ assert result is None+ enqueued = self.delay.call_args.kwargs["executions"]+ assert enqueued[0]["event_filter"] == {"classification": "usable", "reason": None}+ # 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"),+ ]+ )+ def test_an_unshippable_selected_execution_aborts_the_whole_scan(+ self, _name: str, printed_values: dict[str, 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)++ result = self._trigger(stats=_stats(executions=[_execution(rows_read=100), _execution(rows_read=50)]))++ assert result == expected_reason+ self.delay.assert_not_called()+ self.redis.delete.assert_called_once_with(slot_key(1, "cache_key_1", FLAG.thresholds_fingerprint))++ 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.+ light = _execution(rows_read=50, values={"hogql_val_0": "from the run"})+ heavy = _execution(rows_read=100, values={"hogql_val_0_sensitive": "from the run"})++ result = self._trigger(stats=_stats(executions=[light, heavy]))++ assert result is None+ 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"]+ # A warehouse run's own values hold its source credentials, so only the job's print travels.+ assert [execution["values"] for execution in enqueued] == [{}, {}]++ @parameterized.expand(+ [+ ("hogql", HogQLQuery(query="select 1"), "HogQLQuery"),+ ("trends", TrendsQuery(series=[EventsNode(event="$pageview")]), "TrendsQuery"),+ ("funnels", FunnelsQuery(series=[EventsNode(event="a"), EventsNode(event="b")]), "FunnelsQuery"),+ ]+ )+ def test_enqueues_the_run_and_writes_a_pending_slot(self, _name, query, expected_kind) -> None:+ result = self._trigger(query=query)++ assert result is None+ assert self.delay.call_count == 1+ enqueued = self.delay.call_args.kwargs+ assert enqueued["cache_key"] == "cache_key_1"+ assert enqueued["rows_read"] == 10+ assert enqueued["duration_ms"] == 2000+ assert enqueued["trigger"] == "fresh"+ assert enqueued["query_kind"] == expected_kind+ assert (enqueued["insight_id"], enqueued["dashboard_id"]) == (7, 3)+ assert len(enqueued["executions"]) == 1++ key, payload = self.redis.set.call_args.args+ assert key == slot_key(1, "cache_key_1", FLAG.thresholds_fingerprint)+ assert json.loads(payload) == {"pending": True}+ assert self.redis.set.call_args.kwargs == {"ex": 600, "nx": True}+ # 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:+ self._trigger(query=TrendsQuery(series=[EventsNode(event="$pageview")], dateRange=DateRange(date_from="all")))++ assert self.delay.call_args.kwargs["all_time"] is True++ @parameterized.expand(+ [+ (+ "first time for user math",+ TrendsQuery(series=[EventsNode(event="$pageview", math=BaseMathType.FIRST_TIME_FOR_USER)]),+ True,+ ),+ (+ "a first-time funnel step",+ FunnelsQuery(+ series=[EventsNode(event="a", math=FunnelMathType.FIRST_TIME_FOR_USER), EventsNode(event="b")]+ ),+ True,+ ),+ (+ "first-time retention",+ RetentionQuery(retentionFilter=RetentionFilter(retentionType=RetentionType.RETENTION_FIRST_TIME)),+ True,+ ),+ ("plain trends", TrendsQuery(series=[EventsNode(event="$pageview")]), False),+ ("raw sql", HogQLQuery(query="select 1"), False),+ ]+ )+ def test_the_payload_says_whether_the_insight_reads_all_history_by_design(self, _name, query, expected) -> None:+ # Such an insight has to start at the project's first event whatever its date range, so the+ # job must not advise a start date it cannot use.+ self._trigger(query=query)++ assert self.delay.call_args.kwargs["all_history_by_design"] is expected+++class TestOpenFiltersPlaceholder(SimpleTestCase):+ @parameterized.expand(+ [+ ("no placeholder at all", HogQLQuery(query="select count() from events"), False),+ ("open filters", HogQLQuery(query="select count() from events where {filters}"), True),+ (+ "filters with a start date",+ HogQLQuery(+ query="select count() from events where {filters}",+ filters=HogQLFilters(dateRange=DateRange(date_from="-7d")),+ ),+ False,+ ),+ (+ "filters set to all time",+ HogQLQuery(+ query="select count() from events where {filters}",+ filters=HogQLFilters(dateRange=DateRange(date_from="all")),+ ),+ True,+ ),+ # An end date on its own leaves the start of the range open.+ (+ "filters with only an end date",+ HogQLQuery(+ query="select count() from events where {filters}",+ filters=HogQLFilters(dateRange=DateRange(date_to="-1d")),+ ),+ True,+ ),+ (+ "only a dotted call placeholder",+ HogQLQuery(+ query="select toStartOfInterval(timestamp, {filters.interval('day')}), count() from events group by 1"+ ),+ False,+ ),+ ("an insight built from pickers", TrendsQuery(series=[EventsNode(event="$pageview")]), False),+ ]+ )+ def test_only_a_date_carrying_placeholder_puts_the_start_date_on_the_insight(+ self, _name: str, query: HogQLQuery | TrendsQuery, expected: bool+ ) -> None:+ assert _open_filters_placeholder(query) is expecteddiff --git a/posthog/query_scan/tree.py b/posthog/query_scan/tree.pynew file mode 100644index 000000000000..83f223864320--- /dev/null+++ b/posthog/query_scan/tree.py@@ -0,0 +1,265 @@+"""Walk a prepared HogQL tree and attribute conditions to the events reads they constrain.++The tree comes out of ``prepare_ast_for_printing``, so lazy tables are expanded, saved views are+inlined and every node carries a type. The checks match on those types instead of chain strings,+because ``sharded_events`` only exists at print time and a column can reach the events table+through any number of view, subquery and alias layers.++A condition belongs to the events read whose ``TableType`` node its field resolves to, compared by+identity. ``TableType`` compares equal by value, so identity is the only thing that separates two+reads of the same table.+"""++from collections.abc import Iterator++from posthog.hogql import ast+from posthog.hogql.database.schema.events import EventsTable+from posthog.hogql.visitor import TraversingVisitor++from posthog.dataclasses import frozen++# Join types whose ``ON`` condition constrains both sides, so a term in it prunes the read the same+# way a ``where`` term does. An outer join keeps the rows that fail the condition and an anti join+# keeps only those, so neither prunes. A cross-shard join carries a ``GLOBAL`` prefix and prunes+# the same way.+_INNER_JOIN_TYPES = frozenset(+ {+ "JOIN",+ "INNER",+ "INNER JOIN",+ "ANY INNER JOIN",+ "ALL INNER JOIN",+ "ASOF INNER JOIN",+ "SEMI JOIN",+ "ASOF SEMI JOIN",+ }+)+++@frozen(eq=False)+class EventsRead:+ select: ast.SelectQuery+ table_type: ast.TableType+++def find_events_reads(node: ast.AST) -> list[EventsRead]:+ collector = _EventsReadCollector()+ collector.visit(node)+ return collector.reads+++def collect_conditions(node: ast.AST, read: EventsRead) -> list[ast.Expr]:+ """Top-level AND terms of every ``where``, ``prewhere`` and inner-join ``ON`` that constrains+ ``read``.++ A term from an enclosing query counts, because ClickHouse pushes a condition on a subquery's+ or a view's column down into the read. It stops counting at a subquery that slices its own+ rows, which hands up its choice of rows before the outer condition sees them.+ """+ collector = _ConditionCollector()+ collector.visit(node)+ reaching = collector.selects_reaching(read.select)+ return [term for select, term in collector.terms if id(select) in reaching]+++def iter_and_terms(expr: ast.Expr | None) -> Iterator[ast.Expr]:+ if expr is None:+ return+ unwrapped = strip_aliases(expr)+ if isinstance(unwrapped, ast.And):+ for child in unwrapped.exprs:+ yield from iter_and_terms(child)+ return+ yield unwrapped+++def strip_aliases(expr: ast.Expr) -> ast.Expr:+ # The resolver passes re-wrap, so aliases can stack.+ while isinstance(expr, ast.Alias):+ expr = expr.expr+ return expr+++def is_column_of(expr: ast.Expr, read: EventsRead, column: str) -> bool:+ """Whether ``expr`` is a bare reference to ``column`` on ``read``, through any number of+ view, subquery and alias layers."""+ expr = strip_aliases(expr)+ if not isinstance(expr, ast.Field):+ return False+ return any(+ name == column and table_type is read.table_type for table_type, name in resolve_to_table_columns(expr.type)+ )+++def contains_column_of(expr: ast.Expr, read: EventsRead, column: str) -> bool:+ finder = _ColumnFinder(read=read, column=column)+ finder.visit(expr)+ return finder.found+++def resolve_to_table_columns(type_: ast.Type | None) -> list[tuple[ast.TableType, str]]:+ """Follow a field's type down to the database table columns it exports.++ A view or subquery column is a ``FieldType`` whose own type is the expression that select+ exported, which may again be a column of a deeper select. A set query exports one column per+ branch, and a condition on it constrains every branch, so the walk forks and can reach more+ than one table.+ """+ resolved: list[tuple[ast.TableType, str]] = []+ pending: list[ast.Type | None] = [type_]+ # A type reached twice is a cycle from a resolver bug, so each is visited once.+ seen: set[int] = set()++ while pending:+ current = pending.pop()+ if id(current) in seen:+ continue+ seen.add(id(current))+ while isinstance(current, ast.FieldAliasType):+ current = current.type+ if not isinstance(current, ast.FieldType):+ continue+ table_type = _unwrap_table_alias(current.table_type)+ if isinstance(table_type, ast.TableType):+ resolved.append((table_type, _physical_column_name(current)))+ continue+ select_type = _select_type_of(table_type)+ if select_type is None:+ continue+ pending.extend(_exported_columns(select_type, current.name))++ return resolved+++def _physical_column_name(field_type: ast.FieldType) -> str:+ """The database column a field names.++ ``FROM events AS e (id, kind, props, ts)`` renames the table's columns for the query and the+ field keeps the query's name, so map it back the way ``FieldType.resolve_database_field`` does.+ """+ table_type = field_type.table_type+ if isinstance(table_type, ast.ColumnAliasedTableType):+ return table_type.alias_to_original.get(field_type.name, field_type.name)+ return field_type.name+++def _unwrap_table_alias(table_type: ast.Type) -> ast.Type:+ while isinstance(table_type, ast.TableAliasType | ast.ColumnAliasedTableType):+ table_type = table_type.table_type+ if isinstance(table_type, ast.CTETableAliasType):+ return table_type.cte_table_type+ return table_type+++def _select_type_of(table_type: ast.Type) -> ast.SelectQueryType | ast.SelectSetQueryType | None:+ if isinstance(table_type, ast.SelectQueryType | ast.SelectSetQueryType):+ return table_type+ if isinstance(table_type, ast.SelectQueryAliasType | ast.SelectViewType | ast.CTETableType):+ return table_type.select_query_type+ return None+++def _exported_columns(select_type: ast.SelectQueryType | ast.SelectSetQueryType, name: str) -> list[ast.Type]:+ """Each type a select exports under ``name``: one for a plain select, one per branch for a+ set query, whose own entry is a type unified across the branches and holds no lineage."""+ if isinstance(select_type, ast.SelectSetQueryType):+ return [column for branch in select_type.types for column in _exported_columns(branch, name)]+ column = select_type.columns.get(name)+ return [column] if column is not None else []+++def _slices_rows(select: ast.SelectQuery) -> bool:+ """Whether this select picks which of its rows to keep, so a condition applied above it+ cannot reach the read below.++ ``LIMIT``, ``OFFSET`` and ``LIMIT BY`` all do, because the rows come in the select's own order+ and filtering earlier would keep different ones. The outermost select always carries the query+ limit, which costs nothing here because no condition sits above it.+ """+ return select.limit is not None or select.offset is not None or select.limit_by is not None+++def _inner_join_terms(join: ast.JoinExpr | None) -> Iterator[ast.Expr]:+ """Top-level AND terms of every inner-join ``ON`` condition in this select's join chain.++ A ``USING`` list only pairs columns of the two tables, so it is left out.+ """+ while join is not None:+ join_type = join.join_type or ""+ constraint = join.constraint+ if (+ join_type.removeprefix("GLOBAL ") in _INNER_JOIN_TYPES+ and constraint is not None+ and constraint.constraint_type == "ON"+ ):+ yield from iter_and_terms(constraint.expr)+ join = join.next_join+++def _events_table_type(join: ast.JoinExpr) -> ast.TableType | None:+ join_type = join.type+ if join_type is None:+ return None+ table_type = _unwrap_table_alias(join_type)+ if isinstance(table_type, ast.TableType) and isinstance(table_type.table, EventsTable):+ return table_type+ return None+++class _EventsReadCollector(TraversingVisitor):+ def __init__(self) -> None:+ super().__init__()+ self.reads: list[EventsRead] = []++ def visit_select_query(self, node: ast.SelectQuery) -> None:+ join = node.select_from+ while join is not None:+ table_type = _events_table_type(join)+ if table_type is not None:+ self.reads.append(EventsRead(select=node, table_type=table_type))+ join = join.next_join+ super().visit_select_query(node)+++class _ConditionCollector(TraversingVisitor):+ def __init__(self) -> None:+ super().__init__()+ self.terms: list[tuple[ast.SelectQuery, ast.Expr]] = []+ self._enclosing_select: dict[int, ast.SelectQuery] = {}+ self._stack: list[ast.SelectQuery] = []++ def visit_select_query(self, node: ast.SelectQuery) -> None:+ if self._stack:+ self._enclosing_select[id(node)] = self._stack[-1]+ self.terms.extend((node, term) for term in iter_and_terms(node.where))+ self.terms.extend((node, term) for term in iter_and_terms(node.prewhere))+ self.terms.extend((node, term) for term in _inner_join_terms(node.select_from))+ self._stack.append(node)+ super().visit_select_query(node)+ self._stack.pop()++ def selects_reaching(self, select: ast.SelectQuery) -> set[int]:+ """The ids of the selects whose conditions constrain a read in ``select``: the select+ itself, then each enclosing one until a row slice blocks the way."""+ reaching = {id(select)}+ current = select+ while not _slices_rows(current):+ enclosing = self._enclosing_select.get(id(current))+ if enclosing is None:+ break+ reaching.add(id(enclosing))+ current = enclosing+ return reaching+++class _ColumnFinder(TraversingVisitor):+ def __init__(self, *, read: EventsRead, column: str) -> None:+ super().__init__()+ self.read = read+ self.column = column+ self.found = False++ def visit_field(self, node: ast.Field) -> None:+ if is_column_of(node, self.read, self.column):+ self.found = True+ super().visit_field(node)diff --git a/posthog/query_scan/trigger.py b/posthog/query_scan/trigger.pynew file mode 100644index 000000000000..a8710b601026--- /dev/null+++ b/posthog/query_scan/trigger.py@@ -0,0 +1,290 @@+"""Decide whether a run gets analyzed, print its SQL, and enqueue the job.++The runner calls this once per blocking run. The SQL is printed only for a run over the flag's+``floor_ms`` or one ClickHouse stopped. A printer, broker or Redis failure drops the enqueue, never+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.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.placeholders import find_placeholders+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.models.user import User+from posthog.query_scan.event_filter import classify_event_filter+from posthog.query_scan.findings import SQL_QUERY_KIND+from posthog.query_scan.flag import QueryScanFlag+from posthog.query_scan.slot import (+ claim_enqueue_budget,+ clear as clear_slot,+ get as get_slot,+ set_pending,+)+from posthog.query_scan.stub import stub_in_subqueries++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.+MAX_SUBQUERIES = 5++# Math that finds each person's or group's first event, so the read has to start at the project's+# first event whatever date range the insight has.+_FIRST_TIME_MATHS: frozenset[str] = frozenset(+ {+ BaseMathType.FIRST_TIME_FOR_USER,+ BaseMathType.FIRST_MATCHING_EVENT_FOR_USER,+ GroupMathType.FIRST_TIME_FOR_GROUP,+ GroupMathType.FIRST_MATCHING_EVENT_FOR_GROUP,+ FunnelMathType.FIRST_TIME_FOR_USER,+ FunnelMathType.FIRST_TIME_FOR_USER_WITH_FILTERS,+ }+)++SkipReason = Literal[+ "flag_off",+ "below_floor",+ "api_key",+ "no_principal",+ "no_clickhouse_query",+ "not_cacheable",+ "direct_connection",+ "sensitive_values",+ "rate_limited",+ "slot_exists",+ "nothing_to_analyze",+ "too_large",+ "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+++def is_analyzable_principal(user: object) -> TypeGuard[User]:+ """Whether the response may carry the scan summary. Only a real user row is a member of the project;+ a shared-link viewer must not see the project's data volume.+ """+ return isinstance(user, User)+++def maybe_trigger_query_scan(+ *,+ flag: QueryScanFlag | None,+ stats: QueryStats | None,+ team_id: int,+ cache_key: str,+ query: BaseModel,+ trigger: str,+ cacheable: bool,+ insight_id: int | None = None,+ dashboard_id: int | None = None,+ killed: bool = False,+ error_type: str | None = None,+) -> SkipReason | None:+ """Enqueue the analysis for this run. Returns why it was skipped, or None once the job is enqueued."""+ if flag is None or stats is None:+ return "flag_off"++ duration_ms = round(stats.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():+ # An API caller has no surface to read the advice on, so the analysis would only cost.+ return "api_key"+ 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.+ return "direct_connection"+ if not cacheable:+ return "not_cacheable"+ if get_slot(team_id, cache_key, thresholds=flag.thresholds_fingerprint) is not None:+ return "slot_exists"+ if not claim_enqueue_budget(team_id):+ return "rate_limited"+ if not set_pending(team_id, cache_key, thresholds=flag.thresholds_fingerprint):+ # 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):+ # 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:+ # 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++ try:+ analyze_query_scan.delay(+ team_id=team_id,+ cache_key=cache_key,+ executions=executions,+ rows_read=stats.rows_read,+ duration_ms=duration_ms,+ trigger=trigger,+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ killed=killed,+ error_type=error_type,+ query_kind=query_kind,+ open_filters_placeholder=_open_filters_placeholder(query),+ all_time=_all_time(query),+ all_history_by_design=_reads_all_history_by_design(query),+ )+ except Exception:+ # The broker can be down while ClickHouse is fine, and the result is not cached yet, so+ # failing here would throw away a run the person already waited for.+ logger.warning("query_scan_enqueue_failed", team_id=team_id, exc_info=True)+ # Left in place, the claim above reports a pending analysis no job is coming to fill.+ clear_slot(team_id, cache_key, thresholds=flag.thresholds_fingerprint)+ return "enqueue_failed"+ return None+++def _print_executions(stats: QueryStats) -> 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]+ printed: list[dict[str, Any]] = []+ subquery_budget = MAX_SUBQUERIES+ for execution in heaviest:+ entry = _print_execution(execution, subquery_budget)+ if isinstance(entry, str):+ return entry+ subquery_budget -= len(entry["subqueries"])+ printed.append(entry)+ return printed+++def _print_execution(execution: RecordedExecution, subquery_budget: int) -> dict[str, Any] | SkipReason:+ """One execution as the job's payload entry, or why it cannot be shipped."""+ try:+ # The run's context still holds every value the run printed, credentials included.+ context = copy.copy(execution.context)+ context.values = {}+ stub = stub_in_subqueries(execution.tree)+ entry = {+ "stubbed_sql": print_prepared_ast(stub.stubbed, context, dialect="clickhouse"),+ "subqueries": [+ print_prepared_ast(stub_in_subqueries(subquery).stubbed, context, dialect="clickhouse")+ for subquery in stub.subqueries[: max(subquery_budget, 0)]+ ],+ # The parameter values travel as they are: Celery's JSON serializer round-trips the+ # datetimes, dates, UUIDs and decimals among them.+ "values": context.values,+ "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),+ }+ 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"+++def _event_filter_verdict(tree: ast.Expr) -> dict[str, str | 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)+ 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}+++def _source(query: BaseModel) -> BaseModel:+ """The query an insight node wraps, or the query itself."""+ return getattr(query, "source", None) or query+++def _all_time(query: BaseModel) -> bool:+ """Whether the person chose the "All time" date range. The runner turns that into a bound at+ the project's first event, so the plan reports a timestamp filter and cannot tell on its own."""+ source = _source(query)+ date_range = getattr(source, "dateRange", None)+ if date_range is None:+ filters = getattr(source, "filters", None)+ date_range = getattr(filters, "dateRange", None)+ return getattr(date_range, "date_from", None) == "all"+++def _reads_all_history_by_design(query: BaseModel) -> bool:+ """Whether the insight has to read from the project's first event whatever its date range: a+ first-time math or first-time retention finds each person's first event, so a start date would+ change the answer and no start-date advice can help.+ """+ source = _source(query)+ series = getattr(source, "series", None) or []+ if any(getattr(item, "math", None) in _FIRST_TIME_MATHS for item in series):+ return True+ retention_filter = getattr(source, "retentionFilter", None)+ return getattr(retention_filter, "retentionType", None) == RetentionType.RETENTION_FIRST_TIME+++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(...)}``+ substitute a value and cannot bound the query. False for every other kind, which carries no raw SQL.+ """+ if getattr(query, "kind", None) != SQL_QUERY_KIND:+ return False+ try:+ if not find_placeholders(parse_select(getattr(query, "query", "") or "")).has_date_filters:+ return False+ except Exception:+ return False+ date_range = getattr(getattr(query, "filters", None), "dateRange", None)+ date_from = getattr(date_range, "date_from", None)+ # "all" promises the whole table, so the placeholder still expands to no lower bound, and an end+ # date on its own bounds nothing at the start.+ return not date_from or date_from == "all"diff --git a/posthog/schema.py b/posthog/schema.pyindex 08e2754b682d..937b8aa0f1c8 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -233,6 +233,8 @@ from posthog.schema_enums import (PropertyOperator as PropertyOperator,PropertyType as PropertyType,QueryIndexUsage as QueryIndexUsage,+ QueryScanFindingKind as QueryScanFindingKind,+ QueryScanFindingReason as QueryScanFindingReason,QuickFilterContext as QuickFilterContext,QuickFilterType as QuickFilterType,RecordingOrder as RecordingOrder,@@ -2653,6 +2655,19 @@ class QueryResponseAlternative79(BaseModel):)+class QueryScanWarning(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ 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.')+ 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):model_config = ConfigDict(extra="forbid",@@ -6784,12 +6799,77 @@ class QueryResponseAlternative86(BaseModel):)+class QueryScanAnalysis(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ assistant_prompt: str | None = Field(+ default=None,+ description=(+ "The message the Fix with AI button sends to the assistant. Absent when no"+ " finding can be fixed in the query."+ ),+ )+ findings: list[QueryScanWarning] = Field(..., description="Empty when the analysis found nothing to fix.")+ project_share: float | None = Field(+ default=None,+ description="How much of all the project's events the query read, 0 to 1.",+ )+ range_share: float | None = Field(+ default=None,+ description=("How much of the project's events in the query's date range the query read, 0 to 1."),+ )+++class QueryScanResponse(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ analysis: QueryScanAnalysis | None = None+++class QueryScanSummary(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ analysis: QueryScanAnalysis | None = Field(+ default=None,+ description=(+ "The stored analysis, put on the response when it is served. Absent while"+ " the analysis runs, and when none was requested."+ ),+ )+ analysis_requested: bool | None = Field(+ default=None,+ description=(+ "True when the run asked for an analysis, or found one stored. While"+ " `analysis` is absent, poll `GET /query/scan/{cache_key}` for it."+ ),+ )+ duration_ms: int = Field(+ ...,+ description=("ClickHouse time for the last fresh run, summed over its ClickHouse queries."),+ )+ killed: bool | None = Field(+ default=None,+ description="True when ClickHouse stopped the run instead of finishing it.",+ )+ rows_read: int = Field(+ ...,+ description="Rows ClickHouse read for the last fresh run, all tables included.",+ )++class QueryStatus(BaseModel):model_config = ConfigDict(extra="forbid",)budget_remaining_bytes: int | None = Nonebytes_read: int | None = None+ cache_key: str | None = Field(+ default=None,+ description=("Cache key of the run that failed, so clients can ask for its query scan."),+ )complete: bool | None = Field(default=False,description=(@@ -6823,6 +6903,7 @@ class QueryStatus(BaseModel):)query_async: Literal[True] = Field(default=True, description="ONLY async queries use QueryStatus.")query_progress: ClickhouseQueryProgress | None = None+ query_scan: QueryScanSummary | None = Noneresults: Any | None = Nonestart_time: AwareDatetime | None = Field(default=None, description="When was query execution task enqueued.")task_id: str | None = None@@ -7919,6 +8000,10 @@ class TestCachedBasicQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -10807,6 +10892,10 @@ class CachedAccountsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: intquery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -10874,6 +10963,10 @@ class CachedAccountsTableQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: intquery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -10932,6 +11025,10 @@ class CachedActorsPropertyTaxonomyQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -10995,6 +11092,10 @@ class CachedActorsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: intquery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11055,6 +11156,10 @@ class CachedCalendarHeatmapQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11116,6 +11221,10 @@ class CachedDocumentSimilarityQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11174,6 +11283,10 @@ class CachedEndpointsUsageOverviewQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11236,6 +11349,10 @@ class CachedEndpointsUsageTableQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11295,6 +11412,10 @@ class CachedEndpointsUsageTrendsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11353,6 +11474,10 @@ class CachedErrorTrackingBreakdownsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11412,6 +11537,10 @@ class CachedErrorTrackingFingerprintProjectionQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11483,6 +11612,10 @@ class CachedErrorTrackingReleasesQueryResponse(BaseModel):other: ErrorTrackingReleaseSeries | None = Field(..., description="Releases past `maxReleases`, summed.")other_release_count: intquery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11558,6 +11691,10 @@ class CachedErrorTrackingSimilarIssuesQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11619,6 +11756,10 @@ class CachedEventTaxonomyQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11682,6 +11823,10 @@ class CachedEventsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11736,6 +11881,10 @@ class CachedExperimentExposureQueryResponse(BaseModel):last_refresh: AwareDatetimenext_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11776,6 +11925,10 @@ class CachedFunnelCorrelationResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11835,6 +11988,10 @@ class CachedFunnelsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11905,6 +12062,10 @@ class CachedGroupsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: intquery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -11964,6 +12125,10 @@ class CachedLifecycleQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12027,6 +12192,10 @@ class CachedLogsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12085,6 +12254,10 @@ class CachedMCPHarnessBreakdownQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12144,6 +12317,10 @@ class CachedMCPMissingCapabilitiesQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12206,6 +12383,10 @@ class CachedMCPModelBreakdownQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12264,6 +12445,10 @@ class CachedMCPToolCallBreakdownQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12322,6 +12507,10 @@ class CachedMCPToolCallsAndErrorsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12380,6 +12569,10 @@ class CachedMCPToolCategoriesQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12438,6 +12631,10 @@ class CachedMCPToolCategoryCountsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12496,6 +12693,10 @@ class CachedMCPToolCategoryMapQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12554,6 +12755,10 @@ class CachedMCPToolDailyStatsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12612,6 +12817,10 @@ class CachedMCPToolDescriptionsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12670,6 +12879,10 @@ class CachedMCPToolFailureOccurrencesQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12728,6 +12941,10 @@ class CachedMCPToolFailuresQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12786,6 +13003,10 @@ class CachedMCPToolNeighborsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12844,6 +13065,10 @@ class CachedMCPToolQualityDailyStatsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12902,6 +13127,10 @@ class CachedMCPToolQualityRowsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -12964,6 +13193,10 @@ class CachedMCPToolSampleIntentsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13022,6 +13255,10 @@ class CachedMCPToolStatsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13083,6 +13320,10 @@ class CachedMCPToolTopUsersQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13141,6 +13382,10 @@ class CachedMarketingAnalyticsAggregatedQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13216,6 +13461,10 @@ class CachedMarketingAnalyticsAttributionPathsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13293,6 +13542,10 @@ class CachedMarketingAnalyticsAttributionQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13363,6 +13616,10 @@ class CachedMarketingAnalyticsRetentionQueryResponse(BaseModel):description=("How many breakdown values were folded into 'Other', so the table can say so."),)query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13437,6 +13694,10 @@ class CachedMarketingAnalyticsTableQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13497,6 +13758,10 @@ class CachedMetricsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13555,6 +13820,10 @@ class CachedPathsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13613,6 +13882,10 @@ class CachedPropertyValuesQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13676,6 +13949,10 @@ class CachedRecordingsQueryResponse(BaseModel):description=("Cursor for the next page. Contains the ordering value and session_id from the last record."),)query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13734,6 +14011,10 @@ class CachedRetentionQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13796,6 +14077,10 @@ class CachedSessionAttributionExplorerQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13860,6 +14145,10 @@ class CachedSessionBatchEventsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13930,6 +14219,10 @@ class CachedSessionQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -13992,6 +14285,10 @@ class CachedSessionsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14052,6 +14349,10 @@ class CachedSessionsTimelineQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14110,6 +14411,10 @@ class CachedStickinessQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14160,6 +14465,10 @@ class CachedSuggestedQuestionsQueryResponse(BaseModel):last_refresh: AwareDatetimenext_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14197,6 +14506,10 @@ class CachedTeamTaxonomyQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14257,6 +14570,10 @@ class CachedTraceNeighborsQueryResponse(BaseModel):description="ID of the older trace (chronologically before current)",)query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14298,6 +14615,10 @@ class CachedTraceQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14360,6 +14681,10 @@ class CachedTraceSpansAggregationQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14422,6 +14747,10 @@ class CachedTraceSpansAttributeBreakdownQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14484,6 +14813,10 @@ class CachedTraceSpansQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14546,6 +14879,10 @@ class CachedTraceSpansSymbolStatsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14608,6 +14945,10 @@ class CachedTraceSpansTreeQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14670,6 +15011,10 @@ class CachedTracesQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14730,6 +15075,10 @@ class CachedTrendsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14788,6 +15137,10 @@ class CachedUsageMetricsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14846,6 +15199,10 @@ class CachedVectorSearchQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14908,6 +15265,10 @@ class CachedWebAgentAnalyticsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -14971,6 +15332,10 @@ class CachedWebBotsTableQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15034,6 +15399,10 @@ class CachedWebExternalClicksTableQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15106,6 +15475,10 @@ class CachedWebGoalsQueryResponse(BaseModel):)preComputeStrategy: WebAnalyticsPreComputeStrategy | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15167,6 +15540,10 @@ class CachedWebNotableChangesQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimepreComputeStrategy: WebAnalyticsPreComputeStrategy | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15236,6 +15613,10 @@ class CachedWebOverviewQueryResponse(BaseModel):)preComputeStrategy: WebAnalyticsPreComputeStrategy | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15298,6 +15679,10 @@ class CachedWebPageURLSearchQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimepreComputeStrategy: WebAnalyticsPreComputeStrategy | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15375,6 +15760,10 @@ class CachedWebStatsTableQueryResponse(BaseModel):)preComputeStrategy: WebAnalyticsPreComputeStrategy | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -15443,6 +15832,10 @@ class CachedWebVitalsPathBreakdownQueryResponse(BaseModel):)preComputeStrategy: WebAnalyticsPreComputeStrategy | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -17368,6 +17761,10 @@ class GenericCachedQueryResponse(BaseModel):last_refresh: AwareDatetimenext_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -25415,6 +25812,10 @@ class CachedErrorTrackingQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -25481,6 +25882,10 @@ class CachedHogQLQueryResponse(BaseModel):offset: int | None = Nonequery: str | None = Field(default=None, description="Input query string")query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -25534,6 +25939,10 @@ class CachedInsightActorsQueryOptionsResponse(BaseModel):last_refresh: AwareDatetimenext_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -25569,6 +25978,10 @@ class CachedNewExperimentQueryResponse(BaseModel):last_refresh: AwareDatetimenext_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -25603,6 +26016,10 @@ class CachedPathsV2QueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -25661,6 +26078,10 @@ class CachedWebVitalsQueryResponse(BaseModel):modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -28334,6 +28755,10 @@ class CachedErrorTrackingIssueCorrelationQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeoffset: int | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -29975,6 +30400,10 @@ class CachedExperimentQueryResponse(BaseModel):p_value: float | None = Noneprobability: dict[str, float] | None = Nonequery_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -30012,6 +30441,10 @@ class CachedExperimentTrendsQueryResponse(BaseModel):p_value: floatprobability: dict[str, float]query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -30049,6 +30482,10 @@ class CachedLegacyExperimentQueryResponse(BaseModel):p_value: floatprobability: dict[str, float]query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -30545,6 +30982,10 @@ class CachedExperimentFunnelsQueryResponse(BaseModel):next_allowed_client_refresh: AwareDatetimeprobability: dict[str, float]query_metadata: dict[str, Any] | None = None+ query_scan: QueryScanSummary | None = Field(+ default=None,+ description=("The rows and time of the run that produced these results, with its analysis once it is stored."),+ )query_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 9fc37ecc36da..3ca31e5828f8 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3896,6 +3896,21 @@ class LimitContext(Enum):NONE_TYPE_NONE = None+class QueryScanFindingKind(StrEnum):+ NO_EVENT_FILTER = "no_event_filter"+ NO_START_DATE = "no_start_date"+ PERSONS_JOIN = "persons_join"+++class QueryScanFindingReason(StrEnum):+ IN_OR = "in_or"+ WRAPPED = "wrapped"+ NEGATED = "negated"+ DYNAMIC = "dynamic"+ NOT_PRUNED = "not_pruned"+ FILTERS = "filters"++class QuickFilterContext(StrEnum):DASHBOARDS = "dashboards"ERROR_TRACKING_ISSUE_FILTERS = "error-tracking-issue-filters"diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.pyindex ec3243bd68c0..f3984985a550 100644--- a/posthog/tasks/__init__.py+++ b/posthog/tasks/__init__.py@@ -17,6 +17,7 @@ from . import (process_scheduled_changes,proxy,push_notifications,+ query_scan,remote_config,split_person,surveys,@@ -44,6 +45,7 @@ __all__ = ["process_scheduled_changes","proxy","push_notifications",+ "query_scan","remote_config","split_person","surveys",diff --git a/posthog/tasks/query_scan.py b/posthog/tasks/query_scan.pynew file mode 100644index 000000000000..e57c72c64a64--- /dev/null+++ b/posthog/tasks/query_scan.py@@ -0,0 +1,68 @@+from typing import Any++import structlog+from celery import shared_task+from celery.exceptions import SoftTimeLimitExceeded++from posthog.celery_queues import CeleryQueue+from posthog.models.team.team import Team+from posthog.query_scan.job import Execution, QueryScanJob, run_query_scan+from posthog.query_scan.slot import PENDING_TTL_SECONDS+from posthog.scoping_audit import skip_team_scope_audit++logger = structlog.get_logger(__name__)+++# The queue cache warming uses, so a burst of analyses cannot overwhelm ClickHouse. Advisory, so+# no retry. `expires` matches the pending slot's lifetime, and the time limits sit inside it, so a+# job never outlives its claim.+@shared_task(+ ignore_result=True,+ queue=CeleryQueue.ANALYTICS_LIMITED.value,+ expires=PENDING_TTL_SECONDS,+ soft_time_limit=60,+ time_limit=90,+)+@skip_team_scope_audit # Team is not a team-scoped model+def analyze_query_scan(+ team_id: int,+ cache_key: str,+ executions: list[dict[str, Any]],+ rows_read: int,+ duration_ms: int,+ trigger: str,+ query_kind: str | None,+ open_filters_placeholder: bool,+ insight_id: int | None = None,+ dashboard_id: int | None = None,+ killed: bool = False,+ error_type: str | None = None,+ all_time: bool = False,+ all_history_by_design: bool = False,+) -> None:+ team = Team.objects.select_related("organization").filter(pk=team_id).first()+ if team is None:+ return+ try:+ run_query_scan(+ QueryScanJob(+ team=team,+ cache_key=cache_key,+ executions=tuple(Execution.from_payload(execution) for execution in executions),+ rows_read=rows_read,+ duration_ms=duration_ms,+ trigger=trigger,+ query_kind=query_kind,+ open_filters_placeholder=open_filters_placeholder,+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ killed=killed,+ error_type=error_type,+ all_time=all_time,+ all_history_by_design=all_history_by_design,+ )+ )+ except SoftTimeLimitExceeded:+ # The EXPLAINs ran past the soft limit. Leave the pending slot to expire so the next slow+ # run of this query retries, and never re-raise: the analysis is advisory.+ logger.warning("query_scan_task_soft_timeout", team_id=team_id, cache_key=cache_key)diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex fd90d6fc46eb..0af23a8fee64 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -97,6 +97,7 @@'posthog.tasks.plugin_server.hog_function_state_transition','posthog.tasks.proxy.reconcile_proxy_root_redirect','posthog.tasks.push_notifications.send_user_push',+ 'posthog.tasks.query_scan.analyze_query_scan','posthog.tasks.remote_config.cleanup_stale_remote_config_expiry_tracking_task','posthog.tasks.remote_config.refresh_expiring_remote_config_cache_entries','posthog.tasks.remote_config.sync_all_remote_configs',diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 18970fdd47c1..6cca277072a6 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1454,9 +1454,66 @@ export interface ClickhouseQueryProgressApi {time_elapsed: number}+export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]++export const QueryScanFindingKindApi = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ 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 {+ /** The one fact the finding rests on. */+ evidence?: string | null+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string+ 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. */+ findings: QueryScanWarningApi[]+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null+}++export interface QueryScanSummaryApi {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysisApi | null+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number+}+export interface QueryStatusApi {budget_remaining_bytes?: number | nullbytes_read?: number | null+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | null@@ -1476,6 +1533,7 @@ export interface QueryStatusApi {/** ONLY async queries use QueryStatus. */query_async?: truequery_progress?: ClickhouseQueryProgressApi | null+ query_scan?: QueryScanSummaryApi | nullresults?: unknown/** When was query execution task enqueued. */start_time?: string | nulldiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 89018ec24dec..bc66c413f87a 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1968,9 +1968,66 @@ export interface ClickhouseQueryProgressApi {time_elapsed: number}+export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]++export const QueryScanFindingKindApi = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ 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 {+ /** The one fact the finding rests on. */+ evidence?: string | null+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string+ 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. */+ findings: QueryScanWarningApi[]+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null+}++export interface QueryScanSummaryApi {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysisApi | null+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number+}+export interface QueryStatusApi {budget_remaining_bytes?: number | nullbytes_read?: number | null+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | null@@ -1990,6 +2047,7 @@ export interface QueryStatusApi {/** ONLY async queries use QueryStatus. */query_async?: truequery_progress?: ClickhouseQueryProgressApi | null+ query_scan?: QueryScanSummaryApi | nullresults?: unknown/** When was query execution task enqueued. */start_time?: string | null@@ -9332,6 +9390,8 @@ export interface InsightApi {readonly types: readonly unknown[] | null/** @nullable */readonly resolved_date_range: InsightApiResolvedDateRange+ /** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */+ readonly query_scan: unknown_create_in_folder?: stringreadonly alerts: readonly unknown[]/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.tsindex 4fa5b28cf78b..108b75329175 100644--- a/products/endpoints/frontend/generated/api.schemas.ts+++ b/products/endpoints/frontend/generated/api.schemas.ts@@ -1012,9 +1012,66 @@ export interface ClickhouseQueryProgressApi {time_elapsed: number}+export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]++export const QueryScanFindingKindApi = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ 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 {+ /** The one fact the finding rests on. */+ evidence?: string | null+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string+ 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. */+ findings: QueryScanWarningApi[]+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null+}++export interface QueryScanSummaryApi {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysisApi | null+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number+}+export interface QueryStatusApi {budget_remaining_bytes?: number | nullbytes_read?: number | null+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | null@@ -1034,6 +1091,7 @@ export interface QueryStatusApi {/** ONLY async queries use QueryStatus. */query_async?: truequery_progress?: ClickhouseQueryProgressApi | null+ query_scan?: QueryScanSummaryApi | nullresults?: unknown/** When was query execution task enqueued. */start_time?: string | nulldiff --git a/products/experiments/backend/hogql_queries/experiment_trends_query_runner.py b/products/experiments/backend/hogql_queries/experiment_trends_query_runner.pyindex 900740de6f1f..acf347491869 100644--- a/products/experiments/backend/hogql_queries/experiment_trends_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_trends_query_runner.py@@ -29,7 +29,8 @@ from posthog.schema import (TrendsQueryResponse,)-from posthog.hogql import ast+from posthog.hogql import ast, query_stats+from posthog.hogql.query_stats import QueryStatsfrom posthog.clickhouse.query_tagging import tag_queriesfrom posthog.constants import ExperimentNoResultsErrorKeys@@ -252,9 +253,17 @@ class ExperimentTrendsQueryRunner(QueryRunner):shared_results: dict[str, Optional[Any]] = {"count_result": None, "exposure_result": None}errors = []- def run(query_runner: TrendsQueryRunner, result_key: str, is_parallel: bool):+ def run(+ query_runner: TrendsQueryRunner,+ result_key: str,+ is_parallel: bool,+ stats: Optional[QueryStats] = None,+ ):try:- result = query_runner.calculate()+ # A thread starts with no scope, so the totals are handed over, or the response+ # under-reports what ClickHouse read.+ with query_stats.use(stats):+ result = query_runner.calculate()shared_results[result_key] = resultexcept Exception as e:errors.append(e)@@ -270,9 +279,10 @@ class ExperimentTrendsQueryRunner(QueryRunner):run(self.count_query_runner, "count_result", False)run(self.exposure_query_runner, "exposure_result", False)else:+ stats = query_stats.get_active()jobs = [- threading.Thread(target=run, args=(self.count_query_runner, "count_result", True)),- threading.Thread(target=run, args=(self.exposure_query_runner, "exposure_result", True)),+ threading.Thread(target=run, args=(self.count_query_runner, "count_result", True, stats)),+ threading.Thread(target=run, args=(self.exposure_query_runner, "exposure_result", True, stats)),][j.start() for j in jobs] # type: ignore[j.join() for j in jobs] # type: ignorediff --git a/products/product_analytics/backend/hogql_queries/funnels/funnels_query_runner.py b/products/product_analytics/backend/hogql_queries/funnels/funnels_query_runner.pyindex 243306b15d78..9867c9712cd3 100644--- a/products/product_analytics/backend/hogql_queries/funnels/funnels_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/funnels/funnels_query_runner.py@@ -25,9 +25,10 @@ from posthog.schema import (ResolvedDateRangeResponse,)-from posthog.hogql import ast+from posthog.hogql import ast, query_statsfrom posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, HogQLGlobalSettings, LimitContextfrom posthog.hogql.query import execute_hogql_query+from posthog.hogql.query_stats import QueryStatsfrom posthog.hogql.timings import HogQLTimingsfrom posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL@@ -330,13 +331,20 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):results: list[Optional[_T]] = [None] * len(tasks)errors: list[Exception] = []- def run(index: int, timings: HogQLTimings, query_tags: Optional[QueryTags] = None) -> None:+ def run(+ index: int,+ timings: HogQLTimings,+ query_tags: Optional[QueryTags] = None,+ stats: Optional[QueryStats] = None,+ ) -> None:try:# Worker threads start with an empty QueryTags ContextVar — restore the parent's# snapshot so execute_hogql_query has the required feature/product tags.if query_tags is not None:query_tagging.update_tags(query_tags)- results[index] = tasks[index](timings)+ # The query scan accumulator is another ContextVar the thread does not inherit.+ with query_stats.use(stats):+ results[index] = tasks[index](timings)except Exception as exc: # noqa: BLE001errors.append(exc)finally:@@ -351,10 +359,11 @@ class FunnelsQueryRunner(AnalyticsQueryRunner[FunnelsQueryResponse]):run(index, self.timings.clone_for_subquery(index_offset + index))else:parent_tags = query_tagging.get_query_tags().model_copy(deep=True)+ parent_stats = query_stats.get_active()jobs = [threading.Thread(target=run,- args=(index, self.timings.clone_for_subquery(index_offset + index), parent_tags),+ args=(index, self.timings.clone_for_subquery(index_offset + index), parent_tags, parent_stats),)for index in range(len(tasks))]diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.pyindex 26b73e716b4b..c7607cba8394 100644--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py@@ -43,9 +43,10 @@ from posthog.schema import (TrendsQueryResponse,)-from posthog.hogql import ast+from posthog.hogql import ast, query_statsfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, HogQLGlobalSettings, LimitContextfrom posthog.hogql.query import execute_hogql_query+from posthog.hogql.query_stats import QueryStatsfrom posthog.hogql.timings import HogQLTimingsfrom posthog.caching.insights_api import (@@ -413,6 +414,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):timings: HogQLTimings,is_parallel: bool,query_tags: Optional[QueryTags] = None,+ stats: Optional[QueryStats] = None,):try:if query_tags:@@ -420,18 +422,19 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):series_with_extra = self.series[index]- response = execute_hogql_query(- query_type="TrendsQuery",- query=query,- team=self.team,- user=self.user,- workload=self.workload,- settings=self.hogql_settings,- timings=timings,- modifiers=self.modifiers,- limit_context=self.limit_context,- context=self.build_hogql_context(),- )+ with query_stats.use(stats):+ response = execute_hogql_query(+ query_type="TrendsQuery",+ query=query,+ team=self.team,+ user=self.user,+ workload=self.workload,+ settings=self.hogql_settings,+ timings=timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ context=self.build_hogql_context(),+ )timings_matrix[index + 1] = response.timingsres_matrix[index] = self.build_series_response(response, series_with_extra, len(queries))@@ -456,6 +459,8 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):for index, query in enumerate(queries):run(index, query, self.timings.clone_for_subquery(index), False)else:+ # A thread starts with an empty context, so the query tags and the query scan+ # accumulator are handed over explicitly.jobs = [threading.Thread(target=run,@@ -465,6 +470,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):self.timings.clone_for_subquery(index),True,query_tagging.get_query_tags().model_copy(deep=True),+ query_stats.get_active(),),)for index, query in enumerate(queries)diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex b8a3d0876a02..9b88a0db818e 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -102,6 +102,7 @@ from posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTfrom posthog.permissions import TeamMemberStrictManagementPermissionfrom posthog.query_cache import QueryCache+from posthog.query_scan.serve import hydrate_scan_summaryfrom posthog.rate_limit import (AIObservabilitySummarizationBurstThrottle,AIObservabilitySummarizationDailyThrottle,@@ -581,6 +582,10 @@ class InsightSerializer(InsightBasicSerializer):hogql = serializers.SerializerMethodField()types = serializers.SerializerMethodField()resolved_date_range = serializers.SerializerMethodField(read_only=True)+ query_scan = serializers.SerializerMethodField(+ read_only=True,+ help_text="What ClickHouse read for this insight's last slow run, with the findings of its query scan.",+ )_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)alerts = serializers.SerializerMethodField(read_only=True)filter_override_context = serializers.SerializerMethodField(@@ -627,6 +632,7 @@ class InsightSerializer(InsightBasicSerializer):"hogql","types","resolved_date_range",+ "query_scan","_create_in_folder","alerts","filter_override_context",@@ -1054,7 +1060,12 @@ class InsightSerializer(InsightBasicSerializer):@extend_schema_field(OpenApiTypes.ANY)def get_query_status(self, insight: Insight):- return self.insight_result(insight).query_status+ query_status = self.insight_result(insight).query_status+ if not self.context.get("is_shared") or not isinstance(query_status, dict):+ return query_status+ # A shared insight is read from outside the project, and both fields address the stored+ # analysis of its data.+ return {key: value for key, value in query_status.items() if key not in ("cache_key", "query_scan")}def _query_variables_mapping(self, query: dict):if (@@ -1090,6 +1101,24 @@ class InsightSerializer(InsightBasicSerializer):def get_resolved_date_range(self, insight: Insight):return self.insight_result(insight).resolved_date_range+ @extend_schema_field(OpenApiTypes.ANY)+ def get_query_scan(self, insight: Insight):+ # A shared insight is read from outside the project, and the scan describes the+ # project's data volume.+ if self.context.get("is_shared"):+ return None+ result = self.insight_result(insight)+ summary = result.query_scan+ cache_key = result.cache_key+ query_status = result.query_status or {}+ if query_status.get("error"):+ # A killed run has no response to carry the summary, so it rides on the status.+ summary = query_status.get("query_scan") or summary+ cache_key = query_status.get("cache_key") or cache_key+ if not isinstance(summary, dict):+ return None+ return hydrate_scan_summary(self.context["get_team"](), summary, cache_key)+@extend_schema_field(serializers.ListField())def get_alerts(self, insight: Insight):if insight.alertable_query_kind is None:@@ -1276,6 +1305,7 @@ class InsightSerializer(InsightBasicSerializer):query_status=cached_response.get("query_status"),hogql=cached_response.get("hogql"),types=cached_response.get("types"),+ query_scan=cached_response.get("query_scan"),)else:EXPORT_QUERY_CACHE_MISS.inc()@@ -1367,6 +1397,7 @@ class InsightSerializer(InsightBasicSerializer):return self._degraded_insight_result(insight,dashboard,+ error=e,error_message=str(e),error_code=getattr(e, "code_name", None),last_refresh=None,@@ -1378,6 +1409,7 @@ class InsightSerializer(InsightBasicSerializer):return self._degraded_insight_result(insight,dashboard,+ error=e,error_message="concurrency_limit_exceeded",error_code="concurrency_limit_exceeded",last_refresh=now(),@@ -1388,6 +1420,7 @@ class InsightSerializer(InsightBasicSerializer):return self._degraded_insight_result(insight,dashboard,+ error=e,error_message=str(e),error_code=None,last_refresh=None,@@ -1398,13 +1431,18 @@ class InsightSerializer(InsightBasicSerializer):insight: Insight,dashboard: Any,*,+ error: Exception,error_message: str,error_code: str | None,last_refresh: datetime | None,) -> InsightResult:"""A 200 response carrying the failure on query_status, so a failing insight degrades inplace rather than failing the whole request. `error_code` lets the client tell a- deterministic query failure from a transient one."""+ deterministic query failure from a transient one.++ A run ClickHouse stopped carries its scan on the exception, and the analysis is stored+ under the cache key, so both ride along instead of dropping with the results."""+ query_scan = getattr(error, "query_scan", None)return InsightResult(result=None,last_refresh=last_refresh,@@ -1423,7 +1461,8 @@ class InsightSerializer(InsightBasicSerializer):error=True,)),- cache_key=None,+ cache_key=getattr(error, "cache_key", None),+ query_scan=query_scan if isinstance(query_scan, dict) else None,hogql=None,columns=None,has_more=None,diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.pyindex 6c558a02e548..08c5f29512b7 100644--- a/products/product_analytics/backend/tests/api/test_insight.py+++ b/products/product_analytics/backend/tests/api/test_insight.py@@ -39,6 +39,8 @@ from posthog.schema import (NodeKind,PropertyGroupFilter,PropertyGroupFilterValue,+ QueryScanAnalysis,+ QueryScanFindingKind,StickinessQuery,TrendsQuery,)@@ -49,9 +51,13 @@ from posthog import settingsfrom posthog.api.test.dashboards import DashboardAPIfrom posthog.caching.insight_result import InsightResultfrom posthog.constants import AvailableFeature+from posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionModefrom posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, Userfrom posthog.models.project import Project+from posthog.query_scan.findings import build_warning+from posthog.query_scan.flag import QueryScanFlag, QueryScanMode+from posthog.query_scan.test.slots import stored_slotfrom posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.insight_queries import default_pageview_query, insight_query@@ -4162,6 +4168,105 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):self.assertEqual(query_status["error_code"], expected_error_code)+class TestInsightQueryScan(APIBaseTest):+ FLAG = QueryScanFlag(mode=QueryScanMode.SHOW, floor_ms=1000, event_ratio=0.1, persons_ratio=0.5)++ def _insight(self) -> Insight:+ return Insight.objects.create(+ team=self.team,+ created_by=self.user,+ query={"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "SELECT 1"}},+ )++ def _stored_slot(self) -> str:+ return stored_slot(+ QueryScanAnalysis(+ range_share=0.8,+ project_share=0.25,+ findings=[build_warning(kind=QueryScanFindingKind.NO_START_DATE, query_kind="HogQLQuery")],+ )+ )++ @parameterized.expand([("a completed run", False), ("a run clickhouse stopped", True)])+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")+ def test_an_insight_carries_the_query_scan_with_its_findings(+ self, _name: str, killed: bool, mock_calculate: mock.MagicMock+ ) -> None:+ insight = self._insight()+ summary = {"rows_read": 41_200, "duration_ms": 19_000, "analysis_requested": True}+ if killed:+ # A stopped run has no results to carry the advice, so it rides on the exception.+ error = ClickHouseQueryTimeOut("query timed out")+ error.cache_key = "cache-key" # type: ignore[attr-defined]+ error.query_scan = {**summary, "killed": True} # type: ignore[attr-defined]+ mock_calculate.side_effect = error+ else:+ mock_calculate.return_value = InsightResult(+ result=[],+ last_refresh=timezone.now(),+ cache_key="cache-key",+ is_cached=True,+ timezone=self.team.timezone,+ query_scan=summary,+ )+ redis_client = mock.Mock()+ redis_client.get.return_value = self._stored_slot()++ with (+ patch("posthog.query_scan.serve.get_query_scan_flag", return_value=self.FLAG),+ patch("posthog.query_scan.slot.query_cache_raw_client", return_value=redis_client),+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ body = response.json()+ query_scan = body["query_scan"]+ self.assertEqual(query_scan["analysis"]["range_share"], 0.8)+ self.assertEqual(query_scan["analysis"]["project_share"], 0.25)+ self.assertEqual(query_scan.get("killed", False), killed)+ self.assertEqual([finding["kind"] for finding in query_scan["analysis"]["findings"]], ["no_start_date"])+ # The cache key addresses the stored analysis, so the client can poll for it.+ self.assertEqual(body["filters_hash"], "cache-key")++ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")+ def test_a_shared_insight_gets_no_scan_and_no_cache_key_on_its_query_status(+ self, mock_calculate: mock.MagicMock+ ) -> None:+ insight = self._insight()+ sharing_configuration = SharingConfiguration.objects.create(+ team=self.team, insight=insight, enabled=True, access_token="xyz"+ )+ mock_calculate.return_value = InsightResult(+ result=None,+ last_refresh=timezone.now(),+ cache_key="cache-key",+ is_cached=False,+ timezone=self.team.timezone,+ # The shape an async run that ClickHouse stopped leaves on the stored status.+ query_status={+ "id": "query-1",+ "team_id": self.team.pk,+ "error": True,+ "cache_key": "cache-key",+ "query_scan": {"rows_read": 41_200, "duration_ms": 19_000, "killed": True, "analysis_requested": True},+ },+ )+ self.client.logout()++ response = self.client.get(+ f"/api/projects/{self.team.id}/insights/{insight.id}/"+ f"?sharing_access_token={sharing_configuration.access_token}"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ # A shared insight is read from outside the project, and both fields describe the+ # project's own data volume.+ body = response.json()+ self.assertIsNone(body["query_scan"])+ self.assertNotIn("cache_key", body["query_status"])+ self.assertNotIn("query_scan", body["query_status"])++class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def _create_insight(self, name: str = "My insight") -> Insight:return Insight.objects.create(team=self.team, name=name, saved=True, created_by=self.user)diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex da4612e4f716..205846fc4a87 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -962,9 +962,66 @@ export interface ClickhouseQueryProgressApi {time_elapsed: number}+export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]++export const QueryScanFindingKindApi = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ 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 {+ /** The one fact the finding rests on. */+ evidence?: string | null+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string+ 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. */+ findings: QueryScanWarningApi[]+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null+}++export interface QueryScanSummaryApi {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysisApi | null+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number+}+export interface QueryStatusApi {budget_remaining_bytes?: number | nullbytes_read?: number | null+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | nulldashboard_id?: number | null@@ -984,6 +1041,7 @@ export interface QueryStatusApi {/** ONLY async queries use QueryStatus. */query_async?: truequery_progress?: ClickhouseQueryProgressApi | null+ query_scan?: QueryScanSummaryApi | nullresults?: unknown/** When was query execution task enqueued. */start_time?: string | null@@ -8412,6 +8470,8 @@ export interface InsightApi {readonly types: readonly unknown[] | null/** @nullable */readonly resolved_date_range: InsightApiResolvedDateRange+ /** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */+ readonly query_scan: unknown_create_in_folder?: stringreadonly alerts: readonly unknown[]/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */@@ -8540,6 +8600,8 @@ export interface PatchedInsightApi {readonly types?: readonly unknown[] | null/** @nullable */readonly resolved_date_range?: PatchedInsightApiResolvedDateRange+ /** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */+ readonly query_scan?: unknown_create_in_folder?: stringreadonly alerts?: readonly unknown[]/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a485a0027a63..a64adc309bf2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1342,9 +1342,68 @@ export namespace Schemas {time_elapsed: number;}+ export type QueryScanFindingKind = typeof QueryScanFindingKind[keyof typeof QueryScanFindingKind];+++ export const QueryScanFindingKind = {+ NoEventFilter: 'no_event_filter',+ NoStartDate: 'no_start_date',+ 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 {+ /** The one fact the finding rests on. */+ evidence?: string | null;+ /** What "Fix with AI" and the assistant are told to do. */+ fix: string;+ 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. */+ findings: QueryScanWarning[];+ /** How much of all the project's events the query read, 0 to 1. */+ project_share?: number | null;+ /** How much of the project's events in the query's date range the query read, 0 to 1. */+ range_share?: number | null;+ }++ export interface QueryScanSummary {+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */+ analysis?: QueryScanAnalysis | null;+ /** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */+ analysis_requested?: boolean | null;+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */+ duration_ms: number;+ /** True when ClickHouse stopped the run instead of finishing it. */+ killed?: boolean | null;+ /** Rows ClickHouse read for the last fresh run, all tables included. */+ rows_read: number;+ }+export interface QueryStatus {budget_remaining_bytes?: number | null;bytes_read?: number | null;+ /** Cache key of the run that failed, so clients can ask for its query scan. */+ cache_key?: string | null;/** Whether the query is still running. Will be true if the query is complete, even if it errored. Either result or error will be set. */complete?: boolean | null;dashboard_id?: number | null;@@ -1364,6 +1423,7 @@ export namespace Schemas {/** ONLY async queries use QueryStatus. */query_async?: true;query_progress?: ClickhouseQueryProgress | null;+ query_scan?: QueryScanSummary | null;results?: unknown;/** When was query execution task enqueued. */start_time?: string | null;@@ -9338,6 +9398,8 @@ export namespace Schemas {readonly types: readonly unknown[] | null;/** @nullable */readonly resolved_date_range: InsightResolvedDateRange;+ /** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */+ readonly query_scan: unknown;_create_in_folder?: string;readonly alerts: readonly unknown[];/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */@@ -67635,6 +67697,8 @@ export namespace Schemas {readonly types?: readonly unknown[] | null;/** @nullable */readonly resolved_date_range?: PatchedInsightResolvedDateRange;+ /** What ClickHouse read for this insight's last slow run, with the findings of its query scan. */+ readonly query_scan?: unknown;_create_in_folder?: string;readonly alerts?: readonly unknown[];/** Resolved dashboard and tile filter layers used to explain filter precedence in the UI. */@@ -78293,6 +78357,10 @@ export namespace Schemas {export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | unknown | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative56 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107 | QueryResponseAlternative108 | QueryResponseAlternative109 | QueryResponseAlternative110 | QueryResponseAlternative111 | QueryResponseAlternative112;+ export interface QueryScanResponse {+ analysis?: QueryScanAnalysis | null;+ }+export interface QueryStatusResponse {query_status: QueryStatus;}