: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): surface SSH tunnel failures as user errors in direct SQL queries (#79371)
Tom Owersa24d309ce46f
diff --git a/posthog/hogql/direct_sql/clickhouse_adapter.py b/posthog/hogql/direct_sql/clickhouse_adapter.pyindex 422699838ff1..3ac3d9c5ae53 100644--- a/posthog/hogql/direct_sql/clickhouse_adapter.py+++ b/posthog/hogql/direct_sql/clickhouse_adapter.py@@ -6,6 +6,7 @@ import sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokensfrom sqlparse.sql import TokenList+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query@@ -301,7 +302,7 @@ class ClickHouseAdapter:rows, column_names, column_types = _fetch_capped_clickhouse_rows(client, request.sql, request.values or None, statement_timeout_seconds)- except (ClickHouseError, OSError, ExposedHogQLError) as error:+ except (ClickHouseError, OSError, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(diff --git a/posthog/hogql/direct_sql/mysql_adapter.py b/posthog/hogql/direct_sql/mysql_adapter.pyindex 13b63ed65a25..32c84d86eff2 100644--- a/posthog/hogql/direct_sql/mysql_adapter.py+++ b/posthog/hogql/direct_sql/mysql_adapter.py@@ -6,6 +6,7 @@ from opentelemetry import tracefrom pymysql.constants import FIELD_TYPE as MYSQL_FIELD_TYPEfrom sqlparse import tokens as sqlparse_tokensfrom sqlparse.sql import Statement+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult@@ -176,7 +177,7 @@ class MySQLAdapter:)results = cursor.fetchall()description = cursor.description or []- except (pymysql.MySQLError, ExposedHogQLError) as error:+ except (pymysql.MySQLError, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(results=[], types=[], print_columns=[], error=mysql_error_to_message(error))diff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.pyindex b0fa5feb4064..10e593b60991 100644--- a/posthog/hogql/direct_sql/postgres_adapter.py+++ b/posthog/hogql/direct_sql/postgres_adapter.py@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, TypedDict, castimport psycopgfrom opentelemetry import tracefrom psycopg.types.datetime import DateLoader+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult@@ -302,7 +303,7 @@ class PostgresAdapter:# successful, empty result instead of surfacing a spurious error.description = cursor.description or []results = cursor.fetchall() if description else []- except (psycopg.Error, ExposedHogQLError) as error:+ except (psycopg.Error, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))diff --git a/posthog/hogql/direct_sql/redshift_adapter.py b/posthog/hogql/direct_sql/redshift_adapter.pyindex a8e9269e9bf1..e38e97003abb 100644--- a/posthog/hogql/direct_sql/redshift_adapter.py+++ b/posthog/hogql/direct_sql/redshift_adapter.py@@ -4,6 +4,7 @@ import psycopgimport sqlparsefrom opentelemetry import tracefrom sqlparse import tokens as sqlparse_tokens+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query@@ -162,7 +163,7 @@ class RedshiftAdapter:# as an empty result instead of raising on fetch, mirroring Postgres.description = cursor.description or []results = _fetch_capped_redshift_rows(cursor) if description else []- except (psycopg.Error, ExposedHogQLError) as error:+ except (psycopg.Error, BaseSSHTunnelForwarderError, ExposedHogQLError) as error:span.set_attribute("error_type", error.__class__.__name__)if request.debug:return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))diff --git a/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py b/posthog/hogql/direct_sql/test/test_clickhouse_adapter.pyindex 1c6fff88a9bf..5c8ade2c9b5c 100644--- a/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py+++ b/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py@@ -6,18 +6,23 @@ from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCasefrom parameterized import parameterized+from sshtunnel import BaseSSHTunnelForwarderError+from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTablefrom posthog.hogql.database.models import StringDatabaseField, TableNode+from posthog.hogql.direct_sql.adapter import DirectQueryRequestfrom posthog.hogql.direct_sql.clickhouse_adapter import (+ ClickHouseAdapter,_fetch_capped_clickhouse_rows,ensure_read_only_raw_clickhouse_statement,)from posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer.utils import prepare_and_print_ast+from posthog.hogql.timings import HogQLTimingsclass TestDirectClickHouseTable(SimpleTestCase):@@ -87,6 +92,34 @@ class TestDirectClickHouseTeamIdGuard(BaseTest):self._print(is_direct_query=False)+class TestClickHouseAdapterExecute(BaseTest):+ def test_execute_raises_exposed_error_when_ssh_tunnel_fails(self):+ source = MagicMock()+ source.id = "src"+ clickhouse_source = MagicMock()+ clickhouse_source.direct_query_client.side_effect = BaseSSHTunnelForwarderError(+ "Could not establish session to SSH gateway"+ )++ adapter = ClickHouseAdapter()+ request = DirectQueryRequest(+ source=source,+ team=self.team,+ sql="SELECT 1",+ values=None,+ settings=HogQLGlobalSettings(),+ timings=HogQLTimings(),+ query_type="HogQLQuery",+ debug=False,+ )++ with patch.object(adapter, "validate_source_config", return_value=(clickhouse_source, MagicMock())):+ with self.assertRaises(ExposedHogQLError) as error:+ adapter.execute(request)++ self.assertEqual(str(error.exception), "Could not establish session to SSH gateway")++class TestClickHouseReadOnlyGuard(SimpleTestCase):@parameterized.expand([diff --git a/posthog/hogql/test/test_direct_mysql_query.py b/posthog/hogql/test/test_direct_mysql_query.pyindex 750f8bb52401..2041c59a1fd5 100644--- a/posthog/hogql/test/test_direct_mysql_query.py+++ b/posthog/hogql/test/test_direct_mysql_query.py@@ -6,6 +6,7 @@ from unittest.mock import MagicMock, patchimport pymysqlfrom parameterized import parameterized+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.direct_sql.mysql_adapter import mysql_error_to_message, mysql_field_type_to_clickhouse_typefrom posthog.hogql.errors import ExposedHogQLError, QueryError@@ -425,6 +426,28 @@ class TestDirectMySQLQuery(APIBaseTest):self.assertEqual(response.results, [(1, "[email protected]")])self.assertEqual(response.types, [("id", "Int64"), ("email", "String")])+ def test_execute_raises_exposed_error_when_ssh_tunnel_fails(self):+ source = self._create_source()+ self._create_table(source, "orders")++ executor = HogQLQueryExecutor(+ query="SELECT id FROM orders",+ team=self.team,+ connection_id=str(source.id),+ )++ implementation = MagicMock()+ implementation.connect.side_effect = BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")++ with patch(+ "posthog.hogql.direct_sql.mysql_adapter.MySQLAdapter.validate_source_config",+ return_value=(implementation, MagicMock()),+ ):+ with self.assertRaises(ExposedHogQLError) as error:+ executor.execute()++ self.assertEqual(str(error.exception), "Could not establish session to SSH gateway")+def test_hogql_query_for_synced_source_prints_identical_sql_to_pure_direct(self):direct_source = self._create_source(prefix="direct")self._create_table(direct_source, "orders")diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex f9b7c787c4f3..876f4cb216f2 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -9,6 +9,7 @@ from django.test import override_settingsimport psycopgfrom parameterized import parameterized+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings@@ -1768,6 +1769,54 @@ class TestDirectPostgresQuery(APIBaseTest):self.assertEqual(mock_connect.call_args.kwargs["sslmode"], expected_sslmode)+ @override_settings(DEBUG=False, TEST=False)+ @patch("products.warehouse_sources.backend.models.ssh_tunnel.SSHTunnelForwarder")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")+ def test_direct_postgres_ssh_tunnel_failure_raises_exposed_error(self, mock_connect, mock_tunnel_cls):+ mock_tunnel_cls.return_value.__enter__.side_effect = BaseSSHTunnelForwarderError(+ "Could not establish session to SSH gateway"+ )++ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ connection_id="connection_id",+ status=ExternalDataSource.Status.COMPLETED,+ source_type="Postgres",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix="ph3",+ job_inputs={+ "host": "localhost",+ "port": 5432,+ "database": "postgres",+ "user": "postgres",+ "password": "postgres",+ "schema": "ph3",+ **self._SSH_TUNNEL_CONFIG,+ },+ )++ DataWarehouseTable.objects.create(+ name="posthog_dashboard",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern="direct://postgres",+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}},+ )++ executor = HogQLQueryExecutor(+ query="SELECT id FROM posthog_dashboard LIMIT 1",+ team=self.team,+ connection_id=str(source.id),+ )++ with self.assertRaises(ExposedHogQLError) as error:+ executor.execute()++ self.assertEqual(str(error.exception), "Could not establish session to SSH gateway")+ mock_connect.assert_not_called()+@override_settings(DEBUG=False, TEST=False, E2E_TESTING=True)@patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")def test_execute_direct_postgres_query_uses_prefer_sslmode_in_e2e_for_new_sources(self, mock_connect):diff --git a/posthog/hogql/test/test_direct_redshift_query.py b/posthog/hogql/test/test_direct_redshift_query.pyindex c6945198d58f..0bcce5bee169 100644--- a/posthog/hogql/test/test_direct_redshift_query.py+++ b/posthog/hogql/test/test_direct_redshift_query.py@@ -6,6 +6,7 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patchfrom parameterized import parameterized+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.direct_sql.redshift_adapter import RedshiftAdapter, ensure_read_only_raw_redshift_statementfrom posthog.hogql.errors import ExposedHogQLError, QueryError@@ -173,6 +174,29 @@ class TestDirectRedshiftQuery(APIBaseTest):with self.assertRaisesRegex(ExposedHogQLError, "Add a LIMIT clause"):executor.execute()+ def test_execute_raises_exposed_error_when_ssh_tunnel_fails(self):+ source = self._create_source()++ executor = HogQLQueryExecutor(+ query="SELECT id FROM orders",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ )++ implementation = MagicMock()+ implementation.connect.side_effect = BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")++ with patch(+ "posthog.hogql.direct_sql.redshift_adapter.RedshiftAdapter.validate_source_config",+ return_value=(implementation, MagicMock()),+ ):+ with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):+ with self.assertRaises(ExposedHogQLError) as error:+ executor.execute()++ self.assertEqual(str(error.exception), "Could not establish session to SSH gateway")+@parameterized.expand([("synced_with_toggle_on", True, True),