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(ai): remove cached query responses from legacy context (#98161)

Georgiy Tarasovac0a7e106218
diff --git a/ee/hogai/core/executor.py b/ee/hogai/core/executor.py
index 98a84cdea89d..b09c5fdd76c2 100644
--- a/ee/hogai/core/executor.py
+++ b/ee/hogai/core/executor.py
@@ -21,6 +21,7 @@ from posthog.temporal.common.client import async_connect
from products.posthog_ai.backend.models.assistant import Conversation
+from ee.hogai.core.workflow_payload import get_workflow_input_size_estimates
from ee.hogai.queue import ConversationQueueStore
from ee.hogai.stream.redis_stream import (
CONVERSATION_STREAM_MAX_LENGTH,
@@ -118,7 +119,11 @@ class AgentExecutor:
except Exception as e:
posthoganalytics.capture_exception(e, properties={"tag": "max_ai"})
- logger.exception("Error starting workflow", error=e)
+ logger.exception(
+ "Error starting workflow",
+ error=e,
+ workflow_input_estimated_bytes=get_workflow_input_size_estimates(inputs),
+ )
failed = True
if failed:
diff --git a/ee/hogai/core/test/test_workflow_payload.py b/ee/hogai/core/test/test_workflow_payload.py
new file mode 100644
index 000000000000..ed9bb9f1c650
--- /dev/null
+++ b/ee/hogai/core/test/test_workflow_payload.py
@@ -0,0 +1,34 @@
+import json
+from types import SimpleNamespace
+
+from unittest import TestCase
+
+from ee.hogai.core.workflow_payload import get_workflow_input_size_estimates
+
+
+class TestWorkflowPayload(TestCase):
+ def test_size_estimates_expose_only_allowlisted_field_sizes(self) -> None:
+ message = {"content": "A question with a unicode character: é"}
+ inputs = SimpleNamespace(
+ message=message,
+ contextual_tools={"execute_sql": {"query": "SELECT 1"}},
+ billing_context=None,
+ resume_payload={"approved": True},
+ secret="not logged",
+ )
+
+ self.assertEqual(
+ get_workflow_input_size_estimates(inputs),
+ {
+ "message": len(json.dumps(message, ensure_ascii=False).encode("utf-8")),
+ "contextual_tools": 38,
+ "resume_payload": 18,
+ },
+ )
+
+ def test_invalid_field_does_not_hide_other_sizes(self) -> None:
+ circular: list[object] = []
+ circular.append(circular)
+ inputs = SimpleNamespace(message=circular, contextual_tools={})
+
+ self.assertEqual(get_workflow_input_size_estimates(inputs), {"contextual_tools": 2})
diff --git a/ee/hogai/core/workflow_payload.py b/ee/hogai/core/workflow_payload.py
new file mode 100644
index 000000000000..7f0b30065859
--- /dev/null
+++ b/ee/hogai/core/workflow_payload.py
@@ -0,0 +1,14 @@
+import json
+
+
+def get_workflow_input_size_estimates(inputs: object) -> dict[str, int]:
+ sizes: dict[str, int] = {}
+ for field_name in ("message", "contextual_tools", "billing_context", "resume_payload"):
+ value = getattr(inputs, field_name, None)
+ if value is None:
+ continue
+ try:
+ sizes[field_name] = len(json.dumps(value, default=str, ensure_ascii=False).encode("utf-8"))
+ except (TypeError, ValueError, RecursionError):
+ continue
+ return sizes
diff --git a/frontend/src/scenes/max/utils.test.ts b/frontend/src/scenes/max/utils.test.ts
index 518a55a96a86..2a3becf01640 100644
--- a/frontend/src/scenes/max/utils.test.ts
+++ b/frontend/src/scenes/max/utils.test.ts
@@ -6,16 +6,67 @@ import {
AssistantToolCallMessage,
RootAssistantMessage,
} from '~/queries/schema/schema-assistant-messages'
+import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+import { DashboardType, InsightShortId, QueryBasedInsightModel } from '~/types'
import { EnhancedToolCall } from './max-constants'
import {
activeSceneLogicHasMaxContext,
+ dashboardToMaxContext,
+ insightToMaxContext,
findPendingClientToolCall,
isMultiQuestionFormMessage,
threadEndsWithMultiQuestionForm,
} from './utils'
describe('max/utils', () => {
+ it.each(['insight', 'dashboard'] as const)(
+ 'removes nested query responses from %s context without changing the source',
+ (contextType) => {
+ const source = {
+ kind: NodeKind.HogQLQuery as const,
+ query: 'SELECT 1',
+ response: { results: [[1]] },
+ values: { response: 'keep this query value' },
+ }
+ const insight: Partial<QueryBasedInsightModel> = {
+ short_id: 'test-query' as InsightShortId,
+ query: {
+ kind: NodeKind.DataVisualizationNode,
+ source,
+ } as DataVisualizationNode,
+ }
+ const dashboard = {
+ id: 1,
+ tiles: [{ id: 1, insight }],
+ } as DashboardType<QueryBasedInsightModel>
+ const context =
+ contextType === 'insight' ? insightToMaxContext(insight) : dashboardToMaxContext(dashboard).insights[0]
+
+ expect(context.query).toEqual({
+ kind: NodeKind.HogQLQuery as const,
+ query: 'SELECT 1',
+ values: { response: 'keep this query value' },
+ })
+ expect(source.response).toEqual({ results: [[1]] })
+ }
+ )
+
+ it('removes responses from direct queries and nested query arrays', () => {
+ const query = {
+ kind: NodeKind.TrendsQuery as const,
+ response: { results: [] },
+ series: [{ kind: NodeKind.EventsNode as const, event: '$pageview', response: { results: [] } }],
+ }
+
+ expect(insightToMaxContext({ query }).query).toEqual({
+ kind: NodeKind.TrendsQuery as const,
+ series: [{ kind: NodeKind.EventsNode as const, event: '$pageview' }],
+ })
+ expect(query.response).toEqual({ results: [] })
+ expect(query.series[0].response).toEqual({ results: [] })
+ })
+
describe('isMultiQuestionFormMessage()', () => {
it('returns true for AssistantMessage with create_form tool call', () => {
const message = {
diff --git a/frontend/src/scenes/max/utils.ts b/frontend/src/scenes/max/utils.ts
index 3d606f59fc64..8dacb9dc217f 100644
--- a/frontend/src/scenes/max/utils.ts
+++ b/frontend/src/scenes/max/utils.ts
@@ -185,6 +185,22 @@ export function getSlackThreadUrl(slackThreadKey: string, slackWorkspaceDomain?:
return `https://${domain}.slack.com/archives/${channel}/${urlTs}`
}
+function stripQueryResponses<Value>(value: Value): Value {
+ if (value === null || typeof value !== 'object') {
+ return value
+ }
+ if (Array.isArray(value)) {
+ return value.map(stripQueryResponses) as Value
+ }
+
+ const isQueryNode = 'kind' in value && Object.values(NodeKind).includes(value.kind as NodeKind)
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([key]) => !(isQueryNode && key === 'response'))
+ .map(([key, child]) => [key, stripQueryResponses(child)])
+ ) as Value
+}
+
// Utility functions for transforming data to max context
export const insightToMaxContext = (
insight: Partial<QueryBasedInsightModel>,
@@ -199,7 +215,7 @@ export const insightToMaxContext = (
id: insight.short_id!,
name: insight.name || insight.derived_name,
description: insight.description,
- query: source,
+ query: stripQueryResponses(source),
filtersOverride,
variablesOverride,
}