:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(max): bound dashboard context to the conversation window (#64314)
Vasco de Krijgerd605b4ffddd1
diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex f8d4953d1a9d..074dfde5ecda 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -5,6 +5,7 @@ from functools import cached_propertyfrom typing import TYPE_CHECKING, Any, Optional, castfrom uuid import uuid4+import posthoganalyticsfrom langchain_core.prompts import PromptTemplatefrom langchain_core.runnables import RunnableConfigfrom posthoganalytics import capture_exception@@ -23,6 +24,7 @@ from posthog.schema import ()from posthog.constants import AvailableFeature+from posthog.event_usage import groupsfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -56,6 +58,16 @@ from .prompts import (# malicious or buggy client can't blow up the context window.NOTEBOOK_MARKDOWN_MAX_LENGTH = 100_000+# A dashboard's executed-results context is bounded so it can't overflow the conversation window+# (compaction_manager.CONVERSATION_WINDOW_SIZE = 100k). If it overflows, the whole conversation —+# including this dashboard — gets summarized down to a few thousand tokens, so Max loses the+# dashboard it was just asked about. Over budget, we fall back to schema-only (insight names ++# queries, no result tables), which still lets Max identify and describe the dashboard and fetch+# specific numbers via the read_data tool.+DASHBOARD_CONTEXT_TOKEN_BUDGET = 50_000+# ~4 chars/token, matching compaction_manager.APPROXIMATE_TOKEN_LENGTH.+DASHBOARD_CONTEXT_CHAR_BUDGET = DASHBOARD_CONTEXT_TOKEN_BUDGET * 4+def _sanitize_inline_prompt_value(value: str) -> str:"""Make a client-supplied string safe to interpolate into a single prompt line."""@@ -174,6 +186,26 @@ class AssistantContextManager(AssistantContextMixin):return await _get_group_names_sync()+ def _capture_dashboard_budget_exceeded(self, fallbacks: dict[str, list[int]]) -> None:+ overflowed = fallbacks["schema"] + fallbacks["truncated"]+ if not overflowed:+ return+ distinct_id = self._get_user_distinct_id(self._config)+ if not distinct_id:+ return+ posthoganalytics.capture(+ distinct_id=distinct_id,+ event="posthog ai dashboard context budget exceeded",+ properties={+ **self._get_debug_props(self._config),+ "dashboard_ids": overflowed,+ "budget_chars": DASHBOARD_CONTEXT_CHAR_BUDGET,+ # "truncated" means schema itself didn't fit — the more-degraded outcome.+ "fallback": "truncated" if fallbacks["truncated"] else "schema",+ },+ groups=groups(None, self._team),+ )+async def _format_ui_context(self, ui_context: MaxUIContext | None) -> str | None:"""Format UI context into template variables for the prompt.@@ -191,6 +223,11 @@ class AssistantContextManager(AssistantContextMixin):dashboard_context = ""if ui_context.dashboards:dashboard_contexts = []+ # Budget across ALL attached dashboards, not per dashboard, so several attached+ # dashboards can't collectively overflow the window even if each one fits on its own.+ remaining_char_budget = DASHBOARD_CONTEXT_CHAR_BUDGET+ # Dashboard ids that overflowed the budget, keyed by fallback kind — emitted as one event below.+ budget_fallbacks: dict[str, list[int]] = {"schema": [], "truncated": []}for dashboard in ui_context.dashboards:dashboard_filters = (dashboard.filters.model_dump(exclude_none=True)@@ -232,6 +269,22 @@ class AssistantContextManager(AssistantContextMixin):try:dashboard_text = await dashboard_ctx.execute_and_format()+ if len(dashboard_text) > remaining_char_budget:+ # Too large for the remaining window budget — drop to schema-only (insight+ # names + queries, no result tables) so it survives un-summarized; Max keeps+ # the read_data tool for specific numbers. format_schema runs no queries.+ dashboard_text = await dashboard_ctx.format_schema()+ fallback = "schema"+ if len(dashboard_text) > remaining_char_budget:+ fallback = "truncated"+ marker = "\n\n…(dashboard context truncated)"+ # No room for even the marker — stop here so the budget can't go negative.+ if remaining_char_budget <= len(marker):+ budget_fallbacks[fallback].append(dashboard.id)+ break+ dashboard_text = dashboard_text[: remaining_char_budget - len(marker)] + marker+ budget_fallbacks[fallback].append(dashboard.id)+ remaining_char_budget -= len(dashboard_text)dashboard_contexts.append(format_prompt_string(ROOT_DASHBOARD_CONTEXT_PROMPT, content=dashboard_text))@@ -243,6 +296,8 @@ class AssistantContextManager(AssistantContextMixin):)continue+ self._capture_dashboard_budget_exceeded(budget_fallbacks)+if dashboard_contexts:joined_dashboards = "\n\n".join(dashboard_contexts)dashboard_context = (diff --git a/ee/hogai/context/test/test_context.py b/ee/hogai/context/test/test_context.pyindex 12c161a343a9..dc39dd90a48f 100644--- a/ee/hogai/context/test/test_context.py+++ b/ee/hogai/context/test/test_context.py@@ -2,7 +2,7 @@ import datetimefrom typing import castfrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized@@ -40,6 +40,7 @@ from posthog.schema import (from posthog.models.organization import OrganizationMembershipfrom ee.hogai.context import AssistantContextManager+from ee.hogai.context.context import DASHBOARD_CONTEXT_CHAR_BUDGETfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import AssistantMessageUnion@@ -190,6 +191,154 @@ class TestAssistantContextManager(BaseTest):# The insight execution is tested separately - just verify structure hereself.assertNotIn("# Insights", result)+ @staticmethod+ def _dashboard_ui_context(*ids: int) -> MaxUIContext:+ return MaxUIContext(+ dashboards=[+ MaxDashboardContext(+ id=i,+ name=f"Dashboard {i}",+ insights=[+ MaxInsightContext(id=str(i), name="I", query=TrendsQuery(series=[EventsNode(event="x")]))+ ],+ filters=DashboardFilter(),+ )+ for i in ids+ ]+ )++ @parameterized.expand(+ [+ # (name, execute_result, schema_result, expect_schema_fallback, expected_in, expected_not_in,+ # capped_char) — capped_char, when set, must appear at most DASHBOARD_CONTEXT_CHAR_BUDGET times+ # (i.e. the oversized content was bounded, not inlined whole).+ (+ "under_budget_keeps_full_results",+ "Full executed results",+ "SCHEMA",+ False,+ "Full executed results",+ None,+ None,+ ),+ (+ "over_budget_falls_back_to_schema",+ "x" * (DASHBOARD_CONTEXT_CHAR_BUDGET + 5000),+ "SCHEMA-ONLY dashboard context",+ True,+ "SCHEMA-ONLY dashboard context",+ "xxxx",+ None,+ ),+ (+ "schema_also_over_budget_hard_truncates",+ "x" * (DASHBOARD_CONTEXT_CHAR_BUDGET + 5000),+ "y" * (DASHBOARD_CONTEXT_CHAR_BUDGET + 5000),+ True,+ "…(dashboard context truncated)",+ "xxxx",+ "y",+ ),+ ]+ )+ @patch("ee.hogai.context.context.DashboardContext")+ async def test_dashboard_context_budget(+ self,+ _name,+ execute_result,+ schema_result,+ expect_schema_fallback,+ expected_in,+ expected_not_in,+ capped_char,+ MockDashboardContext,+ ):+ # The dashboard's executed results must not overflow the conversation window (which would+ # summarize the dashboard away). Over budget => schema-only; schema also over => hard-truncate.+ inst = MockDashboardContext.return_value+ inst.execute_and_format = AsyncMock(return_value=execute_result)+ inst.format_schema = AsyncMock(return_value=schema_result)++ result = await self.context_manager._format_ui_context(self._dashboard_ui_context(1))++ assert result is not None+ if expect_schema_fallback:+ inst.format_schema.assert_awaited_once()+ else:+ inst.format_schema.assert_not_awaited()+ self.assertIn(expected_in, result)+ if expected_not_in is not None:+ self.assertNotIn(expected_not_in, result)+ if capped_char is not None:+ self.assertLessEqual(result.count(capped_char), DASHBOARD_CONTEXT_CHAR_BUDGET)++ @patch("ee.hogai.context.context.DashboardContext")+ async def test_dashboard_context_budget_is_aggregate_across_dashboards(self, MockDashboardContext):+ # Each dashboard at ~80% of budget fits alone, but two together would overflow — the running+ # budget forces the second to fall back to schema-only rather than blow the window.+ inst = MockDashboardContext.return_value+ inst.execute_and_format = AsyncMock(return_value="r" * int(DASHBOARD_CONTEXT_CHAR_BUDGET * 0.8))+ inst.format_schema = AsyncMock(return_value="SCHEMA")++ result = await self.context_manager._format_ui_context(self._dashboard_ui_context(1, 2))++ assert result is not None+ inst.format_schema.assert_awaited() # the 2nd dashboard exceeded the remaining budget+ self.assertIn("SCHEMA", result)+ # only the first dashboard's executed results are inlined; total stays within budget+ self.assertLessEqual(result.count("r"), DASHBOARD_CONTEXT_CHAR_BUDGET)++ @patch("ee.hogai.context.context.DashboardContext")+ async def test_dashboard_context_budget_drops_dashboard_with_no_room_for_marker(self, MockDashboardContext):+ # The 1st dashboard leaves only a few chars of budget — too little for even the truncation+ # marker. The 2nd must be dropped entirely rather than emitting a marker that overshoots the+ # budget (which would drive the running budget negative).+ # Sentinels are uppercase so they can't collide with the prompt-template prose.+ inst = MockDashboardContext.return_value+ inst.execute_and_format = AsyncMock(return_value="Q" * (DASHBOARD_CONTEXT_CHAR_BUDGET - 10))+ inst.format_schema = AsyncMock(return_value="Z" * 100)++ result = await self.context_manager._format_ui_context(self._dashboard_ui_context(1, 2))++ assert result is not None+ self.assertEqual(result.count("Q"), DASHBOARD_CONTEXT_CHAR_BUDGET - 10) # 1st dashboard inlined whole+ self.assertNotIn("Z", result) # 2nd dashboard dropped, not marker-truncated+ self.assertNotIn("…(dashboard context truncated)", result)+ self.assertLessEqual(result.count("Q"), DASHBOARD_CONTEXT_CHAR_BUDGET)++ @patch("ee.hogai.context.context.posthoganalytics.capture")+ @patch("ee.hogai.context.context.DashboardContext")+ async def test_dashboard_context_budget_exceeded_emits_diagnostic_event(self, MockDashboardContext, mock_capture):+ # Over budget => one diagnostic event so the threshold can be tuned and silent degradation is visible.+ inst = MockDashboardContext.return_value+ inst.execute_and_format = AsyncMock(return_value="x" * (DASHBOARD_CONTEXT_CHAR_BUDGET + 5000))+ inst.format_schema = AsyncMock(return_value="SCHEMA")++ config = RunnableConfig(configurable={"distinct_id": "user-123"})+ context_manager = AssistantContextManager(self.team, self.user, config)+ result = await context_manager._format_ui_context(self._dashboard_ui_context(1))++ assert result is not None+ mock_capture.assert_called_once()+ kwargs = mock_capture.call_args.kwargs+ self.assertEqual(kwargs["event"], "posthog ai dashboard context budget exceeded")+ self.assertEqual(kwargs["distinct_id"], "user-123")+ self.assertEqual(kwargs["properties"]["dashboard_ids"], [1])+ self.assertEqual(kwargs["properties"]["fallback"], "schema")+ self.assertEqual(kwargs["properties"]["budget_chars"], DASHBOARD_CONTEXT_CHAR_BUDGET)++ @patch("ee.hogai.context.context.posthoganalytics.capture")+ @patch("ee.hogai.context.context.DashboardContext")+ async def test_dashboard_context_under_budget_emits_no_event(self, MockDashboardContext, mock_capture):+ inst = MockDashboardContext.return_value+ inst.execute_and_format = AsyncMock(return_value="small results")++ config = RunnableConfig(configurable={"distinct_id": "user-123"})+ context_manager = AssistantContextManager(self.team, self.user, config)+ await context_manager._format_ui_context(self._dashboard_ui_context(1))++ mock_capture.assert_not_called()+@patch("ee.hogai.context.notebook.context.NotebookContext.from_short_id")async def test_format_ui_context_with_markdown_notebook_insertion_context(self, mock_from_short_id):ui_context = MaxUIContext(diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 1f6e24e6d0e4..e1deb5cbea78 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -3,7 +3,6 @@ import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'import { router } from 'kea-router'import { partial } from 'kea-test-utils'import { expectLogic } from 'kea-test-utils'-import posthog from 'posthog-js'import React from 'react'import api, { ApiError } from 'lib/api'@@ -34,8 +33,7 @@ import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'import { maxContextLogic } from './maxContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'import { maxLogic } from './maxLogic'-import { MAX_DASHBOARD_CONTEXT_WAIT_MS, maxThreadLogic } from './maxThreadLogic'-import { MaxContextType } from './maxTypes'+import { maxThreadLogic } from './maxThreadLogic'import {MOCK_CONVERSATION,MOCK_CONVERSATION_ID,@@ -462,123 +460,24 @@ describe('maxThreadLogic', () => {)})- // Simulate being on a dashboard scene whose data has not loaded yet: dashboardLogic.dashboard- // is null, so its maxContext returns []. The first message must wait for the load, otherwise- // it ships with no dashboard context and Max can't see the open dashboard.- const mockLoadingDashboardScene = (): { values: { dashboard: any } } => {- const fakeDashboardLogic: any = {- selectors: {- maxContext: () =>- fakeDashboardLogic.values.dashboard- ? [{ type: MaxContextType.DASHBOARD, data: fakeDashboardLogic.values.dashboard }]- : [],- },- values: { dashboard: null as any },- }+ it('sends the first message immediately even while the dashboard scene is still loading', async () => {+ // Regression guard for the removed #63208 gate: on a Dashboard scene whose+ // dashboardLogic.dashboard is still null, askMax must send synchronously (no poll/wait).+ // If the gate were reinstated, stream would not be called until fake timers advanced.+ const fakeDashboardLogic: any = { selectors: { maxContext: () => [] }, values: { dashboard: null } }jest.spyOn(sceneLogic.selectors, 'activeSceneId').mockReturnValue(Scene.Dashboard)jest.spyOn(sceneLogic.selectors, 'activeSceneLogic').mockReturnValue(fakeDashboardLogic)- jest.spyOn(sceneLogic.selectors, 'activeLoadedScene').mockReturnValue({- paramsToProps: () => ({ id: 1 }),- sceneParams: {},- } as any)- return fakeDashboardLogic- }-- it('waits for the open dashboard to load before sending the first message (regression for #61414)', async () => {- jest.useFakeTimers()- const captureSpy = jest.spyOn(posthog, 'capture')- try {- const streamSpy = mockStream()- const fakeDashboardLogic = mockLoadingDashboardScene()-- maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)- logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })- logic.mount()-- // Fire the first message while the dashboard is still loading.- logic.actions.askMax('what am I seeing on this dashboard?')-- // The gate holds the send while the dashboard is loading.- await jest.advanceTimersByTimeAsync(300)- expect(streamSpy).toHaveBeenCalledTimes(0)-- // Dashboard finishes loading → gate releases → the message sends WITH the dashboard context.- fakeDashboardLogic.values.dashboard = { id: 1, name: 'Test Dashboard', tiles: [] }- await jest.advanceTimersByTimeAsync(500)-- expect(streamSpy).toHaveBeenCalledTimes(1)- expect(streamSpy).toHaveBeenCalledWith(- expect.objectContaining({- ui_context: expect.objectContaining({- dashboards: expect.arrayContaining([expect.objectContaining({ id: 1 })]),- }),- }),- expect.any(Object)- )- // A normal load must NOT report a timeout.- expect(captureSpy).not.toHaveBeenCalledWith('max dashboard context wait timed out', expect.anything())- } finally {- jest.useRealTimers()- }- })-- it('reports a telemetry event and still sends if the dashboard never loads within the cap', async () => {- jest.useFakeTimers()- const captureSpy = jest.spyOn(posthog, 'capture')- try {- const streamSpy = mockStream()- mockLoadingDashboardScene() // dashboard stays null past the wait cap-- maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)- logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })- logic.mount()-- logic.actions.askMax('what am I seeing on this dashboard?')-- // Advance past the 8s wait cap without the dashboard ever loading.- await jest.advanceTimersByTimeAsync(8100)-- // The cap must never block the user — the message still sends...- expect(streamSpy).toHaveBeenCalledTimes(1)- // ...but we record that the wait timed out, so the cap's impact is observable in prod.- expect(captureSpy).toHaveBeenCalledWith(- 'max dashboard context wait timed out',- expect.objectContaining({ dashboard_id: 1, waited_ms: expect.any(Number) })- )- // waited_ms is real elapsed time, so it must be at least the cap (never under-reported).- const timeoutCall = captureSpy.mock.calls.find((c) => c[0] === 'max dashboard context wait timed out')- expect(timeoutCall?.[1]?.waited_ms).toBeGreaterThanOrEqual(MAX_DASHBOARD_CONTEXT_WAIT_MS)- } finally {- jest.useRealTimers()- }- })-- it('releases the gate and sends if the user navigates away while the dashboard is still loading', async () => {- jest.useFakeTimers()- try {- const streamSpy = mockStream()- mockLoadingDashboardScene()+ const streamSpy = mockStream()- maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)- logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })- logic.mount()+ maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)+ logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })+ logic.mount()+ await expectLogic(logic, () => {logic.actions.askMax('what am I seeing on this dashboard?')+ }).toDispatchActions(['askMax'])- // Still on the (never-loading) dashboard → the gate holds.- await jest.advanceTimersByTimeAsync(300)- expect(streamSpy).toHaveBeenCalledTimes(0)-- // User leaves the dashboard before it ever loads. The gate re-reads the scene each tick,- // so it must stop waiting and send rather than block until the timeout.- jest.spyOn(sceneLogic.selectors, 'activeSceneId').mockReturnValue(Scene.SavedInsights)- jest.spyOn(sceneLogic.selectors, 'activeSceneLogic').mockReturnValue(null as any)- await jest.advanceTimersByTimeAsync(300)-- expect(streamSpy).toHaveBeenCalledTimes(1)- } finally {- jest.useRealTimers()- }+ expect(streamSpy).toHaveBeenCalledTimes(1)})it('sends form_answers in ui_context when provided', async () => {diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 1c84c43e372f..dff761fe691d 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -90,12 +90,6 @@ import { getRandomThinkingMessage } from './utils/thinkingMessages'/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'-// On a dashboard, the first message can fire before the dashboard has loaded, when-// dashboardLogic.maxContext still returns []. askMax waits (bounded) for the load so the-// dashboard context is included. Bounded so a stuck/failed load never blocks sending.-export const MAX_DASHBOARD_CONTEXT_WAIT_MS = 8000-const DASHBOARD_CONTEXT_POLL_INTERVAL_MS = 100-export type MessageStatus = 'loading' | 'completed' | 'error'export type ThreadMessage = RootAssistantMessage & {@@ -1006,47 +1000,11 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.clearQueuedMessages()}},- askMax: async ({ prompt, addToThread = true, uiContext }, breakpoint) => {+ askMax: async ({ prompt, addToThread = true, uiContext }) => {// Only process if this thread is the currently active oneif (values.conversationId !== values.activeThreadKey) {return}- // Wait for the open dashboard to finish loading before collecting context (see the- // constants above for why). The scene is re-read every tick, so the gate releases the- // moment the dashboard's metadata lands — and immediately if the user navigates away- // mid-wait (no longer on a dashboard, or onto a different one that's already loaded).- const isDashboardSceneLoading = (): boolean => {- if (sceneLogic.values.activeSceneId !== Scene.Dashboard) {- return false- }- const activeSceneLogic = sceneLogic.values.activeSceneLogic- if (!activeSceneLogic || !('maxContext' in activeSceneLogic.selectors)) {- return false- }- return !(activeSceneLogic.values as { dashboard?: unknown }).dashboard- }- // Measure real elapsed time, not tick count: breakpoint() only guarantees a *minimum*- // delay, so a busy event loop would make a tick counter under-report the wait — letting- // it run past the cap and skewing the telemetry below. performance.now() is monotonic.- const dashboardWaitStart = performance.now()- while (- isDashboardSceneLoading() &&- performance.now() - dashboardWaitStart < MAX_DASHBOARD_CONTEXT_WAIT_MS- ) {- await breakpoint(DASHBOARD_CONTEXT_POLL_INTERVAL_MS)- }- if (isDashboardSceneLoading()) {- // We hit the wait cap while the dashboard was still loading, so the message ships- // without dashboard context (the original "Max can't see this dashboard" symptom).- // Capture it so we can tell whether the cap is ever the binding constraint in prod.- const activeLoadedScene = sceneLogic.values.activeLoadedScene- const sceneProps = activeLoadedScene?.paramsToProps?.(activeLoadedScene?.sceneParams) || {}- posthog.capture('max dashboard context wait timed out', {- waited_ms: Math.round(performance.now() - dashboardWaitStart),- dashboard_id: (sceneProps as { id?: number | string }).id,- conversation_id: values.conversation?.id || values.conversationId,- })- }const contextualTools = Object.fromEntries(values.tools.map((tool) => [tool.identifier, tool.context]))// Always send voice_mode as an explicit boolean when handsFreeLogic is mounted,// not just when active. Otherwise a typed turn following a spoken one inherits