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): reconnect on transient WAL peek connection drops in CDC (#72142)

Tom Owersab7eb229e6ab
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 92a0634d4fda..155a6e135afd 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
@@ -23,6 +23,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.c
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (
_connect_to_postgres,
_connect_with_dropped_retry,
+ _is_connection_dropped_error,
+ _safe_close_connection,
get_primary_key_columns,
)
@@ -109,7 +111,15 @@ class PgCDCStreamReader:
# read paths and absorb those drops in-process instead of failing the whole
# extraction activity; permanent errors (auth, SSL-required) are re-raised
# immediately by the helper.
- self._conn = _connect_with_dropped_retry(
+ self._conn = self._open_streaming_connection()
+
+ def _open_streaming_connection(self) -> psycopg.Connection:
+ """Open a streaming connection to the source through the current tunnel endpoint.
+
+ Shared by the initial ``connect()`` and the in-process reconnect ``read_changes`` runs
+ after a transient mid-peek drop, so both use identical server-side timeouts.
+ """
+ return _connect_with_dropped_retry(
lambda: _connect_to_postgres(
host=self._effective_host,
port=self._effective_port,
@@ -204,6 +214,21 @@ 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:
+ # 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.
+ if slot_acquired or not _is_connection_dropped_error(e) or attempt == _SLOT_READ_MAX_ATTEMPTS - 1:
+ raise
+ _safe_close_connection(conn)
+ self._last_rows_consumed = 0
+ logger.warning("slot_read_dropped_retry", slot_name=self._params.slot_name, attempt=attempt + 1)
+ time.sleep(0.5 * 2**attempt)
+ self._conn = conn = self._open_streaming_connection()
def confirm_position(self, position: str) -> None:
"""Advance the replication slot to the given LSN.
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 f6b33ad4ef62..c275f1d0d664 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
@@ -236,6 +236,85 @@ class TestPgCDCStreamReaderReadChangesSlotInUse:
sleep.assert_not_called()
+class TestPgCDCStreamReaderReadChangesConnectionDropped:
+ def _reader_reading(self, params, iter_side_effect):
+ reader = PgCDCStreamReader(params)
+ fake_cursor = mock.MagicMock()
+ fake_cursor.__iter__.side_effect = iter_side_effect
+ reader._conn = mock.MagicMock()
+ reader._conn.cursor.return_value.__enter__.return_value = fake_cursor
+ reader._decoder = mock.MagicMock()
+ reader._decoder.decode_message.return_value = []
+ return reader, fake_cursor
+
+ def test_read_changes_reconnects_after_mid_peek_drop_before_first_row(self, params):
+ # A transient drop on the peek fetch before any row is yielded reconnects and re-peeks
+ # instead of failing the whole extraction — the peek is non-consuming, so re-reading is safe.
+ rows = [("0/1", 1, b"a"), ("0/2", 1, b"b")]
+ reader, fake_cursor = self._reader_reading(
+ params,
+ [
+ psycopg.OperationalError("consuming input failed: SSL SYSCALL error: EOF detected"),
+ 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
+ # LSN rather than silently reconnecting mid-stream.
+ def rows_then_drop():
+ yield ("0/1", 1, b"a")
+ raise psycopg.OperationalError("consuming input failed: SSL SYSCALL error: EOF detected")
+
+ reader, _ = self._reader_reading(params, [rows_then_drop()])
+ reconnect = mock.MagicMock()
+ with (
+ patch.object(reader, "_open_streaming_connection", reconnect),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"
+ ),
+ ):
+ with pytest.raises(psycopg.OperationalError):
+ list(reader.read_changes(upto_nchanges=10))
+
+ reconnect.assert_not_called()
+
+ def test_read_changes_does_not_retry_non_dropped_operational_error(self, params):
+ # A non-drop OperationalError (not a recognized transient connection loss) is re-raised
+ # immediately, never reconnected, so a real error isn't masked as a transient blip.
+ reader, fake_cursor = self._reader_reading(
+ params,
+ psycopg.OperationalError("some unexpected operational failure"),
+ )
+ reconnect = mock.MagicMock()
+ with (
+ patch.object(reader, "_open_streaming_connection", reconnect),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.stream_reader.time.sleep"
+ ),
+ ):
+ with pytest.raises(psycopg.OperationalError):
+ list(reader.read_changes(upto_nchanges=10))
+
+ assert fake_cursor.__iter__.call_count == 1
+ reconnect.assert_not_called()
+
+
class TestPgCDCStreamReaderConfirmPosition:
def test_confirm_position_retries_transient_dropped_connection(self, params):
good_conn = mock.MagicMock()