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 server-cursor read when connection drops before first row (#69902)

Tom Owersaecc9ef5a734
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 692c9f814fa6..3018e4a8a716 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
@@ -121,6 +121,13 @@ _MIN_RECOVERY_CONFLICT_CHUNK_SIZE = 100
# this the drop is treated as sustained and re-raised for Temporal to retry the whole activity.
_MAX_SETUP_CONNECTION_DROPPED_RETRIES = 5
+# Bounded in-process retries for a transient connection drop hit on the main server-cursor read
+# *before* the first row is yielded (e.g. during the DECLARE, which the connect-only
+# `_connect_with_dropped_retry` doesn't cover). At offset 0 nothing has been emitted, so re-running
+# the read from scratch is safe even for an unordered full-table scan. Past this the drop is treated
+# as sustained and re-raised for Temporal to retry the whole activity.
+_MAX_INITIAL_READ_DROP_RETRIES = 5
+
def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -> bool:
"""Return whether this source must connect over SSL/TLS.
@@ -3401,97 +3408,115 @@ def postgres_source(
)
return
- offset = 0
- try:
- # Retry transient connection-dropped errors (e.g. "server closed the
- # connection unexpectedly") on the initial connect, matching the
- # offset-chunking bootstrap above. Retrying here is always safe: offset
- # is still 0 and no rows have been yielded, so the unsafe-resume concern
- # in the except clause below doesn't apply. Permanent errors (auth,
- # SSL-required) still surface immediately — _is_connection_dropped_error
- # only matches transient drops.
- with _connect_with_dropped_retry(get_connection, logger) as connection:
- with connection.cursor(name=f"posthog_{team_id}_{schema}.{table_name}") as cursor:
- query = _build_query(
- schema,
- table_name,
- should_use_incremental_field,
- table.type,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- enabled_columns=enabled_columns,
- primary_keys=primary_keys,
- row_filters=row_filters,
- xmin_bounds=xmin_bounds,
- )
- logger.debug(f"Postgres query: {query.as_string()}")
+ initial_read_drop_retries = 0
+ while True:
+ offset = 0
+ try:
+ # Retry transient connection-dropped errors (e.g. "server closed the
+ # connection unexpectedly") on the initial connect, matching the
+ # offset-chunking bootstrap above. Retrying here is always safe: offset
+ # is still 0 and no rows have been yielded, so the unsafe-resume concern
+ # in the except clause below doesn't apply. Permanent errors (auth,
+ # SSL-required) still surface immediately — _is_connection_dropped_error
+ # only matches transient drops.
+ with _connect_with_dropped_retry(get_connection, logger) as connection:
+ with connection.cursor(name=f"posthog_{team_id}_{schema}.{table_name}") as cursor:
+ query = _build_query(
+ schema,
+ table_name,
+ should_use_incremental_field,
+ table.type,
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=row_filters,
+ xmin_bounds=xmin_bounds,
+ )
+ logger.debug(f"Postgres query: {query.as_string()}")
- cursor.execute(query)
+ cursor.execute(query)
- column_names = [column.name for column in cursor.description or []]
+ column_names = [column.name for column in cursor.description or []]
- while True:
- rows = cursor.fetchmany(chunk_size)
- if not rows:
- break
+ while True:
+ rows = cursor.fetchmany(chunk_size)
+ if not rows:
+ break
- dicts = [dict(zip(column_names, row)) for row in rows]
- del rows
- yield table_from_iterator(iter(dicts), arrow_schema)
- offset += len(dicts)
- except psycopg.errors.SerializationFailure as e:
- # If we hit a SerializationFailure and we're reading from a read replica, we fallback to offset chunking
- if using_read_replica and "conflict with recovery" in "".join(e.args):
- logger.debug(f"Falling back to offset chunking for table due to SerializationFailure error: {e}.")
- yield from offset_chunking(offset, chunk_size, from_recovery_conflict=True)
+ dicts = [dict(zip(column_names, row)) for row in rows]
+ del rows
+ yield table_from_iterator(iter(dicts), arrow_schema)
+ offset += len(dicts)
return
+ except psycopg.errors.SerializationFailure as e:
+ # If we hit a SerializationFailure and we're reading from a read replica, we fallback to offset chunking
+ if using_read_replica and "conflict with recovery" in "".join(e.args):
+ logger.debug(
+ f"Falling back to offset chunking for table due to SerializationFailure error: {e}."
+ )
+ yield from offset_chunking(offset, chunk_size, from_recovery_conflict=True)
+ return
- raise
- except psycopg.errors.QueryCanceled as e:
- # A FETCH against the server cursor exhausted the 10-min
- # statement_timeout. QueryCanceled subclasses OperationalError, so
- # this clause must precede the connection-dropped handler below.
- if _raised_while_closing_generator(e):
- # Not a real read timeout: the generator is being closed and the
- # cursor/connection teardown round-trip hit the statement_timeout.
- # Swallow it so close() completes cleanly instead of masking the
- # real outcome (e.g. an activity cancellation) with a phantom timeout.
- _safe_close_connection(connection)
- return
- # Retrying is futile (usually a missing index on the incremental
- # field or a scan too large to finish in time), so map it to the
- # same non-retryable QueryTimeoutException the offset-chunking and
- # windowed paths raise instead of leaking a raw, retryable
- # QueryCanceled that Temporal keeps re-attempting.
- timeout_error = _statement_timeout_as_non_retryable(
- e,
- should_use_incremental_field=should_use_incremental_field,
- incremental_field=incremental_field,
- )
- if timeout_error is not None:
- raise timeout_error from e
- raise
- except _CONNECTION_DROPPED_ERROR_TYPES as e:
- # The server cursor holds a transaction open across the slow
- # delta-merge between yields; the source can cull the backend
- # (idle_in_transaction_session_timeout / PgBouncer) and the next
- # fetch fails with "server conn crashed?". Resume from the current
- # offset via offset_chunking, which runs in autocommit so it never
- # holds a transaction open across the merge.
- if not _is_connection_dropped_error(e):
raise
- # Offset-based resume is only safe when the query has a stable
- # ORDER BY (added by _build_query for incremental syncs, and by the
- # xmin branch). A full-table scan has no ORDER BY, so Postgres may
- # return rows in a different order on the resumed query and OFFSET
- # would skip or duplicate rows. In that case re-raise and let the
- # sync restart.
- if not should_use_incremental_field and xmin_bounds is None:
+ except psycopg.errors.QueryCanceled as e:
+ # A FETCH against the server cursor exhausted the 10-min
+ # statement_timeout. QueryCanceled subclasses OperationalError, so
+ # this clause must precede the connection-dropped handler below.
+ if _raised_while_closing_generator(e):
+ # Not a real read timeout: the generator is being closed and the
+ # cursor/connection teardown round-trip hit the statement_timeout.
+ # Swallow it so close() completes cleanly instead of masking the
+ # real outcome (e.g. an activity cancellation) with a phantom timeout.
+ _safe_close_connection(connection)
+ return
+ # Retrying is futile (usually a missing index on the incremental
+ # field or a scan too large to finish in time), so map it to the
+ # same non-retryable QueryTimeoutException the offset-chunking and
+ # windowed paths raise instead of leaking a raw, retryable
+ # QueryCanceled that Temporal keeps re-attempting.
+ timeout_error = _statement_timeout_as_non_retryable(
+ e,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ )
+ if timeout_error is not None:
+ raise timeout_error from e
raise
- logger.debug(f"Connection dropped ({e}). Falling back to offset chunking at offset {offset}.")
- yield from offset_chunking(offset, chunk_size)
- return
+ except _CONNECTION_DROPPED_ERROR_TYPES as e:
+ # The server cursor holds a transaction open across the slow
+ # delta-merge between yields; the source can cull the backend
+ # (idle_in_transaction_session_timeout / PgBouncer) and the next
+ # fetch fails with "server conn crashed?". Resume from the current
+ # offset via offset_chunking, which runs in autocommit so it never
+ # holds a transaction open across the merge.
+ if not _is_connection_dropped_error(e):
+ raise
+ # Offset-based resume is only safe when the query has a stable
+ # ORDER BY (added by _build_query for incremental syncs, and by the
+ # xmin branch). A full-table scan has no ORDER BY, so Postgres may
+ # return rows in a different order on the resumed query and OFFSET
+ # would skip or duplicate rows.
+ if not should_use_incremental_field and xmin_bounds is None:
+ # But a drop before the first row was yielded (offset == 0 — e.g. during
+ # the server-cursor DECLARE, which the connect-only
+ # _connect_with_dropped_retry above doesn't cover) is safe to retry by
+ # re-running the read from scratch: nothing has been emitted, so there is
+ # no resume ordering to get wrong. Mirrors the initial-connect retry. Once
+ # any row is out, re-raise and let Temporal restart the whole activity.
+ if offset == 0 and initial_read_drop_retries < _MAX_INITIAL_READ_DROP_RETRIES:
+ initial_read_drop_retries += 1
+ logger.debug(
+ f"Connection dropped before first row ({e}). Retrying full-table read "
+ f"(attempt {initial_read_drop_retries}/{_MAX_INITIAL_READ_DROP_RETRIES})."
+ )
+ time.sleep(min(2 * initial_read_drop_retries, 30))
+ continue
+ raise
+ logger.debug(f"Connection dropped ({e}). Falling back to offset chunking at offset {offset}.")
+ yield from offset_chunking(offset, chunk_size)
+ return
name = NamingConvention.normalize_identifier(table_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 83201f918a0a..127d304ea133 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
@@ -6412,6 +6412,143 @@ class TestGetRowsInitialConnectRetry:
dj_cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
+class TestGetRowsInitialReadDropRetry:
+ # Regression: the main server-cursor read wrapped only the *connect* in
+ # _connect_with_dropped_retry, so a transient drop during the server-cursor DECLARE
+ # (cursor.execute) — before any row is yielded — escaped and failed the whole sync on a
+ # full-table scan, which has no stable ORDER BY and so can't resume via offset_chunking. At
+ # offset 0 nothing has been emitted, so re-running the read from scratch is safe and it should
+ # retry in process. Once a chunk is out, replaying it would duplicate rows, so the drop must
+ # still propagate.
+ _DROP = "consuming input failed: SSL connection has been closed unexpectedly"
+
+ class _Cursor:
+ def __init__(self, *, batches, drop_on_execute):
+ col = mock.Mock()
+ col.name = "id"
+ self.description = [col]
+ self._batches = list(batches)
+ self._drop_on_execute = drop_on_execute
+
+ def execute(self, *args, **kwargs):
+ if self._drop_on_execute:
+ raise psycopg.OperationalError(TestGetRowsInitialReadDropRetry._DROP)
+ return None
+
+ def fetchmany(self, _n):
+ if not self._batches:
+ return []
+ batch = self._batches.pop(0)
+ if isinstance(batch, BaseException):
+ raise batch
+ return batch
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ class _Connection:
+ def __init__(self, *, batches, drop_on_execute):
+ self.autocommit = False
+ self.closed = False
+ self.broken = False
+ self.adapters = mock.Mock()
+ self._batches = batches
+ self._drop_on_execute = drop_on_execute
+
+ def cursor(self, *args, **kwargs):
+ # The named cursor is the streaming server cursor under test; the unnamed setup cursor
+ # (SET statement_timeout) goes through the patched psycopg.Cursor and stays benign.
+ if "name" in kwargs:
+ return TestGetRowsInitialReadDropRetry._Cursor(
+ batches=self._batches, drop_on_execute=self._drop_on_execute
+ )
+ return mock.MagicMock()
+
+ def commit(self):
+ return None
+
+ def close(self):
+ self.closed = True
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def _run(self, connect_side_effect):
+ @contextmanager
+ def fake_tunnel():
+ yield ("localhost", 5432)
+
+ fake_table = mock.Mock()
+ fake_table.to_arrow_schema.return_value = pa.schema([pa.field("id", pa.int64())])
+ fake_table.type = "table"
+ fake_table.columns = []
+ fake_table.__contains__ = mock.Mock(return_value=False)
+
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"
+ with (
+ patch(f"{module}.time.sleep"),
+ patch(f"{module}.psycopg.connect", side_effect=connect_side_effect) as connect_mock,
+ patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(batches=[], drop_on_execute=False)),
+ patch(f"{module}._get_table", return_value=fake_table),
+ patch(f"{module}._is_read_replica", return_value=False),
+ patch(f"{module}._get_primary_keys", return_value=["id"]),
+ patch(f"{module}._is_partitioned_table", return_value=False),
+ patch(f"{module}._get_table_chunk_size", return_value=100),
+ patch(f"{module}._get_rows_to_sync", return_value=10),
+ patch(f"{module}._role_subject_to_rls", return_value=False),
+ patch(f"{module}._get_partition_settings", return_value=None),
+ ):
+ response = postgres_source(
+ tunnel=lambda: fake_tunnel(),
+ user="u",
+ password="p",
+ database="db",
+ sslmode="prefer",
+ schema="public",
+ table_names=["companies"],
+ should_use_incremental_field=False,
+ logger=structlog.get_logger(),
+ db_incremental_field_last_value=None,
+ team_id=1,
+ )
+ tables = list(cast(Iterable[Any], response.items()))
+ return tables, connect_mock
+
+ def test_retries_full_table_read_when_connection_drops_before_first_row(self):
+ calls = {"n": 0}
+
+ def connect_side_effect(*args, **kwargs):
+ calls["n"] += 1
+ # First read connect succeeds, but the server-cursor DECLARE drops; the retry reconnects
+ # and serves the rows.
+ drop_on_execute = calls["n"] == 1
+ batches = [] if drop_on_execute else [[(1,), (2,), (3,)]]
+ return self._Connection(batches=batches, drop_on_execute=drop_on_execute)
+
+ tables, connect_mock = self._run(connect_side_effect)
+
+ assert connect_mock.call_count >= 2, "the read should have been retried after the DECLARE-time drop"
+ assert sum(table.num_rows for table in tables) == 3
+
+ def test_reraises_full_table_drop_after_rows_yielded(self):
+ # A drop after a chunk is already out must propagate: an unordered full-table scan can't
+ # resume without duplicating rows, so the in-process retry must not swallow it.
+ def connect_side_effect(*args, **kwargs):
+ return self._Connection(
+ batches=[[(1,), (2,)], psycopg.OperationalError(self._DROP)],
+ drop_on_execute=False,
+ )
+
+ with pytest.raises(psycopg.OperationalError, match="SSL connection has been closed unexpectedly"):
+ self._run(connect_side_effect)
+
+
class TestPartitionIterationConnectRetry:
# Regression: the windowed / per-partition read paths opened each window's (or partition's)
# connection with a bare get_connection(), so a transient drop while establishing it — the