: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): keep PostHog DB connection failures retryable in source setup (#65365)
Tom Owers5b01f0923fd0
diff --git a/posthog/temporal/data_imports/sources/postgres/exceptions.py b/posthog/temporal/data_imports/sources/postgres/exceptions.pyindex 2759b4beac57..9e51de613ec5 100644--- a/posthog/temporal/data_imports/sources/postgres/exceptions.py+++ b/posthog/temporal/data_imports/sources/postgres/exceptions.py@@ -16,3 +16,15 @@ class XminUnsupportedError(Exception):is listed in `PostgresSource.get_non_retryable_errors` to stop Temporalretrying into the same wall."""+++class PostHogDatabaseConnectionError(Exception):+ """Raised when loading sync metadata from PostHog's own database fails to connect.++ This is a PostHog-side infrastructure blip (e.g. a transient DNS failure resolving our+ database host), not a problem with the customer's Postgres. Its message intentionally+ avoids the connection-error substrings in `PostgresSource.get_non_retryable_errors`: a+ failure reaching our database stringifies the same as a customer misconfiguration (e.g.+ "Name or service not known"), and must stay retryable rather than be misclassified as+ non-retryable and stop a healthy sync.+ """diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.pyindex 9dd0b4c7bab1..a8b45232846b 100644--- a/posthog/temporal/data_imports/sources/postgres/source.py+++ b/posthog/temporal/data_imports/sources/postgres/source.py@@ -1,6 +1,8 @@import loggingfrom typing import TYPE_CHECKING, Optional, cast+from django.db import OperationalError as DjangoOperationalError+import structlogfrom psycopg import OperationalErrorfrom sshtunnel import BaseSSHTunnelForwarderError@@ -802,13 +804,24 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaconn.close()def source_for_pipeline(self, config: PostgresSourceConfig, inputs: SourceInputs) -> SourceResponse:- from posthog.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally+ from posthog.temporal.data_imports.sources.postgres.exceptions import (+ CDCHandledExternally,+ PostHogDatabaseConnectionError,+ )from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemassh_tunnel = self.make_ssh_tunnel_func(config)- schema = ExternalDataSchema.objects.select_related("source").get(id=inputs.schema_id)+ # This reads sync metadata from PostHog's own database, not the customer's Postgres. A+ # transient failure reaching our database here (e.g. a DNS blip resolving our host) raises+ # the same "Name or service not known" wording a customer host misconfig would, which+ # `get_non_retryable_errors` would misclassify as non-retryable and permanently stop a+ # healthy sync. Re-raise as a retryable error whose message doesn't collide with those.+ try:+ schema = ExternalDataSchema.objects.select_related("source").get(id=inputs.schema_id)+ except DjangoOperationalError as e:+ raise PostHogDatabaseConnectionError("Failed to load sync metadata from PostHog's database") from eschema_metadata = schema.schema_metadata or {}source_schema = (schema_metadata.get("source_schema") if isinstance(schema_metadata.get("source_schema"), str) else Nonediff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex 79619da14740..49b6fa15824e 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -8,7 +8,10 @@ from freezegun import freeze_timefrom unittest import mockfrom unittest.mock import MagicMock, patch-from django.db import connection as django_connection+from django.db import (+ OperationalError as DjangoOperationalError,+ connection as django_connection,+)import psycopgimport pyarrow as pa@@ -24,7 +27,10 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (TemporaryFileSizeExceedsLimitException,)from posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter-from posthog.temporal.data_imports.sources.postgres.exceptions import XminUnsupportedError+from posthog.temporal.data_imports.sources.postgres.exceptions import (+ PostHogDatabaseConnectionError,+ XminUnsupportedError,+)from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (WINDOW_MAX_QUERY_CANCELED_RETRIES,WINDOW_MAX_SERIALIZATION_RETRIES,@@ -239,6 +245,34 @@ class TestPostgresImplementationWiring:assert impl.get_incremental_filter() is filter_postgres_incremental_fields+class TestPostgresSourceMetadataConnectionErrors:+ def test_posthog_database_connection_failure_stays_retryable(self):+ # `source_for_pipeline` first reads sync metadata from PostHog's own database. A transient+ # connection failure there (e.g. a DNS blip resolving our host) surfaces the same+ # "Name or service not known" wording a customer host misconfig would, so it must be+ # re-raised as PostHogDatabaseConnectionError to avoid being misclassified as non-retryable.+ source = PostgresSource()+ config = MagicMock()+ inputs = MagicMock()++ with (+ patch.object(PostgresSource, "make_ssh_tunnel_func", return_value=None),+ patch(+ "products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema"+ ) as mock_schema_model,+ ):+ mock_schema_model.objects.select_related.return_value.get.side_effect = DjangoOperationalError(+ "[Errno -2] Name or service not known"+ )+ with pytest.raises(PostHogDatabaseConnectionError) as exc_info:+ source.source_for_pipeline(config, inputs)++ non_retryable = source.get_non_retryable_errors()+ error_msg = str(exc_info.value)+ is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())+ assert not is_non_retryable, f"A PostHog-side DB connection failure must stay retryable: {error_msg}"++class TestPostgresSourceNonRetryableErrors:@pytest.fixturedef source(self):