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): show errors for unserialized tiles (#72389)

Matt Pua860030ca5384
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 221f6a7be26c..7e145371a3c1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -125,13 +125,13 @@ snapshots:
components-cards-insight-card--access-control-manager-access--light:
hash: v1.k794b7964.ce90a8d28a7c96d6906f3dfc923a72170b34ae1f86bcff632ef293f8b486e10a.oC_u_-gOLmHCxg6nutx9wXeZ4rJbmDfkzKvJ4CkqlsA
components-cards-insight-card--access-control-mixed-permissions--dark:
- hash: v1.k794b7964.ec40f4f4b9d63fa0348a62f350eb17a98552b98a0529357a3044cb23c3ccd538.XNuAyCNAAJRCVNbp_uhtxIIYMkAHp7wphVA9n10-h1E
+ hash: v1.k794b7964.0ad7d3ec24b9c3e13c8d802b01c8ad0ba108562b9d4e092de17045f1f9ff4b4b.CGIvmKTI165JBGIrTrVro07k_yymhmwANP_9W02i3jI
components-cards-insight-card--access-control-mixed-permissions--light:
- hash: v1.k794b7964.a41413b39e5f0734544b5ac649723b2e2c2d39f9d9506872b2e5cb0d28716be9.e2IrHFsMyjjq1iks5oLk68pNZ9u0SFCLRrvej1Ok9Mo
+ hash: v1.k794b7964.7eb6be464885ad467901414d14f6e4a8cc4d6b5cedf65bf4cee144ffcf1bf4e0.rnbXasygMxS8Il_ErU2lhH5UbymU7OAkm8vTrmmOOA4
components-cards-insight-card--access-control-no-access--dark:
- hash: v1.k794b7964.f6f28bb570a00daeab77829db57d01e81916eab508812a58a591e7b80d9b7b38.xEfUn7QLkpze4Q36ko7BBbyupxpuvTwJg1aHxreqTzc
+ hash: v1.k794b7964.47bb3da98257e9aa61e23820a5489e300f2af0813eb141087d2087b14ef4672f.-BZqYVPHvUapBQsZaRqM8KSxjEhZvYWoJ7eJMiL_3ok
components-cards-insight-card--access-control-no-access--light:
- hash: v1.k794b7964.4f63fb1dca0d5e849ad7ea4f1cd7b6a62c14cd10a583be4a9aebdeebabf80867.ORfPzEHvcNrwhBODrQbahR6xceZ4nvZbJaYZSRqSvW4
+ hash: v1.k794b7964.e4d6488b9989fb98f443da019928efaf5ea1caae7f4766aaffbe154615d6bc28.XekZijWH1UI7oxoF6iSe4h4NyMWaNAUiULAVicIduy0
components-cards-insight-card--access-control-viewer-access--dark:
hash: v1.k794b7964.1cddc011d06bb494edfe593774c44d9dfe1ced0e4b9f05bb63828ee30e33876f.PJKPvo-nSQuD0axkzJHmVWHsCK_vt0kvZFjVq2BEIuI
components-cards-insight-card--access-control-viewer-access--light:
@@ -5517,15 +5517,15 @@ snapshots:
scenes-app-dashboards--access-control-dashboard--dark:
hash: v1.k794b7964.11fd596aad9a5ed51c4486b64828e1416573b34c63a10b2ed37b08d25da48d91.jj69suHKiPBYs2VMR83Q_FMRnb4Pg7C4lU0Pra6VdYE
scenes-app-dashboards--access-control-dashboard--light:
- hash: v1.k794b7964.a29a85daeff98faa6ea496a8485323ea965ee6fce98e2f1f67a032cd7bd38f31.VIhetTOlL6LTRVS-ALs4f7DOMCWcDomR7fgQAlRZUvo
+ hash: v1.k794b7964.f4626c33df21d437b98ded1f174ad026eb0720eabc60409240faaed5aa0a5868.RLJrAHUy5YKmQr8FWngDI0xC1SxQmC2uekjwqCb7naQ
scenes-app-dashboards--edit--dark:
hash: v1.k794b7964.b85e622d121e2edfb031fec73921ba7d775a50124f5d68c8c82ad28a51985434.eFMlXYTQdWLdvwn7YobjvgCNrFbx2IMXMt2Lzs0yyo4
scenes-app-dashboards--edit--light:
hash: v1.k794b7964.49c4e9690bd77d8c7a66dea80d23618e98cfbb1092f918bc47d7518de0bd4cad.2kla497MZylrcqwodI1R5fGyLuRQwKmuaXviNn4gVi0
scenes-app-dashboards--erroring--dark:
- hash: v1.k794b7964.a356bf2ce40e53018919ebc890579c0ad6e493385f546d26b1f70471bf99f726.UER3Vv5UUZ1POzJv4_TuxrLBcLfLa8WTZ_hyUX9t72s
+ hash: v1.k794b7964.f1569b95b37fd696ca93e1a429e100488d36b5283e843ba53e94a1dd0237a2c2.89VlumysxOVYUehHA-D-pwFe8LVtLhMbrjf13VAskKY
scenes-app-dashboards--erroring--light:
- hash: v1.k794b7964.5b99ae7b5f3126b06df72ccc0388ac72f1638137bb78cabeb47e9b597deb4dfc.FGPopoAtkZvSgIq_4yhg85qh1yBD3WbPV2uxNT_oK3s
+ hash: v1.k794b7964.1679f49acc091fc932acd5aee0d19e379c6f5158aefea7edb399f9b0d5a6fc71.F46jqKuhhvYhXv4E9pFTt13CpvLyaNv5AJy0pqSt81Y
scenes-app-dashboards--list--dark:
hash: v1.k794b7964.77a682a12b54c824f2105d0209088c4830b950deba55fa6c63f3d1a7ae6b12d9.GPMpy6SAAlg3ijRxYAR-Ekpum8USxQdWhP7-H8qLCx8
scenes-app-dashboards--list--light:
@@ -6239,13 +6239,13 @@ snapshots:
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
+ hash: v1.k794b7964.5e0a4f13fb00ef944649228004095f84fd1d859bd66cdd5ec9e25bd745d6828d.k4NYuOAkHqlOwwSIUSHJiywF8FxVwqlIbahs9NdgpF4
scenes-app-insights-error-empty-states--query-server-error--light:
- hash: v1.k794b7964.4fd0ad961c340f6a29de2b3026e4359724a2760a6c116dbb44084141d4312583.E7-256CCFJuc8LtP4L3NXFwms9PNH3aYu6c36e1OIzE
+ hash: v1.k794b7964.2b569e38b9188a1b6651645db04fc1861a1fbca67c8a36c59a717d949b3e9cb6.6wC07yLeoObvqkr-b3JIDgOLa-iqmpa8aO-eLLzWoEw
scenes-app-insights-error-empty-states--server-error--dark:
- hash: v1.k794b7964.256531339cd2dcd1bc37e23faa2ed005422f6a96d0f5ce68e032c5a5add4a24e.Izm9NrjX1PPmPZ0d0Cp_xzToZV_1DvVuIq51nxvJqsw
+ hash: v1.k794b7964.d4fc60a8e2dcacd414609ab296220b7d67381644f361e874c89790ad0166ac72.AvZwp_QBR6TzTD2jw9dj4M96gEsNdZ05GpMMfFp9RjQ
scenes-app-insights-error-empty-states--server-error--light:
- hash: v1.k794b7964.1680374542e6c9dee3cedcaa28bdd0cb4797a74d7c836b27b6aee6bb4c968547.3hC0bm_bygQVOuMig0V_O8uB-pM3FCBCSLsiLYDroB8
+ hash: v1.k794b7964.35ed59d2bdcc52c93c986a480bcc36b51913b32c3833fb5b5a16ca1ac3bb3e79.mJrsY5F5nRZ_wO8D937ymEISXRwiSmZpf0ImwObTMy8
scenes-app-insights-error-empty-states--validation-error--dark:
hash: v1.k794b7964.855cdd3fac12fc2645b90ff17a8e0150f3cd4e4b646e92b9266e5261459d0d07.yF2PxdOOktpjWsHaPmDXsmLxgz5S3nhheVXgr1Xt1V0
scenes-app-insights-error-empty-states--validation-error--light:
@@ -6603,9 +6603,9 @@ snapshots:
scenes-app-persons-modal--empty--light:
hash: v1.k794b7964.e7f63b65e183d7a65841e8621119799e6a3317e6d33ec71e275c37feedc64225.ANIbBo0qPwf94oVE6MiAcHrmZTqVLcUvl7BNCHsOK2M
scenes-app-persons-modal--server-error--dark:
- hash: v1.k794b7964.af827bbb249790f1a4abcab442aaca303a295cfea82a2787b3d0471af2941e23.KKctp_ROwRfRaBzm9yFjesb9Z7COKD0ygXR4hzm7XYE
+ hash: v1.k794b7964.adbc0f850ac3b8d770822f3a8a23cb14571fd05b7e8916c86eb2fc83409a3bc1.t7p0f-izSULBarHON3lHkXfQ-udGw-hOaKV9LG8BjbM
scenes-app-persons-modal--server-error--light:
- hash: v1.k794b7964.6e730c78790d1b50fc6a4433f5c2f25321ac495dad50f8de2f4bb295cafeb086.Ns6H3VZ3H6z6LOm9jnmre4pJ2NGczjI-WBPXgQ_1Jpg
+ hash: v1.k794b7964.5eec6a4ffa8c66493451b3b0883f29a5ea967e5abfc6d8602af1a911deca978f.Isc_OUoaPkM9XmzSEnT6_GGfw_5iIF5Mcp6vWoE6da4
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:
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 9952d5adc6ce..683f02929e8e 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -370,7 +370,8 @@ function InsightCardInternal(
/>
)
} else if (apiError instanceof ApiError) {
- return <InsightErrorState title={apiError?.detail} />
+ const isDashboardTileError = apiError.code === 'dashboard_tile_error'
+ return <InsightErrorState title={apiError.detail} supportOnly={isDashboardTileError} />
}
return <InsightErrorState />
}
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 62f5f90e0cf9..422e455360d8 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { render } from '@testing-library/react'
+import { fireEvent, render } from '@testing-library/react'
import { useActions, useAsyncActions, useValues } from 'kea'
import { router } from 'kea-router'
@@ -61,6 +61,14 @@ jest.mock('scenes/surveys/utils/opportunityDetection', () => ({
getBestSurveyOpportunityFunnel: () => null,
}))
+jest.mock('scenes/insights/EmptyStates', () => ({
+ InsightErrorState: ({ title, supportOnly }: { title: string; supportOnly?: boolean }) => (
+ <div data-attr="insight-error-state" data-support-only={supportOnly ? 'true' : undefined}>
+ {title}
+ </div>
+ ),
+}))
+
jest.mock('~/exporter/exporterViewLogic', () => ({
getCurrentExporterData: () => null,
}))
@@ -74,11 +82,25 @@ jest.mock('scenes/urls', () => ({
}))
jest.mock('lib/components/Cards/InsightCard', () => ({
- InsightCard: ({ tile, showResizeHandles }: { tile: { id: number }; showResizeHandles: boolean }) => (
+ InsightCard: ({
+ tile,
+ showResizeHandles,
+ apiErrored,
+ apiError,
+ }: {
+ 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}
/>
),
}))
@@ -142,6 +164,7 @@ jest.mock('@posthog/products-dashboards/frontend/components/DashboardWidgetItem/
const mockedUseValues = useValues as jest.Mock
const mockedUseActions = useActions as jest.Mock
const mockedUseAsyncActions = useAsyncActions as jest.Mock
+const mockRemoveTile = jest.fn()
describe('DashboardItems', () => {
beforeEach(() => {
@@ -194,7 +217,7 @@ describe('DashboardItems', () => {
updateContainerWidth: jest.fn(),
updateTileColor: jest.fn(),
toggleTileDescription: jest.fn(),
- removeTile: jest.fn(),
+ removeTile: mockRemoveTile,
duplicateTile: jest.fn(),
refreshDashboardItem: jest.fn(),
refreshDashboardWidgets: jest.fn(),
@@ -285,4 +308,100 @@ describe('DashboardItems', () => {
const { getByTestId } = render(<DashboardItems />)
expect(getByTestId('widget-card')).toBeInTheDocument()
})
+
+ it('shows an actionable error card when a streamed tile fails before its insight is serialized', async () => {
+ const errorTile = { id: 2, error: { type: 'ValidationError', message: 'Invalid filters' } }
+ mockedUseValues.mockImplementation((logic) => {
+ if (logic === dashboardLogic) {
+ return {
+ dashboard: { id: 5 },
+ tiles: [errorTile],
+ layouts: { sm: [{ i: '2', x: 0, y: 0, w: 6, h: 5 }] },
+ dashboardMode: null,
+ placement: DashboardPlacement.Dashboard,
+ isRefreshingQueued: () => false,
+ isRefreshing: () => false,
+ highlightedInsightId: null,
+ refreshStatus: {},
+ dashboardStreaming: false,
+ effectiveEditBarFilters: {},
+ effectiveDashboardVariableOverrides: {},
+ temporaryBreakdownColors: [],
+ dataColorThemeId: null,
+ canEditDashboard: true,
+ layoutZoom: 1,
+ dashboardWidgetsEnabled: true,
+ widgetResultsByTileId: {},
+ widgetRefreshStatus: {},
+ }
+ }
+
+ if (logic === dashboardsModel) {
+ return { nameSortedDashboards: [] }
+ }
+
+ return {}
+ })
+
+ 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'
+ )
+
+ fireEvent.click(getByTestId('more-button'))
+ fireEvent.click(await findByText('Remove from dashboard'))
+ expect(mockRemoveTile).toHaveBeenCalledWith(errorTile)
+ })
+
+ it('treats a streamed tile error with insight metadata as a server failure', () => {
+ const errorTile = {
+ id: 2,
+ insight: { id: 101, short_id: 'abc123', query: { kind: 'InsightVizNode' } },
+ error: {
+ type: 'DashboardTileError',
+ message: 'There is a problem loading this dashboard tile.',
+ },
+ }
+ mockedUseValues.mockImplementation((logic) => {
+ if (logic === dashboardLogic) {
+ return {
+ dashboard: { id: 5 },
+ tiles: [errorTile],
+ layouts: { sm: [{ i: '2', x: 0, y: 0, w: 6, h: 5 }] },
+ dashboardMode: null,
+ placement: DashboardPlacement.Dashboard,
+ isRefreshingQueued: () => false,
+ isRefreshing: () => false,
+ highlightedInsightId: null,
+ refreshStatus: {},
+ dashboardStreaming: false,
+ effectiveEditBarFilters: {},
+ effectiveDashboardVariableOverrides: {},
+ temporaryBreakdownColors: [],
+ dataColorThemeId: null,
+ canEditDashboard: true,
+ layoutZoom: 1,
+ dashboardWidgetsEnabled: true,
+ widgetResultsByTileId: {},
+ widgetRefreshStatus: {},
+ }
+ }
+
+ if (logic === dashboardsModel) {
+ return { nameSortedDashboards: [] }
+ }
+
+ return {}
+ })
+
+ const { container } = render(<DashboardItems />)
+ const insightCard = container.querySelector('[data-attr="insight-card"]')
+
+ expect(insightCard).toHaveAttribute('data-api-errored', 'true')
+ expect(insightCard).toHaveAttribute('data-api-error-status', '500')
+ expect(insightCard).toHaveAttribute('data-api-error-code', 'dashboard_tile_error')
+ expect(insightCard).toHaveAttribute('data-api-error-detail', 'There is a problem loading this dashboard tile.')
+ })
})
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index b42274dca7fb..12e1ec232a72 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -10,6 +10,7 @@ import { GridBackground } from 'react-grid-layout/extras'
import { DashboardWidgetItem } from '@posthog/products-dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem'
import { getDashboardWidgetFetchDisplayError } from '@posthog/products-dashboards/frontend/widgets/constants'
+import { ApiError } from 'lib/api'
import { InsightCard } from 'lib/components/Cards/InsightCard'
import { EditModeEdge } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
@@ -31,6 +32,7 @@ import { insightsModel } from '~/models/insightsModel'
import { DashboardLayoutSize, DashboardMode, DashboardPlacement, DashboardType } from '~/types'
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
+import { DashboardErrorTileItem } from './items/DashboardErrorTileItem'
import { DashboardTextItem } from './items/DashboardTextItem'
const DRAG_AUTO_SCROLL_THRESHOLD = 100
@@ -65,6 +67,7 @@ const MemoizedDashboardButtonTileItem = memo(
DashboardButtonTileItem,
gridTilePropsEqual
) as typeof DashboardButtonTileItem
+const MemoizedDashboardErrorTileItem = memo(DashboardErrorTileItem, gridTilePropsEqual) as typeof DashboardErrorTileItem
const MemoizedDashboardWidgetItem = memo(DashboardWidgetItem, gridTilePropsEqual) as typeof DashboardWidgetItem
export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsProps = {}): JSX.Element {
@@ -525,12 +528,30 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
removeFromDashboard: () => removeTile(tile),
}
+ if (tile.error && !insight) {
+ return (
+ <MemoizedDashboardErrorTileItem
+ key={tile.id}
+ tile={tile}
+ onRemove={commonTileProps.removeFromDashboard}
+ showResizeHandles={showResizeHandles}
+ canEnterEditModeFromEdge={canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={onEnterEditModeFromEdge}
+ onDragHandleMouseDown={onDragHandleMouseDown}
+ showEditingControls={showEditingControls}
+ />
+ )
+ }
+
if (insight) {
// Check if this insight has an error from the server
const isErrorTile = !!tile.error
const apiErrored = isErrorTile || refreshStatus[insight.short_id]?.errored || false
const apiError = isErrorTile
- ? ({ status: 400, detail: `${tile.error!.type}: ${tile.error!.message}` } as any)
+ ? new ApiError(undefined, 500, undefined, {
+ detail: tile.error!.message,
+ code: 'dashboard_tile_error',
+ })
: refreshStatus[insight.short_id]?.error
const loadingQueued = isErrorTile ? false : isRefreshingQueued(insight.short_id)
const loading = isErrorTile ? false : isRefreshing(insight.short_id)
diff --git a/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx b/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx
new file mode 100644
index 000000000000..8d597062c264
--- /dev/null
+++ b/frontend/src/scenes/dashboard/items/DashboardErrorTileItem.tsx
@@ -0,0 +1,69 @@
+import clsx from 'clsx'
+import React from 'react'
+
+import { CardMeta, Resizeable } from 'lib/components/Cards/CardMeta'
+import { DashboardResizeHandles } from 'lib/components/Cards/handles'
+import { EditModeEdge, EditModeEdgeOverlay } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { InsightErrorState } from 'scenes/insights/EmptyStates'
+
+import { DashboardTile, QueryBasedInsightModel } from '~/types'
+
+import { getDashboardTileDisplayName } from '../dashboardUtils'
+
+interface DashboardErrorTileItemProps extends React.HTMLAttributes<HTMLDivElement>, Resizeable {
+ tile: DashboardTile<QueryBasedInsightModel>
+ canEnterEditModeFromEdge?: boolean
+ onEnterEditModeFromEdge?: (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => void
+ onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
+ onRemove?: () => void
+ showEditingControls?: boolean
+}
+
+function DashboardErrorTileItemInternal(
+ {
+ tile,
+ canEnterEditModeFromEdge,
+ children,
+ className,
+ onDragHandleMouseDown,
+ onEnterEditModeFromEdge,
+ onRemove,
+ showEditingControls,
+ showResizeHandles,
+ ...divProps
+ }: DashboardErrorTileItemProps,
+ ref: React.ForwardedRef<HTMLDivElement>
+): JSX.Element {
+ return (
+ <div
+ className={clsx('DashboardTileCard InsightCard border', className)}
+ data-attr="dashboard-tile-error"
+ ref={ref}
+ {...divProps}
+ >
+ <CardMeta
+ topHeading={<span>{getDashboardTileDisplayName(tile)}</span>}
+ showEditingControls={showEditingControls}
+ onMouseDown={onDragHandleMouseDown}
+ moreButtons={
+ onRemove ? (
+ <LemonButton status="danger" onClick={onRemove} fullWidth>
+ Remove from dashboard
+ </LemonButton>
+ ) : undefined
+ }
+ />
+ <InsightErrorState title="There is a problem loading this dashboard tile." supportOnly />
+ {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
+ <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
+ )}
+ {showResizeHandles && <DashboardResizeHandles />}
+ {children}
+ </div>
+ )
+}
+
+export const DashboardErrorTileItem = React.forwardRef<HTMLDivElement, DashboardErrorTileItemProps>(
+ DashboardErrorTileItemInternal
+)
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 0d8988e860e4..a1c7cee55c2f 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -646,6 +646,7 @@ export interface InsightErrorStateProps {
queryId?: string | null
excludeDetail?: boolean
excludeActions?: boolean
+ supportOnly?: boolean
fixWithAIComponent?: JSX.Element
onRetry?: () => void
}
@@ -656,6 +657,7 @@ export function InsightErrorState({
queryId,
excludeDetail = false,
excludeActions = false,
+ supportOnly = false,
fixWithAIComponent,
onRetry,
}: InsightErrorStateProps): JSX.Element {
@@ -676,12 +678,27 @@ export function InsightErrorState({
excludeDetail = true // We don't provide support for self-hosted instances
}
+ if (supportOnly) {
+ excludeActions = true
+ }
+
+ const bugReportLink = (
+ <Link
+ data-attr="insight-error-bug-report"
+ onClick={() => {
+ openSupportForm({ kind: 'bug', target_area: 'analytics' })
+ }}
+ >
+ If this persists, submit a bug report.
+ </Link>
+ )
+
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"
>
- <IconErrorOutline className="text-5xl shrink-0" />
+ <IconErrorOutline className="text-4xl shrink-0 text-danger" />
<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, */}
@@ -689,27 +706,22 @@ export function InsightErrorState({
{title || <span>There was a problem completing this query</span>}
</h2>
- {!excludeDetail && (
+ {!excludeDetail && !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>
- <Link
- data-attr="insight-error-bug-report"
- onClick={() => {
- openSupportForm({ kind: 'bug', target_area: 'analytics' })
- }}
- >
- If this persists, submit a bug report.
- </Link>
- </li>
+ <li>{bugReportLink}</li>
</ol>
</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>}
+
{!excludeActions && (
<div className="flex gap-2 mt-4">
{onRetry ? <RetryButton onRetry={onRetry} query={query} /> : <QueryDebuggerButton query={query} />}
diff --git a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
index 12d7367400ec..1ba9d889c419 100644
--- a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
@@ -1,6 +1,8 @@
-import { cleanup, render } 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'
@@ -66,4 +68,13 @@ describe('insight error states', () => {
expect(container.querySelector('[data-attr="insight-retry-button"]')).not.toBeNull()
expect(container.querySelector('.LemonButtonWithSideAction') !== null).toBe(expectsSideAction)
})
+
+ it('shows support without retry guidance for persistent errors', () => {
+ preflightLogic.actions.loadPreflightSuccess({ cloud: true } as any)
+
+ render(<InsightErrorState title="There is a persistent problem." supportOnly />)
+
+ expect(screen.getByText('If this persists, submit a bug report.')).toBeTruthy()
+ expect(screen.queryByText(/try again/i)).toBeNull()
+ })
})
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 392e1e42d4a7..f7e8fea26142 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -34,14 +34,21 @@ from posthog.models.project import Project
from posthog.models.quick_filter import QuickFilter
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.signals import mute_selected_signals
+from posthog.rbac.user_access_control import UserAccessControl
from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from posthog.user_permissions import UserPermissions
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
from products.dashboards.backend.access import DashboardAccessMethod
-from products.dashboards.backend.api.dashboard import DashboardSerializer
+from products.dashboards.backend.api.dashboard import (
+ DashboardSerializer,
+ DashboardTileErrorSerializer,
+ serialize_tile_with_context,
+)
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text
+from products.product_analytics.backend.api.insight import InsightSerializer
from products.product_analytics.backend.models.insight import Insight
from products.product_analytics.backend.models.insight_variable import InsightVariable
@@ -1154,8 +1161,6 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
mock_request.user = self.user
# Create a proper user access control for the serializer
- from posthog.rbac.user_access_control import UserAccessControl
-
user_access_control = UserAccessControl(self.user, organization_id=str(self.user.current_organization_id))
dashboard_data = DashboardSerializer(
@@ -3382,6 +3387,228 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
self.assertEqual(regular_response["persisted_variables"], dashboard_variables)
self.assertEqual(sse_dashboard["persisted_variables"], dashboard_variables)
+ def test_streamed_tile_error_preserves_insight_metadata_without_exception_detail(self):
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ name="Test Dashboard",
+ created_by=self.user,
+ filters={},
+ )
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Browser usage",
+ filters={},
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ },
+ },
+ )
+ tile = DashboardTile.objects.create(
+ dashboard=dashboard,
+ insight=insight,
+ )
+
+ request = MagicMock()
+ request.user = self.user
+ request.query_params = {}
+ request.data = {}
+ context = {
+ "request": request,
+ "team_id": self.team.id,
+ "get_team": lambda: self.team,
+ "insight_variables": [],
+ "dashboard": dashboard,
+ "raw_results_supported": True,
+ "user_access_control": UserAccessControl(self.user, team=self.team),
+ }
+ with patch.object(InsightSerializer, "get_result", side_effect=RuntimeError("select secret_customer_property")):
+ order, streamed_tile = serialize_tile_with_context(tile, 0, context)
+
+ self.assertEqual(order, 0)
+
+ self.assertEqual(streamed_tile["id"], tile.id)
+ self.assertEqual(streamed_tile["insight"]["id"], insight.id)
+ self.assertEqual(streamed_tile["insight"]["name"], "Browser usage")
+ self.assertEqual(streamed_tile["insight"]["query"], insight.query)
+ self.assertEqual(
+ streamed_tile["error"],
+ {
+ "type": "DashboardTileError",
+ "message": "There is a problem loading this dashboard tile.",
+ },
+ )
+ self.assertNotIn("secret_customer_property", json.dumps(streamed_tile))
+
+ def test_streamed_tile_error_redacts_insight_metadata_for_restricted_user(self):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ restricted_user = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ name="Test Dashboard",
+ created_by=self.user,
+ filters={},
+ )
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Confidential usage",
+ filters={},
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ },
+ },
+ )
+ tile = DashboardTile.objects.create(
+ dashboard=dashboard,
+ insight=insight,
+ )
+ AccessControl.objects.create(resource="insight", resource_id=insight.id, team=self.team, access_level="none")
+
+ request = MagicMock()
+ request.user = restricted_user
+ request.query_params = {}
+ request.data = {}
+ context = {
+ "request": request,
+ "team_id": self.team.id,
+ "get_team": lambda: self.team,
+ "insight_variables": [],
+ "dashboard": dashboard,
+ "raw_results_supported": True,
+ "user_access_control": UserAccessControl(restricted_user, team=self.team),
+ }
+ with patch.object(InsightSerializer, "get_result", side_effect=RuntimeError("boom")):
+ order, streamed_tile = serialize_tile_with_context(tile, 0, context)
+
+ self.assertEqual(order, 0)
+ self.assertEqual(streamed_tile["error"]["type"], "DashboardTileError")
+
+ insight_payload = streamed_tile["insight"]
+ self.assertEqual(insight_payload["id"], insight.id)
+ self.assertEqual(insight_payload["short_id"], insight.short_id)
+ self.assertEqual(insight_payload["user_access_level"], "none")
+
+ self.assertNotIn("name", insight_payload)
+ self.assertNotIn("query", insight_payload)
+ self.assertNotIn("filters", insight_payload)
+
+ def test_non_streamed_dashboard_degrades_to_error_tile_on_insight_failure(self):
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ name="Test Dashboard",
+ created_by=self.user,
+ filters={},
+ )
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Browser usage",
+ filters={},
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ },
+ },
+ )
+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+
+ request = MagicMock()
+ request.user = self.user
+ request.query_params = {}
+ request.data = {}
+ user_permissions = UserPermissions(self.user, team=self.team)
+ mock_view = MagicMock()
+ mock_view.action = "retrieve"
+ mock_view.user_permissions = user_permissions
+ context = {
+ "request": request,
+ "view": mock_view,
+ "team_id": self.team.id,
+ "get_team": lambda: self.team,
+ "insight_variables": [],
+ "dashboard": dashboard,
+ "raw_results_supported": True,
+ "user_access_control": UserAccessControl(self.user, team=self.team),
+ "user_permissions": user_permissions,
+ }
+ with patch.object(InsightSerializer, "get_result", side_effect=RuntimeError("boom")):
+ dashboard_data = DashboardSerializer(dashboard, context=context).data
+
+ tiles = dashboard_data["tiles"]
+ self.assertEqual(len(tiles), 1)
+ failed_tile = tiles[0]
+ self.assertEqual(failed_tile["insight"]["id"], insight.id)
+ self.assertEqual(failed_tile["insight"]["name"], "Browser usage")
+ self.assertEqual(
+ failed_tile["error"],
+ {"type": "DashboardTileError", "message": "There is a problem loading this dashboard tile."},
+ )
+ self.assertNotIn("boom", json.dumps(dashboard_data))
+
+ def test_streamed_tile_error_falls_back_to_minimal_tile_when_fallback_serializer_fails(self):
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ name="Test Dashboard",
+ created_by=self.user,
+ filters={},
+ )
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Confidential usage",
+ filters={},
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview"}],
+ },
+ },
+ )
+ tile = DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+
+ request = MagicMock()
+ request.user = self.user
+ request.query_params = {}
+ request.data = {}
+ context = {
+ "request": request,
+ "team_id": self.team.id,
+ "get_team": lambda: self.team,
+ "insight_variables": [],
+ "dashboard": dashboard,
+ "raw_results_supported": True,
+ "user_access_control": UserAccessControl(self.user, team=self.team),
+ }
+ with (
+ patch.object(InsightSerializer, "get_result", side_effect=RuntimeError("primary boom")),
+ patch.object(
+ DashboardTileErrorSerializer,
+ "to_representation",
+ side_effect=RuntimeError("fallback boom"),
+ ),
+ ):
+ order, streamed_tile = serialize_tile_with_context(tile, 0, context)
+
+ self.assertEqual(order, 0)
+ self.assertEqual(streamed_tile["id"], tile.id)
+ self.assertEqual(
+ streamed_tile["error"],
+ {"type": "DashboardTileError", "message": "There is a problem loading this dashboard tile."},
+ )
+ self.assertNotIn("insight", streamed_tile)
+ self.assertNotIn("Confidential usage", json.dumps(streamed_tile))
+
def test_create_unlisted_dashboard_creates_tags(self):
"""Test that unlisted dashboards get tags"""
response = self.client.post(
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index d054e3b90979..20e21c0ec772 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -34,7 +34,6 @@ from django.shortcuts import get_object_or_404
from django.utils.timezone import now
import structlog
-import pydantic_core
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
@@ -77,7 +76,11 @@ from posthog.models.tagged_item import TaggedItem
from posthog.models.team import Team
from posthog.models.user import User
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlSerializerMixin
+from posthog.rbac.user_access_control import (
+ UserAccessControl,
+ UserAccessControlSerializerMixin,
+ access_level_satisfied_for_resource,
+)
from posthog.renderers import SafeJSONRenderer, ServerSentEventRenderer
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.session_recordings.session_recording_api import get_replay_listing_throttle_error
@@ -145,6 +148,7 @@ from products.notifications.backend.facade.api import (
from products.product_analytics.backend.api.insight import (
INCLUDE_DASHBOARDS_PARAMETER,
DashboardTileBasicSerializer,
+ InsightBasicSerializer,
InsightSerializer,
InsightViewSet,
_get_insight_type,
@@ -156,6 +160,10 @@ from ee.hogai.utils.aio import async_to_sync
logger = structlog.get_logger(__name__)
+DASHBOARD_TILE_ERROR_TYPE = "DashboardTileError"
+DASHBOARD_TILE_ERROR_MESSAGE = "There is a problem loading this dashboard tile."
+DASHBOARD_STREAM_ERROR_MESSAGE = "Dashboard tiles couldn't be loaded. Refresh the dashboard to try again."
+
DASHBOARD_SHARED_FIELDS = [
"id",
"name",
@@ -329,16 +337,18 @@ def serialize_tile_with_context(tile, order: int, context: dict) -> tuple[int, d
tile.layouts = json.loads(tile.layouts)
try:
- tile_data = DashboardTileSerializer(tile, many=False, context=tile_context).data
+ tile_data: dict = DashboardTileSerializer(tile, many=False, context=tile_context).data
return order, tile_data
- except pydantic_core.ValidationError as e:
+ except Exception:
if not tile.insight:
raise
- query = tile.insight.query
- tile.insight.query = None
- tile_data = DashboardTileSerializer(tile, context=tile_context).data
- tile_data["insight"]["query"] = query
- tile_data["error"] = {"type": type(e).__name__, "message": str(e)}
+ logger.exception("Error serializing dashboard tile", tile_id=tile.id)
+ try:
+ tile_data = DashboardTileErrorSerializer(tile, context=tile_context).data
+ except Exception:
+ logger.exception("Error serializing dashboard tile error fallback", tile_id=tile.id)
+ tile_data = {"id": tile.id}
+ tile_data["error"] = {"type": DASHBOARD_TILE_ERROR_TYPE, "message": DASHBOARD_TILE_ERROR_MESSAGE}
return order, tile_data
@@ -800,7 +810,7 @@ class SharedDashboardWidgetMetadataSerializer(serializers.ModelSerializer):
class DashboardTileSerializer(serializers.ModelSerializer):
id: serializers.IntegerField = serializers.IntegerField(required=False)
- insight = InsightSerializer()
+ insight: InsightBasicSerializer = InsightSerializer()
text = TextSerializer()
button_tile = ButtonTileSerializer()
widget = DashboardWidgetSerializer(required=False, allow_null=True)
@@ -839,6 +849,26 @@ class DashboardTileSerializer(serializers.ModelSerializer):
return representation
+class DashboardTileErrorSerializer(DashboardTileSerializer):
+ insight = InsightBasicSerializer()
+
+ def to_representation(self, instance: DashboardTile):
+ representation = super().to_representation(instance)
+
+ insight = instance.insight
+ if insight is not None and self.context.get("dashboard"):
+ insight_representation = representation.get("insight") or {}
+ user_access_level = insight_representation.get("user_access_level")
+ if user_access_level and not access_level_satisfied_for_resource("insight", user_access_level, "viewer"):
+ representation["insight"] = {
+ "id": insight.id,
+ "short_id": insight.short_id,
+ "user_access_level": user_access_level,
+ }
+
+ return representation
+
+
class InsightResultSerializer(InsightSerializer):
"""InsightSerializer restricted to identifiers + result only."""
@@ -2077,8 +2107,7 @@ class DashboardSerializer(DashboardMetadataSerializer):
try:
tile_data = reused_serializer.to_representation(tile)
- except pydantic_core.ValidationError:
- # Fall back to the fresh-serializer path, which handles the error shape
+ except Exception:
order, tile_data = serialize_tile_with_context(tile, order, self.context)
serialized_tiles.append(cast(ReturnDict, tile_data))
@@ -2445,13 +2474,13 @@ class DashboardsViewSet(
serialize_tile_with_context, thread_sensitive=True
)(tile, order, context)
initial_tiles.append(tile_data)
- except Exception as e:
- logger.exception(f"Error serializing initial tile {tile.id}: {e}")
+ except Exception:
+ logger.exception("Error serializing initial dashboard tile", tile_id=tile.id)
# Add error tile to initial tiles
initial_tiles.append(
{
"id": tile.id,
- "error": {"type": type(e).__name__, "message": str(e)},
+ "error": {"type": DASHBOARD_TILE_ERROR_TYPE, "message": DASHBOARD_TILE_ERROR_MESSAGE},
}
)
@@ -2469,18 +2498,32 @@ class DashboardsViewSet(
)(tile, order, context)
tile_json = renderer.render({"type": "tile", "order": order, "tile": tile_data}).decode()
yield f"data: {tile_json}\n\n".encode()
- except Exception as e:
- logger.exception(f"Error serializing tile {tile.id}: {e}")
- error_json = renderer.render({"type": "error", "tile_id": tile.id, "error": str(e)}).decode()
- yield f"data: {error_json}\n\n".encode()
+ except Exception:
+ # Tile-shaped, not {type:"error"}: the frontend's streamTiles routes
+ # {type:"error"} to onError (a transient toast) and drops the tile.
+ logger.exception("Error serializing dashboard tile", tile_id=tile.id)
+ error_tile_json = renderer.render(
+ {
+ "type": "tile",
+ "order": order,
+ "tile": {
+ "id": tile.id,
+ "error": {
+ "type": DASHBOARD_TILE_ERROR_TYPE,
+ "message": DASHBOARD_TILE_ERROR_MESSAGE,
+ },
+ },
+ }
+ ).decode()
+ yield f"data: {error_tile_json}\n\n".encode()
# Send completion signal
complete_json = renderer.render({"type": "complete"}).decode()
yield f"data: {complete_json}\n\n".encode()
- except Exception as e:
- logger.exception(f"Error in tile streaming: {e}")
- error_json = renderer.render({"type": "error", "error": str(e)}).decode()
+ except Exception:
+ logger.exception("Error streaming dashboard tiles")
+ error_json = renderer.render({"type": "error", "error": DASHBOARD_STREAM_ERROR_MESSAGE}).decode()
yield f"data: {error_json}\n\n".encode()
return sse_streaming_response(