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(max): keep open dashboard in Max context when an insight fails (#61414)

Vasco de Krijger72ee4362e9cd
diff --git a/ee/hogai/context/dashboard/context.py b/ee/hogai/context/dashboard/context.py
index 695f36cbeffb..3c070b2305ba 100644
--- a/ee/hogai/context/dashboard/context.py
+++ b/ee/hogai/context/dashboard/context.py
@@ -4,6 +4,7 @@ from typing import Generic
from pydantic import BaseModel
+from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from ee.hogai.context.insight.context import InsightContext
@@ -94,9 +95,10 @@ class DashboardContext:
insights="",
)
- # Run all insights in parallel with semaphore control
+ # return_exceptions=True keeps one failing insight from dropping the whole dashboard.
insight_tasks = [self._execute_insight_with_semaphore(insight) for insight in self.insights]
- insight_results = await asyncio.gather(*insight_tasks)
+ insight_results = await asyncio.gather(*insight_tasks, return_exceptions=True)
+ formatted_insights = self._resolve_insight_results(insight_results, "Error preparing insight context.")
return format_prompt_string(
prompt_template,
@@ -104,7 +106,7 @@ class DashboardContext:
dashboard_id=self.dashboard_id,
dashboard_url=self.dashboard_url,
description=self.description,
- insights="\n\n".join(insight_results),
+ insights="\n\n".join(formatted_insights),
)
async def format_schema(self, prompt_template: str = DASHBOARD_RESULT_TEMPLATE) -> str:
@@ -118,12 +120,12 @@ class DashboardContext:
description=self.description,
)
- insight_schemas = []
- for insight in self.insights:
- schema = await insight.format_schema()
- insight_schemas.append(schema)
-
- insights_text = "\n\n".join(insight_schemas) if insight_schemas else ""
+ # No semaphore (unlike execute_and_format): schema formatting runs no queries, so there's
+ # no DB load to bound. return_exceptions=True keeps one failure from dropping the dashboard.
+ schema_results = await asyncio.gather(
+ *(insight.format_schema() for insight in self.insights), return_exceptions=True
+ )
+ insight_schemas = self._resolve_insight_results(schema_results, "Error preparing insight schema.")
return format_prompt_string(
prompt_template,
@@ -132,9 +134,26 @@ class DashboardContext:
dashboard_id=self.dashboard_id,
dashboard_url=self.dashboard_url,
description=self.description,
- insights=insights_text,
+ insights="\n\n".join(insight_schemas),
)
+ def _resolve_insight_results(self, results: Sequence[str | BaseException], error_message: str) -> list[str]:
+ """Map gathered per-insight results to strings so one failure can't drop the dashboard.
+
+ Cancellation is re-raised (never swallowed); any other exception is captured and
+ replaced with a short placeholder.
+ """
+ formatted: list[str] = []
+ for insight, result in zip(self.insights, results):
+ if isinstance(result, asyncio.CancelledError):
+ raise result
+ if isinstance(result, BaseException):
+ capture_exception(result)
+ formatted.append(f'Insight "{insight.name or "Insight"}": {error_message}')
+ else:
+ formatted.append(result)
+ return formatted
+
async def _execute_insight_with_semaphore(self, insight: InsightContext) -> str:
"""Execute a single insight with semaphore control."""
async with self._semaphore:
diff --git a/ee/hogai/context/dashboard/test/test_context.py b/ee/hogai/context/dashboard/test/test_context.py
index 7c17f5097d72..34cdae6d0999 100644
--- a/ee/hogai/context/dashboard/test/test_context.py
+++ b/ee/hogai/context/dashboard/test/test_context.py
@@ -1,5 +1,7 @@
+import asyncio
+
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
from posthog.schema import EventsNode, TrendsQuery
@@ -173,16 +175,17 @@ class TestDashboardContext(BaseTest):
# Should NOT include results
self.assertNotIn("Results:", result)
- @patch("ee.hogai.context.insight.context.InsightContext.format_schema")
- async def test_format_schema_handles_exceptions(self, mock_format_schema):
- """Test that format_schema propagates exceptions in insight schema formatting"""
- mock_format_schema.side_effect = Exception("Schema error")
+ @patch("ee.hogai.context.dashboard.context.capture_exception")
+ @patch("ee.hogai.context.insight.context.InsightContext.format_schema", new_callable=AsyncMock)
+ async def test_format_schema_propagates_cancellation(self, mock_format_schema, mock_capture):
+ # Cancellation must propagate through the schema path too, never degrade or get captured.
+ mock_format_schema.side_effect = asyncio.CancelledError()
insights_data: list[DashboardInsightContext] = [
DashboardInsightContext(
query=TrendsQuery(series=[EventsNode(event="pageview")]),
- name="Failing Insight",
- insight_id="fail",
+ name="Cancelled Insight",
+ short_id="insight-1",
)
]
@@ -193,11 +196,10 @@ class TestDashboardContext(BaseTest):
dashboard_id="404",
)
- # Exception should propagate
- with self.assertRaises(Exception) as context:
+ with self.assertRaises(asyncio.CancelledError):
await dashboard_ctx.format_schema()
- self.assertIn("Schema error", str(context.exception))
+ mock_capture.assert_not_called()
async def test_dashboard_without_id(self):
"""Test that dashboard works without an ID"""
@@ -317,3 +319,104 @@ class TestDashboardContext(BaseTest):
self.assertIn("Custom: Custom Template Dashboard", result)
self.assertIn("Custom template result", result)
+
+ @patch("ee.hogai.context.dashboard.context.capture_exception")
+ @patch("ee.hogai.context.insight.context.InsightContext.execute_and_format", new_callable=AsyncMock)
+ async def test_one_failing_insight_does_not_drop_whole_dashboard(self, mock_execute_and_format, mock_capture):
+ """A single insight raising (e.g. a query-prep error outside InsightContext's own
+ try/except) must NOT drop the entire dashboard from context — the dashboard, its
+ surviving insights, and an error placeholder for the failed one should all remain."""
+ mock_execute_and_format.side_effect = [ValueError("boom"), "Insight results: 200 users"]
+
+ insights_data: list[DashboardInsightContext] = [
+ DashboardInsightContext(
+ query=TrendsQuery(series=[EventsNode(event="pageview")]),
+ name="Broken Insight",
+ short_id="insight-1",
+ ),
+ DashboardInsightContext(
+ query=TrendsQuery(series=[EventsNode(event="signup")]),
+ name="Working Insight",
+ short_id="insight-2",
+ ),
+ ]
+
+ dashboard_ctx = DashboardContext(
+ team=self.team,
+ insights_data=insights_data,
+ name="Mixed Dashboard",
+ dashboard_id="789",
+ )
+
+ result = await dashboard_ctx.execute_and_format()
+
+ # The dashboard itself and the working insight survive.
+ self.assertIn("Dashboard name: Mixed Dashboard", result)
+ self.assertIn("Insight results: 200 users", result)
+ # The failed insight degrades to a placeholder instead of taking down the dashboard.
+ self.assertIn("Broken Insight", result)
+ self.assertIn("Error preparing insight context", result)
+ # The failure is surfaced, not silently swallowed.
+ mock_capture.assert_called_once()
+
+ @patch("ee.hogai.context.dashboard.context.capture_exception")
+ @patch("ee.hogai.context.insight.context.InsightContext.execute_and_format", new_callable=AsyncMock)
+ async def test_cancelled_insight_propagates_and_is_not_captured(self, mock_execute_and_format, mock_capture):
+ # CancelledError must propagate (cooperative cancellation), never degrade to a placeholder
+ # or get captured — otherwise a cancelled task is silently turned into "an error occurred".
+ mock_execute_and_format.side_effect = asyncio.CancelledError()
+
+ insights_data: list[DashboardInsightContext] = [
+ DashboardInsightContext(
+ query=TrendsQuery(series=[EventsNode(event="pageview")]),
+ name="Cancelled Insight",
+ short_id="insight-1",
+ ),
+ ]
+
+ dashboard_ctx = DashboardContext(
+ team=self.team,
+ insights_data=insights_data,
+ name="Cancelled Dashboard",
+ dashboard_id="790",
+ )
+
+ with self.assertRaises(asyncio.CancelledError):
+ await dashboard_ctx.execute_and_format()
+
+ mock_capture.assert_not_called()
+
+ @patch("ee.hogai.context.dashboard.context.capture_exception")
+ @patch("ee.hogai.context.insight.context.InsightContext.format_schema", new_callable=AsyncMock)
+ async def test_one_failing_insight_schema_does_not_drop_whole_dashboard(self, mock_format_schema, mock_capture):
+ # format_schema shares the same degrade-or-reraise path as execute_and_format, so one
+ # failing schema must degrade to a placeholder rather than drop the whole dashboard.
+ mock_format_schema.side_effect = [ValueError("boom"), "Schema: signups by day"]
+
+ insights_data: list[DashboardInsightContext] = [
+ DashboardInsightContext(
+ query=TrendsQuery(series=[EventsNode(event="pageview")]),
+ name="Broken Insight",
+ short_id="insight-1",
+ ),
+ DashboardInsightContext(
+ query=TrendsQuery(series=[EventsNode(event="signup")]),
+ name="Working Insight",
+ short_id="insight-2",
+ ),
+ ]
+
+ dashboard_ctx = DashboardContext(
+ team=self.team,
+ insights_data=insights_data,
+ name="Mixed Dashboard",
+ dashboard_id="791",
+ )
+
+ result = await dashboard_ctx.format_schema()
+
+ self.assertIn("Mixed Dashboard", result)
+ self.assertIn("Schema: signups by day", result)
+ self.assertIn("Broken Insight", result)
+ self.assertIn("Error preparing insight schema", result)
+ mock_capture.assert_called_once()
diff --git a/ee/hogai/context/insight/format/test/test_utils.py b/ee/hogai/context/insight/format/test/test_utils.py
index 4aee64038cfa..3256e90f9f3d 100644
--- a/ee/hogai/context/insight/format/test/test_utils.py
+++ b/ee/hogai/context/insight/format/test/test_utils.py
@@ -49,6 +49,12 @@ class TestFormatUtils(BaseTest):
matrix = [["single", "row"]]
self.assertEqual(format_matrix(matrix), "single|row")
+ def test_format_matrix_coerces_none_and_non_string_cells(self):
+ # A None or non-string cell must not raise "sequence item N: expected str instance,
+ # NoneType found" and crash the whole insight/dashboard context build.
+ matrix = [["label", None, 42]]
+ self.assertEqual(format_matrix(matrix), "label||42")
+
def test_format_percentage(self):
self.assertEqual(format_percentage(0.5), "50%")
self.assertEqual(format_percentage(0.123), "12.3%")
diff --git a/ee/hogai/context/insight/format/utils.py b/ee/hogai/context/insight/format/utils.py
index c540302aa49f..a2db7b1bf23e 100644
--- a/ee/hogai/context/insight/format/utils.py
+++ b/ee/hogai/context/insight/format/utils.py
@@ -10,10 +10,11 @@ from posthog.hogql_queries.insights.utils.breakdowns import (
)
-def format_matrix(matrix: list[list[str]]) -> str:
+def format_matrix(matrix: list[list[Any]]) -> str:
+ # Coerce cells: a None (or non-str) cell would make "|".join raise and crash the build.
lines: list[str] = []
for row in matrix:
- lines.append("|".join(row))
+ lines.append("|".join("" if cell is None else str(cell) for cell in row))
return "\n".join(lines).strip()
diff --git a/frontend/src/scenes/max/maxContextLogic.test.ts b/frontend/src/scenes/max/maxContextLogic.test.ts
index 6b3cb15b71cb..ff4acaa67d2f 100644
--- a/frontend/src/scenes/max/maxContextLogic.test.ts
+++ b/frontend/src/scenes/max/maxContextLogic.test.ts
@@ -1,11 +1,13 @@
import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
+import posthog from 'posthog-js'
import '@posthog/icons'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
+import { sceneLogic } from 'scenes/sceneLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -19,7 +21,9 @@ import {
} from '~/types'
import { maxContextLogic } from './maxContextLogic'
+import { createMaxContextHelpers } from './maxTypes'
import { maxMocks } from './testUtils'
+import { dashboardToMaxContext } from './utils'
describe('maxContextLogic', () => {
let logic: ReturnType<typeof maxContextLogic.build>
@@ -673,4 +677,76 @@ describe('maxContextLogic', () => {
expect(mockInsightLogicInstance.unmount).toHaveBeenCalled()
})
})
+
+ describe('open dashboard scene context (before tiles have streamed in)', () => {
+ // A dashboard's tiles stream in after its metadata, so dashboard.tiles is
+ // undefined during that window (and after some metadata-only updates).
+ const dashboardWithoutTiles = {
+ ...mockDashboard,
+ tiles: undefined,
+ } as unknown as DashboardType<QueryBasedInsightModel>
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('createMaxContextHelpers.dashboard tolerates missing tiles', () => {
+ expect(createMaxContextHelpers.dashboard(dashboardWithoutTiles).data.tiles).toEqual([])
+ })
+
+ it('dashboardToMaxContext tolerates missing tiles', () => {
+ expect(dashboardToMaxContext(dashboardWithoutTiles).insights).toEqual([])
+ })
+
+ it('passes the open dashboard to Max even before its tiles have loaded', async () => {
+ // Simulate the dashboard scene being active, mirroring how dashboardLogic.maxContext
+ // builds its context from the (not yet fully loaded) dashboard value.
+ jest.spyOn(sceneLogic.selectors, 'activeSceneLogic').mockReturnValue({
+ selectors: {
+ maxContext: () => [createMaxContextHelpers.dashboard(dashboardWithoutTiles)],
+ },
+ } as any)
+ jest.spyOn(sceneLogic.selectors, 'activeLoadedScene').mockReturnValue({
+ paramsToProps: () => ({ id: dashboardWithoutTiles.id }),
+ sceneParams: {},
+ } as any)
+
+ await expectLogic(logic).toMatchValues({
+ compiledContext: partial({
+ dashboards: [partial({ id: mockDashboard.id, type: 'dashboard', insights: [] })],
+ }),
+ })
+ })
+ })
+
+ describe('scene context errors are surfaced, not silently swallowed', () => {
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('reports an exception (instead of blanking context silently) when a scene maxContext selector throws', async () => {
+ const captureException = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ jest.spyOn(sceneLogic.selectors, 'activeSceneLogic').mockReturnValue({
+ selectors: {
+ maxContext: () => {
+ throw new Error('boom from scene maxContext')
+ },
+ },
+ } as any)
+ jest.spyOn(sceneLogic.selectors, 'activeLoadedScene').mockReturnValue({
+ paramsToProps: () => ({}),
+ sceneParams: {},
+ } as any)
+
+ // Reading scene context triggers the throwing selector.
+ await expectLogic(logic).toMatchValues({ sceneContext: [] })
+
+ expect(captureException).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'boom from scene maxContext' }),
+ expect.objectContaining({ feature: 'max_scene_context' })
+ )
+ })
+ })
})
diff --git a/frontend/src/scenes/max/maxContextLogic.ts b/frontend/src/scenes/max/maxContextLogic.ts
index eaf1e5ba3941..a6ddd69e6c2d 100644
--- a/frontend/src/scenes/max/maxContextLogic.ts
+++ b/frontend/src/scenes/max/maxContextLogic.ts
@@ -1,5 +1,6 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { IconBug, IconCheckbox, IconDashboard, IconGraph, IconNotebook } from '@posthog/icons'
@@ -68,6 +69,30 @@ const addOrUpdateEntity = <TContext extends EntityWithIdAndType>(state: TContext
const removeEntity = <TContext extends EntityWithIdAndType>(state: TContext[], id: string | number): TContext[] =>
state.filter((item) => item.id !== id)
+// A throw while building scene context blanks out ALL of PostHog AI's auto-collected context
+// (e.g. PostHog AI reporting it has no dashboard and falling back to search). The selector that
+// catches it runs on every read, so dedupe by message to avoid spamming when it keeps
+// throwing — but never let the failure stay silent.
+const reportedSceneContextErrors = new Set<string>()
+const reportSceneContextError = (error: unknown): void => {
+ const err = error instanceof Error ? error : new Error(String(error))
+ const key = `${err.name}: ${err.message}`
+ if (reportedSceneContextErrors.has(key)) {
+ return
+ }
+ // Bound growth in case messages embed dynamic content.
+ if (reportedSceneContextErrors.size > 50) {
+ reportedSceneContextErrors.clear()
+ }
+ reportedSceneContextErrors.add(key)
+ // eslint-disable-next-line no-console
+ console.error(
+ '[PostHog AI] Failed to build scene context — it will have no auto-collected context for this scene:',
+ err
+ )
+ posthog.captureException(err, { feature: 'max_scene_context' })
+}
+
export type LoadedEntitiesMap = { dashboard: number[]; insight: string[] }
export const maxContextLogic = kea<maxContextLogicType>([
@@ -504,8 +529,9 @@ export const maxContextLogic = kea<maxContextLogicType>([
state,
activeLoadedScene?.paramsToProps?.(activeLoadedScene?.sceneParams) || {}
)
- } catch {
- // If the maxContext selector fails, return empty array
+ } catch (error) {
+ // Surface the failure instead of silently returning empty context.
+ reportSceneContextError(error)
}
}
return []
diff --git a/frontend/src/scenes/max/maxTypes.ts b/frontend/src/scenes/max/maxTypes.ts
index b47d5b7e820c..e4d65c955f3b 100644
--- a/frontend/src/scenes/max/maxTypes.ts
+++ b/frontend/src/scenes/max/maxTypes.ts
@@ -176,7 +176,7 @@ export const createMaxContextHelpers = {
type: MaxContextType.DASHBOARD,
data: {
...dashboard,
- tiles: dashboard.tiles.map((tile) => ({
+ tiles: (dashboard.tiles ?? []).map((tile) => ({
...tile,
insight: tile.insight ? pickInsightFields(tile.insight) : tile.insight,
})),
diff --git a/frontend/src/scenes/max/utils.ts b/frontend/src/scenes/max/utils.ts
index d791724ea017..182d7af10c2c 100644
--- a/frontend/src/scenes/max/utils.ts
+++ b/frontend/src/scenes/max/utils.ts
@@ -174,7 +174,9 @@ export const dashboardToMaxContext = (dashboard: DashboardType<InsightWithQuery>
id: dashboard.id,
name: dashboard.name,
description: dashboard.description,
- insights: dashboard.tiles.filter((tile) => tile.insight).map((tile) => insightToMaxContext(tile.insight!)),
+ insights: (dashboard.tiles ?? [])
+ .filter((tile) => tile.insight)
+ .map((tile) => insightToMaxContext(tile.insight!)),
filters: dashboard.filters,
}
}