: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(data-warehouse): pass active direct connection to AI SQL tools (#81554)
posthog[bot]97403760aa77
diff --git a/ee/hogai/tools/execute_sql/tool.py b/ee/hogai/tools/execute_sql/tool.pyindex 0b1a37521c67..fb6631306aab 100644--- a/ee/hogai/tools/execute_sql/tool.py+++ b/ee/hogai/tools/execute_sql/tool.py@@ -102,13 +102,20 @@ class ExecuteSQLTool(HogQLGeneratorMixin, MaxTool):display: AssistantDataVisualizationDisplayType | None = None,chart_settings: AssistantDataVisualizationChartSettings | dict[str, object] | None = None,) -> tuple[str, ToolMessagesArtifact | None]:+ connection_id = self.context.get("connection_id") or Noneparsed_query = self._parse_output({"query": query})- try:- await self._quality_check_output(- output=parsed_query,- )- except PydanticOutputParserException as e:- return format_prompt_string(EXECUTE_SQL_RECOVERABLE_ERROR_PROMPT, error=str(e)), None+ if connection_id:+ # An external connection's tables aren't in the ClickHouse catalog, so local HogQL+ # validation would reject them. Tag the query with the connection and defer validation+ # to the runner, which resolves the connection's schema.+ parsed_query.query.source = parsed_query.query.source.model_copy(update={"connectionId": connection_id})+ else:+ try:+ await self._quality_check_output(+ output=parsed_query,+ )+ except PydanticOutputParserException as e:+ return format_prompt_string(EXECUTE_SQL_RECOVERABLE_ERROR_PROMPT, error=str(e)), Nonesource_query = (parsed_query.query.source.model_copy(update={"filters": filters})diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 451caa36b7ad..713fa34631a6 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6158,8 +6158,10 @@ const api = {},},fixHogQLErrors: {- async fix(query: string, error?: string): Promise<Record<string, any>> {- return await new ApiRequest().fixHogQLErrors().create({ data: { query, error } })+ async fix(query: string, error?: string, connectionId?: string): Promise<Record<string, any>> {+ return await new ApiRequest()+ .fixHogQLErrors()+ .create({ data: { query, error, connection_id: connectionId } })},},diff --git a/frontend/src/scenes/data-warehouse/editor/components/FixErrorButton.tsx b/frontend/src/scenes/data-warehouse/editor/components/FixErrorButton.tsxindex e245de93a914..80170e09a647 100644--- a/frontend/src/scenes/data-warehouse/editor/components/FixErrorButton.tsx+++ b/frontend/src/scenes/data-warehouse/editor/components/FixErrorButton.tsx@@ -20,7 +20,7 @@ interface FixErrorButtonProps {}export function FixErrorButton({ type, size, contentOverride, source }: FixErrorButtonProps): JSX.Element {- const { queryInput, fixErrorsError, metadata } = useValues(sqlEditorLogic)+ const { queryInput, fixErrorsError, metadata, selectedConnectionId } = useValues(sqlEditorLogic)const { fixErrors: fixHogQLErrors } = useActions(sqlEditorLogic)const { responseError } = useValues(dataNodeLogic)const { responseLoading: fixHogQLErrorsLoading } = useValues(fixSQLErrorsLogic)@@ -70,7 +70,7 @@ export function FixErrorButton({ type, size, contentOverride, source }: FixErrordisabledReason={disabledReason}icon={icon}onClick={() => {- fixHogQLErrors(queryInput ?? '', queryError)+ fixHogQLErrors(queryInput ?? '', queryError, selectedConnectionId)posthog.capture(`sql-editor-fix-error-click`, { source })}}>diff --git a/frontend/src/scenes/data-warehouse/editor/fixSQLErrorsLogic.ts b/frontend/src/scenes/data-warehouse/editor/fixSQLErrorsLogic.tsindex f72ec33db0da..d33e13aed1a9 100644--- a/frontend/src/scenes/data-warehouse/editor/fixSQLErrorsLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/fixSQLErrorsLogic.ts@@ -19,8 +19,10 @@ export interface fixSQLErrorsLogicValues {export interface fixSQLErrorsLogicActions {fixErrors: (query: string,- error?: string+ error?: string,+ connectionId?: string) => {+ connectionId: string | undefinederror: string | undefinedquery: string}@@ -34,12 +36,14 @@ export interface fixSQLErrorsLogicActions {fixErrorsSuccess: (response: Response,payload?: {+ connectionId: string | undefinederror: string | undefinedquery: string}) => {response: Responsepayload?: {+ connectionId: string | undefinederror: string | undefinedquery: string}@@ -51,14 +55,14 @@ export type fixSQLErrorsLogicType = MakeLogicType<fixSQLErrorsLogicValues, fixSQexport const fixSQLErrorsLogic = kea<fixSQLErrorsLogicType>([path(['scenes', 'data-warehouse', 'editor', 'fixSQLErrorsLogic']),actions({- fixErrors: (query: string, error?: string) => ({ query, error }),+ fixErrors: (query: string, error?: string, connectionId?: string) => ({ query, error, connectionId }),}),loaders({response: [null as Response | null,{- fixErrors: async ({ query, error }) => {- const response = await api.fixHogQLErrors.fix(query, error)+ fixErrors: async ({ query, error, connectionId }) => {+ const response = await api.fixHogQLErrors.fix(query, error, connectionId)return response as Response},diff --git a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.tsindex 3602b320de1f..6b4b9e1689e0 100644--- a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.test.ts@@ -27,6 +27,16 @@ describe('maxSqlTool', () => {filters: { dateRange: { date_from: '-30d' } },},})+ expect(context.connection_id).toBeNull()+ })++ it('passes the selected direct connection id as context', () => {+ const context = getExecuteSqlToolContext('SELECT 1', {+ ...sourceQuery,+ source: { ...sourceQuery.source, connectionId: 'conn-123' },+ })++ expect(context.connection_id).toEqual('conn-123')})it.each([diff --git a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.tsindex 0cdd1cee8955..c6068fcb8943 100644--- a/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts+++ b/frontend/src/scenes/data-warehouse/editor/maxSqlTool.ts@@ -21,6 +21,7 @@ export function getExecuteSqlToolContext(return {current_query: queryInput,current_query_node: getCurrentQueryNodeContext(sourceQuery),+ connection_id: 'connectionId' in sourceQuery.source ? (sourceQuery.source.connectionId ?? null) : null,}}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex b7a06627f427..27d218755c70 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -733,8 +733,10 @@ export interface sqlEditorLogicActions {} // draftsLogicfixErrors: (query: string,- error?: string | undefined+ error?: string | undefined,+ connectionId?: string | undefined) => {+ connectionId: string | undefinederror: string | undefinedquery: string} // fixSQLErrorsLogic@@ -749,12 +751,14 @@ export interface sqlEditorLogicActions {response: Response,payload?:| {+ connectionId: string | undefinederror: string | undefinedquery: string}| undefined) => {payload?: {+ connectionId: string | undefinederror: string | undefinedquery: string}diff --git a/products/data_warehouse/backend/max_tools.py b/products/data_warehouse/backend/max_tools.pyindex 0edb44b7a925..845fe655d6cf 100644--- a/products/data_warehouse/backend/max_tools.py+++ b/products/data_warehouse/backend/max_tools.py@@ -5,6 +5,7 @@ from langchain_core.prompts import ChatPromptTemplatefrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Database+from posthog.hogql.direct_connection import get_direct_connection_sourcefrom posthog.hogql.errors import ExposedHogQLError, ResolutionErrorfrom posthog.hogql.functions.mapping import HOGQL_AGGREGATIONS, HOGQL_CLICKHOUSE_FUNCTIONS, HOGQL_POSTHOG_FUNCTIONSfrom posthog.hogql.metadata import get_table_names@@ -186,7 +187,13 @@ class HogQLQueryFixerTool(MaxTool):context_prompt_template: str = SQL_ASSISTANT_ROOT_SYSTEM_PROMPTdef _run_impl(self) -> tuple[str, str | None]:- database = Database.create_for(team=self._team, user=self._user)+ connection_id = self.context.get("connection_id") or None+ # A direct-query connection's tables live outside the ClickHouse catalog. Build the database+ # from that connection so the prompt shows its real tables instead of only `events` etc.+ source = get_direct_connection_source(self._team, connection_id, user=self._user) if connection_id else None+ database = Database.create_for(+ team=self._team, user=self._user, connection_id=str(source.id) if source else None+ )hogql_context = HogQLContext(team=self._team, user=self._user, enable_select_queries=True, database=database)all_table_names = database.get_all_table_names()@@ -210,7 +217,9 @@ class HogQLQueryFixerTool(MaxTool):for _ in range(3):try:result = self._model.invoke(messages)- parsed_result = self._parse_output(result, hogql_context)+ # Direct-query tables can't be printed to ClickHouse SQL, so the local validation the+ # retry loop relies on doesn't apply; the runner validates against the connection instead.+ parsed_result = self._parse_output(result, hogql_context, validate=source is None)breakexcept PydanticOutputParserException as e:messages.append(@@ -250,12 +259,14 @@ The newly updated query gave us this error:include_raw=False,)- def _parse_output(self, output, hogql_context: HogQLContext):+ def _parse_output(self, output, hogql_context: HogQLContext, validate: bool = True):result = parse_pydantic_structured_output(SchemaGeneratorOutput[str])(output) # type: ignore- # We also ensure the generated SQL is validassert result.query is not None+ result.query = result.query.rstrip(";").strip()+ if not validate:+ return result.query+ # We also ensure the generated SQL is validtry:- result.query = result.query.rstrip(";").strip()prepare_and_print_ast(parse_select(result.query), context=hogql_context, dialect="clickhouse")except (ExposedHogQLError, ResolutionError) as err:err_msg = str(err)diff --git a/products/data_warehouse/backend/presentation/views/fix_hogql.py b/products/data_warehouse/backend/presentation/views/fix_hogql.pyindex b644cd2ab087..14fa93733eb5 100644--- a/products/data_warehouse/backend/presentation/views/fix_hogql.py+++ b/products/data_warehouse/backend/presentation/views/fix_hogql.py@@ -26,6 +26,7 @@ class FixHogQLViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):query = request.data.get("query", None)error = request.data.get("error", "")+ connection_id = request.data.get("connection_id", None)if query is None:return Response(@@ -36,13 +37,19 @@ class FixHogQLViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):trace_id = f"fix_hogql_query_{uuid.uuid4()}"user = cast(User, request.user)+ fix_hogql_context: dict[str, str] = {+ "hogql_query": query,+ "error_message": error,+ }+ # Only present when the query targets a direct-query data warehouse connection, so the fixer+ # sees that connection's tables instead of only the ClickHouse catalog.+ if connection_id:+ fix_hogql_context["connection_id"] = connection_id+config: RunnableConfig = {"configurable": {"contextual_tools": {- "fix_hogql_query": {- "hogql_query": query,- "error_message": error,- }+ "fix_hogql_query": fix_hogql_context,},"team": self.team,"user": user,diff --git a/products/data_warehouse/backend/tests/api/test_fix_hogql.py b/products/data_warehouse/backend/tests/api/test_fix_hogql.pyindex 6ce80538802d..0bd2b7178381 100644--- a/products/data_warehouse/backend/tests/api/test_fix_hogql.py+++ b/products/data_warehouse/backend/tests/api/test_fix_hogql.py@@ -1,6 +1,8 @@from posthog.test.base import APIBaseTestfrom unittest import mock+from parameterized import parameterized+from products.data_warehouse.backend.max_tools import HogQLQueryFixerTool@@ -17,9 +19,24 @@ class TestFixHogQL(APIBaseTest):assert response.status_code == 200- def test_context_passed_correctly(self):+ @parameterized.expand(+ [+ ("without_connection", None, {"hogql_query": "q", "error_message": "e"}),+ (+ "with_connection",+ "018f0000-0000-0000-0000-000000000000",+ {+ "hogql_query": "q",+ "error_message": "e",+ "connection_id": "018f0000-0000-0000-0000-000000000000",+ },+ ),+ ]+ )+ def test_context_passed_correctly(self, _name, connection_id, expected_context):query = "select timestam from events"error = "Unable to resolve field: timestam"+ expected_context = {**expected_context, "hogql_query": query, "error_message": error}captured_tool = None@@ -32,6 +49,10 @@ class TestFixHogQL(APIBaseTest):return wrapper+ body = {"query": query, "error": error}+ if connection_id is not None:+ body["connection_id"] = connection_id+with (mock.patch("products.data_warehouse.backend.max_tools.MaxChatOpenAI"),mock.patch.object(HogQLQueryFixerTool, "_parse_output", return_value="select timestamp from events"),@@ -39,12 +60,9 @@ class TestFixHogQL(APIBaseTest):):response = self.client.post(f"/api/environments/{self.team.id}/fix_hogql/",- {"query": query, "error": error},+ body,)assert response.status_code == 200assert captured_tool is not None- assert captured_tool.context == {- "hogql_query": query,- "error_message": error,- }+ assert captured_tool.context == expected_context