: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(postgres): stop capturing CDC prerequisite connection failures (#63795)
Tom Owersd405937f940f
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 763fce26214e..21b34640f773 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -17,10 +17,12 @@ import structlogimport temporaliofrom dateutil import parserfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_field+from psycopg import OperationalErrorfrom rest_framework import filters, serializers, status, viewsetsfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.schema import (SourceFieldFileUploadConfig,@@ -53,7 +55,11 @@ from posthog.temporal.data_imports.sources.postgres.cdc.config import (DEFAULT_LAG_WARNING_THRESHOLD_MB,)from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import cdc_pg_connection-from posthog.temporal.data_imports.sources.postgres.postgres import get_primary_key_columns, source_requires_ssl+from posthog.temporal.data_imports.sources.postgres.postgres import (+ SSLRequiredError,+ get_primary_key_columns,+ source_requires_ssl,+)from posthog.temporal.data_imports.sources.postgres.source import PostgresSourcefrom products.cdp.backend.api.hog_function import HogFunctionSerializer@@ -2441,6 +2447,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixislot_name=slot_name,publication_name=publication_name,)+ except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ # Probing a user-supplied database to validate it is expected to fail when the host,+ # credentials, or SSH tunnel are wrong or the server drops the connection. Surface it+ # to the wizard as a 400, but don't capture it — these are user/upstream connection+ # problems, not bugs in our code, and capturing every one floods error tracking.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to Postgres to check prerequisites: {e}"},+ )except Exception as e:capture_exception(e, {"source_type": source_type, "team_id": self.team_id})return Response(diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 4d1308565412..cefe4300a842 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -15,6 +15,7 @@ from django.utils import timezoneimport psycopgfrom parameterized import parameterizedfrom rest_framework import status+from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.schema import (SourceFieldFileUploadConfig,@@ -34,7 +35,7 @@ from posthog.temporal.data_imports.sources.bigquery.bigquery import BigQuerySourfrom posthog.temporal.data_imports.sources.common.base import FieldType, WebhookCreationResultfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.custom.source import MAX_CUSTOM_SOURCES_PER_TEAM-from posthog.temporal.data_imports.sources.postgres.postgres import PostgresDiscoveredSchema+from posthog.temporal.data_imports.sources.postgres.postgres import PostgresDiscoveredSchema, SSLRequiredErrorfrom posthog.temporal.data_imports.sources.postgres.source import PostgresSourcefrom posthog.temporal.data_imports.sources.stripe.constants import (BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,@@ -7614,6 +7615,66 @@ class TestCheckCDCPrerequisitesForSource(APIBaseTest):assert "Could not connect to source" in response.json()["message"]+class TestCheckCDCPrerequisitesWizard(APIBaseTest):+ """The detail=False wizard endpoint validates a client-supplied Postgres config before the+ source exists. Connecting to a user's database is expected to fail on bad creds/host/tunnel,+ so those connection errors should surface as a 400 without being captured to error tracking."""++ BASE_PAYLOAD = {+ "source_type": "Postgres",+ "host": "db.example.com",+ "port": 5432,+ "database": "postgres",+ "user": "postgres",+ "password": "password",+ "cdc_management_mode": "posthog",+ "tables": ["public.users"],+ }++ def _post(self, **overrides):+ return self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/check_cdc_prerequisites/",+ data={**self.BASE_PAYLOAD, **overrides},+ format="json",+ )++ @parameterized.expand(+ [+ (+ "operational_error",+ psycopg.OperationalError(+ 'connection failed: connection to server at "127.0.0.1", port 46377 failed: '+ "server closed the connection unexpectedly"+ ),+ ),+ ("ssh_tunnel_error", BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")),+ ("ssl_required_error", SSLRequiredError("SSL/TLS is required but not supported by the server")),+ ]+ )+ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")+ @patch.object(PostgresSource, "is_database_host_valid", return_value=(True, None))+ @patch.object(PostgresSource, "ssh_tunnel_is_valid", return_value=(True, None))+ def test_connection_failure_returns_400_without_capture(+ self, _name, exc, _mock_ssh, _mock_host, mock_capture+ ) -> None:+ with patch.object(PostgresSource, "check_cdc_prerequisites", side_effect=exc):+ response = self._post()+ assert response.status_code == 400, response.content+ assert "Could not connect to Postgres to check prerequisites" in response.json()["message"]+ # User/upstream connection failures must not pollute error tracking.+ mock_capture.assert_not_called()++ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")+ @patch.object(PostgresSource, "is_database_host_valid", return_value=(True, None))+ @patch.object(PostgresSource, "ssh_tunnel_is_valid", return_value=(True, None))+ @patch.object(PostgresSource, "check_cdc_prerequisites", side_effect=ValueError("unexpected bug"))+ def test_unexpected_error_is_still_captured(self, _mock_prereqs, _mock_ssh, _mock_host, mock_capture) -> None:+ response = self._post()+ assert response.status_code == 400, response.content+ # Genuine bugs (not connection failures) should still be captured.+ mock_capture.assert_called_once()++class TestEnableCDC(APIBaseTest):@patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)def test_enable_cdc_rejects_source_type_without_cdc_support(self, _flag) -> None: