: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
fix(dashboards): show the real query error on rejected tile refreshes (#115814)
posthog[bot]d684f941ed28
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 236fc8d3a8ca..7d69697b929e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -497,9 +497,9 @@ snapshots:components-cards-insight-card--capacity-cooldown--narrow--light:hash: v1.k794b7964.c79d5e095dca03b4d0c640a4fdd6bbfce9a4c611d4dfcf54118b012688073920.kbucWQpmGl5l1HtxNnrrkN544BGhjh0Jn4DhhufGG8Ucomponents-cards-insight-card--error-states--dark:- hash: v1.k794b7964.dca2213d0a2f6dc232e1b2ac1505aa4a5b97b1dc9b9f2ac09dab969ed1eb12dd.O8WWpdu2VcmOz94y1p3UhIYwWZxSBZKZYOTJZNnO9qI+ hash: v1.k794b7964.934c3f48f60fdf3226805efb3f27cb2a4cb6dff59b15826aab76bf6724df1692.1kxPseMx8Fmqbof1l53C1hngF1WPEBA5AxR0IvW-il4components-cards-insight-card--error-states--light:- hash: v1.k794b7964.d90e498e5a47b95cba7e1b5445154e90a70967b63769ec5247cad1b1ce9844d5.Y_T61wU-rlDrcHcd-jH2huLM9fAvExetaNNy8t-M8gM+ hash: v1.k794b7964.f0daa20aaa8ae6ed1984b2ad818d5da3b61ac6571d14fdc9c6a6e6061c634c40.yQPOVT5Ju6nWJ32v-Df6pHhRNdz8LPs85WNvtD11Op4components-cards-insight-card--insight-card--dark:hash: v1.k794b7964.fdfc67abaeb31b9a0d3a230ee9510916ffb36d5aad1d2321edaa896bb343ff9b.3W6qDwBKmZQGvb56bckNdiwYQhuA5gIf0DfLmUFN0eUcomponents-cards-insight-card--insight-card--light:diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 08c7fe0103c2..72e471bbf726 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -23,6 +23,8 @@ export function isFeatureFlagGatedError(error: unknown): boolean {/** DRF code for `ClickHouseQueryMemoryLimitExceeded` (posthog/exceptions.py). Keep in sync with the backend. */export const CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE = 'clickhouse_memory_limit_exceeded'+export const TABLE_ACCESS_DENIED_ERROR_CODE = 'table_access_denied'+/*** A 409 from the approvals gate: the change was policy-gated and a change request was created,* or one is already pending. Approval 409 bodies always carry `change_request_id`diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsxindex 6545fa2fb3e1..2af74511ec46 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx@@ -244,6 +244,14 @@ export const ErrorStates: Story = {queryId: 'permission-query-id',}),},+ {+ name: 'Table access denied',+ error: new ApiError("You don't have access to table `events`.", 400, undefined, {+ detail: "You don't have access to table `events`.",+ code: 'table_access_denied',+ queryId: 'table-access-query-id',+ }),+ },{name: 'Temporary server failure',error: new ApiError('The query service is temporarily unavailable.', 503, undefined, {diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 01f40805f1f7..22258ffbd018 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -3228,50 +3228,64 @@ describe('dashboardLogic', () => {})})- it('keeps tile data and marks the tile errored when a refresh terminates in a rejection stub', async () => {- const dashboard = dashboards[5]- const insight1 = dashboard.tiles[0].insight!- const insight2 = dashboard.tiles[1].insight!- const resultsBeforeRefresh = logic.values.insightTiles.map((t) => t.insight!.result)- expect(resultsBeforeRefresh.every((r) => r != null)).toBe(true)-- // What getInsightWithRetry resolves to when the app-level concurrency limiter (or a- // server-side calculation error) rejects every attempt: an insight-shaped payload with- // no result and an errored query_status- const getInsightWithRetrySpy = jest- .spyOn(dashboardUtils, 'getInsightWithRetry')- .mockImplementation(async (_teamId, insight) => ({- ...insight,- result: null,- query_status: {- id: 'rejected-query',- team_id: 2,- query_async: true,- complete: false,- error: true,- error_code: 'rate_limited',- error_message: 'Queries are a little too busy right now.',- },- }))+ it.each([+ ['rate_limited', 'Queries are a little too busy right now.', 429],+ ['table_access_denied', "You don't have access to table `events`.", 400],+ [null, "'NoneType' object has no attribute 'get'", null],+ ])(+ 'keeps tile data and marks the tile errored when a refresh terminates in a %s rejection stub',+ async (errorCode, errorMessage, expectedStatus) => {+ const dashboard = dashboards[5]+ const insight1 = dashboard.tiles[0].insight!+ const insight2 = dashboard.tiles[1].insight!+ const resultsBeforeRefresh = logic.values.insightTiles.map((t) => t.insight!.result)+ expect(resultsBeforeRefresh.every((r) => r != null)).toBe(true)++ // What getInsightWithRetry resolves to when the app-level concurrency limiter (or a+ // server-side calculation error) rejects every attempt: an insight-shaped payload with+ // no result and an errored query_status+ const getInsightWithRetrySpy = jest+ .spyOn(dashboardUtils, 'getInsightWithRetry')+ .mockImplementation(async (_teamId, insight) => ({+ ...insight,+ result: null,+ query_status: {+ id: 'rejected-query',+ team_id: 2,+ query_async: true,+ complete: false,+ error: true,+ error_code: errorCode,+ error_message: errorMessage,+ },+ }))- try {- await expectLogic(logic, () => {- logic.actions.triggerDashboardRefresh()- }).toFinishAllListeners()+ try {+ await expectLogic(logic, () => {+ logic.actions.triggerDashboardRefresh()+ }).toFinishAllListeners()- // The stub must not be committed as a successful refresh: tiles keep their data- expect(logic.values.insightTiles.map((t) => t.insight!.result)).toEqual(resultsBeforeRefresh)- // and surface an error state instead of rendering the null result as an empty insight- expect(logic.values.refreshStatus[insight1.short_id]).toEqual(- expect.objectContaining({ errored: true })- )- expect(logic.values.refreshStatus[insight2.short_id]).toEqual(- expect.objectContaining({ errored: true })- )- } finally {- getInsightWithRetrySpy.mockRestore()+ // The stub must not be committed as a successful refresh: tiles keep their data+ expect(logic.values.insightTiles.map((t) => t.insight!.result)).toEqual(resultsBeforeRefresh)+ // and surface an error state instead of rendering the null result as an empty insight+ for (const shortId of [insight1.short_id, insight2.short_id]) {+ const status = logic.values.refreshStatus[shortId]+ expect(status?.errored).toBe(true)+ expect(status?.error).toEqual(+ expectedStatus === null+ ? undefined+ : expect.objectContaining({+ status: expectedStatus,+ detail: errorMessage,+ code: errorCode,+ })+ )+ }+ } finally {+ getInsightWithRetrySpy.mockRestore()+ }}- })+ )it('pins the "X out of Y" denominator when a tile aborts mid-cycle and keeps siblings tracked', async () => {const dashboard = dashboards[5]diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 3971657da137..14116dd0be5e 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -4441,16 +4441,12 @@ export const dashboardLogic = kea<dashboardLogicType>([true)- if (refreshedInsight && !isRefreshRejectionStub(refreshedInsight)) {- const queryError = getInsightQueryError(refreshedInsight)- if (queryError) {- actions.setRefreshError(insight.short_id, queryError)- } else {- dashboardsModel.actions.updateDashboardInsight(refreshedInsight, undefined, dashboardId)- actions.setRefreshStatus(insight.short_id)- }+ const queryError = refreshedInsight ? getInsightQueryError(refreshedInsight) : null+ if (refreshedInsight && !isRefreshRejectionStub(refreshedInsight) && !queryError) {+ dashboardsModel.actions.updateDashboardInsight(refreshedInsight, undefined, dashboardId)+ actions.setRefreshStatus(insight.short_id)} else {- actions.setRefreshError(insight.short_id)+ actions.setRefreshError(insight.short_id, queryError?.code ? queryError : undefined)}} catch (e: any) {actions.setRefreshError(insight.short_id, e)@@ -4538,29 +4534,24 @@ export const dashboardLogic = kea<dashboardLogicType>([tile.filters_overrides)- if (refreshedInsight && !isRefreshRejectionStub(refreshedInsight)) {- const queryError = getInsightQueryError(refreshedInsight)- if (queryError) {- actions.setRefreshError(insight.short_id, queryError)- tilesErroredCount++- } else {- dashboardsModel.actions.updateDashboardInsight(refreshedInsight, undefined, dashboardId)- actions.setRefreshStatus(insight.short_id)- tilesRefreshedCount++- if (refreshedInsight.is_cached) {- tilesRefreshedCachedCount++- }- reportDashboardTileRefreshed(- dashboardId,- tile,- urlFilters,- urlVariables,- Math.floor(performance.now() - insightRefreshStartTime),- false- )+ const queryError = refreshedInsight ? getInsightQueryError(refreshedInsight) : null+ if (refreshedInsight && !isRefreshRejectionStub(refreshedInsight) && !queryError) {+ dashboardsModel.actions.updateDashboardInsight(refreshedInsight, undefined, dashboardId)+ actions.setRefreshStatus(insight.short_id)+ tilesRefreshedCount+++ if (refreshedInsight.is_cached) {+ tilesRefreshedCachedCount++}+ reportDashboardTileRefreshed(+ dashboardId,+ tile,+ urlFilters,+ urlVariables,+ Math.floor(performance.now() - insightRefreshStartTime),+ false+ )} else {- actions.setRefreshError(insight.short_id)+ actions.setRefreshError(insight.short_id, queryError?.code ? queryError : undefined)tilesErroredCount++}} catch (e: any) {diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.tsindex d052c3bd3915..695f42b07596 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts@@ -598,20 +598,22 @@ describe('shouldSharedDashboardAutoForceForStaleTime', () => {describe('getInsightQueryError', () => {it.each([- ['clickhouse_memory_limit_exceeded', 513],- ['invalid_query', 400],- ])('maps error code %s to status %s', (errorCode, expectedStatus) => {+ ['clickhouse_memory_limit_exceeded', 'Query ran out of memory', 513, 'Query ran out of memory'],+ ['rate_limited', 'concurrency_limit_exceeded', 429, 'Too many queries are running right now.'],+ ['invalid_query', 'Query is invalid', 400, 'Query is invalid'],+ ])('maps error code %s with message %s to status %s', (errorCode, errorMessage, expectedStatus, expectedDetail) => {const error = getInsightQueryError({query_status: {id: 'query-id',error: true,- error_message: 'Query ran out of memory',+ error_message: errorMessage,error_code: errorCode,},} as unknown as InsightModel)expect(error?.status).toBe(expectedStatus)expect(error?.data?.code).toBe(errorCode)+ expect(error?.detail).toBe(expectedDetail)})it('reads the memory code out of the error message when the status field is absent', () => {diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.tsindex 119c009ccffd..b51dbe9bb71f 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts@@ -34,6 +34,12 @@ import {import { SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES } from './dashboardConstants'+// The backend labels every transient capacity failure with this code, whatever its message: PostHog's+// own per-org concurrency limit, and ClickHouse refusing the query because the cluster is busy.+const RATE_LIMITED_ERROR_CODE = 'rate_limited'+const RATE_LIMIT_ERROR_MESSAGE = 'concurrency_limit_exceeded'+const RATE_LIMIT_USER_MESSAGE = 'Too many queries are running right now.'+export function getInsightQueryError(insight: InsightModel): ApiError | null {const queryStatus = insight.query_statusif (!queryStatus?.error) {@@ -45,9 +51,10 @@ export function getInsightQueryError(insight: InsightModel): ApiError | null {// A tile failure arrives without the HTTP status the query originally failed with, so the// status is rebuilt from the code. Out of memory must stay 513: as a 400 the tile tells the// user their query definition is broken, which sends them to fix a query that was never wrong.- const status = code === CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE ? 513 : 400+ // A capacity rejection must stay 429 for the same reason: the query is fine, PostHog is busy.+ const status = code === CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE ? 513 : code === RATE_LIMITED_ERROR_CODE ? 429 : 400return new ApiError(undefined, status, undefined, {- detail: parsedError.message,+ detail: parsedError.message === RATE_LIMIT_ERROR_MESSAGE ? RATE_LIMIT_USER_MESSAGE : parsedError.message,code,queryId: queryStatus.id,})@@ -206,11 +213,6 @@ export const SEARCH_PARAM_FILTERS_KEY = 'query_filters'export const AUTO_PREVIEW_TILE_LIMIT: number = 22-// The backend labels every transient capacity failure with this code, whatever its message: PostHog's-// own per-org concurrency limit, and ClickHouse refusing the query because the cluster is busy.-const RATE_LIMITED_ERROR_CODE = 'rate_limited'-const RATE_LIMIT_ERROR_MESSAGE = 'concurrency_limit_exceeded'-// A refresh that was rejected (concurrency limit, server-side calculation error) still resolves with an// insight-shaped payload: no result, an errored query_status. Committing it to the dashboard would wipe// the tile's existing data and render as an empty insight instead of an error.diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsxindex 23aafc2b58f9..de2edf0c9bcf 100644--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx@@ -14,7 +14,7 @@ import * as trafficControllerPng from '@posthog/brand/hoggies/png/traffic-controimport { IconArchive, IconFunnels, IconInfo, IconPlusSmall, IconRefresh, IconWarning } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'-import { CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE } from 'lib/api-error'+import { CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE, TABLE_ACCESS_DENIED_ERROR_CODE } from 'lib/api-error'import { pngHoggie } from 'lib/brand/hoggies'import { AccessControlAction } from 'lib/components/AccessControlAction'import { MCPUseCaseCard } from 'lib/components/MCPHint/MCPUseCaseCard'@@ -617,13 +617,15 @@ export function InsightValidationError({// unless the code says otherwise: a memory failure is not a broken query definition.const errorKind = getInsightErrorKind(400, validationErrorCode)const isMemoryLimitError = errorKind === 'memory_limit'+ const isPermissionError = errorKind === 'permission'const displayDetail = getInsightValidationDetail(detail)const showQueryDebuggerInstruction =query &&!isMemoryLimitError &&+ !isPermissionError &&displayDetail !== 'Check the query for errors, then run it again.' &&placement !== DashboardPlacement.Export- const shouldExcludeActions = excludeActions || placement === DashboardPlacement.Export+ const shouldExcludeActions = excludeActions || isPermissionError || placement === DashboardPlacement.Exportconst defaultCta =cta ?? (onRetry ? <RetryButton onRetry={onRetry} query={query} /> : <QueryDebuggerButton query={query} />)@@ -644,10 +646,14 @@ export function InsightValidationError({<InsightErrorHoggie kind={errorKind} /><h2 data-attr="insight-loading-too-long" className="text-xl leading-tight font-bold mb-0 text-danger">- {getInsightErrorTitle(errorKind, null)}+ {getInsightErrorTitle(errorKind, isPermissionError ? displayDetail : null)}</h2>- <p className="text-sm text-muted max-w-120 mb-2">{renderDetailWithLinks(displayDetail)}</p>+ <p className="text-sm text-muted max-w-120 mb-2">+ {isPermissionError+ ? 'Ask a project admin to grant you access to this table.'+ : renderDetailWithLinks(displayDetail)}+ </p>{showQueryDebuggerInstruction && !shouldExcludeActions && (<p className="text-sm text-muted max-w-120 mb-2">Open the query debugger and correct the query.</p>@@ -744,6 +750,9 @@ function getInsightErrorKind(status?: number | null, code?: string | null): Insiif (code === CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE) {return 'memory_limit'}+ if (code === TABLE_ACCESS_DENIED_ERROR_CODE) {+ return 'permission'+ }if (status === 429) {return 'rate_limit'}diff --git a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsxindex 9761c0061fee..17e1d1a598cf 100644--- a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx+++ b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx@@ -66,21 +66,38 @@ describe('insight error states', () => {})})- it('labels a memory failure as unfinished rather than invalid', () => {- render(- <InsightValidationError- detail={CLUSTER_MEMORY_DETAIL}- validationErrorCode="clickhouse_memory_limit_exceeded"- query={{ kind: 'InsightVizNode' }}- />- )+ it.each([+ {+ code: 'clickhouse_memory_limit_exceeded',+ detail: CLUSTER_MEMORY_DETAIL,+ expectedTitle: "This query couldn't finish",+ expectedNextStep: CLUSTER_MEMORY_DETAIL,+ aiDebug: true,+ queryDebugger: true,+ },+ {+ code: 'table_access_denied',+ detail: "You don't have access to table `events`.",+ expectedTitle: "You don't have access to table `events`.",+ expectedNextStep: 'Ask a project admin to grant you access to this table.',+ aiDebug: false,+ queryDebugger: false,+ },+ ])(+ 'does not label a $code failure as an invalid query',+ ({ code, detail, expectedTitle, expectedNextStep, aiDebug, queryDebugger }) => {+ render(+ <InsightValidationError detail={detail} validationErrorCode={code} query={{ kind: 'InsightVizNode' }} />+ )- expect(screen.getByText("This query couldn't finish")).toBeTruthy()- expect(screen.queryByText("We couldn't run this query")).toBeNull()- expect(screen.getByText(CLUSTER_MEMORY_DETAIL)).toBeTruthy()- expect(screen.queryByText('Open the query debugger and correct the query.')).toBeNull()- expect(screen.getByText('Debug with PostHog AI')).toBeTruthy()- })+ expect(screen.getByText(expectedTitle)).toBeTruthy()+ expect(screen.getByText(expectedNextStep)).toBeTruthy()+ expect(screen.queryByText("We couldn't run this query")).toBeNull()+ expect(screen.queryByText('Open the query debugger and correct the query.')).toBeNull()+ expect(screen.queryByText('Debug with PostHog AI') !== null).toBe(aiDebug)+ expect(screen.queryByText('Open in query debugger') !== null).toBe(queryDebugger)+ }+ )it('replaces generic invalid-query detail with a next step', () => {render(