Skip to content

: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.

fix(postgres): keep foreign-server connection failures retryable (#68813)

Tom Owersd07689d90c1c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py
index 9e51de613ec5..812f27c8b00a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/exceptions.py
@@ -28,3 +28,17 @@ class PostHogDatabaseConnectionError(Exception):
"Name or service not known"), and must stay retryable rather than be misclassified as
non-retryable and stop a healthy sync.
"""
+
+
+class ForeignServerUnreachableError(Exception):
+ """Raised when a setup query touched a postgres_fdw foreign table whose foreign server failed.
+
+ postgres_fdw/dblink report a failure to connect to a *foreign* server with SQLSTATE 08001
+ (`SqlclientUnableToEstablishSqlconnection`), embedding the downstream libpq error verbatim —
+ e.g. "... failed: Connection refused". That English wording collides with the connect-time
+ substrings in `PostgresSource.get_non_retryable_errors` (which target the *direct* connection to
+ the customer's database), so a foreign server that's briefly down (failover, restart) would be
+ misclassified as a permanent misconfiguration and stop a healthy sync. The server-side sibling of
+ `PostHogDatabaseConnectionError`: its message intentionally avoids those substrings so a transient
+ foreign-server outage stays retryable.
+ """
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index 395e4837edb6..de7d4d1c6e37 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -5,6 +5,7 @@ from django.db import OperationalError as DjangoOperationalError
import structlog
from psycopg import OperationalError
+from psycopg.errors import SqlclientUnableToEstablishSqlconnection
from sshtunnel import BaseSSHTunnelForwarderError
if TYPE_CHECKING:
@@ -141,6 +142,15 @@ RLS_WARNING_MESSAGE = (
"Granting the sync role BYPASSRLS will silence the check."
)
+# Stable, classifiable message for a postgres_fdw foreign-server connection failure surfaced during
+# setup. Kept clear of the connect-time substrings in `get_non_retryable_errors` so the condition
+# stays retryable — see `ForeignServerUnreachableError`.
+_FOREIGN_SERVER_UNREACHABLE_ERROR = (
+ "A table selected for sync is a postgres_fdw foreign table and PostHog could not connect to the "
+ "foreign server it points at. This is usually a transient outage of that downstream server; if it "
+ "persists, check that the foreign server is running and reachable from your source database."
+)
+
@SourceRegistry.register
class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):
@@ -939,6 +949,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (
CDCHandledExternally,
+ ForeignServerUnreachableError,
PostHogDatabaseConnectionError,
)
@@ -982,31 +993,40 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
# Prefer the per-row `schema_metadata.source_schema` so multi-schema warehouse sources work
# without needing to encode the schema in `config.schema`. Falls back to `config.schema` for
# legacy single-schema warehouse sources whose rows haven't been reconciled yet.
- response = postgres_source(
- tunnel=ssh_tunnel,
- user=config.user,
- password=config.password,
- database=config.database,
- sslmode="prefer",
- schema=source_schema or config.schema or "public",
- table_names=[source_table_name or inputs.schema_name],
- should_use_incremental_field=inputs.should_use_incremental_field,
- logger=inputs.logger,
- incremental_field=inputs.incremental_field,
- incremental_field_type=inputs.incremental_field_type,
- db_incremental_field_last_value=inputs.db_incremental_field_last_value,
- chunk_size_override=schema.chunk_size_override,
- team_id=inputs.team_id,
- require_ssl=require_ssl,
- is_initial_sync=not schema.initial_sync_complete,
- enabled_columns=inputs.enabled_columns,
- row_filters=inputs.row_filters,
- # xmin state is read straight off the schema here (the generic `SourceInputs` stays
- # Postgres-agnostic). xmin rides the normal full per-schema path — no CDC dispatch.
- is_xmin=schema.is_xmin,
- xmin_last_value=schema.xmin_last_value,
- xmin_num_wraparound=schema.xmin_num_wraparound,
- )
+ try:
+ response = postgres_source(
+ tunnel=ssh_tunnel,
+ user=config.user,
+ password=config.password,
+ database=config.database,
+ sslmode="prefer",
+ schema=source_schema or config.schema or "public",
+ table_names=[source_table_name or inputs.schema_name],
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ logger=inputs.logger,
+ incremental_field=inputs.incremental_field,
+ incremental_field_type=inputs.incremental_field_type,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
+ chunk_size_override=schema.chunk_size_override,
+ team_id=inputs.team_id,
+ require_ssl=require_ssl,
+ is_initial_sync=not schema.initial_sync_complete,
+ enabled_columns=inputs.enabled_columns,
+ row_filters=inputs.row_filters,
+ # xmin state is read straight off the schema here (the generic `SourceInputs` stays
+ # Postgres-agnostic). xmin rides the normal full per-schema path — no CDC dispatch.
+ is_xmin=schema.is_xmin,
+ xmin_last_value=schema.xmin_last_value,
+ xmin_num_wraparound=schema.xmin_num_wraparound,
+ )
+ except SqlclientUnableToEstablishSqlconnection as e:
+ # A setup query (e.g. the duplicate-PK probe) touched a postgres_fdw foreign table and the
+ # foreign server it points at refused/failed the connection (SQLSTATE 08001). libpq embeds
+ # the downstream error verbatim (e.g. "... Connection refused"), which would otherwise
+ # collide with the connect-time non-retryable rules meant for the direct connection and
+ # permanently disable the sync on a transient foreign-server blip. Re-raise clear of those
+ # substrings so it stays retryable.
+ raise ForeignServerUnreachableError(_FOREIGN_SERVER_UNREACHABLE_ERROR) from e
# `SourceResponse.name` must match `DataWarehouseTable.url_pattern` (both derived from the
# storage key when present, otherwise the row name) so HogQL reads from where we wrote.
storage_schema_name = schema.resolved_s3_folder_name or inputs.schema_name
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index ef655797519e..1ed726ce3950 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
ValidatedRowFilter,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (
+ ForeignServerUnreachableError,
PostHogDatabaseConnectionError,
XminUnsupportedError,
)
@@ -285,6 +286,58 @@ class TestPostgresSourceMetadataConnectionErrors:
assert not is_non_retryable, f"A PostHog-side DB connection failure must stay retryable: {error_msg}"
+class TestPostgresSourceForeignServerConnectionError:
+ def test_foreign_server_connection_failure_stays_retryable(self):
+ # A setup query touched a postgres_fdw foreign table and the foreign server it points at
+ # refused the connection (SQLSTATE 08001). libpq embeds "... Connection refused" verbatim,
+ # which would collide with the connect-time "Connection refused" non-retryable rule meant for
+ # the direct connection — so a transient foreign-server outage must be re-raised clear of that
+ # substring to stay retryable instead of disabling a healthy sync.
+ source = PostgresSource()
+ schema_model = mock.MagicMock()
+ schema_model.is_cdc = False
+ schema_model.cdc_mode = None
+ schema_model.schema_metadata = {"source_schema": "public", "source_table_name": "orders"}
+ schema_model.initial_sync_complete = True
+
+ inputs = mock.MagicMock(
+ schema_id="00000000-0000-0000-0000-000000000000",
+ schema_name="orders",
+ team_id=1,
+ )
+ config = mock.MagicMock(user="u", password="p", database="db", schema="public")
+
+ fdw_error = psycopg.errors.SqlclientUnableToEstablishSqlconnection(
+ 'could not connect to server "some_fdw_server"\n'
+ 'DETAIL: connection to server at "10.0.0.5", port 5432 failed: Connection refused\n'
+ "\tIs the server running on that host and accepting TCP/IP connections?"
+ )
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.models.external_data_schema.ExternalDataSchema.objects"
+ ) as objects_mock,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.postgres_source",
+ side_effect=fdw_error,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.source_requires_ssl",
+ return_value=False,
+ ),
+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),
+ ):
+ objects_mock.select_related.return_value.get.return_value = schema_model
+ with pytest.raises(ForeignServerUnreachableError) as exc_info:
+ source.source_for_pipeline(config, inputs)
+
+ error_msg = str(exc_info.value)
+ non_retryable = source.get_non_retryable_errors()
+ is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
+ assert not is_non_retryable, f"A foreign-server connection failure must stay retryable: {error_msg}"
+ assert "Connection refused" not in error_msg
+
+
class TestPostgresSourceNonRetryableErrors:
@pytest.fixture
def source(self):