: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(posthog-ai): preserve compacted context and bound sql previews (#100991)
Georgiy Tarasov5b87a2a27516
diff --git a/ee/hogai/chat_agent/insights/nodes.py b/ee/hogai/chat_agent/insights/nodes.pyindex a82089fd9e63..17b4c6c14938 100644--- a/ee/hogai/chat_agent/insights/nodes.py+++ b/ee/hogai/chat_agent/insights/nodes.py@@ -21,6 +21,7 @@ from posthog.exceptions_capture import capture_exceptionfrom products.product_analytics.backend.facade.models import Insight+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.core.node import AssistantNodefrom ee.hogai.core.shared_prompts import HYPERLINK_USAGE_INSTRUCTIONS@@ -565,7 +566,10 @@ class InsightSearchNode(AssistantNode):"""Execute query and format results with timing instrumentation."""try:query_executor = AssistantQueryExecutor(- team=self._team, user=self._user, utc_now_datetime=self._utc_now_datetime+ team=self._team,+ user=self._user,+ utc_now_datetime=self._utc_now_datetime,+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,)results, _ = await query_executor.arun_and_format_query(query_obj, debug_timing=True)return resultsdiff --git a/ee/hogai/chat_agent/query_executor/nodes.py b/ee/hogai/chat_agent/query_executor/nodes.pyindex cab59f1647e3..0aad818b7b73 100644--- a/ee/hogai/chat_agent/query_executor/nodes.py+++ b/ee/hogai/chat_agent/query_executor/nodes.py@@ -6,6 +6,7 @@ from posthog.schema import ArtifactMessage, AssistantMessage, AssistantToolCallMfrom ee.hogai.artifacts.utils import unwrap_visualization_artifact_contentfrom ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.core.node import AssistantNodefrom ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.utils.types import AssistantState, PartialAssistantState@@ -28,6 +29,7 @@ class QueryExecutorNode(AssistantNode):try:context = InsightContext(+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,team=self._team,user=self._user,query=content.query,diff --git a/ee/hogai/chat_agent/test/test_chat_agent.py b/ee/hogai/chat_agent/test/test_chat_agent.pyindex aa68895a454a..c21d6aa597d7 100644--- a/ee/hogai/chat_agent/test/test_chat_agent.py+++ b/ee/hogai/chat_agent/test/test_chat_agent.py@@ -1687,6 +1687,12 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):@patch("ee.hogai.tools.read_taxonomy.tool.ReadTaxonomyTool._run_impl")@patch("ee.hogai.core.agent_modes.executables.AgentExecutable._get_model")async def test_compacting_conversation_on_the_second_turn(self, mock_model, mock_tool, mock_should_compact):+ compacted_model_input: list[BaseMessage] = []++ def respond_after_compaction(model_input: list[BaseMessage]) -> messages.AIMessage:+ compacted_model_input.extend(model_input)+ return messages.AIMessage(content=[{"text": "After summary", "type": "text"}])+mock_model.side_effect = cycle( # Changed from return_value to side_effect[FakeChatAnthropic(@@ -1697,13 +1703,7 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):)]),- FakeChatAnthropic(- responses=[- messages.AIMessage(- content=[{"text": "After summary", "type": "text"}],- )- ]- ),+ FakeAnthropicRunnableLambdaWithTokenCounter(respond_after_compaction),])mock_tool.return_value = ("Event list" * 200000, None)@@ -1727,7 +1727,6 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):),),("message", AssistantToolCallMessage(tool_call_id="1", content="Event list" * 200000)),- ("message", HumanMessage(content="First")), # Should copy this message("message", AssistantMessage(content="After summary")),]output, _ = await self._run_assistant_graph(graph, message="First", conversation=self.conversation)@@ -1735,12 +1734,17 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):snapshot = await graph.aget_state({"configurable": {"thread_id": str(self.conversation.id)}})state = AssistantState.model_validate(snapshot.values)- # should be equal to the copied human message- new_human_message = cast(HumanMessage, output[3][1])- self.assertEqual(state.start_id, new_human_message.id)- # should be equal to the summary message (ContextMessage)- self.assertIsInstance(state.messages[4], ContextMessage)- self.assertEqual(state.root_conversation_start_id, state.messages[4].id)+ original_request = cast(HumanMessage, output[0][1])+ self.assertEqual(state.start_id, original_request.id)+ self.assertEqual(+ [message for message in state.messages if isinstance(message, HumanMessage)], [original_request]+ )+ summary_message = next(message for message in state.messages if message.id == state.root_conversation_start_id)+ self.assertIsInstance(summary_message, ContextMessage)+ model_input_text = str([message.content for message in compacted_model_input])+ self.assertIn("Summary", model_input_text)+ self.assertIn("First", model_input_text)+ self.assertNotIn("Event list" * 200000, model_input_text)@patch("ee.hogai.tools.search.SearchTool._arun_impl", return_value=("Docs doubt it", None))@patch(diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex 87117a49a82d..51ebe5c5f67b 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -35,6 +35,7 @@ from products.notebooks.backend.facade.widgets import reusable_widget_catalog_cofrom ee.hogai.context.dashboard.context import DashboardContext, DashboardInsightContextfrom ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.context.notebook.prompts import ROOT_NOTEBOOKS_CONTEXT_PROMPT, cell_guidance_promptfrom ee.hogai.core.mixins import AssistantContextMixinfrom ee.hogai.utils.helpers import find_start_message, find_start_message_idx, insert_messages_before_start@@ -543,6 +544,7 @@ class AssistantContextManager(AssistantContextMixin):variables_override = {k: v.model_dump(mode="json") for k, v in insight.variablesOverride.items()}return InsightContext(+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,team=self._team,user=self._user,event_source=self.event_source,diff --git a/ee/hogai/context/dashboard/context.py b/ee/hogai/context/dashboard/context.pyindex 423abe3aed04..478ad936b955 100644--- a/ee/hogai/context/dashboard/context.py+++ b/ee/hogai/context/dashboard/context.py@@ -8,6 +8,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.utils.helpers import build_dashboard_urlfrom ee.hogai.utils.prompt import format_prompt_stringfrom ee.hogai.utils.types.base import AnyPydanticModelQuery@@ -166,6 +167,7 @@ class DashboardContext:def _create_insight_context(self, data: DashboardInsightContext) -> InsightContext:"""Create an InsightContext from DashboardInsightContext model."""return InsightContext(+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,team=self.team,query=data.query,user=self.user,diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex 3882324d9a0e..596b687d7ccc 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -45,10 +45,12 @@ class InsightContext:filters_override: dict | None = None,variables_override: dict | None = None,event_source: EventSource = EventSource.POSTHOG_AI,- ):+ max_sql_result_chars: int | None = None,+ ) -> None:self.team = teamself.user = userself.event_source = event_source+ self.max_sql_result_chars = max_sql_result_charsself.query = queryself.name = nameself.description = description@@ -100,6 +102,7 @@ class InsightContext:user=self.user,include_prompt_framing=include_prompt_framing,event_source=self.event_source,+ max_sql_result_chars=self.max_sql_result_chars,)except Exception as e:error_message = f"Error executing query: {str(e)}"diff --git a/ee/hogai/context/insight/format/sql.py b/ee/hogai/context/insight/format/sql.pyindex 2c7a7ebac3b1..e5225ec7809f 100644--- a/ee/hogai/context/insight/format/sql.py+++ b/ee/hogai/context/insight/format/sql.py@@ -14,6 +14,12 @@ class SQLResultsFormatter:"""MAX_CELL_LENGTH = 500+ MAX_RESULT_CHARS = 64_000+ MIN_RESULT_CHARS = 512+ PREVIEW_GUIDANCE = (+ "Omitted rows or shortened cells are not evidence of missing data. "+ "Select fewer columns, aggregate, filter, or paginate with a stable ORDER BY to inspect more data."+ )def __init__(self,@@ -21,11 +27,16 @@ class SQLResultsFormatter:results: list[dict[str, Any]],columns: list[str],max_cell_length: int | None = MAX_CELL_LENGTH,- ):+ *,+ max_result_chars: int | None = None,+ ) -> None:self._query = queryself._results = resultsself._columns = columnsself._max_cell_length = max_cell_length+ self._max_result_chars = max_result_chars+ if max_result_chars is not None and max_result_chars < self.MIN_RESULT_CHARS:+ raise ValueError("The SQL preview budget must be at least 512 characters")self._has_truncated_values = False@property@@ -33,7 +44,7 @@ class SQLResultsFormatter:return self._has_truncated_valuesdef _format_cell(self, cell: Any) -> str:- """Format a single cell value, truncating large dicts/arrays or stringified JSON."""+ """MCP keeps JSON-only truncation; native agent previews also bound plain text."""if cell is None:# Bare str(None) yields "None", which LLMs read as a value rather than as missing data.return NULL_MARKER@@ -50,19 +61,63 @@ class SQLResultsFormatter:isinstance(cell, str) and cell_str and cell_str[0] in ("{", "["))- if self._max_cell_length is not None and is_json_like and len(cell_str) > self._max_cell_length:+ if (+ self._max_cell_length is not None+ and (is_json_like or self._max_result_chars is not None)+ and len(cell_str) > self._max_cell_length+ ):self._has_truncated_values = True- return cell_str[: self._max_cell_length] + TRUNCATED_MARKER+ prefix_length = self._max_cell_length+ if self._max_result_chars is not None:+ prefix_length = max(0, prefix_length - len(TRUNCATED_MARKER))+ return cell_str[:prefix_length] + TRUNCATED_MARKERreturn cell_str+ def _preview_notice(self, shown_rows: int, *, omitted_header: bool = False) -> str:+ details = f"Showing {shown_rows} of {len(self._results)} returned rows."+ if omitted_header:+ details += " The header or first row is too wide to show."+ if self._has_truncated_values:+ details += " Some cells were shortened."+ return f"[SQL result preview: {details} {self.PREVIEW_GUIDANCE}]"++ @classmethod+ def bound_fallback(cls, content: str, max_result_chars: int | None) -> str:+ if max_result_chars is None or len(content) <= max_result_chars:+ return content+ notice = f"\n[Incomplete SQL result preview. Any JSON shown may be cut off. {cls.PREVIEW_GUIDANCE}]"+ return content[: max(0, max_result_chars - len(notice))] + notice+def format(self) -> str:+ self._has_truncated_values = Falselines: list[str] = []- lines.append("|".join(self._columns))+ header = "|".join(self._columns)+ budget = self._max_result_chars+ if budget is not None and len(header) > budget:+ return self._preview_notice(0, omitted_header=True)+ lines.append(header)+ chars = len(header)+ shown_rows = 0for row in self._results:if isinstance(row, dict):- lines.append("|".join([self._format_cell(cell) for cell in row.values()]))+ line = "|".join([self._format_cell(cell) for cell in row.values()])else:- lines.append("|".join([self._format_cell(cell) for cell in row])) # type: ignore+ line = "|".join([self._format_cell(cell) for cell in row]) # type: ignore+ if budget is not None and chars + len(line) + 1 > budget:+ break+ lines.append(line)+ chars += len(line) + 1+ shown_rows += 1++ if budget is not None and (shown_rows < len(self._results) or self._has_truncated_values):+ notice = self._preview_notice(shown_rows, omitted_header=shown_rows == 0 and bool(self._results))+ while shown_rows > 0 and chars + len(notice) + 1 > budget:+ chars -= len(lines.pop()) + 1+ shown_rows -= 1+ notice = self._preview_notice(shown_rows, omitted_header=shown_rows == 0)+ if chars + len(notice) + 1 > budget:+ return self._preview_notice(0, omitted_header=True)+ lines.append(notice)return "\n".join(lines)diff --git a/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.py b/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.pyindex ca7d3107d1b4..564fdc523c7b 100644--- a/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.py+++ b/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.py@@ -32,6 +32,15 @@ def _mock_team() -> MagicMock:class TestFormatQueryResultsForLlm(TestCase):+ def test_shared_sql_formatter_keeps_large_mcp_output(self) -> None:+ value = "example text " * 6000+ result = format_query_results_for_llm(+ DataVisualizationNode(source=HogQLQuery(query="SELECT example FROM example_table")),+ {"columns": ["example"], "results": [[value]]},+ _mock_team(),+ )+ self.assertEqual(result, "example\n" + value)+@parameterized.expand([(diff --git a/ee/hogai/context/insight/format/test/test_sql.py b/ee/hogai/context/insight/format/test/test_sql.pyindex d23f818f3503..bcd2ff5439a9 100644--- a/ee/hogai/context/insight/format/test/test_sql.py+++ b/ee/hogai/context/insight/format/test/test_sql.py@@ -1,13 +1,68 @@from typing import Any-from posthog.test.base import BaseTest+from django.test import SimpleTestCase++from parameterized import parameterizedfrom posthog.schema import AssistantHogQLQueryfrom .. import NULL_MARKER, TRUNCATED_MARKER, SQLResultsFormatter-class TestSQLResultsFormatter(BaseTest):+class TestSQLResultsFormatter(SimpleTestCase):+ @parameterized.expand([511, 512, 513])+ def test_preview_at_total_budget_boundary(self, total_chars: int) -> None:+ rows = [{"a": "x" * 250, "b": "y" * (total_chars - 255)}]+ formatter = SQLResultsFormatter(AssistantHogQLQuery(query="SELECT 1"), rows, ["a", "b"], max_result_chars=512)+ output = formatter.format()+ self.assertLessEqual(len(output), 512)+ if total_chars <= 512:+ self.assertEqual(len(output), total_chars)+ self.assertNotIn("SQL result preview", output)+ else:+ self.assertIn("Showing 0 of 1 returned rows", output)++ @parameterized.expand(["text", "json", "unicode"])+ def test_bounded_preview_shortens_cells_and_omits_complete_rows(self, kind: str) -> None:+ value: str | dict[str, str] = "x" * 20000+ if kind == "json":+ value = {"example": "x" * 20000}+ elif kind == "unicode":+ value = "🦔" * 20000+ rows = [{"id": i, "value": value} for i in range(100)]+ formatter = SQLResultsFormatter(+ AssistantHogQLQuery(query="SELECT 1"), rows, ["id", "value"], max_result_chars=2000+ )+ result = formatter.format()+ table, notice = result.rsplit("\n", 1)+ shown_rows = table.splitlines()[1:]+ self.assertLessEqual(len(result), 2000)+ self.assertEqual(len(shown_rows), 3)+ self.assertTrue(all(len(row.split("|", 1)[1]) <= 500 for row in shown_rows))+ self.assertIn("Showing 3 of 100 returned rows", notice)+ self.assertIn("Some cells were shortened", notice)+ self.assertIn("not evidence of missing data", notice)+ self.assertEqual(rows[0]["value"], value)++ @parameterized.expand(["header", "row"])+ def test_bounded_preview_omits_oversized_table_structure(self, kind: str) -> None:+ columns = ["x" * 600] if kind == "header" else ["a", "b"]+ rows = [{"a": "x" * 500, "b": "y" * 500}]+ formatter = SQLResultsFormatter(AssistantHogQLQuery(query="SELECT 1"), rows, columns, max_result_chars=512)+ result = formatter.format()+ self.assertLessEqual(len(result), 512)+ self.assertIn("Showing 0 of 1 returned rows", result)+ self.assertIn("too wide to show", result)++ @parameterized.expand([0, 1, 2])+ def test_bounded_preview_preserves_small_results(self, count: int) -> None:+ rows = [{"id": i, "value": None} for i in range(count)]+ query = AssistantHogQLQuery(query="SELECT 1")+ self.assertEqual(+ SQLResultsFormatter(query, rows, ["id", "value"], max_result_chars=512).format(),+ SQLResultsFormatter(query, rows, ["id", "value"]).format(),+ )+def test_format_basic(self):query = AssistantHogQLQuery(query="SELECT 1")results = [diff --git a/ee/hogai/context/insight/prompts.py b/ee/hogai/context/insight/prompts.pyindex 08c07180e67d..282dcdb3e4e1 100644--- a/ee/hogai/context/insight/prompts.py+++ b/ee/hogai/context/insight/prompts.py@@ -48,7 +48,7 @@ Always add `LIMIT 100` to your queries. The maximum allowed limit is 500 rows. IIt's expected that the data point for the current period may show a drop in value, as data collection for it is still ongoing. Do not point this out.Do not copy the results table as the user sees it in the UI.{{#has_truncated_values}}-Some JSON/array values were truncated. You can write a more specific SQL query to explore individual properties or array elements if needed.+Some cell values were shortened. You can write a more specific SQL query to inspect those values if needed.{{/has_truncated_values}}{{#has_null_values}}Cells shown as `(null)` are SQL NULL: the column had no value for those rows, usually because the property is absent on that event. Treat them as missing data. Never report `(null)` as a value, and never conclude a property is set to "null" or "None" from them.diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 29a553b3b7f1..4550ba0676fe 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -152,11 +152,15 @@ class AssistantQueryExecutor:utc_now_datetime: datetime,user: "User",event_source: EventSource = EventSource.POSTHOG_AI,- ):+ max_sql_result_chars: int | None = None,+ ) -> None:self._team = teamself._utc_now_datetime = utc_now_datetimeself._user = userself._event_source = event_source+ if max_sql_result_chars is not None and max_sql_result_chars < SQLResultsFormatter.MIN_RESULT_CHARS:+ raise ValueError("The SQL preview budget must be at least 512 characters")+ self._max_sql_result_chars = max_sql_result_charsasync def arun_format_and_capture(self,@@ -224,6 +228,8 @@ class AssistantQueryExecutor:# Fallback to raw JSON if formatting fails - ensures robustnessfallback_start = time.time()fallback_results = json.dumps(response_dict["results"], cls=DjangoJSONEncoder, separators=(",", ":"))+ if isinstance(query, AssistantHogQLQuery | HogQLQuery | DataVisualizationNode):+ fallback_results = SQLResultsFormatter.bound_fallback(fallback_results, self._max_sql_result_chars)fallback_elapsed = time.time() - fallback_starttotal_elapsed = time.time() - start_timeif debug_timing:@@ -519,6 +525,16 @@ class AssistantQueryExecutor:if not is_supported_query(query):raise NotImplementedError(f"Unsupported query type: {query_type}")+ warning_prefix = format_warehouse_sync_warnings(response) + format_access_control_warnings(response)+ result_budget = self._max_sql_result_chars+ if isinstance(query, AssistantHogQLQuery | HogQLQuery | DataVisualizationNode) and result_budget is not None:+ result_budget -= len(warning_prefix)+ if result_budget < SQLResultsFormatter.MIN_RESULT_CHARS:+ return SQLResultsFormatter.bound_fallback(+ "[SQL result preview omitted because query warnings exceed the preview budget.]\n" + warning_prefix,+ self._max_sql_result_chars,+ )+try:# Handle assistant-specific query types with direct formattingif isinstance(query, AssistantTrendsQuery | TrendsQuery):@@ -551,13 +567,21 @@ class AssistantQueryExecutor:formatter_name = "SQLResultsFormatter"max_cell_length = SQLResultsFormatter.MAX_CELL_LENGTH if truncate_results else Noneresult = SQLResultsFormatter(- query.source, response["results"], response["columns"], max_cell_length=max_cell_length+ query.source,+ response["results"],+ response["columns"],+ max_cell_length=max_cell_length,+ max_result_chars=result_budget,).format()elif isinstance(query, AssistantHogQLQuery | HogQLQuery):formatter_name = "SQLResultsFormatter"max_cell_length = SQLResultsFormatter.MAX_CELL_LENGTH if truncate_results else Noneresult = SQLResultsFormatter(- query, response["results"], response["columns"], max_cell_length=max_cell_length+ query,+ response["results"],+ response["columns"],+ max_cell_length=max_cell_length,+ max_result_chars=result_budget,).format()else:raise NotImplementedError(f"Unsupported query type: {query_type}")@@ -568,9 +592,10 @@ class AssistantQueryExecutor:f"{TIMING_LOG_PREFIX} {formatter_name}.format() completed in {elapsed:.3f}s for {query_type}")- warning_prefix = format_warehouse_sync_warnings(response) + format_access_control_warnings(response)if warning_prefix:result = warning_prefix + result+ if isinstance(query, AssistantHogQLQuery | HogQLQuery | DataVisualizationNode):+ result = SQLResultsFormatter.bound_fallback(result, self._max_sql_result_chars)return resultexcept Exception:elapsed = time.time() - start_time@@ -626,6 +651,7 @@ async def execute_and_format_query(truncate_results: bool = True,include_prompt_framing: bool = True,event_source: EventSource = EventSource.POSTHOG_AI,+ max_sql_result_chars: int | None = None,) -> str:"""Executes a supported query and formats the results for the AI assistant:@@ -649,7 +675,9 @@ async def execute_and_format_query("""query = validate_assistant_query(query_model.model_dump(mode="json"))utc_now_datetime = timezone.now().astimezone(UTC)- query_runner = AssistantQueryExecutor(team, utc_now_datetime, user=user, event_source=event_source)+ query_runner = AssistantQueryExecutor(+ team, utc_now_datetime, user=user, event_source=event_source, max_sql_result_chars=max_sql_result_chars+ )results, used_fallback = await query_runner.arun_and_format_query(query, execution_mode, insight_id, truncate_results=truncate_resultsdiff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex d801c601ef53..e856064adcf0 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -5,8 +5,9 @@ import time_machinefrom posthog.test.base import NonAtomicBaseTestfrom unittest.mock import Mock, patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settings+from parameterized import parameterizedfrom rest_framework.exceptions import APIExceptionfrom posthog.schema import (@@ -40,7 +41,10 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_contextfrom posthog.errors import ExposedCHQueryError+from posthog.models import Organization, Team, User+from ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.context.insight.query_executor import (AssistantQueryExecutor,execute_and_format_query,@@ -51,6 +55,45 @@ from ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.utils.query import validate_assistant_query+class TestSQLResultBudgets(SimpleTestCase):+ @parameterized.expand(["table", "fallback", "warnings"])+ async def test_sql_result_budget_reaches_formatting_and_fallback(self, kind: str) -> None:+ response: dict[str, Any] = {"results": [["x" * 2000] for _ in range(100)]}+ if kind != "fallback":+ response["columns"] = ["example"]+ if kind == "warnings":+ response["warnings"] = [{"type": "warehouse_sync", "message": "Sync is delayed. " * 100}]+ context = InsightContext(+ team=Team(id=1, organization=Organization()),+ user=User(),+ query=HogQLQuery(query="SELECT 1"),+ max_sql_result_chars=2000,+ )+ with (+ patch("ee.hogai.context.insight.query_executor.process_query_dict", return_value=response),+ patch("ee.hogai.context.insight.query_executor.capture_exception"),+ ):+ result = await context.execute_and_format(prompt_template="{{{results}}}", include_prompt_framing=False)+ self.assertLessEqual(len(result), 2000)+ self.assertIn("SQL result preview", result)+ self.assertEqual(response["results"][0][0], "x" * 2000)+ if kind == "fallback":+ self.assertIn("JSON shown may be cut off", result)++ def test_synchronous_execution_keeps_sql_budget(self) -> None:+ runner = AssistantQueryExecutor(+ team=Team(id=1, organization=Organization()),+ user=User(),+ utc_now_datetime=datetime.now(),+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,+ )+ response = {"columns": ["example"], "results": [["x" * 2000] for _ in range(300)]}+ with patch("ee.hogai.context.insight.query_executor.process_query_dict", return_value=response):+ result, used_fallback = runner.run_and_format_query(HogQLQuery(query="SELECT 1"))+ self.assertLessEqual(len(result), SQLResultsFormatter.MAX_RESULT_CHARS)+ self.assertFalse(used_fallback)++class TestAssistantQueryExecutor(NonAtomicBaseTest):CLASS_DATA_LEVEL_SETUP = Falsediff --git a/ee/hogai/core/agent_modes/compaction_manager.py b/ee/hogai/core/agent_modes/compaction_manager.pyindex 66685924c877..22f580a7d5c4 100644--- a/ee/hogai/core/agent_modes/compaction_manager.py+++ b/ee/hogai/core/agent_modes/compaction_manager.py@@ -29,7 +29,7 @@ from posthog.sync import database_sync_to_asyncfrom ee.hogai.context.prompts import CONTEXT_INITIAL_MODE_PROMPTfrom ee.hogai.core.agent_modes.prompts import ROOT_AGENT_MODE_REMINDER_PROMPT, ROOT_TODO_REMINDER_PROMPTfrom ee.hogai.tools.todo_write import TodoWriteTool-from ee.hogai.utils.helpers import find_start_message, find_start_message_idx, insert_messages_before_start+from ee.hogai.utils.helpers import find_start_messagefrom ee.hogai.utils.prompt import format_prompt_stringfrom ee.hogai.utils.types import AssistantMessageUnion@@ -40,7 +40,7 @@ LangchainTools = Sequence[dict[str, Any] | type | Callable | BaseTool]class InsertionResult(BaseModel):messages: Sequence[AssistantMessageUnion]- updated_start_id: str+ updated_start_id: str | Noneupdated_window_start_id: str@@ -129,139 +129,48 @@ class ConversationCompactionManager(ABC):summary_message: ContextMessage,agent_mode: AgentMode,start_id: str | None = None,+ *,+ window_start_id: str | None = None,) -> InsertionResult:"""Finds the optimal position to insert the summary message in the conversation window."""- window_start_id_candidate = self.find_window_boundary(messages, max_messages=16, max_tokens=2048)+ active_window = self.get_messages_in_window(messages, window_start_id)+ boundary_id = self.find_window_boundary(active_window, max_messages=16, max_tokens=2048)start_message = find_start_message(messages, start_id)- if not start_message:+ if not isinstance(start_message, HumanMessage):raise ValueError("Start message not found")+ if summary_message.id is None:+ raise ValueError("Summary message must have an ID")- start_message_copy = start_message.model_copy(deep=True)- start_message_copy.id = str(uuid4())-- # The last messages were too large to fit into the window. Copy the last human message to the start of the window.- if not window_start_id_candidate:- return self._handle_no_window_boundary(messages, summary_message, start_message_copy, agent_mode)-- # Find the updated window- start_message_idx = find_start_message_idx(messages, window_start_id_candidate)- new_window = messages[start_message_idx:]-- # If the start human message is in the window, insert the summary message before it- # and update the window start.- if start_id and next((m for m in new_window if m.id == start_id), None):- return self._handle_start_in_window(- messages,- summary_message,- start_id,- window_start_id_candidate,- agent_mode,- )-- # If the start message is not in the window, insert the summary message and human message at the start of the window.- return self._handle_start_outside_window(- new_window,- summary_message,- start_message_copy,- window_start_id_candidate,+ boundary_idx = next(+ (idx for idx, message in enumerate(messages) if boundary_id is not None and message.id == boundary_id),+ len(messages),+ )+ retained_messages = messages[boundary_idx:]+ inserted_messages: list[AssistantMessageUnion] = [summary_message]+ if not any(message is start_message for message in retained_messages):+ # The original request stays in the archived history, and the thread renders every HumanMessage,+ # so the copy the model needs is a ContextMessage: it reaches the model as a user turn but never+ # reaches the rendered thread or the stream.+ inserted_messages.append(ContextMessage(content=start_message.content, id=str(uuid4())))++ # Keep the display history intact; only the model's window moves past archived messages.+ updated_messages: Sequence[AssistantMessageUnion] = [+ *messages[:boundary_idx],+ *inserted_messages,+ *retained_messages,+ ]+ updated_messages = self._insert_reminders_after_summary(+ updated_messages,+ summary_message.id,agent_mode,all_messages=messages,+ window_messages=retained_messages,)- def _handle_no_window_boundary(- self,- messages: Sequence[T],- summary_message: ContextMessage,- start_message_copy: HumanMessage,- agent_mode: AgentMode,- ) -> InsertionResult:- """Handle case where no window boundary was found (messages too large)."""- # Build the new window- new_window_messages: Sequence[AssistantMessageUnion] = [summary_message, start_message_copy]-- # Prepare result messages with summary and start- result_messages = [*messages, summary_message, start_message_copy]-- # Insert todo and/or mode reminders between summary and start- summary_id = summary_message.id- if summary_id:- result_messages_with_reminders = self._insert_reminders_after_summary(- result_messages, summary_id, agent_mode, all_messages=messages, window_messages=new_window_messages- )- else:- result_messages_with_reminders = result_messages-- return InsertionResult(- messages=result_messages_with_reminders,- updated_start_id=start_message_copy.id,- updated_window_start_id=summary_message.id,- )-- def _handle_start_in_window(- self,- messages: Sequence[T],- summary_message: ContextMessage,- start_id: str,- window_start_id_candidate: str,- agent_mode: AgentMode,- ) -> InsertionResult:- """Handle case where start message is within the window boundary."""- # Insert summary before start message- updated_messages = insert_messages_before_start(messages, [summary_message], start_id=start_id)-- # Calculate the actual window from window_start_id_candidate onwards- start_message_idx = find_start_message_idx(messages, window_start_id_candidate)- window_messages = messages[start_message_idx:]-- # Insert todo and/or mode reminders after summary- if summary_message.id:- updated_messages = list(- self._insert_reminders_after_summary(- updated_messages,- summary_message.id,- agent_mode,- all_messages=messages,- window_messages=window_messages,- )- )-- return InsertionResult(- messages=updated_messages,- updated_start_id=start_id,- updated_window_start_id=window_start_id_candidate,- )-- def _handle_start_outside_window(- self,- new_window: Sequence[T],- summary_message: ContextMessage,- start_message_copy: HumanMessage,- window_start_id_candidate: str,- agent_mode: AgentMode,- all_messages: Sequence[T] | None = None,- ) -> InsertionResult:- """Handle case where start message is outside the window boundary."""- # Insert summary and start copy at the beginning of window- updated_messages = list(- insert_messages_before_start(- new_window, [summary_message, start_message_copy], start_id=window_start_id_candidate- )- )-- # Insert todo and/or mode reminders after summary- # The window is the new_window (which will be checked for mode/todo presence)- summary_id = summary_message.id- if summary_id:- updated_messages = list(- self._insert_reminders_after_summary(- updated_messages, summary_id, agent_mode, all_messages=all_messages, window_messages=new_window- )- )-return InsertionResult(messages=updated_messages,- updated_start_id=start_message_copy.id,- updated_window_start_id=window_start_id_candidate,+ updated_start_id=start_message.id,+ updated_window_start_id=summary_message.id,)def _insert_reminders_after_summary(@@ -320,7 +229,7 @@ class ConversationCompactionManager(ABC):Estimate token count for a message using character/4 heuristic."""char_count = 0- if isinstance(message, HumanMessage):+ if isinstance(message, HumanMessage | ContextMessage):char_count = len(message.content)elif isinstance(message, AssistantMessage):char_count = len(message.content) + sum(diff --git a/ee/hogai/core/agent_modes/executables.py b/ee/hogai/core/agent_modes/executables.pyindex a24c7eb53e0a..c1973f14e00b 100644--- a/ee/hogai/core/agent_modes/executables.py+++ b/ee/hogai/core/agent_modes/executables.py@@ -177,6 +177,7 @@ class AgentExecutable(BaseAgentLoopRootExecutable):summary_message,state.agent_mode_or_default,start_id=start_id,+ window_start_id=window_id,)window_id = insertion_result.updated_window_start_idstart_id = insertion_result.updated_start_iddiff --git a/ee/hogai/core/agent_modes/test/test_compaction_manager.py b/ee/hogai/core/agent_modes/test/test_compaction_manager.pyindex 0af19c5ceca9..146b86216b1c 100644--- a/ee/hogai/core/agent_modes/test/test_compaction_manager.py+++ b/ee/hogai/core/agent_modes/test/test_compaction_manager.py@@ -1,8 +1,9 @@from uuid import uuid4-from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.test import SimpleTestCase+from langchain_core.messages import (AIMessage as LangchainAIMessage,BaseMessage,@@ -20,16 +21,121 @@ from posthog.schema import (HumanMessage,)-from ee.hogai.utils.types.base import AssistantMessageUnion+from ee.hogai.utils.anthropic import convert_to_anthropic_messages+from ee.hogai.utils.helpers import convert_tool_messages_to_dict, should_output_assistant_message+from ee.hogai.utils.types.base import ArtifactRefMessage, AssistantMessageUnionfrom ..compaction_manager import AnthropicConversationCompactionManager-class TestAnthropicConversationCompactionManager(BaseTest):+class TestAnthropicConversationCompactionManager(SimpleTestCase):def setUp(self):super().setUp()self.window_manager = AnthropicConversationCompactionManager()+ @parameterized.expand(["human_boundary", "assistant_boundary", "oversized_final_result"])+ def test_compacted_model_input_keeps_task_and_progress(self, boundary: str) -> None:+ request = HumanMessage(content="Compare the example cohorts", id="request")+ progress = AssistantMessage(+ id="progress",+ content="",+ tool_calls=[+ AssistantToolCall(+ id="todo",+ name=AssistantTool.TODO_WRITE,+ args={"todos": [{"id": "1", "content": "Explain the comparison", "status": "in_progress"}]},+ )+ ],+ )+ messages: list[AssistantMessageUnion] = [+ request,+ progress,+ AssistantToolCallMessage(id="todo-result", tool_call_id="todo", content="Updated"),+ AssistantMessage(+ id="large-call",+ content="",+ tool_calls=[AssistantToolCall(id="sql-large", name="execute_sql", args={"query": "SELECT 1"})],+ ),+ ArtifactRefMessage(id="artifact", artifact_id="example1", content_type="visualization", source="artifact"),+ AssistantToolCallMessage(id="large-result", tool_call_id="sql-large", content="x" * 9000),+ ]+ if boundary == "human_boundary":+ request = HumanMessage(content="Explain the comparison", id="follow-up")+ messages.append(request)+ if boundary != "oversized_final_result":+ messages.extend(+ [+ AssistantMessage(+ id="small-call",+ content="",+ tool_calls=[+ AssistantToolCall(id="sql-small", name="execute_sql", args={"query": "SELECT 2"}),+ AssistantToolCall(id="sql-other", name="execute_sql", args={"query": "SELECT 3"}),+ ],+ ),+ AssistantToolCallMessage(id="small-result", tool_call_id="sql-small", content="2"),+ AssistantToolCallMessage(id="other-result", tool_call_id="sql-other", content="3"),+ ]+ )+ summary = ContextMessage(id="summary", content="Both cohorts were queried. Explain the difference.")+ result = self.window_manager.update_window(messages, summary, AgentMode.PRODUCT_ANALYTICS, start_id=request.id)+ window = self.window_manager.get_messages_in_window(result.messages, result.updated_window_start_id)+ model_input = convert_to_anthropic_messages(window, convert_tool_messages_to_dict(window))+ text = str([message.content for message in model_input])++ self.assertEqual(window[0].id, summary.id)+ self.assertIn(summary.content, text)+ self.assertIn(request.content, text)+ self.assertIn("Explain the comparison", text)+ self.assertIn("product_analytics mode", text)+ self.assertNotIn("x" * 9000, text)+ self.assertTrue(all(message in result.messages for message in messages))+ self.assertEqual(result.updated_start_id, request.id)+ rendered_requests = [+ message+ for message in result.messages+ if should_output_assistant_message(message)+ and isinstance(message, HumanMessage)+ and message.content == request.content+ ]+ self.assertEqual(rendered_requests, [request])+ if boundary != "oversized_final_result":+ tool_calls = [+ call["id"]+ for message in model_input+ if isinstance(message, LangchainAIMessage)+ for call in message.tool_calls+ ]+ self.assertEqual(tool_calls, ["sql-small", "sql-other"])+ self.assertIn("sql-small", text)+ self.assertIn("sql-other", text)++ def test_repeated_compaction_stays_within_active_window(self) -> None:+ messages: list[AssistantMessageUnion] = [+ HumanMessage(id="request", content="Compare the cohorts"),+ AssistantMessage(id="old-result", content="x" * 9000),+ ]+ first = self.window_manager.update_window(+ messages,+ ContextMessage(id="summary-one", content="First summary " * 1000),+ AgentMode.PRODUCT_ANALYTICS,+ start_id="request",+ )+ second = self.window_manager.update_window(+ first.messages,+ ContextMessage(id="summary-two", content="The comparison is complete"),+ AgentMode.PRODUCT_ANALYTICS,+ start_id=first.updated_start_id,+ window_start_id=first.updated_window_start_id,+ )+ window = self.window_manager.get_messages_in_window(second.messages, second.updated_window_start_id)+ self.assertEqual(window[0].id, "summary-two")+ self.assertNotIn("summary-one", [message.id for message in window])+ self.assertNotIn("old-result", [message.id for message in window])+ model_input = convert_to_anthropic_messages(window, convert_tool_messages_to_dict(window))+ self.assertIn("Compare the cohorts", str([message.content for message in model_input]))+ self.assertTrue(all(message in second.messages for message in first.messages))+def test_find_window_boundary_basic(self):"""Test finding window boundary with basic messages"""messages: list[AssistantMessageUnion] = [@@ -377,10 +483,10 @@ class TestAnthropicConversationCompactionManager(BaseTest):self.assertEqual(result.messages[0].id, start_id)self.assertEqual(result.messages[-3].id, summary_id)last_msg = result.messages[-1]- assert isinstance(last_msg, HumanMessage) # Type narrowing+ assert isinstance(last_msg, ContextMessage) # Type narrowingself.assertEqual(last_msg.content, "Initial question")self.assertNotEqual(last_msg.id, start_id)- self.assertEqual(result.updated_start_id, last_msg.id)+ self.assertEqual(result.updated_start_id, start_id)self.assertEqual(result.updated_window_start_id, summary_id)def test_update_window_initiator_in_window(self):@@ -447,21 +553,21 @@ class TestAnthropicConversationCompactionManager(BaseTest):messages, summary_message, AgentMode.PRODUCT_ANALYTICS, start_id=start_id)- # The start message should NOT be in the result (only its copy)- start_messages = [msg for msg in result.messages if msg.id == start_id]- self.assertEqual(len(start_messages), 0, "Original start message should not be in result")+ window = self.window_manager.get_messages_in_window(result.messages, result.updated_window_start_id)+ self.assertTrue(any(msg.id == start_id for msg in result.messages))+ self.assertFalse(any(msg.id == start_id for msg in window))# Find the copied start message (same content, different ID)copied_start = next(- (msg for msg in result.messages if isinstance(msg, HumanMessage) and msg.content == "Initial question"),+ (msg for msg in window if isinstance(msg, ContextMessage) and msg.content == "Initial question"),None,)self.assertIsNotNone(copied_start, "Copied start message should exist")assert copied_start is not None # Type narrowingself.assertNotEqual(copied_start.id, start_id, "Copied message should have new ID")- # The copied start message should have a new ID returned- self.assertEqual(result.updated_start_id, copied_start.id)+ # The start ID keeps pointing at the original request+ self.assertEqual(result.updated_start_id, start_id)# Summary, mode reminder, and copied start should be at the beginning of the windowsummary_idx = next(i for i, msg in enumerate(result.messages) if msg.id == summary_id)@@ -708,8 +814,8 @@ class TestAnthropicConversationCompactionManager(BaseTest):self.assertEqual(len(result.messages), 5) # original 2 + summary + mode reminder + copied startself.assertEqual(result.messages[-3].id, summary_id)self.assertEqual(result.updated_window_start_id, summary_id)- # Updated start ID should be the copied message- self.assertNotEqual(result.updated_start_id, start_id)+ # Updated start ID keeps pointing at the original request+ self.assertEqual(result.updated_start_id, start_id)def test_update_window_single_message_conversation(self):"""Test update_window with a minimal single-message conversation"""@@ -763,7 +869,7 @@ class TestAnthropicConversationCompactionManager(BaseTest):assert isinstance(result.messages[3], ContextMessage)self.assertIn("product_analytics", result.messages[3].content)self.assertNotEqual(result.messages[3].id, summary_id)- self.assertIsInstance(result.messages[4], HumanMessage)+ self.assertIsInstance(result.messages[4], ContextMessage)self.assertNotEqual(result.messages[4].id, start_id) # Copied start message has new IDdef test_mode_message_injection_when_feature_flag_enabled_start_in_window(self):@@ -838,7 +944,7 @@ class TestAnthropicConversationCompactionManager(BaseTest):if isinstance(msg, ContextMessage) and "session_replay" in msg.content)copied_start = next(- (msg for msg in result.messages if isinstance(msg, HumanMessage) and msg.content == "Initial question"),+ (msg for msg in result.messages if isinstance(msg, ContextMessage) and msg.content == "Initial question"),None,)self.assertIsNotNone(copied_start)@@ -856,7 +962,7 @@ class TestAnthropicConversationCompactionManager(BaseTest):self.assertIsInstance(mode_msg, ContextMessage)assert isinstance(mode_msg, ContextMessage)self.assertIn("session_replay", mode_msg.content)- self.assertIsInstance(result.messages[copied_start_idx], HumanMessage)+ self.assertIsInstance(result.messages[copied_start_idx], ContextMessage)self.assertNotEqual(copied_start.id, start_id)def test_no_mode_message_injection_when_mode_evident_in_window(self):@@ -1041,7 +1147,9 @@ class TestAnthropicConversationCompactionManager(BaseTest):self.assertIsInstance(window_messages[1], ContextMessage)assert isinstance(window_messages[1], ContextMessage)self.assertIn("product_analytics", window_messages[1].content)- self.assertIsInstance(window_messages[2], HumanMessage)+ self.assertIsInstance(window_messages[2], ContextMessage)+ assert isinstance(window_messages[2], ContextMessage)+ self.assertEqual(window_messages[2].content, "Question")# Verify the mode reminder is NOT the switch_mode tool callhas_switch_mode_in_window = any(@@ -1472,9 +1580,9 @@ class TestAnthropicConversationCompactionManager(BaseTest):]self.assertGreater(len(todo_reminders), 0)- # Should NOT have mode reminder (only summary context message)+ # Should NOT have mode reminder (context messages are only the summary and the copied start)context_messages = [msg for msg in result.messages if isinstance(msg, ContextMessage)]- mode_reminders = [msg for msg in context_messages if msg.id != summary_id]+ mode_reminders = [msg for msg in context_messages if "product_analytics" in msg.content]self.assertEqual(len(mode_reminders), 0)def test_mode_reminder_only_no_todo_reminder(self):diff --git a/ee/hogai/core/agent_modes/test/test_executables.py b/ee/hogai/core/agent_modes/test/test_executables.pyindex 2023a55490b8..3d1e0050f413 100644--- a/ee/hogai/core/agent_modes/test/test_executables.py+++ b/ee/hogai/core/agent_modes/test/test_executables.py@@ -1,11 +1,12 @@from posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import AsyncMock, MagicMock, patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom langchain_core.messages import (AIMessage as LangchainAIMessage,HumanMessage as LangchainHumanMessage,+ SystemMessage,)from langchain_core.runnables import RunnableBinding, RunnableConfigfrom parameterized import parameterized@@ -23,6 +24,7 @@ from posthog.models import Team, Userfrom ee.hogai.chat_agent.mode_manager import ChatAgentModeManagerfrom ee.hogai.context import AssistantContextManager+from ee.hogai.core.agent_modes.executables import AgentExecutablefrom ee.hogai.llm import MaxChatAnthropicfrom ee.hogai.tool_errors import MaxToolError, MaxToolFatalError, MaxToolRetryableError, MaxToolTransientErrorfrom ee.hogai.tools.read_taxonomy.core import ReadEvents@@ -73,6 +75,77 @@ def _create_agent_tools_node(return mode_manager.tools_node+class TestAgentCompactionInput(SimpleTestCase):+ async def test_repeated_compaction_preserves_model_input_and_iteration_count(self) -> None:+ toolkit = MagicMock()+ toolkit.get_tools = AsyncMock(return_value=[])+ prompts = MagicMock()+ prompts.get_prompts = AsyncMock(side_effect=lambda *_: [SystemMessage(content="Analyze the example data")])+ node = AgentExecutable(+ team=Team(),+ user=User(),+ toolkit_manager_class=MagicMock(return_value=toolkit),+ prompt_builder_class=MagicMock(return_value=prompts),+ node_path=(),+ )+ model = MagicMock()+ model.get_num_tokens_from_messages.return_value = 450_000+ model.ainvoke = AsyncMock(+ return_value=LangchainAIMessage(+ content="", tool_calls=[{"id": "next-tool", "name": "execute_sql", "args": {"query": "SELECT 3"}}]+ )+ )+ state = AssistantState(+ start_id="request",+ root_tool_calls_count=5,+ messages=[+ HumanMessage(id="request", content="Compare the example cohorts"),+ AssistantMessage(+ id="large-call",+ content="",+ tool_calls=[AssistantToolCall(id="large", name="execute_sql", args={"query": "SELECT 1"})],+ ),+ AssistantToolCallMessage(id="large-result", tool_call_id="large", content="x" * 9000),+ AssistantMessage(+ id="small-call",+ content="",+ tool_calls=[AssistantToolCall(id="small", name="execute_sql", args={"query": "SELECT 2"})],+ ),+ AssistantToolCallMessage(id="small-result", tool_call_id="small", content="2"),+ ],+ )+ with (+ patch.object(node, "_get_model", return_value=model),+ patch(+ "ee.hogai.core.agent_modes.executables.AnthropicConversationSummarizer.summarize",+ new=AsyncMock(side_effect=["First comparison complete", "Second comparison complete"]),+ ),+ ):+ first = await node.arun(state, {})+ first_input = str([message.content for message in model.ainvoke.call_args.args[0]])+ self.assertIn("First comparison complete", first_input)+ self.assertIn("Compare the example cohorts", first_input)+ self.assertNotIn("x" * 9000, first_input)+ self.assertEqual(first.root_tool_calls_count, 6)+ assert first.messages is not None+ state = AssistantState(+ messages=[+ *first.messages,+ AssistantToolCallMessage(id="next-result", tool_call_id="next-tool", content="y" * 9000),+ ],+ start_id=first.start_id,+ root_conversation_start_id=first.root_conversation_start_id,+ root_tool_calls_count=first.root_tool_calls_count,+ )+ second = await node.arun(state, {})+ second_input = str([message.content for message in model.ainvoke.call_args.args[0]])+ self.assertIn("Second comparison complete", second_input)+ self.assertIn("Compare the example cohorts", second_input)+ self.assertNotIn("First comparison complete", second_input)+ self.assertNotIn("y" * 9000, second_input)+ self.assertEqual(second.root_tool_calls_count, 7)++class TestAgentNode(ClickhouseTestMixin, BaseTest):async def test_node_handles_plain_chat_response(self):with patch(diff --git a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py b/ee/hogai/tools/execute_sql/test/test_mcp_tool.pyindex 0c1042b23c9f..392fc4485e2a 100644--- a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py@@ -1,17 +1,21 @@from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_eventfrom unittest.mock import AsyncMock, patch+from django.test import SimpleTestCase+from asgiref.sync import sync_to_asyncfrom parameterized import parameterizedfrom posthog.schema import HogQLNotice, HogQLQuery-from posthog.models import EventDefinition+from posthog.event_usage import EventSource+from posthog.models import EventDefinition, Organization, Team, Userfrom posthog.sync import database_sync_to_asyncfrom products.product_analytics.backend.facade.models import Insight, InsightVariablefrom ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.tools.execute_sql.compatibility_hints import ACCEPTED_CAST_TYPES, NESTABLE_BINARY_FUNCTIONSfrom ee.hogai.tools.execute_sql.mcp_tool import (@@ -22,6 +26,32 @@ from ee.hogai.tools.execute_sql.mcp_tool import ()+class TestExecuteSQLMCPOutputLimits(SimpleTestCase):+ @parameterized.expand(+ [+ ("default", EventSource.MCP, True),+ ("untruncated", EventSource.MCP, False),+ ("first_party_default", EventSource.POSTHOG_AI, True),+ ("first_party_untruncated", EventSource.POSTHOG_AI, False),+ ]+ )+ async def test_mcp_preserves_large_results(self, _name: str, source: EventSource, truncate: bool) -> None:+ value = "example text " * 200+ tool = ExecuteSQLMCPTool(team=Team(id=1, organization=Organization()), user=User(), event_source=source)+ response = {"columns": ["text", "json"], "results": [[value, {"example": value}] for _ in range(100)]}+ with patch("ee.hogai.context.insight.query_executor.process_query_dict", return_value=response):+ result = await tool.execute(+ ExecuteSQLMCPToolArgs(+ query="SELECT text, json FROM example_table", connectionId="example-connection", truncate=truncate+ )+ )+ self.assertGreater(len(result.content), SQLResultsFormatter.MAX_RESULT_CHARS)+ self.assertEqual(result.content.count(value), 100 if truncate else 200)+ self.assertNotIn("SQL result preview", result.content)+ if not truncate:+ self.assertNotIn("...truncated", result.content)++class TestExecuteSQLMCPTool(ClickhouseTestMixin, NonAtomicBaseTest):CLASS_DATA_LEVEL_SETUP = Falsediff --git a/ee/hogai/tools/execute_sql/test/test_tool.py b/ee/hogai/tools/execute_sql/test/test_tool.pyindex 831c8af6b34e..18d3ab17009b 100644--- a/ee/hogai/tools/execute_sql/test/test_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_tool.py@@ -1,11 +1,14 @@from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event, flush_persons_and_events-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import SimpleTestCasefrom asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfigfrom posthog.schema import (ArtifactContentType,+ ArtifactSource,AssistantToolCallMessage,ChartDisplayType,DataVisualizationNode,@@ -14,13 +17,51 @@ from posthog.schema import (VisualizationArtifactContent,)+from posthog.models import Organization, Team, User+from products.posthog_ai.backend.models.assistant import AgentArtifact, Conversationfrom products.product_analytics.backend.facade.models import Insightfrom ee.hogai.context.context import AssistantContextManager+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.tools.execute_sql.tool import ExecuteSQLTool, ExecuteSQLToolArgsfrom ee.hogai.utils.types import AssistantState-from ee.hogai.utils.types.base import NodePath+from ee.hogai.utils.types.base import ArtifactRefMessage, NodePath+++class TestExecuteSQLPreview(SimpleTestCase):+ async def test_native_tool_bounds_results_and_preserves_artifact_query(self) -> None:+ context = MagicMock(spec=AssistantContextManager)+ context.get_contextual_tools.return_value = {"execute_sql": {"connection_id": "example-connection"}}+ context.artifacts.acreate = AsyncMock(return_value=AgentArtifact(short_id="preview1"))+ context.artifacts.create_message.return_value = ArtifactRefMessage(+ id="artifact",+ artifact_id="preview1",+ content_type=ArtifactContentType.VISUALIZATION,+ source=ArtifactSource.ARTIFACT,+ )+ tool = ExecuteSQLTool(+ team=Team(id=1, organization=Organization()),+ user=User(),+ context_manager=context,+ description="Execute an example SQL query",+ node_path=(NodePath(name="test", tool_call_id="sql"),),+ )+ query = "SELECT text FROM example_table"+ response = {"columns": ["text"], "results": [["example text " * 200] for _ in range(300)]}+ with patch("ee.hogai.context.insight.query_executor.process_query_dict", return_value=response):+ _, artifact = await tool._arun_impl(query, "Example query", "Example description")+ assert artifact is not None+ message = artifact.messages[-1]+ assert isinstance(message, AssistantToolCallMessage)+ self.assertLess(len(message.content), SQLResultsFormatter.MAX_RESULT_CHARS + 2000)+ self.assertIn("SQL result preview", message.content)+ self.assertIn("Some cells were shortened", message.content)+ self.assertEqual(message.ui_payload, {"execute_sql": query})+ self.assertEqual(context.artifacts.acreate.call_args.args[0].query.source.query, query)+ artifact_ref = artifact.messages[0]+ assert isinstance(artifact_ref, ArtifactRefMessage)+ self.assertEqual(artifact_ref.artifact_id, "preview1")class TestExecuteSQLTool(ClickhouseTestMixin, NonAtomicBaseTest):diff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.pyindex fb6631306aab..0a933d401434 100644--- a/ee/hogai/tools/execute_sql/tool.py+++ b/ee/hogai/tools/execute_sql/tool.py@@ -28,6 +28,7 @@ from ee.hogai.chat_agent.sql.prompts import ()from ee.hogai.context import AssistantContextManagerfrom ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.tool import MaxTool, ToolMessagesArtifactfrom ee.hogai.tool_errors import MaxToolRetryableErrorfrom ee.hogai.utils.prompt import format_prompt_string@@ -154,6 +155,7 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):)insight_context = InsightContext(+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,team=self._team,query=artifact_query,name=viz_title,diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex 701588c1b746..cc1a37227990 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -56,6 +56,7 @@ from ee.hogai.context.error_tracking import ErrorTrackingIssueContextfrom ee.hogai.context.experiment import ExperimentContextfrom ee.hogai.context.feature_flag import FeatureFlagContextfrom ee.hogai.context.insight.context import InsightContext+from ee.hogai.context.insight.format.sql import SQLResultsFormatterfrom ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.context.survey import SurveyContextfrom ee.hogai.tool import MaxTool, ToolMessagesArtifact@@ -442,6 +443,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):# Create insight contextcontext = InsightContext(+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,team=self._team,user=self._user,query=result.content.query,@@ -801,6 +803,7 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):match content:case VisualizationArtifactContent():context = InsightContext(+ max_sql_result_chars=SQLResultsFormatter.MAX_RESULT_CHARS,team=self._team,user=self._user,query=content.query,diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 3aa3aa79ad61..3f18d17c5465 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -26,7 +26,6 @@ ee/hogai/chat_agent/trends/test/test_toolkit.py::TestTrendsToolkitee/hogai/context/insight/format/test/test_lifecycle.py::TestLifecycleResultsFormatteree/hogai/context/insight/format/test/test_paths.py::TestPathsResultsFormatteree/hogai/context/insight/format/test/test_retention.py::TestRetentionResultsFormatter-ee/hogai/context/insight/format/test/test_sql.py::TestSQLResultsFormatteree/hogai/context/insight/format/test/test_stickiness.py::TestStickinessResultsFormatteree/hogai/context/insight/format/test/test_utils.py::TestFormatUtilsee/hogai/context/insight/test/test_query_executor.py::TestValidateAssistantQuery