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): retry CDC WAL reads dropped by Neon's internal walsender (#87075)

Tom Owers5fa4c7c4e330
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
index 33aff7b54e77..2610224207df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
@@ -217,14 +217,17 @@ class PgCDCStreamReader:
self._last_rows_consumed = 0
logger.warning("slot_read_busy_retry", slot_name=self._params.slot_name, attempt=attempt + 1)
time.sleep(0.5 * 2**attempt)
- except psycopg.OperationalError as e:
+ except (psycopg.OperationalError, psycopg.errors.InternalError_) as e:
# A transient drop on the peek fetch (pooler/firewall idle cull, failover, network
- # blip — e.g. "consuming input failed: SSL SYSCALL error: EOF detected") is the same
- # class connect()/confirm_position() already absorb in-process. Reconnect and
- # re-peek: the peek is non-consuming, so re-reading from the slot's last confirmed
- # position is safe. Only retry before the first row lands — once events have been
- # yielded the caller has buffered them, so a re-peek would duplicate; let it surface
- # and Temporal replays the whole run from the last confirmed LSN.
+ # blip — e.g. "consuming input failed: SSL SYSCALL error: EOF detected", or Neon's
+ # walsender losing its connection to a safekeeper) is the same class
+ # connect()/confirm_position() already absorb in-process — InternalError_ is the
+ # generic XX000 class those pooler/Neon-internal drops arrive as (see
+ # _is_connection_dropped_error). Reconnect and re-peek: the peek is non-consuming, so
+ # re-reading from the slot's last confirmed position is safe. Only retry before the
+ # first row lands — once events have been yielded the caller has buffered them, so a
+ # re-peek would duplicate; let it surface and Temporal replays the whole run from the
+ # last confirmed LSN.
if slot_acquired or not _is_connection_dropped_error(e) or attempt == _SLOT_READ_MAX_ATTEMPTS - 1:
raise
_safe_close_connection(conn)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py
index c275f1d0d664..1c02c73a7377 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py
@@ -273,6 +273,37 @@ class TestPgCDCStreamReaderReadChangesConnectionDropped:
assert reader._conn is new_conn
assert reader.last_rows_consumed == len(rows)
+ def test_read_changes_reconnects_after_mid_peek_internal_error_drop_before_first_row(self, params):
+ # Neon's walsender surfaces a lost connection to a safekeeper as a generic XX000
+ # InternalError_ rather than an OperationalError — the retry loop must catch this type too,
+ # or the drop escapes uncaught and fails the whole extraction instead of reconnecting.
+ rows = [("0/1", 1, b"a"), ("0/2", 1, b"b")]
+ reader, fake_cursor = self._reader_reading(
+ params,
+ [
+ psycopg.errors.InternalError_(
+ "[walsender] Failed to read WAL (req_lsn=0/1000000, len=8192): failed to connect "
+ "to safekeeper-1.cell-1.us-east-1.aws.neon.tech:6401 to fetch WAL: poll error: "
+ "server closed the connection unexpectedly"
+ ),
+ iter(rows),
+ ],
+ )
+ new_conn = mock.MagicMock()
+ new_conn.cursor.return_value.__enter__.return_value = fake_cursor
+ reconnect = mock.MagicMock(return_value=new_conn)
+ with (
+ patch.object(reader, "_open_streaming_connection", reconnect),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"
+ ),
+ ):
+ list(reader.read_changes(upto_nchanges=10))
+
+ reconnect.assert_called_once()
+ assert reader._conn is new_conn
+ assert reader.last_rows_consumed == len(rows)
+
def test_read_changes_does_not_retry_drop_after_row_yielded(self, params):
# Once a row has been yielded the caller has buffered events, so a re-peek would duplicate
# them — the drop must surface and let Temporal replay the whole run from the last confirmed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index a73d8f703fb1..551a63bb727b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -307,11 +307,20 @@ _CONNECTION_DROPPED_ERROR_SUBSTRINGS = (
# fresh reconnect re-establishes a new session — the same transient class. Matching only the
# "(authenticated)" wrapper would be too broad: a non-:closed "Internal error (authenticated): ..."
# could be a permanent pooler/protocol failure that should surface immediately, not be retried.
+#
+# Neon's own compute-side WAL relay ("walsender") surfaces the same generic XX000 InternalError_
+# when it loses connectivity to a safekeeper — the storage-tier peer that actually holds the WAL,
+# since a Neon compute doesn't keep it locally: "[walsender] Failed to read WAL (...): failed to
+# connect to safekeeper-<n>.<cell>....neon.tech:<port> to fetch WAL: ... server closed the
+# connection unexpectedly". Not a pooler, but the same transient class — a safekeeper failover or
+# network blip — and a fresh peek recovers once Neon's storage tier is reachable again. Match the
+# stable "failed to connect to safekeeper" phrase, excluding the volatile hostname/port.
_POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS = (
"edbhandlerexited",
"echeckoutretries",
"echeckouttimeout",
"internal error (authenticated): :closed",
+ "failed to connect to safekeeper",
)
# Connect-time capacity errors: the source refuses a *new* connection because it has hit a
@@ -389,8 +398,9 @@ def _is_connection_dropped_error(error: BaseException) -> bool:
if isinstance(error, psycopg.errors.ProtocolViolation | psycopg.OperationalError):
message = " ".join(str(arg) for arg in error.args).lower()
return any(substring in message for substring in _CONNECTION_DROPPED_ERROR_SUBSTRINGS)
- # Supavisor's pooler drop arrives as a generic XX000 InternalError_, not the libpq/PgBouncer
- # types above, so match it on its own narrow signature (see _POOLER_CONNECTION_DROPPED_*).
+ # Supavisor's pooler drop and Neon's own walsender-to-safekeeper drop both arrive as a generic
+ # XX000 InternalError_, not the libpq/PgBouncer types above, so match on their own narrow
+ # signatures (see _POOLER_CONNECTION_DROPPED_*).
if isinstance(error, psycopg.errors.InternalError_):
message = " ".join(str(arg) for arg in error.args).lower()
return any(substring in message for substring in _POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS)
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 90c3a3563db3..844d1c668e11 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
@@ -1833,6 +1833,16 @@ class TestIsConnectionDroppedError:
# local pre-handshake failure (e.g. the worker briefly out of file descriptors), not a
# server-side rejection. Transient; the reconnect must catch it.
psycopg.OperationalError("connection is bad: no error details available"),
+ # Neon's compute-side walsender loses connectivity to a safekeeper (the storage-tier
+ # peer holding the WAL) and surfaces it as a generic XX000 InternalError_, not the
+ # libpq/Supavisor signatures above. Transient — a safekeeper failover or network blip —
+ # so the reconnect must catch it. Hostname/port are volatile and excluded from the match.
+ psycopg.errors.InternalError_(
+ "[walsender] Failed to read WAL (req_lsn=0/1000000, len=8192): failed to connect to "
+ "safekeeper-1.cell-1.us-east-1.aws.neon.tech:6401 to fetch WAL: poll error: connection "
+ 'to server at "safekeeper-1.cell-1.us-east-1.aws.neon.tech" (203.0.113.10), port 6401 '
+ "failed: server closed the connection unexpectedly"
+ ),
],
)
def test_connection_dropped_errors_are_detected(self, error):