Skip to content

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

fix(insights): surface memory-limit errors to users (#67437)

Vasco de Krijger383f5b2fcb4b
diff --git a/ee/clickhouse/test/test_error.py b/ee/clickhouse/test/test_error.py
index 40cda3fbd667..b334c00188f2 100644
--- a/ee/clickhouse/test/test_error.py
+++ b/ee/clickhouse/test/test_error.py
@@ -39,7 +39,7 @@ from posthog.errors import clickhouse_error_type, wrap_clickhouse_query_error
code=241,
),
"ClickHouseQueryMemoryLimitExceeded",
- "Query has reached the max memory limit before completing. See our docs for how to improve your query memory footprint. You may need to narrow date range or materialize.",
+ "This query ran out of memory before it could finish, usually because it's scanning too much data. Try a shorter date range or narrower filters, or see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries",
None,
"CHQueryErrorMemoryLimitExceeded",
),
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7430c2274265..8b7655a4eb1b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5942,6 +5942,10 @@ snapshots:
hash: v1.k794b7964.4292e7593e17b889ac3a9011418979edcd88c9543d592162c8fab2b1809fc620.lLy6rdV3V-0PqRYWFCO75_6NSPC52a3xUdM_zUx4C6g
scenes-app-insights-error-empty-states--long-loading--light:
hash: v1.k794b7964.37ac1f8ed685e7329f75ccc361aeebbbb444ec01aa76b524d6f385f6c9f07eca.ZVg1oU7Td2E71vfg8AmOVfM7esqQYD_y6fZQ4rAeZfY
+ scenes-app-insights-error-empty-states--memory-limit-exceeded--dark:
+ hash: v1.k794b7964.ef18ee16bcec4b43d74979a5131a3f325f8e0542b6b4cba050746f6b02699ab9.kOLq5BxzD8AlGlxKgleq3uJTw_ddM6GTSmML4MNaZ5o
+ scenes-app-insights-error-empty-states--memory-limit-exceeded--light:
+ hash: v1.k794b7964.5db627722825a5e96b5c9a60b66b003822ef339c07c8cb0475bbe726df99a14b.wl_oFPQ_LwRebMnu1nHg-LQxBV-L9Q5nRkkKxr3gH9g
scenes-app-insights-error-empty-states--query-server-error--dark:
hash: v1.k794b7964.db45c81ffa03fff1a49b29fb04f9883c6b03b7d7d7418b7cd9d7499f9459a5d9.K6zGAMzWQhYlzQvilSGffIr2NsKmiVM3aYJEikdEEUM
scenes-app-insights-error-empty-states--query-server-error--light:
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index cb8be304eb83..66d58f58b4fc 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -26,7 +26,7 @@ import { insightLogic } from 'scenes/insights/insightLogic'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-import { extractValidationError } from '~/queries/nodes/InsightViz/utils'
+import { extractValidationError, extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'
import { Query } from '~/queries/Query/Query'
import { DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
import { queryVizRendersToCanvas } from '~/queries/utils'
@@ -316,7 +316,12 @@ function InsightCardInternal(
if (apiErrored) {
const validationError = extractValidationError(apiError)
if (validationError) {
- return <InsightValidationError detail={validationError} />
+ return (
+ <InsightValidationError
+ detail={validationError}
+ validationErrorCode={extractValidationErrorCode(apiError)}
+ />
+ )
} else if (apiError instanceof ApiError) {
return <InsightErrorState title={apiError?.detail} />
}
diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx
index b64caa1951db..ceea3b8ed5a6 100644
--- a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.test.tsx
@@ -1,6 +1,6 @@
import React from 'react'
-import { extractTextFromChildren, isTrustedImageSrc, slugifyHeading } from './LemonMarkdown'
+import { extractTextFromChildren, slugifyHeading } from './LemonMarkdown'
describe('LemonMarkdown utilities', () => {
describe('slugifyHeading', () => {
@@ -135,31 +135,4 @@ describe('LemonMarkdown utilities', () => {
expect(extractTextFromChildren(top)).toBe('deep')
})
})
-
- describe('isTrustedImageSrc', () => {
- // jsdom serves tests from http://localhost, so same-origin checks resolve against localhost.
- it.each([
- ['/static/screenshot.png'],
- ['http://localhost/img.png'],
- ['https://posthog.com/img.png'],
- ['https://us.posthog.com/img.png'],
- ['https://app.posthog.com/a/b/c.png'],
- ])('trusts %s', (src) => {
- expect(isTrustedImageSrc(src)).toBe(true)
- })
-
- it.each([
- ['https://evil.com/img.png'],
- ['https://notposthog.com/img.png'],
- ['https://evil.posthog.com.attacker.com/img.png'],
- ['https://posthog.com.attacker.com/img.png'],
- ['data:image/png;base64,iVBORw0KGgo='],
- ['blob:https://posthog.com/abc'],
- ['javascript:alert(1)'],
- [''],
- [undefined],
- ])('distrusts %s', (src) => {
- expect(isTrustedImageSrc(src)).toBe(false)
- })
- })
})
diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx
index 7fbe29517639..fa35ab89be6b 100644
--- a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx
+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx
@@ -9,6 +9,7 @@ import remarkGfm from 'remark-gfm'
import { CodeSnippet, getLanguage, Language } from 'lib/components/CodeSnippet'
import { RichContentMention } from 'lib/components/RichContentEditor/RichContentNodeMention'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
+import { isTrustedPostHogUrl } from 'lib/utils/trustedUrl'
import { Link } from '../Link'
import remarkMentions from './mention'
@@ -60,27 +61,6 @@ export function slugifyHeading(text: string): string {
.replace(/^-|-$/g, '')
}
-/**
- * Whether an image source is trusted enough to render inline within untrusted content.
- * Trusted = served from PostHog itself: same-origin (incl. relative URLs) or any `posthog.com` host.
- * Anything else (including `data:`/`blob:` URIs) is untrusted and should be rendered as a link.
- */
-export function isTrustedImageSrc(src: string | undefined): boolean {
- if (!src) {
- return false
- }
- let url: URL
- try {
- url = new URL(src, window.location.origin)
- } catch {
- return false
- }
- if (url.protocol !== 'https:' && url.protocol !== 'http:') {
- return false
- }
- return url.hostname === window.location.hostname || /(^|\.)posthog\.com$/i.test(url.hostname)
-}
-
export function extractTextFromChildren(children: React.ReactNode): string {
if (typeof children === 'string') {
return children
@@ -148,7 +128,7 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({
...(disableImages
? {
img: ({ src, alt }: any): JSX.Element =>
- isTrustedImageSrc(src) ? (
+ isTrustedPostHogUrl(src) ? (
<img src={src} alt={alt} loading="lazy" />
) : (
<Link to={src} target="_blank" targetBlankIcon disableDocsPanel>
diff --git a/frontend/src/lib/utils/trustedUrl.test.ts b/frontend/src/lib/utils/trustedUrl.test.ts
new file mode 100644
index 000000000000..bc8a2ca13d63
--- /dev/null
+++ b/frontend/src/lib/utils/trustedUrl.test.ts
@@ -0,0 +1,28 @@
+import { isTrustedPostHogUrl } from './trustedUrl'
+
+describe('isTrustedPostHogUrl', () => {
+ // jsdom serves tests from http://localhost, so same-origin checks resolve against localhost.
+ it.each([
+ ['/static/screenshot.png'],
+ ['http://localhost/img.png'],
+ ['https://posthog.com/img.png'],
+ ['https://us.posthog.com/img.png'],
+ ['https://app.posthog.com/a/b/c.png'],
+ ])('trusts %s', (url) => {
+ expect(isTrustedPostHogUrl(url)).toBe(true)
+ })
+
+ it.each([
+ ['https://evil.com/img.png'],
+ ['https://notposthog.com/img.png'],
+ ['https://evil.posthog.com.attacker.com/img.png'],
+ ['https://posthog.com.attacker.com/img.png'],
+ ['data:image/png;base64,iVBORw0KGgo='],
+ ['blob:https://posthog.com/abc'],
+ ['javascript:alert(1)'],
+ [''],
+ [undefined],
+ ])('distrusts %s', (url) => {
+ expect(isTrustedPostHogUrl(url)).toBe(false)
+ })
+})
diff --git a/frontend/src/lib/utils/trustedUrl.ts b/frontend/src/lib/utils/trustedUrl.ts
new file mode 100644
index 000000000000..1a4ef4cdebd3
--- /dev/null
+++ b/frontend/src/lib/utils/trustedUrl.ts
@@ -0,0 +1,20 @@
+/**
+ * Whether a URL is trusted enough to load or link to from within untrusted content.
+ * Trusted = served from PostHog itself: same-origin (incl. relative URLs) or any `posthog.com` host.
+ * Anything else (including `data:`/`blob:` URIs) is untrusted.
+ */
+export function isTrustedPostHogUrl(url: string | undefined): boolean {
+ if (!url) {
+ return false
+ }
+ let parsed: URL
+ try {
+ parsed = new URL(url, window.location.origin)
+ } catch {
+ return false
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ return false
+ }
+ return parsed.hostname === window.location.hostname || /(^|\.)posthog\.com$/i.test(parsed.hostname)
+}
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 75a44156ba7c..87b1388952fd 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -250,6 +250,7 @@ export function InsightVizDisplay({
<InsightValidationError
query={query}
detail={validationError}
+ validationErrorCode={validationErrorCode}
onRetry={
cta
? undefined
diff --git a/frontend/src/queries/nodes/InsightViz/utils.test.ts b/frontend/src/queries/nodes/InsightViz/utils.test.ts
new file mode 100644
index 000000000000..d73f974206c2
--- /dev/null
+++ b/frontend/src/queries/nodes/InsightViz/utils.test.ts
@@ -0,0 +1,17 @@
+import { extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'
+
+describe('extractValidationErrorCode', () => {
+ test.each([
+ ['code set directly on the error (async polling shape)', { status: 400, code: 'some_code' }, 'some_code'],
+ ['code in the response body (sync DRF shape)', { status: 512, data: { code: 'some_code' } }, 'some_code'],
+ [
+ 'memory-limit error (status 513)',
+ { status: 513, code: 'clickhouse_memory_limit_exceeded' },
+ 'clickhouse_memory_limit_exceeded',
+ ],
+ ['non-validation status', { status: 500, code: 'some_code' }, null],
+ ['no error', null, null],
+ ])('%s', (_name, error, expected) => {
+ expect(extractValidationErrorCode(error)).toBe(expected)
+ })
+})
diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.ts
index d8c0c2c3e525..808c266435d3 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.ts
@@ -182,28 +182,34 @@ export const getQueryBasedDashboard = (
}
}
+// Statuses whose responses carry an actionable validation message: 400 (bad query), 512 (query
+// estimated too expensive to run), 513 (out of memory)
+const VALIDATION_ERROR_STATUSES = new Set([400, 512, 513])
+
+const hasValidationErrorStatus = (error: Error | Record<string, any> | null | undefined): boolean =>
+ VALIDATION_ERROR_STATUSES.has((error as Record<string, any> | null | undefined)?.status)
+
export const extractValidationError = (error: Error | Record<string, any> | null | undefined): string | null => {
- if (error instanceof ApiError || (error && typeof error === 'object' && 'status' in error)) {
- // We use 512 for query timeouts
+ if (hasValidationErrorStatus(error)) {
// Async queries put the error message on data.error_message, while synchronous ones use detail
- return error?.status === 400 || error?.status === 512
- ? (error.detail || error.data?.error_message)?.replace('Try ', 'Try\u00A0') // Add unbreakable space for better line breaking
- : null
+ const anyError = error as Record<string, any>
+ // Add unbreakable space for better line breaking
+ return (anyError.detail || anyError.data?.error_message)?.replace('Try ', 'Try\u00A0') ?? null
}
return null
}
export const extractValidationErrorCode = (error: Error | Record<string, any> | null | undefined): string | null => {
- if (error instanceof ApiError || (error && typeof error === 'object' && 'status' in error)) {
- if (error?.status === 400 || error?.status === 512) {
- return error.code ?? error.data?.code ?? null
- }
+ if (hasValidationErrorStatus(error)) {
+ const anyError = error as Record<string, any>
+ return anyError.code ?? anyError.data?.code ?? null
}
return null
}
+// 512 only (query estimated too expensive) — OOM is 513, so this can't misfire on a memory error.
export const isTimeoutError = (error: Error | Record<string, any> | null | undefined): boolean => {
if (error instanceof ApiError || (error && typeof error === 'object' && 'status' in error)) {
return error?.status === 512
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.ts
index f99abf20de75..fde96eaac70b 100644
--- a/frontend/src/queries/query.test.ts
+++ b/frontend/src/queries/query.test.ts
@@ -199,6 +199,22 @@ describe('query', () => {
})
describe('pollForResults error message parsing', () => {
+ it('prefers the structured error_code from the query status over one parsed from the message', async () => {
+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce({
+ data: {
+ query_status: {
+ error_message: 'This query ran out of memory before it could finish',
+ error_code: 'clickhouse_memory_limit_exceeded',
+ },
+ },
+ })
+
+ await expect(pollForResults('test-query-id')).rejects.toMatchObject({
+ detail: 'This query ran out of memory before it could finish',
+ code: 'clickhouse_memory_limit_exceeded',
+ })
+ })
+
it('parses ErrorDetail list format and extracts message and code', async () => {
jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce({
data: {
diff --git a/frontend/src/queries/query.ts b/frontend/src/queries/query.ts
index 146d46881f13..cd2d9a60a10c 100644
--- a/frontend/src/queries/query.ts
+++ b/frontend/src/queries/query.ts
@@ -135,9 +135,8 @@ export async function pollForResults(
const parsed = parseErrorMessage(e.data?.query_status?.error_message)
e.detail = parsed.message
- if (parsed.code) {
- e.code = parsed.code
- }
+ // Prefer the structured code from QueryStatus over one parsed out of the message
+ e.code = e.data?.query_status?.error_code ?? parsed.code ?? e.code
// Attach queryId to error for downstream error handling
e.queryId = queryId
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index c23c9a9a7488..379c44f9e6cf 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -41231,6 +41231,11 @@
"description": "If the query failed, this will be set to true. More information can be found in the error_message field.",
"type": "boolean"
},
+ "error_code": {
+ "default": null,
+ "description": "Stable machine-readable code for the error (the DRF exception code), when known.",
+ "type": ["string", "null"]
+ },
"error_message": {
"default": null,
"type": ["string", "null"]
@@ -41278,7 +41283,7 @@
"$ref": "#/definitions/integer"
}
},
- "required": ["id", "query_async", "team_id", "error", "complete", "error_message"],
+ "required": ["id", "query_async", "team_id", "error", "complete", "error_message", "error_code"],
"type": "object"
},
"QueryStatusResponse": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 19d3591a7a73..f24a5e4d075a 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2338,6 +2338,11 @@ export type QueryStatus = {
complete: boolean
/** @default null */
error_message: string | null
+ /**
+ * Stable machine-readable code for the error (the DRF exception code), when known.
+ * @default null
+ */
+ error_code: string | null
results?: any
/**
* When was the query execution task picked up by a worker.
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 51d62d3fd4ce..b93cb0026fea 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -119,6 +119,7 @@ describe('dashboardLogic', () => {
id: '123',
team_id: 2,
error_message: null,
+ error_code: null,
error: false,
},
},
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx
index 0c459b587471..e6225c53426a 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx
@@ -155,6 +155,40 @@ export const ValidationError: Story = {
},
}
+export const MemoryLimitExceeded: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/insights/': () => [
+ 200,
+ { count: 1, results: [{ ...insight, result: null }] },
+ ],
+ },
+ post: {
+ '/api/environments/:team_id/query/:kind/': async () => {
+ await delay(100)
+ return HttpResponse.json(
+ {
+ type: 'server_error',
+ code: 'clickhouse_memory_limit_exceeded',
+ detail: "This query ran out of memory before it could finish, usually because it's scanning too much data. Try a shorter date range or narrower filters, or see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries",
+ },
+ { status: 513 }
+ )
+ },
+ },
+ })
+
+ return <App />
+ },
+ parameters: {
+ testOptions: {
+ waitForLoadersToDisappear: false,
+ waitForSelector: '[data-attr=insight-memory-limit-debug-with-ai]',
+ },
+ },
+}
+
export const EstimatedQueryExecutionTimeTooLong: Story = {
render: () => {
useStorybookMocks({
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 9bae7da895ec..5952f9a5ee33 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -22,14 +22,18 @@ import { Link } from 'lib/lemon-ui/Link'
import { LoadingBar } from 'lib/lemon-ui/LoadingBar'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
+import { isTrustedPostHogUrl } from 'lib/utils/trustedUrl'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
+import { autoRunMaxPrompt } from 'scenes/max/maxPrompt'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'
import { seriesToActionsAndEvents } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
import { FunnelsQuery, Node, NodeKind, QueryStatus } from '~/queries/schema/schema-general'
@@ -40,6 +44,7 @@ import {
FilterType,
InsightLogicProps,
SavedInsightsTabs,
+ SidePanelTab,
} from '~/types'
import { MathAvailability } from '../filters/ActionFilter/ActionFilterRow/ActionFilterRow'
@@ -50,6 +55,17 @@ import { sampleDataStateLogic } from './sampleDataStateLogic'
const HedgehogConstruction2 = pngHoggie(construction2Png)
+// Matches ClickHouseQueryMemoryLimitExceeded.default_code on the backend. Keep the two in sync.
+const CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE = 'clickhouse_memory_limit_exceeded'
+
+const MEMORY_LIMIT_AI_PROMPT = autoRunMaxPrompt(
+ "This insight ran out of memory before it could finish. Help me work out why it's scanning so much data and how to fix it: a shorter date range, narrower filters, or materializing the data."
+)
+
+// Stop the capture before trailing sentence punctuation so a URL ending a sentence (".", ")") keeps
+// a clean href. No `g` flag needed: split() finds all matches and interleaves the captured URLs.
+const DETAIL_URL_REGEX = /(https?:\/\/[^\s]*[^\s.,;:!?)\]}'"])/
+
export function InsightEmptyState({
heading,
detail,
@@ -516,17 +532,40 @@ export function InsightTimeoutState({ queryId }: { queryId?: string | null }): J
)
}
+// Render embedded URLs (e.g. backend docs links) as clickable links. Only PostHog-host URLs are
+// linkified — error detail can echo user-controlled text.
+export function renderDetailWithLinks(detail: string): (string | JSX.Element)[] {
+ // Splitting on a capturing group interleaves text and URL matches, so odd indexes are the URLs
+ return detail.split(DETAIL_URL_REGEX).map((part, index) =>
+ index % 2 === 1 && isTrustedPostHogUrl(part) ? (
+ <Link key={index} to={part} target="_blank">
+ {part}
+ </Link>
+ ) : (
+ part
+ )
+ )
+}
+
export function InsightValidationError({
detail,
+ validationErrorCode,
query,
onRetry,
cta,
}: {
detail: string
+ validationErrorCode?: string | null
query?: Record<string, any> | null
onRetry?: () => void
cta?: JSX.Element
}): JSX.Element {
+ const { openSidePanel } = useActions(sidePanelStateLogic)
+ const debugWithAI = (): void => openSidePanel(SidePanelTab.Max, MEMORY_LIMIT_AI_PROMPT)
+ const isMemoryLimitError = validationErrorCode === CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE
+ const defaultCta =
+ cta ?? (onRetry ? <RetryButton onRetry={onRetry} query={query} /> : <QueryDebuggerButton query={query} />)
+
return (
<div
data-attr="insight-empty-state"
@@ -546,9 +585,28 @@ export function InsightValidationError({
{/* but rather that it's something with the definition of the query itself */}
</h2>
- <p className="text-sm text-muted max-w-120 mb-2">{detail}</p>
-
- {cta ?? (onRetry ? <RetryButton onRetry={onRetry} query={query} /> : <QueryDebuggerButton query={query} />)}
+ <p className="text-sm text-muted max-w-120 mb-2">{renderDetailWithLinks(detail)}</p>
+
+ {/* For memory-limit errors, lead with the AI debugger but keep the retry/debugger action
+ beside it so users who decline AI consent (or lack AI access) still have a next step.
+ onClick fires when consent was already given (popover hidden); onApprove fires after
+ the consent flow completes — same pattern as InsightAIAnalysis. */}
+ {isMemoryLimitError && !cta ? (
+ <div className="flex items-center gap-2">
+ <AIConsentPopoverWrapper onApprove={debugWithAI}>
+ <LemonButton
+ type="primary"
+ onClick={debugWithAI}
+ data-attr="insight-memory-limit-debug-with-ai"
+ >
+ Debug with PostHog AI
+ </LemonButton>
+ </AIConsentPopoverWrapper>
+ {defaultCta}
+ </div>
+ ) : (
+ defaultCta
+ )}
{detail.includes('Exclusion') && (
<div className="mt-4">
diff --git a/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx
index f7098d69a63f..0702d3cc047e 100644
--- a/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/InsightEmptyState.test.tsx
@@ -3,6 +3,7 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import '@testing-library/jest-dom'
import { cleanup, render } from '@testing-library/react'
+import { isValidElement } from 'react'
import { teamLogic } from 'scenes/teamLogic'
@@ -10,69 +11,100 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { TeamType } from '~/types'
-import { InsightEmptyState } from './EmptyStates'
+import { InsightEmptyState, renderDetailWithLinks } from './EmptyStates'
-describe('<InsightEmptyState />', () => {
- beforeEach(() => {
- initKeaTests()
- useMocks({
- get: {
- '/api/projects/:projectId/tasks/': { count: 0, results: [] },
- },
+describe('EmptyStates', () => {
+ describe('<InsightEmptyState />', () => {
+ beforeEach(() => {
+ initKeaTests()
+ useMocks({
+ get: {
+ '/api/projects/:projectId/tasks/': { count: 0, results: [] },
+ },
+ })
})
- })
- const mountWithTeam = (overrides: Partial<TeamType>): void => {
- teamLogic.mount()
- teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, ...overrides })
- }
+ const mountWithTeam = (overrides: Partial<TeamType>): void => {
+ teamLogic.mount()
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, ...overrides })
+ }
+
+ afterEach(() => {
+ cleanup()
+ })
- afterEach(() => {
- cleanup()
+ it.each([
+ {
+ name: 'sample data before any events were ingested',
+ team: { ingested_event: false, is_demo: false },
+ props: {},
+ expectSampleData: true,
+ },
+ {
+ name: 'the regular empty state once events were ingested',
+ team: { ingested_event: true, is_demo: false },
+ props: {},
+ expectSampleData: false,
+ },
+ {
+ name: 'the regular empty state in demo projects',
+ team: { ingested_event: false, is_demo: true },
+ props: {},
+ expectSampleData: false,
+ },
+ {
+ name: 'custom copy over sample data when no variant was passed',
+ team: { ingested_event: false, is_demo: false },
+ props: { heading: 'No revenue data' },
+ expectSampleData: false,
+ },
+ {
+ name: 'sample data over custom copy when a variant explicitly opted in',
+ team: { ingested_event: false, is_demo: false },
+ props: { heading: 'No rows', sampleDataVariant: 'table' as const },
+ expectSampleData: true,
+ },
+ {
+ name: 'the regular empty state when the call site opted out',
+ team: { ingested_event: false, is_demo: false },
+ props: { sampleDataVariant: null },
+ expectSampleData: false,
+ },
+ ])('renders $name', ({ team, props, expectSampleData }) => {
+ mountWithTeam(team)
+ const { container } = render(<InsightEmptyState {...props} />)
+
+ expect(!!container.querySelector('[data-attr="insight-sample-data-state"]')).toBe(expectSampleData)
+ expect(!!container.querySelector('[data-attr="insight-empty-state"]')).toBe(!expectSampleData)
+ })
})
- it.each([
- {
- name: 'sample data before any events were ingested',
- team: { ingested_event: false, is_demo: false },
- props: {},
- expectSampleData: true,
- },
- {
- name: 'the regular empty state once events were ingested',
- team: { ingested_event: true, is_demo: false },
- props: {},
- expectSampleData: false,
- },
- {
- name: 'the regular empty state in demo projects',
- team: { ingested_event: false, is_demo: true },
- props: {},
- expectSampleData: false,
- },
- {
- name: 'custom copy over sample data when no variant was passed',
- team: { ingested_event: false, is_demo: false },
- props: { heading: 'No revenue data' },
- expectSampleData: false,
- },
- {
- name: 'sample data over custom copy when a variant explicitly opted in',
- team: { ingested_event: false, is_demo: false },
- props: { heading: 'No rows', sampleDataVariant: 'table' as const },
- expectSampleData: true,
- },
- {
- name: 'the regular empty state when the call site opted out',
- team: { ingested_event: false, is_demo: false },
- props: { sampleDataVariant: null },
- expectSampleData: false,
- },
- ])('renders $name', ({ team, props, expectSampleData }) => {
- mountWithTeam(team)
- const { container } = render(<InsightEmptyState {...props} />)
+ describe('renderDetailWithLinks', () => {
+ const linkedUrls = (detail: string): string[] =>
+ renderDetailWithLinks(detail)
+ .filter((part): part is JSX.Element => isValidElement(part))
+ .map((el) => (el.props as { to: string }).to)
- expect(!!container.querySelector('[data-attr="insight-sample-data-state"]')).toBe(expectSampleData)
- expect(!!container.querySelector('[data-attr="insight-empty-state"]')).toBe(!expectSampleData)
+ it.each([
+ ['links a PostHog docs URL', 'see https://posthog.com/docs/x for help', ['https://posthog.com/docs/x']],
+ ['links a PostHog subdomain URL', 'visit https://eu.posthog.com/foo now', ['https://eu.posthog.com/foo']],
+ [
+ 'strips trailing punctuation from the href',
+ 'read https://posthog.com/docs/x.',
+ ['https://posthog.com/docs/x'],
+ ],
+ [
+ 'links the production memory-limit docs URL including its fragment',
+ 'see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries',
+ [
+ 'https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries',
+ ],
+ ],
+ ['leaves an external URL as plain text', 'go to https://evil.example.com/phish', []],
+ ['leaves a lookalike host as plain text', 'open https://posthog.com.evil.com/x here', []],
+ ['renders plain detail with no links', 'This query ran out of memory.', []],
+ ])('%s', (_name, detail, expected) => {
+ expect(linkedUrls(detail)).toEqual(expected)
+ })
})
})
diff --git a/frontend/src/scenes/max/maxPrompt.ts b/frontend/src/scenes/max/maxPrompt.ts
new file mode 100644
index 000000000000..95c26a637ea7
--- /dev/null
+++ b/frontend/src/scenes/max/maxPrompt.ts
@@ -0,0 +1,11 @@
+// Dependency-free on purpose, like max-storage-keys.ts: call sites live in scene code
+// (e.g. insight error states), where importing maxLogic itself would risk import cycles.
+
+/**
+ * Build the options string for `openSidePanel(SidePanelTab.Max, ...)` that makes the panel
+ * auto-submit the prompt on open — the counterpart of the `!` prefix handled by
+ * `parseCommandString` in maxLogic.
+ */
+export function autoRunMaxPrompt(prompt: string): string {
+ return `!${prompt}`
+}
diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx
index 32f550ad0223..9fd83ece5f30 100644
--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx
+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx
@@ -42,6 +42,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { isSharedView } from '~/exporter/exporterViewLogic'
import { Noun } from '~/models/groupsModel'
import { MAX_SELECT_RETURNED_ROWS } from '~/queries/nodes/DataTable/DataTableExport'
+import { extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'
import { FunnelsActorsQuery, NodeKind } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
@@ -306,7 +307,11 @@ export function PersonsModal({
<div className="relative min-h-20 p-2 deprecated-space-y-2 rounded bg-border-light overflow-y-auto mb-2">
{errorObject ? (
validationError ? (
- <InsightValidationError query={query} detail={validationError} />
+ <InsightValidationError
+ query={query}
+ detail={validationError}
+ validationErrorCode={extractValidationErrorCode(errorObject)}
+ />
) : (
<InsightErrorState query={query} />
)
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index f43f8b0ff500..3d99e466457e 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -967,6 +967,7 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
"end_time": None,
"error": False,
"error_message": None,
+ "error_code": None,
"expiration_time": mock.ANY,
"id": mock.ANY,
"query_async": True,
diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.py
index 352e7f8afbfb..96f07b6f0921 100644
--- a/posthog/clickhouse/client/execute_async.py
+++ b/posthog/clickhouse/client/execute_async.py
@@ -143,7 +143,10 @@ class QueryStatusManager:
if not byte_results:
raise QueryNotFoundError(f"Query {self.query_id} not found for team {self.team_id}")
- query_status = QueryStatus(**json.loads(byte_results))
+ loaded = json.loads(byte_results)
+ # Drop unknown keys so a status written by a newer deploy (with extra fields) doesn't fail
+ # validation here — QueryStatus forbids extra fields.
+ query_status = QueryStatus(**{k: v for k, v in loaded.items() if k in QueryStatus.model_fields})
if show_progress and not query_status.complete:
query_status.query_progress = self.get_clickhouse_progresses()
@@ -249,6 +252,12 @@ def execute_process_query(
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 staff
query_status.error_message = str(err)
+ if isinstance(err, APIException):
+ # get_codes() returns a list/dict for compound validation errors; only scalar codes
+ # are meaningful to the frontend, which matches on specific code strings.
+ codes = err.get_codes()
+ if isinstance(codes, str):
+ query_status.error_code = codes
logger.exception("Error processing query async", team_id=team_id, query_id=query_id, exc_info=True)
if not is_user_safe_error:
# User-safe errors (e.g. a malformed HogQL query) are already returned to the user as a 400,
diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.py
index 82d3914179a0..e90708350952 100644
--- a/posthog/clickhouse/client/test/test_execute_async.py
+++ b/posthog/clickhouse/client/test/test_execute_async.py
@@ -23,6 +23,7 @@ from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, execute_process_query
from posthog.clickhouse.query_tagging import tag_queries
from posthog.errors import CHQueryErrorTooManySimultaneousQueries, ExposedCHQueryError
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
from posthog.models import Organization, Team
from posthog.models.user import User
from posthog.redis import get_client
@@ -224,6 +225,21 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):
assert result.error_message
self.assertRegex(result.error_message, "trailing tokens after expression")
+ def test_async_query_user_safe_error_carries_error_code(self):
+ query = build_query("SELECT * FROM events")
+ query_id = uuid.uuid4().hex
+
+ with patch("posthog.api.services.query.process_query_dict", side_effect=ClickHouseQueryMemoryLimitExceeded()):
+ client.enqueue_process_query_task(
+ self.team, self.user.id, query, query_id=query_id, _test_only_bypass_celery=True
+ )
+
+ result = client.get_query_status(self.team.id, query_id)
+ self.assertTrue(result.error)
+ self.assertTrue(result.complete)
+ assert result.error_message
+ self.assertEqual(result.error_code, ClickHouseQueryMemoryLimitExceeded.default_code)
+
def test_async_query_server_errors(self):
query = build_query("SELECT * FROM events")
diff --git a/posthog/errors.py b/posthog/errors.py
index d0540099b602..1d99a6f86437 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -500,8 +500,9 @@ CLICKHOUSE_ERROR_CODE_LOOKUP: dict[int, ErrorCodeMeta] = {
239: ErrorCodeMeta("CANNOT_MUNMAP"),
240: ErrorCodeMeta("CANNOT_MREMAP"),
241: ErrorCodeMeta(
+ # Code 241 short-circuits to ClickHouseQueryMemoryLimitExceeded in wrap_clickhouse_query_error,
+ # so the user-facing copy lives on that exception's default_detail, not on user_safe here.
"MEMORY_LIMIT_EXCEEDED",
- user_safe="Query exceeds memory limits. Try reducing its scope by changing the time range.",
category=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,
),
242: ErrorCodeMeta("TABLE_IS_READ_ONLY"),
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 51f5fb2b5cea..22ca7200208d 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -82,8 +82,15 @@ class ClickHouseQueryTimeOut(APIException):
class ClickHouseQueryMemoryLimitExceeded(APIException):
- status_code = 504
- default_detail = "Query has reached the max memory limit before completing. See our docs for how to improve your query memory footprint. You may need to narrow date range or materialize."
+ # Custom code in the actionable-validation family (400/512/513) the frontend routes to the
+ # "problem with this query" panel. Distinct from 512 (query-too-slow) so an out-of-memory
+ # failure is never mistaken for a timeout on either the client or in status-based alerting.
+ status_code = 513
+ # Stable machine-readable code so the frontend can recognise out-of-memory failures without
+ # matching on the (translatable, changeable) detail copy. Keep in sync with the frontend
+ # CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE constant.
+ default_code = "clickhouse_memory_limit_exceeded"
+ default_detail = "This query ran out of memory before it could finish, usually because it's scanning too much data. Try a shorter date range or narrower filters, or see our docs for more ways to speed it up: https://posthog.com/docs/product-analytics/troubleshooting#how-do-i-speed-up-my-insights-and-queries"
class ExceptionContext(TypedDict):
diff --git a/posthog/schema.py b/posthog/schema.py
index 1e46647a1677..0f2198dfc944 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5731,6 +5731,10 @@ class QueryStatus(BaseModel):
"If the query failed, this will be set to true. More information can be found in the error_message field."
),
)
+ error_code: str | None = Field(
+ default=None,
+ description=("Stable machine-readable code for the error (the DRF exception code), when known."),
+ )
error_message: str | None = None
expiration_time: AwareDatetime | None = None
id: str
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index 12b0d9b0a749..f644ab72dfce 100644
--- a/posthog/session_recordings/test/test_session_recordings.py
+++ b/posthog/session_recordings/test/test_session_recordings.py
@@ -1364,8 +1364,8 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
(
"clickhouse_memory_limit",
ClickHouseQueryMemoryLimitExceeded(),
- 504,
- "max memory limit",
+ 513,
+ "ran out of memory",
),
]
)
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 2c964eb7a26a..305d158f2078 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1485,6 +1485,8 @@ export interface QueryStatusApi {
end_time?: string | null
/** If the query failed, this will be set to true. More information can be found in the error_message field. */
error?: boolean | null
+ /** Stable machine-readable code for the error (the DRF exception code), when known. */
+ error_code?: string | null
error_message?: string | null
expiration_time?: string | null
id: string
diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.ts
index d726ac3f4daa..c0f80a971b43 100644
--- a/products/endpoints/frontend/generated/api.schemas.ts
+++ b/products/endpoints/frontend/generated/api.schemas.ts
@@ -944,6 +944,8 @@ export interface QueryStatusApi {
end_time?: string | null
/** If the query failed, this will be set to true. More information can be found in the error_message field. */
error?: boolean | null
+ /** Stable machine-readable code for the error (the DRF exception code), when known. */
+ error_code?: string | null
error_message?: string | null
expiration_time?: string | null
id: string
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 143fb5c5a995..1c83607a370e 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -838,6 +838,8 @@ export interface QueryStatusApi {
end_time?: string | null
/** If the query failed, this will be set to true. More information can be found in the error_message field. */
error?: boolean | null
+ /** Stable machine-readable code for the error (the DRF exception code), when known. */
+ error_code?: string | null
error_message?: string | null
expiration_time?: string | null
id: string
diff --git a/products/revenue_analytics/frontend/nodes/shared.tsx b/products/revenue_analytics/frontend/nodes/shared.tsx
index 2cb6ceef0dea..fdd9980e08f4 100644
--- a/products/revenue_analytics/frontend/nodes/shared.tsx
+++ b/products/revenue_analytics/frontend/nodes/shared.tsx
@@ -14,7 +14,7 @@ import {
import { InsightsWrapper } from 'scenes/insights/InsightsWrapper'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
-import { extractValidationError, isTimeoutError } from '~/queries/nodes/InsightViz/utils'
+import { extractValidationError, extractValidationErrorCode, isTimeoutError } from '~/queries/nodes/InsightViz/utils'
import { AnyResponseType, GoalLine, RevenueAnalyticsGoal, TrendsFilter } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
import { GraphDataset } from '~/types'
@@ -86,7 +86,13 @@ export const TileWrapper = ({ title, tooltip, extra, children, context }: TileWr
}
if (validationError) {
- return <InsightValidationError query={query} detail={validationError} />
+ return (
+ <InsightValidationError
+ query={query}
+ detail={validationError}
+ validationErrorCode={extractValidationErrorCode(responseErrorObject)}
+ />
+ )
}
if (
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 556c11af750b..f646451262b2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -594,6 +594,8 @@ export namespace Schemas {
end_time?: string | null;
/** If the query failed, this will be set to true. More information can be found in the error_message field. */
error?: boolean | null;
+ /** Stable machine-readable code for the error (the DRF exception code), when known. */
+ error_code?: string | null;
error_message?: string | null;
expiration_time?: string | null;
id: string;