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(dashboards): add retry for failed insight tiles (#86686)

Matt Puae8f08292f0eb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6e0b5c569146..a219aeb6f6cc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -161,17 +161,21 @@ snapshots:
components-cards-insight-card--access-control-manager-access--light:
hash: v1.k794b7964.0431bdfb0012bc06a0c27570a66b6639b9fcab5c6d2c871893adbf2fc996d325.N4VtYwiHepp7lYjreIZcUjItBZwyQ1ctUjD-NJU7fRo
components-cards-insight-card--access-control-mixed-permissions--dark:
- hash: v1.k794b7964.85e20bfb9088393116f64372f4eabd57bde931ce6a590e2bd9849770193c92a4.vRJPRG97bL9HRdz0aX7mgYgJqU2c2ttBNCs5z0dbgAA
+ hash: v1.k794b7964.de937230d1ba7b08d82e1a1a0b521b5bdacc1bcb02d64d49df3e46c5965a58cd.IK-MZlquedZD6zSfxseRqubFBnyJ0K5PCNWVev68JVs
components-cards-insight-card--access-control-mixed-permissions--light:
- hash: v1.k794b7964.7eb6be464885ad467901414d14f6e4a8cc4d6b5cedf65bf4cee144ffcf1bf4e0.rnbXasygMxS8Il_ErU2lhH5UbymU7OAkm8vTrmmOOA4
+ hash: v1.k794b7964.e5cb460779d83337f36d2d99b31028d08d6b99123b509f2a23890fe392ee7c6d.JH1pWKZirNfE7anbvNJHgit9PQxo6uMLJs0HmfzWMOI
components-cards-insight-card--access-control-no-access--dark:
- hash: v1.k794b7964.47bb3da98257e9aa61e23820a5489e300f2af0813eb141087d2087b14ef4672f.-BZqYVPHvUapBQsZaRqM8KSxjEhZvYWoJ7eJMiL_3ok
+ hash: v1.k794b7964.1969dbc9c3252162f76e33f24dd40730cda7db6eb9cb07eab9de078fb2b0fa97.ta55BvCCWvdKIV8yVtGvhYTveFxqbapq05-3r5by9TI
components-cards-insight-card--access-control-no-access--light:
- hash: v1.k794b7964.e4d6488b9989fb98f443da019928efaf5ea1caae7f4766aaffbe154615d6bc28.XekZijWH1UI7oxoF6iSe4h4NyMWaNAUiULAVicIduy0
+ hash: v1.k794b7964.ac83ff06db1fd9b37cd856fb580b2df7824c1211e2cc3e93ec49933cc52b4443.TFWXYW2KIwnrAScgRTusDFAf_oQs4MSadpmkyRzfLT0
components-cards-insight-card--access-control-viewer-access--dark:
hash: v1.k794b7964.5f3e7c9a9923ca547abac285ccd1d4e220df5132c95f96a25d4e71418ab595e0.mVhI7r6cz_F9H3wZ4y7DaEGsVhVzj1MD2mK539UwvJc
components-cards-insight-card--access-control-viewer-access--light:
hash: v1.k794b7964.bf2be6132e7d881f5648da794c30b861a8970b30aad98024e1470afa20fb1184.QjEzM0TKMP1UfPhiAgRyZW3hsOIKbNn5o8Un7s1Yswc
+ components-cards-insight-card--error-states--dark:
+ hash: v1.k794b7964.d8e18524ed1c2436d6ab464f0eb71658ead08c429b7863661799fbd0bf8b66d1.W9dKoEcV57cz6YPmXpfiI8AX3CvNpUJLL4odBELvmlQ
+ components-cards-insight-card--error-states--light:
+ hash: v1.k794b7964.8422b995b4b5b8872b2d12317cc2ed0d675f40d959d201a890e3338d366a243a.0dItnqTFKmFpM3hUqlrMS71DqZBAkwGMDjW7z5KLiB0
components-cards-insight-card--insight-card--dark:
hash: v1.k794b7964.fdfc67abaeb31b9a0d3a230ee9510916ffb36d5aad1d2321edaa896bb343ff9b.3W6qDwBKmZQGvb56bckNdiwYQhuA5gIf0DfLmUFN0eU
components-cards-insight-card--insight-card--light:
@@ -6857,9 +6861,9 @@ snapshots:
scenes-app-insights-error-empty-states--empty--light:
hash: v1.k794b7964.43e8dc4bf97bb67ddaf60c572621f44670e53ae5e49adc85129ce56fe34112c2.sbomFpq1C6A2uPO2QNzFMa2oPgeAiU2Y6lNYz6qH_dc
scenes-app-insights-error-empty-states--estimated-query-execution-time-too-long--dark:
- hash: v1.k794b7964.48716a48b2caaeeeca99f6223c47d9509d443b7a54b75ba3264d4d48c6b10fc2.qfYybMOhpeaoivbNtF0AYxe9-sbO8hjM9sVEwkZsSyo
+ hash: v1.k794b7964.fdde648da67a1ad03bef921fa62aff639acba275cb908e964ef214ea9e600d17.b0uYWTxVHoeGSR0U85AkoZdiNrc3zm8D4KaGyPT1H0g
scenes-app-insights-error-empty-states--estimated-query-execution-time-too-long--light:
- hash: v1.k794b7964.64c380e25170b0fc5f041051d81ecaffbee6c7d27b5cd089791b6c3a935aee1e.vh2_IGlmhOovhn4Enx5sywCBxW_ozxGNdkO36J6U95E
+ hash: v1.k794b7964.666b12cd5ea2009ce3ea7269cd44cebd467b48ef272c2863f4fb78c74dd55d51.GDCwHpSZ6n5sIduVSyu002ujA_IAa6rp53i5w9nqk0Q
scenes-app-insights-error-empty-states--funnel-single-step--dark:
hash: v1.k794b7964.95191b5eabf851e9190e78385e9b9c66305ef02e0239996a2505c12642a8cfe7.AzXYpom0Oilotqx9JOMUfUrK5VA4GaPcLHki2FkLGxw
scenes-app-insights-error-empty-states--funnel-single-step--light:
@@ -6869,21 +6873,21 @@ snapshots:
scenes-app-insights-error-empty-states--long-loading--light:
hash: v1.k794b7964.c17cf8b6b9ca9b3fa5cd570116c12705ec424367a8cf0cbe3934f7057a64bad6.xV9MB_rar116TwlG94C5F8W9YaSMd7NPI_AOO1OD9Ic
scenes-app-insights-error-empty-states--memory-limit-exceeded--dark:
- hash: v1.k794b7964.ef18ee16bcec4b43d74979a5131a3f325f8e0542b6b4cba050746f6b02699ab9.kOLq5BxzD8AlGlxKgleq3uJTw_ddM6GTSmML4MNaZ5o
+ hash: v1.k794b7964.2e48c122e036581194c9b2d7d1e9512af8193b1f72a74837cf5f12ba82b1fd72.9cdSq276OLtEWO5BwAxPIeX9y1JUV_x3gKBDf1DxZ80
scenes-app-insights-error-empty-states--memory-limit-exceeded--light:
- hash: v1.k794b7964.5db627722825a5e96b5c9a60b66b003822ef339c07c8cb0475bbe726df99a14b.wl_oFPQ_LwRebMnu1nHg-LQxBV-L9Q5nRkkKxr3gH9g
+ hash: v1.k794b7964.75ab2e919b3f7c36ea5cc85e3def80af2d1a130c359303da7a6350ffb08eca31.aQkEQ2HXsHZl7vz-D5BJxN5gMtRSX9RhzppllBsBZ2w
scenes-app-insights-error-empty-states--query-server-error--dark:
- hash: v1.k794b7964.c30da1434c9c4cfc8ea0e808803370c4d9f77c38f1758dfdb4840ab58def1675.V7oqqsPrl1k8BBlI9jTHhj9KZ_LkWDGixSpg3GhFXv8
+ hash: v1.k794b7964.3005e0852a46a87ff251d145e22896b53f4bdd198e13e80ea8976eab02e34a16.l95y2LouxfDErePKQrTqH9A6exoO8zAfDKZ_POxOsoY
scenes-app-insights-error-empty-states--query-server-error--light:
- hash: v1.k794b7964.8cbd2901888aa723067ddea0dc2c6045628c0cb872438beca4e667592d25aaf6.4GmhzW21hmldOgELAwHy522bovvzkaq8b4i0NowPhb8
+ hash: v1.k794b7964.ff89adcdbb0a5a832b14c2d574ed78dfbc195fb2bc2aaa4ed7c3f1636b36974e.ejXhasY1o2oPJ35r3ndql95zA9f88G-l5XSr7ejlMQM
scenes-app-insights-error-empty-states--server-error--dark:
- hash: v1.k794b7964.c78c9eaddad034d4747bccc025468e045b9e641e8f70daa75c428ac94def566c.WSvKXlMMIMORSx1W_7pTEH4AQMQUtr_4cSHSVfBGl_0
+ hash: v1.k794b7964.09dc5604dc08ef589a43b504f4aad31cda03648a9e27c579e6c763cb446f6833.8_m3YxsizkrlwUHm7vZcquY8S-bnfmJuWDt9oiJUQTM
scenes-app-insights-error-empty-states--server-error--light:
- hash: v1.k794b7964.79b5b63d2b650cc4f924ddf5a268fa8ef317b61002f878ba729b43114ff2458c.TeYRm6KIzF4y5I9oHWuR5KmccQgDWrUc9JHk9Hq0p4o
+ hash: v1.k794b7964.67b3c028f98c71f3eb47d7e73447fbcb74a9e984ccf743ff53e463c8cf7a231c.RIXyy_KJP-pL-IW6sDS96WmPLCXwkchITd5ZTxjt7OE
scenes-app-insights-error-empty-states--validation-error--dark:
- hash: v1.k794b7964.855cdd3fac12fc2645b90ff17a8e0150f3cd4e4b646e92b9266e5261459d0d07.yF2PxdOOktpjWsHaPmDXsmLxgz5S3nhheVXgr1Xt1V0
+ hash: v1.k794b7964.96f7a06307278330f327a5f2681c8151c8db64c5237d805d57a336d29dd83407.SgzGhQipeeQzM_7BmUHeTX2J0iq-wQl6zfd7CsTqpLI
scenes-app-insights-error-empty-states--validation-error--light:
- hash: v1.k794b7964.e232ea060b03d0822779abbb60dcc292ef83dd8b5ffc76ce3f07078793c0385c.iF5uqRK20wurdp2qDmMgridMiGRNah0j1gTzHZiP5XE
+ hash: v1.k794b7964.30a50838e3fb15d9abf86197d074efed4fe0acc540be4ee3adf7a8194c4e5a7b.j4SWfv-lyqqnzhuC1zMkUVkisAelL9bSR4FBAmpD4_o
scenes-app-insights-insight-quick-start--default--dark:
hash: v1.k794b7964.9c2221e83fa5d09056672573226c948c5b9cd30716e6eb5e09d1e4ea3e94e336.WkGH5TXIN9Ysp3dVcJiXuGCjwdmC2Zquw_iUGoyj0jc
scenes-app-insights-insight-quick-start--default--light:
@@ -7341,17 +7345,17 @@ snapshots:
scenes-app-persons-modal--empty--light:
hash: v1.k794b7964.e7f63b65e183d7a65841e8621119799e6a3317e6d33ec71e275c37feedc64225.ANIbBo0qPwf94oVE6MiAcHrmZTqVLcUvl7BNCHsOK2M
scenes-app-persons-modal--server-error--dark:
- hash: v1.k794b7964.adbc0f850ac3b8d770822f3a8a23cb14571fd05b7e8916c86eb2fc83409a3bc1.t7p0f-izSULBarHON3lHkXfQ-udGw-hOaKV9LG8BjbM
+ hash: v1.k794b7964.21e85f4158f642f522f97c358e6f9de24cd6c8aef0c4c55463de1a9c3be4caef.qwQif7mBTHcMdHuwp3loQVSw6H7wIKCHBZWlebXEVqQ
scenes-app-persons-modal--server-error--light:
- hash: v1.k794b7964.5eec6a4ffa8c66493451b3b0883f29a5ea967e5abfc6d8602af1a911deca978f.Isc_OUoaPkM9XmzSEnT6_GGfw_5iIF5Mcp6vWoE6da4
+ hash: v1.k794b7964.5ae91c78255c7fc68354ddd297f4df93d44933119a5116a882bfa2219b2b3e39.qvWZfbPkAWQ-NnGZea_Zc0QI4WfFVrTUcqgpdye24ms
scenes-app-persons-modal--session-actors-with-results--dark:
hash: v1.k794b7964.7e150e0a298fa1016c7f1f1053c953b327361ecd8c483ad807de75740ddf5365.thDvSDMw1nG9kY-N_3vT5mm_oRHGXEjqq73W7a0OrCw
scenes-app-persons-modal--session-actors-with-results--light:
hash: v1.k794b7964.06bf1cfa3c36b096bffcbd9813e57ba01ef570c714499940b780f19597b92a2f.GOGGIKLLkTw2K2STHQODj0UOI1r34dPh0Vv5J0D7EDU
scenes-app-persons-modal--timeout-error--dark:
- hash: v1.k794b7964.4990e48a51720815269a303482913d98e1ed27e9889b7e39f3aca327cd8ac2dd.tvaBLf81zCweBjjiY5q36G2aAEDYzTdMhsdC1h-qGUY
+ hash: v1.k794b7964.198f177e15c26e75e10fbc9e46d736fbd86a367e8bfb809dad12c85efba1e811.rBonHuZ_-rmyn6JeK-0zaNAfeoXf50x8EygtotElnv4
scenes-app-persons-modal--timeout-error--light:
- hash: v1.k794b7964.bb5638d68a03c39d567e44ae8b05cddea7c269f8474fb75ee89e866fd5f1385a.24FCotqJyIROot5hGcX_ALTmkLy6yRNVXrrRZSZ7nzg
+ hash: v1.k794b7964.eb2c0a8a104af820051487560fc4aeb7857ff6521babd0501900dce13f6cecf2.HoayhjneyMZ7mDgBJLtroSxUmo2qOEDDrcxQACwSjow
scenes-app-persons-modal--with-results--dark:
hash: v1.k794b7964.543e6b89c21b4a0de9fca38a2a7b585c4e467382f5ce5772d50424b866ec9f31.ya9rrl_NUzwRgesGT5CjUr6YpnBH7zRoH2U6TQnyZ5U
scenes-app-persons-modal--with-results--light:
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx
index 5848f03f02c9..21dd8773d764 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx
@@ -17,6 +17,7 @@ import EXAMPLE_TRENDS_PIE from '../../../../mocks/fixtures/api/projects/team_id/
import EXAMPLE_TRENDS_TABLE from '../../../../mocks/fixtures/api/projects/team_id/insights/trendsTable.json'
import EXAMPLE_TRENDS_HORIZONTAL_BAR from '../../../../mocks/fixtures/api/projects/team_id/insights/trendsValue.json'
import EXAMPLE_TRENDS_WORLD_MAP from '../../../../mocks/fixtures/api/projects/team_id/insights/trendsWorldMap.json'
+import { ApiError } from '../../../api-error'
import { InsightCard as InsightCardComponent } from './index'
import type { InsightCardProps } from './InsightCard'
@@ -216,6 +217,72 @@ export const InsightCard: Story = {
},
}
+export const ErrorStates: Story = {
+ render: () => {
+ const errors = [
+ {
+ name: 'Invalid query',
+ error: new ApiError('The query is invalid.', 400, undefined, {
+ detail: 'The query is invalid.',
+ code: 'invalid_query',
+ queryId: 'invalid-query-id',
+ }),
+ },
+ {
+ name: 'Rate limit',
+ error: new ApiError('Too many requests.', 429, new Headers({ 'Retry-After': '120' }), {
+ detail: 'Too many requests.',
+ code: 'rate_limited',
+ queryId: 'rate-limit-query-id',
+ }),
+ },
+ {
+ name: 'Permission denied',
+ error: new ApiError('You do not have permission to run this query.', 403, undefined, {
+ detail: 'You do not have permission to run this query.',
+ code: 'permission_denied',
+ queryId: 'permission-query-id',
+ }),
+ },
+ {
+ name: 'Temporary server failure',
+ error: new ApiError('The query service is temporarily unavailable.', 503, undefined, {
+ detail: 'The query service is temporarily unavailable.',
+ code: 'service_unavailable',
+ queryId: 'temporary-query-id',
+ }),
+ },
+ {
+ name: 'Unknown server failure',
+ error: new ApiError('The query service failed.', 500, undefined, {
+ detail: 'The query service failed.',
+ code: 'server_error',
+ queryId: 'server-query-id',
+ }),
+ },
+ ]
+
+ return (
+ <div className="grid gap-4 grid-cols-2 min-w-[60rem]">
+ {errors.map(({ name, error }) => (
+ <InsightCardComponent
+ key={name}
+ tile={defaultTile}
+ insight={{ ...EXAMPLE_TRENDS, name } as unknown as QueryBasedInsightModel}
+ apiErrored
+ apiError={error}
+ refresh={() => {}}
+ queryId={error.data?.queryId}
+ rename={() => {}}
+ duplicate={() => {}}
+ placement="SavedInsightGrid"
+ />
+ ))}
+ </div>
+ )
+ },
+}
+
// Access Control Stories
export const AccessControlNoAccess: Story = {
render: () => {
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 2bb1651dc0df..c5b2464a1303 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -24,6 +24,7 @@ import {
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { extractValidationError, extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'
import { Query } from '~/queries/Query/Query'
@@ -163,6 +164,8 @@ export interface InsightCardProps extends Resizeable {
apiErrored?: boolean
/** Might contain more information on the error that occurred on the server. */
apiError?: Error
+ /** Query ID associated with the error, when available from the insight response. */
+ queryId?: string
/** Whether the card should be highlighted with a blue border. */
highlighted?: boolean
/** Whether loading timed out. */
@@ -227,6 +230,7 @@ function InsightCardInternal(
loading,
apiError,
apiErrored,
+ queryId,
timedOut,
highlighted,
showResizeHandles,
@@ -327,6 +331,7 @@ function InsightCardInternal(
const openCreateAnomalyAlertModal = useCallback(() => setAlertModal({ defaultToAnomalyDetection: true }), [])
const closeAlertModal = useCallback(() => setAlertModal(null), [])
const hasResults = !!insight?.result || !!(insight as any)?.results
+ const sharedView = isSharedView()
// Empty states that completely replace the Query component.
const BlockingEmptyState = (() => {
@@ -351,6 +356,7 @@ function InsightCardInternal(
<InsightErrorState
data-attr="insight-access-denied-state"
title={errorMessage || "You don't have permission to view this insight."}
+ titleStatus={403}
excludeDetail
/>
)
@@ -367,15 +373,23 @@ function InsightCardInternal(
<InsightValidationError
detail={validationError}
validationErrorCode={extractValidationErrorCode(apiError)}
+ query={insight.query}
+ excludeActions={sharedView}
+ placement={placement}
/>
)
} else if (apiError instanceof ApiError) {
- const isDashboardTileError = apiError.code === 'dashboard_tile_error'
return (
<InsightErrorState
title={apiError.detail}
- queryId={apiError.data?.queryId}
- supportOnly={isDashboardTileError}
+ titleStatus={apiError.status}
+ queryId={apiError.data?.queryId ?? queryId}
+ retryAfter={apiError.formattedRetryAfter}
+ retryLoading={loading}
+ query={insight.query}
+ excludeActions={sharedView}
+ placement={placement}
+ onRetry={sharedView ? undefined : refresh}
/>
)
}
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 1bb555112b68..19bbf592cc66 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -10,7 +10,7 @@ import { Link } from 'lib/lemon-ui/Link'
import { cn } from 'lib/utils/css-classes'
import { DashboardFilterBar } from 'scenes/dashboard/DashboardFilters'
import { DashboardItems } from 'scenes/dashboard/DashboardItems'
-import { DashboardLogicProps, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { DashboardLoadAction, DashboardLogicProps, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
import { InsightErrorState } from 'scenes/insights/EmptyStates'
import { SceneExport } from 'scenes/sceneTypes'
@@ -94,6 +94,7 @@ function DashboardScene({
canEditDashboard,
tiles,
itemsLoading,
+ dashboardLoading,
layoutEditMode,
dashboardFailedToLoad,
accessDeniedToDashboard,
@@ -101,7 +102,7 @@ function DashboardScene({
} = useValues(dashboardLogic)
const { layoutZoom } = useValues(dashboardLogic)
const { currentTeamId } = useValues(teamLogic)
- const { reportDashboardViewed, abortAnyRunningQuery, setLayoutZoom } = useActions(dashboardLogic)
+ const { reportDashboardViewed, abortAnyRunningQuery, loadDashboard, setLayoutZoom } = useActions(dashboardLogic)
const { addInsightToDashboardModalVisible } = useValues(addInsightToDashboardLogic)
useAttachedContext(
@@ -152,7 +153,16 @@ function DashboardScene({
<DashboardPublicAccessBanner dashboard={dashboard} placement={placement} />
{dashboardFailedToLoad ? (
- <InsightErrorState title="There was an error loading this dashboard" supportOnly />
+ <InsightErrorState
+ title="There was an error loading this dashboard"
+ onRetry={
+ placement === DashboardPlacement.Export
+ ? undefined
+ : () => loadDashboard({ action: DashboardLoadAction.Update })
+ }
+ retryLoading={dashboardLoading}
+ placement={placement}
+ />
) : !tiles || tiles.length === 0 ? (
<EmptyDashboardComponent loading={itemsLoading || !dashboard} canEdit={canEditDashboard} />
) : (
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index b633c2c90ebf..9c092bb998fa 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -22,6 +22,7 @@ jest.mock('kea', () => ({
jest.mock('scenes/dashboard/dashboardLogic', () => ({
dashboardLogic: { __mock: 'dashboardLogic' },
+ DashboardLoadAction: { Update: 'update' },
}))
jest.mock('~/models/dashboardsModel', () => ({
@@ -62,15 +63,17 @@ jest.mock('scenes/surveys/utils/opportunityDetection', () => ({
}))
jest.mock('scenes/insights/EmptyStates', () => ({
- InsightErrorState: ({ title, supportOnly }: { title: string; supportOnly?: boolean }) => (
- <div data-attr="insight-error-state" data-support-only={supportOnly ? 'true' : undefined}>
+ InsightErrorState: ({ title, onRetry }: { title: string; onRetry?: () => void }) => (
+ <div data-attr="insight-error-state" data-has-retry={onRetry ? 'true' : undefined}>
{title}
+ {onRetry && <button onClick={onRetry}>Retry error tile</button>}
</div>
),
}))
jest.mock('~/exporter/exporterViewLogic', () => ({
getCurrentExporterData: () => null,
+ isSharedView: () => false,
}))
jest.mock('scenes/urls', () => ({
@@ -82,27 +85,33 @@ jest.mock('scenes/urls', () => ({
}))
jest.mock('lib/components/Cards/InsightCard', () => ({
- InsightCard: ({
- tile,
- showResizeHandles,
- apiErrored,
- apiError,
- }: {
+ InsightCard: (props: {
tile: { id: number }
showResizeHandles: boolean
apiErrored?: boolean
- apiError?: Error & { status?: number; detail?: string | null; code?: string | null }
- }) => (
- <div
- data-attr="insight-card"
- data-tile-id={String(tile.id)}
- data-show-resize-handles={String(showResizeHandles)}
- data-api-errored={apiErrored ? 'true' : undefined}
- data-api-error-status={apiError?.status}
- data-api-error-detail={apiError?.detail ?? undefined}
- data-api-error-code={apiError?.code ?? undefined}
- />
- ),
+ queryId?: string
+ apiError?: Error & {
+ status?: number
+ detail?: string | null
+ code?: string | null
+ data?: { queryId?: string }
+ }
+ refresh?: () => void
+ }): JSX.Element => {
+ mockInsightCard(props)
+ const { tile, showResizeHandles, apiErrored, apiError } = props
+ return (
+ <div
+ data-attr="insight-card"
+ data-tile-id={String(tile.id)}
+ data-show-resize-handles={String(showResizeHandles)}
+ data-api-errored={apiErrored ? 'true' : undefined}
+ data-api-error-status={apiError?.status}
+ data-api-error-detail={apiError?.detail ?? undefined}
+ data-api-error-code={apiError?.code ?? undefined}
+ />
+ )
+ },
}))
jest.mock('./items/DashboardTextItem', () => ({
@@ -171,9 +180,12 @@ const mockedUseValues = useValues as jest.Mock
const mockedUseActions = useActions as jest.Mock
const mockedUseAsyncActions = useAsyncActions as jest.Mock
const mockRemoveTile = jest.fn()
+const mockTriggerDashboardRefresh = jest.fn()
+const mockInsightCard = jest.fn()
describe('DashboardItems', () => {
beforeEach(() => {
+ mockInsightCard.mockClear()
jest.clearAllMocks()
mockedUseValues.mockImplementation((logic) => {
@@ -226,6 +238,7 @@ describe('DashboardItems', () => {
removeTile: mockRemoveTile,
duplicateTile: jest.fn(),
refreshDashboardItem: jest.fn(),
+ loadDashboard: mockTriggerDashboardRefresh,
refreshDashboardWidgets: jest.fn(),
moveToDashboard: jest.fn(),
copyToDashboard: jest.fn(),
@@ -424,10 +437,10 @@ describe('DashboardItems', () => {
const { findByText, getByTestId, getByText } = render(<DashboardItems />)
expect(getByText('Tile')).toBeInTheDocument()
- expect(getByText('There is a problem loading this dashboard tile.')).toHaveAttribute(
- 'data-support-only',
- 'true'
- )
+ expect(getByText('There is a problem loading this dashboard tile.')).toHaveAttribute('data-has-retry', 'true')
+
+ fireEvent.click(getByText('Retry error tile'))
+ expect(mockTriggerDashboardRefresh).toHaveBeenCalled()
fireEvent.click(getByTestId('more-button'))
fireEvent.click(await findByText('Remove from dashboard'))
@@ -538,6 +551,12 @@ describe('DashboardItems', () => {
expect(insightCard).toHaveAttribute('data-api-errored', 'true')
expect(insightCard).toHaveAttribute('data-api-error-status', '400')
expect(insightCard).toHaveAttribute('data-api-error-code', 'query_memory_limit')
+ expect(mockInsightCard).toHaveBeenCalledWith(
+ expect.objectContaining({
+ refresh: expect.any(Function),
+ queryId: 'failed-query-id',
+ })
+ )
expect(insightCard).toHaveAttribute(
'data-api-error-detail',
'This query ran out of memory before it could finish'
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 6613ee74769e..399f2f17ba4a 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -20,7 +20,7 @@ import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic
import { objectsEqual } from 'lib/utils/objects'
import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'
import { getAddTileMenuItems } from 'scenes/dashboard/DashboardHeaderActions'
-import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import {
BREAKPOINTS,
BREAKPOINT_COLUMN_COUNTS,
@@ -34,7 +34,7 @@ import { useSurveyLinkedInsights } from 'scenes/surveys/hooks/useSurveyLinkedIns
import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityDetection'
import { urls } from 'scenes/urls'
-import { getCurrentExporterData } from '~/exporter/exporterViewLogic'
+import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogic'
import { insightsModel } from '~/models/insightsModel'
import { DashboardLayoutSize, DashboardMode, DashboardPlacement, DashboardType } from '~/types'
@@ -92,6 +92,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
highlightedInsightId,
refreshStatus,
dashboardStreaming,
+ dashboardLoading,
effectiveEditBarFilters,
effectiveDashboardVariableOverrides,
effectiveBreakdownColors,
@@ -111,6 +112,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
removeTile,
duplicateTile,
refreshDashboardItem,
+ loadDashboard,
refreshDashboardWidgets,
scheduleRefreshDashboardWidgets,
applyWidgetIssueMetadataChange,
@@ -131,6 +133,10 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const bestSurveyOpportunityFunnel = surveyLinkedInsightsLoading
? null
: getBestSurveyOpportunityFunnel(tiles || [], surveyLinkedInsights)
+ const retryFailedDashboardTile = isSharedView()
+ ? undefined
+ : () => loadDashboard({ action: DashboardLoadAction.Update })
+ const refreshDashboardTile = isSharedView() ? undefined : refreshDashboardItem
// Tile currently being resized. Its viz is unmounted for the duration of the gesture so the chart doesn't
// redraw on every frame as the tile's dimensions change — the dominant cost that makes resizing feel laggy.
@@ -545,6 +551,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
<MemoizedDashboardErrorTileItem
key={tile.id}
tile={tile}
+ onRetry={retryFailedDashboardTile}
+ retryLoading={dashboardLoading}
+ placement={placement}
onRemove={commonTileProps.removeFromDashboard}
showResizeHandles={showResizeHandles}
canEnterEditModeFromEdge={canEnterEditModeFromEdge}
@@ -580,11 +589,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
loading={loading}
apiErrored={apiErrored}
apiError={apiError}
+ queryId={insight.query_status?.id}
highlighted={highlightedInsightId && insight.short_id === highlightedInsightId}
updateColor={(color) => updateTileColor(tile.id, color)}
toggleShowDescription={() => toggleTileDescription(tile.id)}
ribbonColor={tile.color}
- refresh={() => refreshDashboardItem({ tile })}
+ refresh={
+ refreshDashboardTile ? () => refreshDashboardTile({ tile }) : undefined
+ }
rename={() => renameInsight(insight)}
duplicate={() => duplicateTile(tile)}
setOverride={() => setTileOverride(tile)}
diff --git a/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx b/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx
index 8d597062c264..38777456c5d1 100644
--- a/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx
+++ b/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx
@@ -7,7 +7,7 @@ import { EditModeEdge, EditModeEdgeOverlay } from 'lib/components/Cards/InsightC
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { InsightErrorState } from 'scenes/insights/EmptyStates'
-import { DashboardTile, QueryBasedInsightModel } from '~/types'
+import { DashboardPlacement, DashboardTile, QueryBasedInsightModel } from '~/types'
import { getDashboardTileDisplayName } from '../dashboardUtils'
@@ -17,6 +17,9 @@ interface DashboardErrorTileItemProps extends React.HTMLAttributes<HTMLDivElemen
onEnterEditModeFromEdge?: (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => void
onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
onRemove?: () => void
+ onRetry?: () => void
+ retryLoading?: boolean
+ placement?: DashboardPlacement
showEditingControls?: boolean
}
@@ -29,6 +32,9 @@ function DashboardErrorTileItemInternal(
onDragHandleMouseDown,
onEnterEditModeFromEdge,
onRemove,
+ onRetry,
+ retryLoading,
+ placement,
showEditingControls,
showResizeHandles,
...divProps
@@ -54,7 +60,12 @@ function DashboardErrorTileItemInternal(
) : undefined
}
/>
- <InsightErrorState title="There is a problem loading this dashboard tile." supportOnly />
+ <InsightErrorState
+ title="There is a problem loading this dashboard tile."
+ onRetry={onRetry}
+ retryLoading={retryLoading}
+ placement={placement}
+ />
{canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
<EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
)}
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 0c6d194a0acb..6bad9e77bf05 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -6,12 +6,15 @@ import { useEffect, useState } from 'react'
import { TextMorph } from 'torph/react'
import * as construction2Png from '@posthog/brand/hoggies/png/construction-2'
+import * as doctorPng from '@posthog/brand/hoggies/png/doctor-1'
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
+import * as stampDeniedPng from '@posthog/brand/hoggies/png/stamp-denied'
+import * as trafficControllerPng from '@posthog/brand/hoggies/png/traffic-controller'
import { IconArchive, IconFunnels, IconInfo, IconPlusSmall, IconRefresh, IconWarning } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { AccessControlAction } from 'lib/components/AccessControlAction'
-import { CodeSnippet } from 'lib/components/CodeSnippet'
import { MCPUseCaseCard } from 'lib/components/MCPHint/MCPUseCaseCard'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { dayjs } from 'lib/dayjs'
@@ -19,7 +22,6 @@ import { holidaysMatcher, isChristmas } from 'lib/holidays'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { IconChristmasOrnament, IconErrorOutline, IconOpenInNew } from 'lib/lemon-ui/icons'
-import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { Link } from 'lib/lemon-ui/Link'
import { LoadingBar } from 'lib/lemon-ui/LoadingBar'
@@ -40,12 +42,12 @@ 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 { VALIDATION_ERROR_STATUSES } from '~/queries/nodes/InsightViz/utils'
import { FunnelsQuery, Node, NodeKind, QueryStatus } from '~/queries/schema/schema-general'
import { isFunnelsDataWarehouseNode } from '~/queries/utils'
import {
AccessControlLevel,
AccessControlResourceType,
+ DashboardPlacement,
FilterType,
InsightLogicProps,
SavedInsightsTabs,
@@ -59,6 +61,10 @@ import { SampleDataState, SampleDataVariant } from './SampleDataState'
import { sampleDataStateLogic } from './sampleDataStateLogic'
const HedgehogConstruction2 = pngHoggie(construction2Png)
+const HedgehogDoctor = pngHoggie(doctorPng)
+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
+const HedgehogStampDenied = pngHoggie(stampDeniedPng)
+const HedgehogTrafficController = pngHoggie(trafficControllerPng)
// Matches ClickHouseQueryMemoryLimitExceeded.default_code on the backend. Keep the two in sync.
const CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE = 'clickhouse_memory_limit_exceeded'
@@ -206,9 +212,11 @@ function QueryDebuggerButton({ query }: { query?: Record<string, any> | null }):
const RetryButton = ({
onRetry,
query,
+ loading = false,
}: {
onRetry: () => void
query?: Record<string, any> | Node | null
+ loading?: boolean
}): JSX.Element => {
const sideAction = query
? {
@@ -233,6 +241,7 @@ const RetryButton = ({
data-attr="insight-retry-button"
size="small"
type="primary"
+ loading={loading}
onClick={() => onRetry()}
sideAction={sideAction}
>
@@ -588,16 +597,26 @@ export function InsightValidationError({
query,
onRetry,
cta,
+ excludeActions = false,
+ placement,
}: {
detail: string
validationErrorCode?: string | null
query?: Record<string, any> | null
onRetry?: () => void
cta?: JSX.Element
+ excludeActions?: boolean
+ placement?: DashboardPlacement | 'SavedInsightGrid'
}): 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 displayDetail = getInsightValidationDetail(detail)
+ const showQueryDebuggerInstruction =
+ query &&
+ displayDetail !== 'Check the query for errors, then run it again.' &&
+ placement !== DashboardPlacement.Export
+ const shouldExcludeActions = excludeActions || placement === DashboardPlacement.Export
const defaultCta =
cta ?? (onRetry ? <RetryButton onRetry={onRetry} query={query} /> : <QueryDebuggerButton query={query} />)
@@ -615,44 +634,43 @@ export function InsightValidationError({
data-attr="insight-empty-state"
className="flex flex-col items-center justify-center gap-2 rounded px-4 py-6 h-full w-full text-center text-balance"
>
- <IconWarning className="text-4xl shrink-0 text-muted mb-2" />
-
- <h2
- data-attr="insight-loading-too-long"
- className="text-xl leading-tight font-bold mb-0"
- // TODO: Use an actual `text-warning` color once @adamleithp changes are live
- // eslint-disable-next-line react/forbid-dom-props
- style={{ color: 'var(--warning)' }}
- >
- There is a problem with this query
+ <InsightErrorHoggie kind="invalid_query" />
+
+ <h2 data-attr="insight-loading-too-long" className="text-xl leading-tight font-bold mb-0 text-danger">
+ We couldn't run this query
{/* Note that this phrasing above signals the issue is not intermittent, */}
{/* 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">{renderDetailWithLinks(detail)}</p>
+ <p className="text-sm text-muted max-w-120 mb-2">{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>
+ )}
{/* 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
- )}
+ {!shouldExcludeActions &&
+ (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') && (
+ {detail.includes('Exclusion') && placement !== DashboardPlacement.Export && (
<div className="mt-4">
<Link
data-attr="insight-funnels-emptystate-help"
@@ -671,19 +689,101 @@ export function InsightValidationError({
const RAW_SERVER_ERROR_PATTERN =
/Stack trace:|DB::Exception|Traceback \(most recent call last\)|object at 0x[0-9a-f]+|^[A-Za-z_.]+(Error|Exception)[:(]/
+function getInsightValidationDetail(detail: string): string {
+ if (isRawServerErrorTitle(detail)) {
+ return 'The query could not run.'
+ }
+ if (/^the query is invalid\.?$/i.test(detail.trim())) {
+ return 'Check the query for errors, then run it again.'
+ }
+ return detail
+}
+
/**
* A string title on this state can come straight from the backend, so it can be a raw exception
- * body instead of user-facing copy. Show those behind a collapsible, not in the heading, so the
- * page keeps a clear message with the retry and bug-report guidance. When the response status is
- * known, trust the backend's classification: VALIDATION_ERROR_STATUSES mark messages written for
- * the user (however long), anything else is a server-side failure. Exception markers demote even
- * on those statuses, because staff accounts receive raw traces there too.
+ * body instead of user-facing copy. Hide raw exception text and show curated remediation instead.
*/
export function isRawServerErrorTitle(title: string, status?: number | null): boolean {
if (RAW_SERVER_ERROR_PATTERN.test(title)) {
return true
}
- return status != null && !VALIDATION_ERROR_STATUSES.has(status)
+ return status != null && status >= 500
+}
+
+type InsightErrorKind = 'rate_limit' | 'invalid_query' | 'permission' | 'transient' | 'server' | 'unknown'
+
+const ERROR_HOGGIES: Record<InsightErrorKind, React.ComponentType<{ className?: string }>> = {
+ rate_limit: HedgehogTrafficController,
+ invalid_query: HedgehogMagnifyingGlass,
+ permission: HedgehogStampDenied,
+ transient: HedgehogConstruction2,
+ server: HedgehogDoctor,
+ unknown: HedgehogDoctor,
+}
+
+function InsightErrorHoggie({ kind }: { kind: InsightErrorKind }): JSX.Element {
+ const Hoggie = ERROR_HOGGIES[kind]
+ return <Hoggie className="w-24 h-24 mb-2" />
+}
+
+function getInsightErrorKind(status?: number | null): InsightErrorKind {
+ if (status === 429) {
+ return 'rate_limit'
+ }
+ if (status === 400 || status === 422) {
+ return 'invalid_query'
+ }
+ if (status === 401 || status === 403) {
+ return 'permission'
+ }
+ if (status === 502 || status === 503 || status === 504) {
+ return 'transient'
+ }
+ if (status != null && status >= 500) {
+ return 'server'
+ }
+ return 'unknown'
+}
+
+function getInsightErrorTitle(
+ kind: InsightErrorKind,
+ fallback: string | JSX.Element | null | undefined,
+ titleStatus?: number | null
+): string | JSX.Element {
+ if (kind === 'invalid_query') {
+ return "We couldn't run this query"
+ }
+ if (kind === 'transient') {
+ return "This query couldn't run right now"
+ }
+ if (kind === 'server') {
+ return "PostHog couldn't complete this query"
+ }
+ if (kind === 'unknown') {
+ if (titleStatus == null) {
+ return fallback ?? 'There was a problem completing this query'
+ }
+ return "We couldn't complete this query"
+ }
+ return fallback ?? 'There was a problem completing this query'
+}
+
+function getInsightErrorRemediation(kind: InsightErrorKind, retryAfter?: string | null): string | null {
+ switch (kind) {
+ case 'rate_limit':
+ return `Try again ${retryAfter ?? 'later'}.`
+ case 'invalid_query':
+ return 'Open the query debugger and correct the query.'
+ case 'permission':
+ return 'Ask a project admin to grant you access to this insight.'
+ case 'transient':
+ return 'Try again in a moment.'
+ case 'server':
+ case 'unknown':
+ return 'Try again in a moment. If the problem continues, contact support.'
+ default:
+ return null
+ }
}
export interface InsightErrorStateProps {
@@ -692,6 +792,9 @@ export interface InsightErrorStateProps {
titleStatus?: number | null
query?: Record<string, any> | Node | null
queryId?: string | null
+ retryAfter?: string | null
+ retryLoading?: boolean
+ placement?: DashboardPlacement | 'SavedInsightGrid'
excludeDetail?: boolean
excludeActions?: boolean
supportOnly?: boolean
@@ -704,13 +807,22 @@ export function InsightErrorState({
titleStatus,
query,
queryId,
+ retryAfter,
+ retryLoading = false,
+ placement,
excludeDetail = false,
excludeActions = false,
supportOnly = false,
fixWithAIComponent,
onRetry,
}: InsightErrorStateProps): JSX.Element {
- const rawServerError = typeof title === 'string' && isRawServerErrorTitle(title, titleStatus) ? title : null
+ const errorKind = getInsightErrorKind(titleStatus)
+ const canRetry = errorKind !== 'invalid_query' && errorKind !== 'permission'
+ const safeTitle = typeof title === 'string' && isRawServerErrorTitle(title, titleStatus) ? null : title
+ const displayTitle = getInsightErrorTitle(errorKind, safeTitle, titleStatus)
+ const isExport = placement === DashboardPlacement.Export
+ const showBugReport = !isExport && (errorKind === 'transient' || errorKind === 'server' || errorKind === 'unknown')
+ const remediation = getInsightErrorRemediation(errorKind, retryAfter)
const { preflight } = useValues(preflightLogic)
const { openSupportForm } = useActions(supportLogic)
@@ -742,63 +854,47 @@ export function InsightErrorState({
If this persists, submit a bug report.
</Link>
)
+ const showErrorIcon = errorKind === 'transient' || errorKind === 'server' || errorKind === 'unknown'
return (
<div
data-attr="insight-empty-state"
- className="flex flex-col items-center gap-2 justify-center rounded px-4 py-6 h-full w-full"
+ className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 rounded px-4 py-6 w-full text-center"
>
- <IconErrorOutline className="text-4xl shrink-0 text-danger" />
+ {showErrorIcon ? (
+ <IconErrorOutline className="text-4xl shrink-0 text-danger mb-2" />
+ ) : (
+ <InsightErrorHoggie kind={errorKind} />
+ )}
<h2 className="text-xl text-danger leading-tight mb-6" data-attr="insight-loading-too-long">
{/* Note that this default phrasing signals the issue is intermittent, */}
{/* and that perhaps the query will complete on retry */}
- {!rawServerError && title ? title : <span>There was a problem completing this query</span>}
+ {displayTitle}
</h2>
- {rawServerError && (
- <LemonCollapse
- className="max-w-160 w-full"
- size="small"
- panels={[
- {
- key: 'error-details',
- header: 'Error details',
- content: (
- // Capped height: in fixed-height hosts (dashboard tiles), an uncapped
- // trace would push the collapse toggle out of the scrollable area
- <CodeSnippet wrap thing="error details" className="max-h-80 overflow-y-auto">
- {rawServerError}
- </CodeSnippet>
- ),
- },
- ]}
- />
- )}
-
- {!excludeDetail && !supportOnly && (
+ {!supportOnly && (
<div className="mt-4">
- We apologize for this unexpected situation. There are a couple of things you can do:
- <ol>
- <li>
- First and foremost you can <b>try again</b>. We recommend you wait a moment before doing so.
- </li>
- <li>{bugReportLink}</li>
- </ol>
+ {remediation && <p>{remediation}</p>}
+ {!excludeDetail && showBugReport && <p>{bugReportLink}</p>}
</div>
)}
{/* Outside the excludeDetail gate: self-hosted sets excludeDetail=true, but
supportOnly still needs the bug-report path or it dead-ends. */}
- {supportOnly && <div className="mt-4">{bugReportLink}</div>}
+ {supportOnly && !isExport && <div className="mt-4">{bugReportLink}</div>}
- {!excludeActions && (
+ {!excludeActions && errorKind !== 'permission' && (
<div className="flex gap-2 mt-4">
- {onRetry ? <RetryButton onRetry={onRetry} query={query} /> : <QueryDebuggerButton query={query} />}
+ {onRetry && canRetry ? (
+ <RetryButton onRetry={onRetry} query={query} loading={retryLoading} />
+ ) : (
+ <QueryDebuggerButton query={query} />
+ )}
{fixWithAIComponent ?? null}
</div>
)}
- <QueryIdDisplay queryId={queryId} />
+ {!isExport && <QueryIdDisplay queryId={queryId} />}
</div>
)
}
diff --git a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
index 10c5596f16da..539faa651d28 100644
--- a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
@@ -1,10 +1,11 @@
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { cleanup, render, screen } from '@testing-library/react'
import posthog from 'posthog-js'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { DashboardPlacement } from '~/types'
import { InsightErrorState, InsightValidationError, isRawServerErrorTitle } from './EmptyStates'
@@ -23,7 +24,7 @@ describe('insight error states', () => {
})
it('reports "insight error message shown" when a validation error renders', () => {
- render(
+ const { container } = render(
<InsightValidationError
detail="Funnels require at least two steps."
validationErrorCode="funnels_require_at_least_two_steps"
@@ -33,6 +34,11 @@ describe('insight error states', () => {
const shownCalls = captureSpy.mock.calls.filter((call) => call[0] === 'insight error message shown')
expect(shownCalls).toHaveLength(1)
+ expect(
+ container.querySelector('[data-attr="insight-loading-too-long"]')?.classList.contains('text-danger')
+ ).toBe(true)
+ expect(screen.getByText('Open the query debugger and correct the query.')).toBeTruthy()
+ expect(screen.getByText('Open in query debugger')).toBeTruthy()
// Exact match: raw error detail must stay out of telemetry
expect(shownCalls[0][1]).toEqual({
error_type: 'validation',
@@ -53,6 +59,21 @@ describe('insight error states', () => {
})
})
+ it('replaces generic invalid-query detail with a next step', () => {
+ render(
+ <InsightValidationError
+ detail="The query is invalid."
+ validationErrorCode="invalid_query"
+ query={{ kind: 'InsightVizNode' }}
+ />
+ )
+
+ expect(screen.getByText('Check the query for errors, then run it again.')).toBeTruthy()
+ expect(screen.queryByText('The query is invalid.')).toBeNull()
+ expect(screen.queryByText('Open the query debugger and correct the query.')).toBeNull()
+ expect(screen.getByText('Open in query debugger')).toBeTruthy()
+ })
+
// The retry button only offers a side action (query debugger link) when it has a query. Without
// one, `sideAction` must stay undefined so LemonButton doesn't render a stray empty side action.
it.each([
@@ -88,24 +109,94 @@ describe('insight error states', () => {
{ title: 'Code: 241. DB::Exception: Memory limit exceeded. Stack trace:\n0.', status: 400, raw: true },
// Non-validation statuses mean a server-side failure whose text is not meant for the heading
{ title: 'ClickHouse error while executing query.', status: 500, raw: true },
+ { title: 'You do not have permission to run this query.', status: 403, raw: false },
{ title: 'The query was cancelled', status: undefined, raw: false },
{ title: 'This project has no events yet', status: undefined, raw: false },
])('classifies "$title" (status: $status) as raw=$raw', ({ title, status, raw }) => {
expect(isRawServerErrorTitle(title, status)).toBe(raw)
})
- it('keeps a raw ClickHouse error out of the heading but reachable in the details panel', () => {
+ it('does not expose raw ClickHouse errors', () => {
const clickhouseError =
'Code: 47. DB::Exception: Not found column mat_$survey_submission_id. Stack trace:\n0. DB::Exception::Exception()'
const { container } = render(<InsightErrorState title={clickhouseError} onRetry={() => {}} />)
const heading = container.querySelector('[data-attr="insight-loading-too-long"]')
expect(heading?.textContent).toBe('There was a problem completing this query')
- // The raw error stays hidden until the user opens the details panel.
expect(screen.queryByText(/DB::Exception/)).toBeNull()
+ expect(screen.getByText(/Try again in a moment/)).toBeTruthy()
+ })
+
+ it.each([
+ { status: 429, expectedCopy: 'Try again in 2 minutes.', retry: true },
+ { status: 400, expectedCopy: 'Open the query debugger and correct the query.', retry: false },
+ {
+ status: 403,
+ expectedCopy: 'Ask a project admin to grant you access to this insight.',
+ retry: false,
+ queryDebugger: false,
+ bugReport: false,
+ },
+ { status: 503, expectedCopy: 'Try again in a moment.', retry: true, queryDebugger: false, bugReport: true },
+ ])(
+ 'shows the correct action for HTTP $status errors',
+ ({ status, expectedCopy, retry, queryDebugger = !retry, bugReport = false }) => {
+ preflightLogic.actions.loadPreflightSuccess({ cloud: true } as any)
+
+ const { container } = render(
+ <InsightErrorState
+ title="The query failed."
+ titleStatus={status}
+ retryAfter={status === 429 ? 'in 2 minutes' : undefined}
+ query={{ kind: 'InsightVizNode' }}
+ onRetry={() => {}}
+ />
+ )
+
+ expect(screen.getByText(expectedCopy)).toBeTruthy()
+ expect(container.querySelector('[data-attr="insight-retry-button"]') !== null).toBe(retry)
+ expect(screen.queryByText('Open in query debugger') !== null).toBe(queryDebugger)
+ expect(screen.queryByText('If this persists, submit a bug report.') !== null).toBe(bugReport)
+ }
+ )
+
+ it('uses user-facing copy for invalid query errors', () => {
+ render(<InsightErrorState title="This query is invalid" titleStatus={400} query={{ kind: 'InsightVizNode' }} />)
+
+ expect(screen.getByText("We couldn't run this query")).toBeTruthy()
+ expect(screen.queryByText('This query is invalid')).toBeNull()
+ })
+
+ it.each([
+ { status: 503, expectedTitle: "This query couldn't run right now" },
+ { status: 500, expectedTitle: "PostHog couldn't complete this query" },
+ { status: 418, expectedTitle: "We couldn't complete this query" },
+ ])('uses clear copy for server error $status', ({ status, expectedTitle }) => {
+ render(<InsightErrorState title="Internal server error" titleStatus={status} />)
+
+ expect(screen.getByText(expectedTitle)).toBeTruthy()
+ expect(screen.queryByText('Internal server error')).toBeNull()
+ })
+
+ it('preserves custom titles when the status is unknown', () => {
+ render(<InsightErrorState title="Failed to load this data." />)
- fireEvent.click(screen.getByText('Error details'))
- expect(screen.getByText(/DB::Exception/)).toBeTruthy()
+ expect(screen.getByText('Failed to load this data.')).toBeTruthy()
+ expect(screen.queryByText("We couldn't complete this query")).toBeNull()
+ })
+
+ it('preserves JSX titles when the status is unknown', () => {
+ render(<InsightErrorState title={<pre data-attr="error-details">Query failed</pre>} />)
+
+ expect(screen.getByTestId('error-details')).toBeTruthy()
+ expect(screen.queryByText("We couldn't complete this query")).toBeNull()
+ })
+
+ it.each([500, 503, 418])('shows an error icon instead of a mascot for server failure %s', (status) => {
+ const { container } = render(<InsightErrorState title="Internal server error" titleStatus={status} />)
+
+ expect(container.querySelector('svg.text-danger')).not.toBeNull()
+ expect(container.querySelector('img')).toBeNull()
})
it('shows support without retry guidance for persistent errors', () => {
@@ -116,4 +207,26 @@ describe('insight error states', () => {
expect(screen.getByText('If this persists, submit a bug report.')).toBeTruthy()
expect(screen.queryByText(/try again/i)).toBeNull()
})
+
+ it('hides support links and query IDs in exported errors', () => {
+ render(
+ <InsightErrorState
+ title="There was a server problem."
+ titleStatus={500}
+ queryId="export-query-id"
+ placement={DashboardPlacement.Export}
+ />
+ )
+
+ expect(screen.queryByText('If this persists, submit a bug report.')).toBeNull()
+ expect(screen.queryByText(/export-query-id/)).toBeNull()
+ })
+
+ it('keeps the next step visible when error details are excluded', () => {
+ render(
+ <InsightErrorState title="You do not have permission to run this query." titleStatus={403} excludeDetail />
+ )
+
+ expect(screen.getByText('Ask a project admin to grant you access to this insight.')).toBeTruthy()
+ })
})