: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(mcp): name the rejected construct and the rewrite on execute-sql failures (#103996)
posthog[bot]8f344acc1c26
diff --git a/ee/hogai/chat_agent/sql/errors.py b/ee/hogai/chat_agent/sql/errors.pynew file mode 100644index 000000000000..7b88ef5e667d--- /dev/null+++ b/ee/hogai/chat_agent/sql/errors.py@@ -0,0 +1,40 @@+"""Turn a HogQL validation exception into the message a SQL-writing caller acts on."""++from posthog.hogql.errors import BaseHogQLError++# Both the antlr-based cpp parser and the hand-rolled rust-py parser produce terse low-level wording+# on syntax failures. Any message opening with one of these reads as parser internals on its own.+_SYNTAX_ERROR_PREFIXES = (+ "no viable alternative",+ "trailing tokens after expression",+ "unexpected token in expression",+ "mismatched input",+)++# A parser message plus the fragment it points at is enough to locate the bad construct without+# echoing the whole query back, which for a long query buries the one part that needs rewriting.+_MAX_SYNTAX_DETAIL_CHARS = 200+_MAX_SYNTAX_FRAGMENT_CHARS = 60+++def hogql_validation_message(err: BaseHogQLError, query: str) -> str:+ """Build the validation message for a HogQL error, naming the construct a syntax failure hit.++ A friendly lead sentence replaces the terse parser wording, but the detail and the offending+ fragment follow it. Without them the caller cannot tell which construct was rejected, so it+ retries the same query instead of rewriting the one bad part.+ """+ message = str(err)+ if not message.startswith(_SYNTAX_ERROR_PREFIXES):+ return message++ clipped = _clip(message, _MAX_SYNTAX_DETAIL_CHARS).rstrip(".")+ described = f"HogQL parsing error: this query isn't valid HogQL. Parser detail: {clipped}."+ if err.start is None or err.end is None or not 0 <= err.start < err.end <= len(query):+ return described+ fragment = _clip(query[err.start : err.end].strip(), _MAX_SYNTAX_FRAGMENT_CHARS)+ return f"{described} The query failed at character {err.start}, near: {fragment}" if fragment else described+++def _clip(text: str, limit: int) -> str:+ return f"{text[:limit]}…" if len(text) > limit else textdiff --git a/ee/hogai/chat_agent/sql/mixins.py b/ee/hogai/chat_agent/sql/mixins.pyindex 27f2d23279ba..700994bae969 100644--- a/ee/hogai/chat_agent/sql/mixins.py+++ b/ee/hogai/chat_agent/sql/mixins.py@@ -43,6 +43,7 @@ from ee.hogai.core.mixins import AssistantContextMixinfrom ee.hogai.utils.warehouse import serialize_database_schemafrom ..schema_generator.parsers import PydanticOutputParserException, parse_pydantic_structured_output+from .errors import hogql_validation_messagefrom .prompts import (HOGQL_GENERATOR_SYSTEM_PROMPT,SQL_EXPRESSIONS_DOCS,@@ -187,22 +188,9 @@ class HogQLOutputParserMixin(HogQLDatabaseMixin):prepare_and_print_ast(parsed_query, context=hogql_context, dialect="clickhouse")except (ExposedHogQLError, HogQLNotImplementedError, QueryError, ResolutionError) as err:- err_msg = str(err)- # Both the antlr-based cpp parser and the hand-rolled rust-py parser produce- # terse low-level error wording on syntax failures ("no viable alternative…",- # "trailing tokens after expression…", "unexpected token in expression…",- # "mismatched input … expecting …"). Replace any of them with a single- # human/LLM-friendly message.- if err_msg.startswith(- (- "no viable alternative",- "trailing tokens after expression",- "unexpected token in expression",- "mismatched input",- )- ):- err_msg = "HogQL parsing error: this query isn't valid HogQL."- raise PydanticOutputParserException(llm_output=cleaned_query, validation_message=err_msg)+ raise PydanticOutputParserException(+ llm_output=cleaned_query, validation_message=hogql_validation_message(err, cleaned_query)+ )return AssistantHogQLQuery(query=cleaned_query)diff --git a/ee/hogai/tools/execute_sql/compatibility_hints.py b/ee/hogai/tools/execute_sql/compatibility_hints.pynew file mode 100644index 000000000000..37265351282e--- /dev/null+++ b/ee/hogai/tools/execute_sql/compatibility_hints.py@@ -0,0 +1,125 @@+"""Turn a known HogQL compatibility rejection into the rewrite that HogQL accepts.++HogQL is close enough to ClickHouse SQL that callers write plain ClickHouse and get a rejection+that states the rule but not the way out: ``greatest`` is binary here, ``LIKE`` takes no ``\\_``+escape, and ``CAST`` knows a short list of type names. The error names the construct, so the caller+knows which call failed, and then retries the same shape because nothing told it what HogQL accepts+instead. Each rule below adds the one accepted rewrite for a failure we see repeatedly.+"""++import re++# ClickHouse takes any number of arguments for these; HogQL caps both at 2, and nesting is exact+# rather than approximate because both are associative. `test_nesting_rewrite_is_actually_accepted`+# pins the cap against the validator, so lifting it in `mapping.py` fails a test rather than leaving+# this advice quietly wrong.+NESTABLE_BINARY_FUNCTIONS = ("greatest", "least")++# The type names `visit_type_cast` accepts, one per target type. Anything else — including every+# width-suffixed ClickHouse spelling such as `Float64` — is rejected.+ACCEPTED_CAST_TYPES = ("Int", "Float", "String", "Boolean", "Date", "DateTime")++# ClickHouse spellings mapped onto the accepted name, longest prefix first so `datetime64` resolves+# to DateTime and `date32` to Date. Matching a caller's spelling against this list beats deriving it+# from ACCEPTED_CAST_TYPES, which cannot tell `date32` from an abbreviation of `datetime`.+_CAST_TYPE_PREFIXES = (+ ("datetime", "DateTime"),+ ("timestamp", "DateTime"),+ ("date", "Date"),+ ("string", "String"),+ ("float", "Float"),+ ("double", "Float"),+ ("bool", "Boolean"),+ ("int", "Int"),+)++# Decimal is deliberately absent above. HogQL accepts no Decimal cast, but Float is the wrong+# substitute: it swaps exact decimal arithmetic for binary floating point, which moves the result of+# a money query rather than failing. `toDecimal` is the exact equivalent, so point at that instead.+_DECIMAL_PREFIX = "decimal"++# ClickHouse decorations that carry no meaning for a HogQL cast.+_CAST_WRAPPER_RE = re.compile(r"^(?:nullable|lowcardinality)\((.*)\)$")+_CAST_WIDTH_RE = re.compile(r"^u?(.+?)\d*$")++_TOO_MANY_ARGS_RE = re.compile(r"Function '(\w+)' expects (\d+) arguments?, found (\d+)")+_BAD_ESCAPE_RE = re.compile(r"unrecognised escape '\\(.)'")+_BAD_CAST_RE = re.compile(r"Unsupported type cast to '([^']{1,40})'")+++def _nested_call(name: str, arity: int) -> str:+ """Render the accepted nesting for an over-arity call, e.g. `greatest(x1, greatest(x2, x3))`."""+ call = f"x{arity}"+ for position in range(arity - 1, 0, -1):+ call = f"{name}(x{position}, {call})"+ return call+++def _normalize_cast_type(type_name: str) -> str:+ """Strip the decorations that carry no meaning for a HogQL cast: wrappers, width, unsignedness."""+ normalized = type_name.strip().lower()+ if wrapper := _CAST_WRAPPER_RE.match(normalized):+ return _normalize_cast_type(wrapper.group(1))+ width = _CAST_WIDTH_RE.match(normalized)+ return width.group(1) if width else normalized+++def suggest_cast_type(type_name: str) -> str | None:+ """Map a rejected ClickHouse cast type name onto the HogQL spelling, if one matches."""+ bare = _normalize_cast_type(type_name)+ for prefix, accepted in _CAST_TYPE_PREFIXES:+ if bare.startswith(prefix):+ return accepted+ return None+++def build_compatibility_hint(error_message: str) -> str | None:+ """Build an additive hint naming the accepted rewrite, or None if no rule matches."""+ for rule in (_arity_rewrite, _escape_rewrite, _cast_rewrite):+ rewrite = rule(error_message)+ if rewrite is not None:+ return f"<hogql_compatibility_hint>\n{rewrite}\n</hogql_compatibility_hint>"+ return None+++def _arity_rewrite(error_message: str) -> str | None:+ match = _TOO_MANY_ARGS_RE.search(error_message)+ if match is None:+ return None+ name, expected, found = match.group(1), int(match.group(2)), int(match.group(3))+ if name not in NESTABLE_BINARY_FUNCTIONS or expected != 2 or found <= 2:+ return None+ return (+ f"`{name}` takes exactly 2 arguments in HogQL, unlike ClickHouse. Nest two-argument calls "+ f"instead: {_nested_call(name, found)}."+ )+++def _escape_rewrite(error_message: str) -> str | None:+ match = _BAD_ESCAPE_RE.search(error_message)+ if match is None:+ return None+ char = match.group(1)+ return (+ f"HogQL string literals do not define the escape `\\{char}`. To match a literal `{char}` "+ f"with LIKE, escape the backslash itself: '%\\\\{char}%'. To match a plain substring with no "+ "wildcards at all, `position(haystack, needle) > 0` avoids escaping entirely."+ )+++def _cast_rewrite(error_message: str) -> str | None:+ match = _BAD_CAST_RE.search(error_message)+ if match is None:+ return None+ type_name = match.group(1)+ lead = (+ f"HogQL casts do not take width-suffixed ClickHouse type names such as `{type_name}`. "+ f"Accepted type names are: {', '.join(ACCEPTED_CAST_TYPES)}."+ )+ if _normalize_cast_type(type_name).startswith(_DECIMAL_PREFIX):+ return (+ f"{lead} None of them holds an exact decimal, so do not cast to Float here: that changes "+ "the arithmetic and can move the result. Use `toDecimal(x, scale)` instead."+ )+ suggestion = suggest_cast_type(type_name)+ return f"{lead} Use `CAST(x AS {suggestion})` or `to{suggestion}(x)`." if suggestion else leaddiff --git a/ee/hogai/tools/execute_sql/mcp_tool.py b/ee/hogai/tools/execute_sql/mcp_tool.pyindex 52db3a9f76a3..34f7c7ebe591 100644--- a/ee/hogai/tools/execute_sql/mcp_tool.py+++ b/ee/hogai/tools/execute_sql/mcp_tool.py@@ -17,6 +17,7 @@ from ee.hogai.chat_agent.sql.mixins import HogQLOutputParserMixinfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.mcp_tool import MCPTool, MCPToolResult, mcp_tool_registryfrom ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tools.execute_sql.compatibility_hints import build_compatibility_hintfrom ee.hogai.tools.execute_sql.direct_connection_suggestions import build_direct_connection_suggestionfrom ee.hogai.tools.execute_sql.import_suggestions import build_import_suggestion, extract_unknown_tables@@ -84,7 +85,9 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):validated = await self._validate_hogql_query(args.query)except PydanticOutputParserException as e:message = f"Query validation failed: {e.validation_message}"- suggestion = await self._maybe_unknown_table_suggestion(e.validation_message)+ suggestion = await self._maybe_unknown_table_suggestion(+ e.validation_message+ ) or build_compatibility_hint(e.validation_message)if suggestion:message = f"{message}\n\n{suggestion}"raise MaxToolRetryableError(message)@@ -105,9 +108,17 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):user=self._user,event_source=self._event_source,)- results = await insight_context.execute_and_format(- prompt_template="{{{results}}}", truncate_results=args.truncate, include_prompt_framing=False- )+ try:+ results = await insight_context.execute_and_format(+ prompt_template="{{{results}}}", truncate_results=args.truncate, include_prompt_framing=False+ )+ except MaxToolRetryableError as e:+ # A connection query defers validation to the runner, so the compatibility rejections+ # the local validator would have enriched above surface here instead.+ hint = build_compatibility_hint(str(e))+ if not hint:+ raise+ raise MaxToolRetryableError(f"{e}\n\n{hint}") from ereturn MCPToolResult(content=_prepend_taxonomy_warnings(results, taxonomy_warnings),diff --git a/ee/hogai/tools/execute_sql/test/test_compatibility_hints.py b/ee/hogai/tools/execute_sql/test/test_compatibility_hints.pynew file mode 100644index 000000000000..abff3b247e20--- /dev/null+++ b/ee/hogai/tools/execute_sql/test/test_compatibility_hints.py@@ -0,0 +1,88 @@+from parameterized import parameterized++from ee.hogai.tools.execute_sql.compatibility_hints import build_compatibility_hint, suggest_cast_type+++class TestSuggestCastType:+ @parameterized.expand(+ [+ ("Float64", "Float"),+ ("Float32", "Float"),+ ("Int64", "Int"),+ ("UInt8", "Int"),+ ("Integer", "Int"),+ ("DateTime64", "DateTime"),+ ("Date32", "Date"),+ ("Timestamp", "DateTime"),+ ("Nullable(Float64)", "Float"),+ ("LowCardinality(String)", "String"),+ ]+ )+ def test_maps_clickhouse_spelling_to_hogql(self, type_name: str, expected: str) -> None:+ assert suggest_cast_type(type_name) == expected++ @parameterized.expand([("Map(String, String)",), ("Tuple",), ("Enum8",), ("d",), ("Decimal(10, 2)",)])+ def test_no_suggestion_for_unmappable_type(self, type_name: str) -> None:+ assert suggest_cast_type(type_name) is None+++class TestBuildCompatibilityHint:+ def test_none_for_unrelated_error(self) -> None:+ assert build_compatibility_hint("Unknown table `charges`.") is None++ @parameterized.expand(+ [+ ("greatest", "Function 'greatest' expects 2 arguments, found 3", "greatest(x1, greatest(x2, x3))"),+ ("least", "Function 'least' expects 2 arguments, found 3", "least(x1, least(x2, x3))"),+ (+ "four_args",+ "Function 'greatest' expects 2 arguments, found 4",+ "greatest(x1, greatest(x2, greatest(x3, x4)))",+ ),+ ]+ )+ def test_over_arity_suggests_nesting(self, _name: str, message: str, expected_rewrite: str) -> None:+ hint = build_compatibility_hint(message)+ assert hint is not None+ assert expected_rewrite in hint++ def test_under_arity_gets_no_nesting_rewrite(self) -> None:+ # Nesting cannot fix a call that has too few arguments, so the rule must not fire.+ assert build_compatibility_hint("Function 'greatest' expects 2 arguments, found 1") is None++ def test_over_arity_on_other_function_gets_no_nesting_rewrite(self) -> None:+ # `bar` is genuinely 4-argument in ClickHouse too — nesting would be wrong advice.+ assert build_compatibility_hint("Function 'bar' expects 4 arguments, found 5") is None++ def test_bad_escape_suggests_escaped_backslash_and_position(self) -> None:+ hint = build_compatibility_hint("unrecognised escape '\\_'")+ assert hint is not None+ assert "'%\\\\_%'" in hint+ assert "position(" in hint++ def test_bad_cast_names_accepted_types_and_the_rewrite(self) -> None:+ hint = build_compatibility_hint("Unsupported type cast to 'float64'")+ assert hint is not None+ assert "CAST(x AS Float)" in hint+ assert "toFloat(x)" in hint++ @parameterized.expand([("Decimal(10, 2)",), ("Decimal64(4)",), ("Nullable(Decimal(10, 2))",)])+ def test_decimal_cast_points_at_todecimal_and_warns_off_float(self, type_name: str) -> None:+ # Float is an accepted cast name and the nearest spelling, so a prefix match would suggest+ # it. That silently swaps exact decimal arithmetic for binary floating point.+ hint = build_compatibility_hint(f"Unsupported type cast to '{type_name}'")+ assert hint is not None+ assert "toDecimal(x, scale)" in hint+ assert "CAST(x AS Float)" not in hint++ def test_unmappable_cast_still_lists_accepted_types(self) -> None:+ hint = build_compatibility_hint("Unsupported type cast to 'Enum8'")+ assert hint is not None+ assert "Boolean" in hint+ assert "CAST(x AS" not in hint++ def test_hint_is_delimited(self) -> None:+ hint = build_compatibility_hint("Function 'greatest' expects 2 arguments, found 3")+ assert hint is not None+ assert hint.startswith("<hogql_compatibility_hint>")+ assert hint.endswith("</hogql_compatibility_hint>")diff --git a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py b/ee/hogai/tools/execute_sql/test/test_mcp_tool.pyindex 5554e7e25c27..0c1042b23c9f 100644--- a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py@@ -2,6 +2,7 @@ from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_evfrom unittest.mock import AsyncMock, patchfrom asgiref.sync import sync_to_async+from parameterized import parameterizedfrom posthog.schema import HogQLNotice, HogQLQuery@@ -12,6 +13,7 @@ from products.product_analytics.backend.facade.models import Insight, InsightVarfrom ee.hogai.context.insight.context import InsightContextfrom ee.hogai.tool_errors import MaxToolRetryableError+from ee.hogai.tools.execute_sql.compatibility_hints import ACCEPTED_CAST_TYPES, NESTABLE_BINARY_FUNCTIONSfrom ee.hogai.tools.execute_sql.mcp_tool import (ExecuteSQLMCPTool,ExecuteSQLMCPToolArgs,@@ -80,6 +82,64 @@ class TestExecuteSQLMCPTool(ClickhouseTestMixin, NonAtomicBaseTest):self.assertIn("validation failed", str(ctx.exception).lower())+ @parameterized.expand(+ [+ ("trailing_tokens", "SELECT 1 FROM events LIMIT 1 blah", "blah"),+ ("reserved_keyword", "SELECT count() FROM events WHERE GROUP BY", "BY"),+ ("bad_operator", "SELECT * FROM events WHERE 1 === 2", "="),+ ]+ )+ async def test_syntax_error_locates_the_offending_fragment(+ self, _name: str, query: str, expected_fragment: str+ ) -> None:+ # A bare "this query isn't valid HogQL" tells the caller nothing about which construct to+ # rewrite, so it retries the same query. The parser knows the offset and the token; keep both.+ with self.assertRaises(MaxToolRetryableError) as ctx:+ await self.tool.execute(ExecuteSQLMCPToolArgs(query=query))++ message = str(ctx.exception)+ self.assertIn("Parser detail:", message)+ self.assertIn("The query failed at character", message)+ self.assertIn(expected_fragment, message)++ @parameterized.expand(+ [+ ("variadic_greatest", "SELECT greatest(1, 2, 3) FROM events", "greatest(x1, greatest(x2, x3))"),+ ("variadic_least", "SELECT least(1, 2, 3) FROM events", "least(x1, least(x2, x3))"),+ ("like_escape", r"SELECT 1 FROM events WHERE event LIKE '%\_x%'", "position("),+ ("width_suffixed_cast", "SELECT CAST(1 AS Float64) FROM events", "CAST(x AS Float)"),+ ]+ )+ async def test_compatibility_rejection_carries_an_accepted_rewrite(+ self, _name: str, query: str, expected_rewrite: str+ ) -> None:+ # Each shape is valid ClickHouse that HogQL rejects. The rejection must name the rewrite,+ # not just the rule, or the caller has to guess what HogQL accepts instead.+ with self.assertRaises(MaxToolRetryableError) as ctx:+ await self.tool.execute(ExecuteSQLMCPToolArgs(query=query))++ message = str(ctx.exception)+ self.assertIn("<hogql_compatibility_hint>", message)+ self.assertIn(expected_rewrite, message)++ @parameterized.expand([(name,) for name in NESTABLE_BINARY_FUNCTIONS])+ async def test_nesting_rewrite_is_actually_accepted(self, name: str) -> None:+ # Pins the advice against the validator: if the arity cap is ever lifted, the flat call+ # starts passing and this test says the nesting hint has gone stale.+ with self.assertRaises(MaxToolRetryableError):+ await self.tool.execute(ExecuteSQLMCPToolArgs(query=f"SELECT {name}(1, 2, 3) FROM events"))++ result = await self.tool.execute(+ ExecuteSQLMCPToolArgs(query=f"SELECT {name}(1, {name}(2, 3)) AS x FROM events")+ )+ self.assertIsNotNone(result.content)++ @parameterized.expand([(name,) for name in ACCEPTED_CAST_TYPES])+ async def test_suggested_cast_types_are_actually_accepted(self, type_name: str) -> None:+ # The hint lists these as the accepted spellings, so each one has to survive validation.+ result = await self.tool.execute(ExecuteSQLMCPToolArgs(query=f"SELECT CAST(1 AS {type_name}) AS x"))+ self.assertIsNotNone(result.content)+async def test_validation_error_for_empty_query(self):with self.assertRaises(MaxToolRetryableError):await self.tool.execute(@@ -230,6 +290,42 @@ class TestExecuteSQLMCPTool(ClickhouseTestMixin, NonAtomicBaseTest):{"query": captured["query"].model_dump(mode="json", exclude_none=True)},)+ async def test_deferred_execution_error_gains_the_compatibility_hint(self):+ # A connection query skips local validation, so a compatibility rejection arrives from the+ # runner. It has to gain the same rewrite the validation path attaches.+ async def fake_execute_and_format(self, *args, **kwargs):+ raise MaxToolRetryableError("Function 'greatest' expects 2 arguments, found 3")++ with patch(+ "ee.hogai.tools.execute_sql.mcp_tool.InsightContext.execute_and_format",+ new=fake_execute_and_format,+ ):+ with self.assertRaises(MaxToolRetryableError) as ctx:+ await self.tool.execute(+ ExecuteSQLMCPToolArgs(query="SELECT greatest(1, 2, 3) FROM t", connectionId="conn_abc"),+ )++ message = str(ctx.exception)+ self.assertIn("Function 'greatest' expects 2 arguments, found 3", message)+ self.assertIn("greatest(x1, greatest(x2, x3))", message)++ async def test_deferred_execution_error_without_a_rule_is_left_alone(self):+ # Most runner failures match no rule. Those must reach the caller unchanged rather than+ # gaining an empty or misleading block.+ async def fake_execute_and_format(self, *args, **kwargs):+ raise MaxToolRetryableError("Connection refused by the upstream source")++ with patch(+ "ee.hogai.tools.execute_sql.mcp_tool.InsightContext.execute_and_format",+ new=fake_execute_and_format,+ ):+ with self.assertRaises(MaxToolRetryableError) as ctx:+ await self.tool.execute(+ ExecuteSQLMCPToolArgs(query="SELECT 1 FROM t", connectionId="conn_abc"),+ )++ self.assertEqual(str(ctx.exception), "Connection refused by the upstream source")+async def test_send_raw_query_without_a_connection_raises(self):# There is nothing to send it to, and silently compiling it as HogQL instead would run# something other than what the caller asked for.diff --git a/products/data_warehouse/backend/max_tools.py b/products/data_warehouse/backend/max_tools.pyindex 845fe655d6cf..4a8d7b413921 100644--- a/products/data_warehouse/backend/max_tools.py+++ b/products/data_warehouse/backend/max_tools.py@@ -14,6 +14,7 @@ from posthog.hogql.printer import prepare_and_print_astfrom ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserException, parse_pydantic_structured_outputfrom ee.hogai.chat_agent.schema_generator.utils import SchemaGeneratorOutput+from ee.hogai.chat_agent.sql.errors import hogql_validation_messagefrom ee.hogai.chat_agent.sql.toolkit import SQL_SCHEMAfrom ee.hogai.llm import MaxChatOpenAIfrom ee.hogai.tool import MaxTool@@ -269,14 +270,8 @@ The newly updated query gave us this error:try:prepare_and_print_ast(parse_select(result.query), context=hogql_context, dialect="clickhouse")except (ExposedHogQLError, ResolutionError) as err:- err_msg = str(err)- # Both the antlr-based cpp parser and the hand-rolled rust-py parser produce- # terse low-level error wording on syntax failures; collapse them into a- # single human/LLM-friendly message regardless of which backend handled the parse.- if err_msg.startswith(- ("no viable alternative", "trailing tokens after expression", "unexpected token in expression")- ):- err_msg = "HogQL parsing error: this query isn't valid HogQL."- raise PydanticOutputParserException(llm_output=result.query, validation_message=err_msg)+ raise PydanticOutputParserException(+ llm_output=result.query, validation_message=hogql_validation_message(err, result.query)+ )return result.query