: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): don't capture expected CDC prereq connection failures (#65018)
Tom Owersedce264c8319
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex fdef797e9edc..578ab88e6d7c 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -2736,6 +2736,16 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixislot_name=request.data.get("cdc_slot_name") or None,publication_name=request.data.get("cdc_publication_name") or None,)+ except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ # Probing the source's database to validate it is expected to fail when the host,+ # credentials, or SSH tunnel are wrong, the server requires/refuses SSL, or it drops the+ # connection. Surface it 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. Mirrors the detail=False check_cdc_prerequisites handler.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to check prerequisites: {e}"},+ )except Exception as e:capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})return Response(@@ -2801,6 +2811,14 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixislot_name=request.data.get("cdc_slot_name") or None,publication_name=request.data.get("cdc_publication_name") or None,)+ except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:+ # Expected user/upstream connection failure (bad host/credentials/SSH tunnel, server+ # requires/refuses SSL, dropped connection). Surface as a 400 without capturing — see the+ # check_cdc_prerequisites_for_source handler above.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to check prerequisites: {e}"},+ )except Exception as e:capture_exception(e, {"source_id": str(instance.id), "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 bac634eb61f7..dbf50ce66d09 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@@ -36,6 +36,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.cdc.adapter import PostgresCDCAdapterfrom 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 (@@ -8065,11 +8066,39 @@ class TestCheckCDCPrerequisitesForSource(APIBaseTest):assert mock_validate.call_args.kwargs["publication_name"] == "customer_pub"assert mock_validate.call_args.kwargs["management_mode"] == "self_managed"- @patch(- "posthog.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.validate_prerequisites",- side_effect=psycopg.OperationalError("connection refused"),+ @parameterized.expand(+ [+ (+ "ssl_required_error",+ SSLRequiredError("SSL/TLS connection is required but your database does not support it."),+ ),+ (+ "operational_error",+ psycopg.OperationalError(+ 'connection failed: connection to server at "127.0.0.1", port 5434 failed: '+ "server does not support SSL, but SSL was required"+ ),+ ),+ ("ssh_tunnel_error", BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")),+ ])- def test_returns_400_on_connection_exception(self, _mock_validate) -> None:+ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")+ def test_connection_failure_returns_400_without_capture(self, _name, exc, mock_capture) -> None:+ source = _make_postgres_source(self.team.pk, self.user)+ with patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=exc):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/check_cdc_prerequisites_for_source/",+ data={"cdc_management_mode": "posthog"},+ format="json",+ )+ assert response.status_code == 400+ assert "Could not connect to source" 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(PostgresCDCAdapter, "validate_prerequisites", side_effect=ValueError("unexpected bug"))+ def test_unexpected_error_is_still_captured(self, _mock_validate, mock_capture) -> None:source = _make_postgres_source(self.team.pk, self.user)response = self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/check_cdc_prerequisites_for_source/",@@ -8077,7 +8106,7 @@ class TestCheckCDCPrerequisitesForSource(APIBaseTest):format="json",)assert response.status_code == 400- assert "Could not connect to source" in response.json()["message"]+ mock_capture.assert_called_once()class TestCheckCDCPrerequisitesWizard(APIBaseTest):@@ -8232,12 +8261,41 @@ class TestEnableCDC(APIBaseTest):source.refresh_from_db()assert (source.job_inputs or {}).get("cdc_enabled") is not True- @patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)- @patch(- "posthog.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.validate_prerequisites",- side_effect=psycopg.OperationalError("connection refused"),+ @parameterized.expand(+ [+ (+ "ssl_required_error",+ SSLRequiredError("SSL/TLS connection is required but your database does not support it."),+ ),+ (+ "operational_error",+ psycopg.OperationalError(+ 'connection failed: connection to server at "127.0.0.1", port 5434 failed: '+ "server does not support SSL, but SSL was required"+ ),+ ),+ ("ssh_tunnel_error", BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")),+ ])- def test_enable_cdc_returns_400_on_prereq_check_exception(self, _check, _flag) -> None:+ @patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)+ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")+ def test_enable_cdc_connection_failure_returns_400_without_capture(self, _name, exc, mock_capture, _flag) -> None:+ source = _make_postgres_source(self.team.pk, self.user)+ with patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=exc):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/enable_cdc/",+ data={"cdc_management_mode": "posthog"},+ format="json",+ )+ assert response.status_code == 400+ assert "Could not connect to source" 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.is_cdc_enabled_for_team", return_value=True)+ @patch("products.data_warehouse.backend.api.external_data_source.capture_exception")+ @patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=ValueError("unexpected bug"))+ def test_enable_cdc_unexpected_error_is_still_captured(self, _check, mock_capture, _flag) -> None:source = _make_postgres_source(self.team.pk, self.user)response = self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/enable_cdc/",@@ -8245,7 +8303,7 @@ class TestEnableCDC(APIBaseTest):format="json",)assert response.status_code == 400- assert "Could not connect to source" in response.json()["message"]+ mock_capture.assert_called_once()@patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)@patch(