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 connect-time recovery conflicts in offset chunking (#69657)

Tom Owers1b3c92f9b9af
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 9ade323c9032..692c9f814fa6 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
@@ -373,6 +373,19 @@ def _is_dropped_or_connection_limit(error: BaseException) -> bool:
return _is_connection_dropped_error(error) or _is_connection_limit_error(error)
+def _is_recovery_conflict_error(error: BaseException) -> bool:
+ """True if the error is a Postgres hot-standby recovery conflict, at read or connect time.
+
+ A read canceled by the standby surfaces as SerializationFailure (SQLSTATE 40001), but when the
+ standby cancels the *connection's own startup* the failure comes back as a plain
+ OperationalError ("connection failed: ... FATAL: canceling statement due to conflict with
+ recovery") with no SQLSTATE-mapped subclass. Match the stable message so both are recognised.
+ """
+ if not isinstance(error, psycopg.OperationalError):
+ return False
+ return "conflict with recovery" in " ".join(str(arg) for arg in error.args)
+
+
def _raise_if_setup_connection_broken(connection: psycopg.Connection) -> None:
"""Surface a connection dropped during metadata discovery as a retryable error.
@@ -3170,10 +3183,30 @@ def postgres_source(
floor_retries = 0
# Open lazily inside the loop so a recovery conflict (or connection drop) raised by
# the connect itself is caught by the handlers below. A hot standby can cancel the
- # connection's own startup with "conflict with recovery" (SerializationFailure) when
- # we reconnect mid-recovery — opening outside the loop let that escape the whole
- # fallback even though it's the same transient condition the loop already retries.
+ # connection's own startup with "conflict with recovery" when we reconnect
+ # mid-recovery — opening outside the loop let that escape the whole fallback even
+ # though it's the same transient condition the loop already retries.
connection: psycopg.Connection | None = None
+
+ def handle_recovery_conflict(e: BaseException) -> None:
+ # Shared bookkeeping for a recovery conflict hit either while reading a chunk
+ # (SerializationFailure) or while (re)connecting for one (the standby cancels the
+ # connection's own startup). Shrink the chunk toward the floor first; only once
+ # stuck at the floor count down to the non-retryable abort.
+ nonlocal chunk_size, successive_errors, floor_retries
+ successive_errors += 1
+ reduced_chunk_size = _next_recovery_conflict_chunk_size(chunk_size, successive_errors)
+ if reduced_chunk_size < chunk_size:
+ chunk_size = reduced_chunk_size
+ logger.debug(f"Reducing chunk size to {chunk_size} to reduce load on read replica")
+ floor_retries = 0
+ elif chunk_size <= _MIN_RECOVERY_CONFLICT_CHUNK_SIZE:
+ floor_retries += 1
+ if floor_retries >= _MAX_READ_RECOVERY_CONFLICT_RETRIES:
+ _safe_close_connection(connection)
+ raise _recovery_conflict_abort_error(floor_retries) from e
+ time.sleep(min(2 * successive_errors, 30))
+
while True:
try:
if connection is None or connection.closed:
@@ -3216,23 +3249,8 @@ def postgres_source(
except psycopg.errors.SerializationFailure as e:
if "due to conflict with recovery" not in "".join(e.args):
raise
-
logger.debug(f"SerializationFailure error: {e}. Retrying chunk at offset {offset}")
-
- successive_errors += 1
- # Shrink toward the floor first; only once stuck at the floor do we count down to
- # the abort.
- reduced_chunk_size = _next_recovery_conflict_chunk_size(chunk_size, successive_errors)
- if reduced_chunk_size < chunk_size:
- chunk_size = reduced_chunk_size
- logger.debug(f"Reducing chunk size to {chunk_size} to reduce load on read replica")
- floor_retries = 0
- elif chunk_size <= _MIN_RECOVERY_CONFLICT_CHUNK_SIZE:
- floor_retries += 1
- if floor_retries >= _MAX_READ_RECOVERY_CONFLICT_RETRIES:
- _safe_close_connection(connection)
- raise _recovery_conflict_abort_error(floor_retries) from e
- time.sleep(min(2 * successive_errors, 30))
+ handle_recovery_conflict(e)
except psycopg.errors.QueryCanceled as e:
# A chunk hit the 10-min statement_timeout. QueryCanceled
# subclasses OperationalError, so this clause must precede the
@@ -3271,6 +3289,17 @@ def postgres_source(
) from e
raise
except _CONNECTION_DROPPED_ERROR_TYPES as e:
+ if _is_recovery_conflict_error(e):
+ # A recovery conflict raised by the (re)connect itself surfaces as a plain
+ # OperationalError ("connection failed: ... conflict with recovery"), not a
+ # SerializationFailure, so it bypasses the handler above. Same transient
+ # condition — drop the dead connection so the loop reopens at the same
+ # offset, and route it through the shared recovery-conflict retry.
+ logger.debug(f"Recovery conflict on connect ({e}). Retrying chunk at offset {offset}")
+ _safe_close_connection(connection)
+ connection = None
+ handle_recovery_conflict(e)
+ continue
if not _is_dropped_or_connect_timeout(e):
_safe_close_connection(connection)
raise
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 6f54c7d7f245..83201f918a0a 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
@@ -2039,11 +2039,18 @@ class TestServerCursorCloseStatementTimeout:
class TestOffsetChunkingConnectRecoveryConflict:
"""A recovery conflict raised by the connect itself in the offset-chunking fallback — a hot
standby cancelling the new connection's startup with "conflict with recovery" — must be retried
- in-process, not escape `get_rows`. The bootstrap connect used to run outside the retry loop, so
- the conflict bypassed the loop's recovery-conflict handler and failed the whole sync.
+ in-process, not escape `get_rows`. It surfaces as a SerializationFailure when the standby cancels
+ a chunk read, but as a plain OperationalError ("connection failed: ... conflict with recovery")
+ when it cancels the connection's own startup — the latter bypassed the loop's SerializationFailure
+ handler and failed the whole sync.
"""
_RECOVERY_CONFLICT = "canceling statement due to conflict with recovery"
+ # psycopg wraps a startup-time cancel as a plain OperationalError with no SQLSTATE-mapped subclass.
+ _CONNECT_RECOVERY_CONFLICT = (
+ 'connection failed: connection to server at "localhost", port 5432 failed: '
+ "FATAL: canceling statement due to conflict with recovery"
+ )
class _NamedCursor:
def __init__(self):
@@ -2109,7 +2116,14 @@ class TestOffsetChunkingConnectRecoveryConflict:
def __exit__(self, *args):
return False
- def test_recovery_conflict_on_offset_chunking_connect_is_retried_in_process(self):
+ @pytest.mark.parametrize(
+ "connect_error",
+ [
+ psycopg.errors.SerializationFailure(_RECOVERY_CONFLICT),
+ psycopg.OperationalError(_CONNECT_RECOVERY_CONFLICT),
+ ],
+ )
+ def test_recovery_conflict_on_offset_chunking_connect_is_retried_in_process(self, connect_error):
@contextmanager
def fake_tunnel():
yield ("localhost", 5432)
@@ -2128,7 +2142,7 @@ class TestOffsetChunkingConnectRecoveryConflict:
# Calls 1 (setup) and 2 (initial server-cursor read) succeed; the offset-chunking
# bootstrap connect hits the recovery conflict twice before succeeding.
if connect_calls["n"] in (3, 4):
- raise psycopg.errors.SerializationFailure(self._RECOVERY_CONFLICT)
+ raise connect_error
return connection
module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"