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(hogai): resolve SQL variables in agent query tool (#66953)

Christiaan Hendriksen3e88f6c9fcdd
diff --git a/ee/hogai/chat_agent/sql/mixins.py b/ee/hogai/chat_agent/sql/mixins.py
index 006b77565a92..e5c52328e70f 100644
--- a/ee/hogai/chat_agent/sql/mixins.py
+++ b/ee/hogai/chat_agent/sql/mixins.py
@@ -12,6 +12,7 @@ from posthog.schema import (
ChartSettingsFormatting,
DataVisualizationNode,
HogQLQuery,
+ HogQLVariable,
Settings,
Style,
)
@@ -27,13 +28,16 @@ from posthog.hogql.errors import (
)
from posthog.hogql.filters import replace_filters
from posthog.hogql.parser import parse_select
-from posthog.hogql.placeholders import find_placeholders, replace_placeholders
+from posthog.hogql.placeholders import find_placeholders
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.variables import replace_variables
from posthog.models import Team
from posthog.models.user import User
from posthog.sync import database_sync_to_async
+from products.product_analytics.backend.models.insight_variable import InsightVariable
+
from ee.hogai.chat_agent.schema_generator.utils import SchemaGeneratorOutput
from ee.hogai.core.mixins import AssistantContextMixin
from ee.hogai.utils.warehouse import serialize_database_schema
@@ -134,6 +138,26 @@ class HogQLOutputParserMixin(HogQLDatabaseMixin):
suffix=result.y_axis_suffix,
)
+ def _get_insight_variables(self, placeholder_fields: list[list[str | int]]) -> list[HogQLVariable]:
+ code_names = {str(chain[1]) for chain in placeholder_fields if len(chain) >= 2 and chain[0] == "variables"}
+ if not code_names:
+ return []
+ insight_variables = InsightVariable.objects.filter(team_id=self._team.pk, code_name__in=code_names)
+ return [
+ HogQLVariable(variableId=str(variable.id), code_name=variable.code_name)
+ for variable in insight_variables
+ if variable.code_name
+ ]
+
+ def _build_query_variables(self, query: str) -> dict[str, HogQLVariable]:
+ parsed_query = parse_select(query, placeholders={})
+ finder = find_placeholders(parsed_query)
+ return {variable.variableId: variable for variable in self._get_insight_variables(finder.placeholder_fields)}
+
+ @database_sync_to_async
+ def _abuild_query_variables(self, query: str) -> dict[str, HogQLVariable]:
+ return self._build_query_variables(query)
+
def _validate_hogql_query_sync(self, query: str) -> AssistantHogQLQuery:
"""
Validate a HogQL query string and return AssistantHogQLQuery.
@@ -150,7 +174,6 @@ class HogQLOutputParserMixin(HogQLDatabaseMixin):
try:
parsed_query = parse_select(cleaned_query, placeholders={})
- # Replace placeholders with dummy values to compile the generated query.
finder = find_placeholders(parsed_query)
# Handle filter placeholders using the proper filter replacement system.
@@ -158,12 +181,9 @@ class HogQLOutputParserMixin(HogQLDatabaseMixin):
if finder.has_filters:
parsed_query = cast(ast.SelectQuery, replace_filters(parsed_query, None, self._team))
- # Handle remaining non-filter placeholders with dummy values.
- if finder.placeholder_fields:
- dummy_placeholders: dict[str, ast.Expr] = {
- str(field[0]): ast.Constant(value=1) for field in finder.placeholder_fields
- }
- parsed_query = cast(ast.SelectQuery, replace_placeholders(parsed_query, dummy_placeholders))
+ if any(field and field[0] == "variables" for field in finder.placeholder_fields):
+ variables = self._get_insight_variables(finder.placeholder_fields)
+ parsed_query = cast(ast.SelectQuery, replace_variables(parsed_query, variables, self._team))
prepare_and_print_ast(parsed_query, context=hogql_context, dialect="clickhouse")
except (ExposedHogQLError, HogQLNotImplementedError, QueryError, ResolutionError) as err:
diff --git a/ee/hogai/chat_agent/sql/test/test_sql_mixins.py b/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
index 8ff0ae25d69f..ab15ddde49c8 100644
--- a/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
+++ b/ee/hogai/chat_agent/sql/test/test_sql_mixins.py
@@ -1,7 +1,13 @@
from posthog.test.base import NonAtomicBaseTest
+from parameterized import parameterized
+
from posthog.schema import ChartDisplayType, DataVisualizationNode, HogQLQuery
+from posthog.sync import database_sync_to_async
+
+from products.product_analytics.backend.models.insight_variable import InsightVariable
+
from ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserException
from ee.hogai.chat_agent.sql.mixins import HogQLGeneratorMixin, SQLSchemaGeneratorOutput
@@ -268,3 +274,36 @@ class TestSQLMixins(NonAtomicBaseTest):
with self.assertRaises(PydanticOutputParserException):
await mixin._quality_check_output(invalid_output)
+
+ async def test_quality_check_unrecognized_placeholder_reports_clean_error(self):
+ mixin = self._node
+
+ output = self._sql_output("SELECT {some_other} AS d FROM events")
+
+ with self.assertRaises(PydanticOutputParserException) as context:
+ await mixin._quality_check_output(output)
+
+ self.assertIn("some_other", context.exception.validation_message)
+
+ @parameterized.expand(
+ [
+ ("resolves_to_default_in_string_context", "SELECT coalesce({variables.district_name}, '') AS d", False),
+ ("missing_variable_is_reported", "SELECT {variables.nonexistent} AS d", True),
+ ]
+ )
+ async def test_quality_check_resolves_insight_variables(self, _name: str, query: str, should_raise: bool):
+ await database_sync_to_async(InsightVariable.objects.create)(
+ team=self.team,
+ name="District name",
+ code_name="district_name",
+ type=InsightVariable.Type.STRING,
+ default_value="barbaz",
+ )
+ mixin = self._node
+ output = self._sql_output(query)
+
+ if should_raise:
+ with self.assertRaises(PydanticOutputParserException):
+ await mixin._quality_check_output(output)
+ else:
+ await mixin._quality_check_output(output)
diff --git a/ee/hogai/tools/execute_sql/mcp_tool.py b/ee/hogai/tools/execute_sql/mcp_tool.py
index 96c93d71aeaa..f9d7c156ab5b 100644
--- a/ee/hogai/tools/execute_sql/mcp_tool.py
+++ b/ee/hogai/tools/execute_sql/mcp_tool.py
@@ -62,7 +62,7 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):
query = HogQLQuery(query=cleaned_query, connectionId=args.connectionId)
else:
try:
- query = await self._validate_hogql_query(args.query)
+ validated = await self._validate_hogql_query(args.query)
except PydanticOutputParserException as e:
message = f"Query validation failed: {e.validation_message}"
suggestion = await self._maybe_import_suggestion(e.validation_message)
@@ -70,6 +70,9 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):
message = f"{message}\n\n{suggestion}"
raise MaxToolRetryableError(message)
+ variables = await self._abuild_query_variables(validated.query)
+ query = HogQLQuery(query=validated.query, variables=variables) if variables else validated
+
# Warn (non-fatally) when the query references events/properties absent from the project
# taxonomy — the most common silent-wrong-answer surface for agents (e.g. `event = 'purchase'`
# returning 0 because the real event is `paid_bill`). The query still runs.
diff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.py
index 3a35a019e648..2a6f5d9ec79c 100644
--- a/ee/hogai/tools/execute_sql/tool.py
+++ b/ee/hogai/tools/execute_sql/tool.py
@@ -115,6 +115,9 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):
if filters is not None
else parsed_query.query.source
)
+ variables = await self._abuild_query_variables(source_query.query)
+ if variables:
+ source_query = source_query.model_copy(update={"variables": variables})
artifact_query = parsed_query.query.model_copy(update={"source": source_query})
if display or chart_settings:
if isinstance(chart_settings, AssistantDataVisualizationChartSettings):