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 source lock_timeout during server-cursor read (#71759)

Tom Owersbf49e75f52c9
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 68c2323f98a6..08967886e5be 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
@@ -128,6 +128,14 @@ _MAX_SETUP_CONNECTION_DROPPED_RETRIES = 5
# as sustained and re-raised for Temporal to retry the whole activity.
_MAX_INITIAL_READ_DROP_RETRIES = 5
+# Bounded in-process retries for a source-side lock_timeout hit while opening the main server-cursor
+# read *before* the first row is yielded — the DECLARE waited past the source's lock_timeout for a
+# lock another transaction held (a concurrent DDL / VACUUM FULL taking ACCESS EXCLUSIVE conflicts
+# with our ACCESS SHARE). It's transient: the lock frees once that transaction ends. At offset 0
+# nothing has been emitted, so re-running the read from scratch is safe for any sync type. Past this
+# the conflict is treated as sustained and re-raised for Temporal to retry the whole activity.
+_MAX_INITIAL_READ_LOCK_TIMEOUT_RETRIES = 5
+
def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -> bool:
"""Return whether this source must connect over SSL/TLS.
@@ -3512,6 +3520,7 @@ def postgres_source(
return
initial_read_drop_retries = 0
+ initial_read_lock_timeout_retries = 0
while True:
offset = 0
try:
@@ -3587,6 +3596,26 @@ def postgres_source(
if timeout_error is not None:
raise timeout_error from e
raise
+ except psycopg.errors.LockNotAvailable as e:
+ # The server-cursor DECLARE waited past the source's lock_timeout for a lock
+ # another transaction holds (a concurrent DDL / VACUUM FULL takes ACCESS
+ # EXCLUSIVE, which conflicts with our ACCESS SHARE). It's transient — the lock
+ # frees once that transaction ends — so it must stay retryable and is never a
+ # NonRetryableError. LockNotAvailable subclasses OperationalError, so this clause
+ # must precede the connection-dropped handler below. At offset 0 nothing has been
+ # emitted, so re-running the read from scratch is safe for any sync type; retry in
+ # process with bounded backoff instead of failing the activity and flooding error
+ # tracking. Once a row is out, or the conflict is sustained, propagate so Temporal
+ # retries the whole activity.
+ if offset == 0 and initial_read_lock_timeout_retries < _MAX_INITIAL_READ_LOCK_TIMEOUT_RETRIES:
+ initial_read_lock_timeout_retries += 1
+ logger.debug(
+ f"Lock timeout before first row ({e}). Retrying read "
+ f"(attempt {initial_read_lock_timeout_retries}/{_MAX_INITIAL_READ_LOCK_TIMEOUT_RETRIES})."
+ )
+ time.sleep(min(2 * initial_read_lock_timeout_retries, 30))
+ continue
+ 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
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 a50579feaecf..21b9211ebf72 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
@@ -6831,6 +6831,140 @@ class TestGetRowsInitialReadDropRetry:
self._run(connect_side_effect)
+class TestGetRowsInitialReadLockTimeoutRetry:
+ # Regression: a source-side lock_timeout hit while opening the server-cursor DECLARE
+ # (cursor.execute) raises psycopg.errors.LockNotAvailable, which subclasses OperationalError and
+ # so was caught by the connection-dropped handler, failed _is_connection_dropped_error, and
+ # re-raised — failing the activity and flooding error tracking with a handled exception for a
+ # transient lock conflict (a concurrent DDL / VACUUM FULL holding ACCESS EXCLUSIVE). It's
+ # transient, so it must stay retryable; before the first row is yielded (offset 0) re-running the
+ # read from scratch is safe, so it should retry in process. Once a chunk is out, replaying it
+ # would duplicate rows, so the lock timeout must still propagate.
+ _LOCK_TIMEOUT = "canceling statement due to lock timeout"
+
+ class _Cursor:
+ # The read server cursor. `state["declare_locks_left"]` is how many DECLAREs (cursor.execute)
+ # should hit the source's lock_timeout before one succeeds; it's shared across reconnects so
+ # the in-process retry opens a fresh cursor that finally gets through. Batches drive the
+ # post-DECLARE fetch, and a batch that is an exception is raised mid-stream.
+ def __init__(self, *, batches, state):
+ col = mock.Mock()
+ col.name = "id"
+ self.description = [col]
+ self._batches = list(batches)
+ self._state = state
+
+ def execute(self, *args, **kwargs):
+ if self._state["declare_locks_left"] > 0:
+ self._state["declare_locks_left"] -= 1
+ raise psycopg.errors.LockNotAvailable(TestGetRowsInitialReadLockTimeoutRetry._LOCK_TIMEOUT)
+ 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, state):
+ self.autocommit = False
+ self.closed = False
+ self.broken = False
+ self.adapters = mock.Mock()
+ self._batches = batches
+ self._state = state
+
+ def cursor(self, *args, **kwargs):
+ # Only the named server cursor (the read under test) can hit the lock timeout; the unnamed
+ # setup cursor stays benign so the lock fires on the DECLARE, not on setup.
+ if "name" in kwargs:
+ return TestGetRowsInitialReadLockTimeoutRetry._Cursor(batches=self._batches, state=self._state)
+ 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, *, declare_locks_left, batches):
+ @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)
+
+ # Shared across every read connection so the retry's fresh cursor sees the decremented count.
+ state = {"declare_locks_left": declare_locks_left}
+
+ def connect_side_effect(*args, **kwargs):
+ return self._Connection(batches=batches, state=state)
+
+ 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=[], state={"declare_locks_left": 0})),
+ 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, state
+
+ def test_retries_read_when_lock_timeout_before_first_row(self):
+ # The first read DECLARE hits the source's lock_timeout; the in-process retry opens a fresh
+ # server cursor that succeeds and serves the rows. If the retry branch were removed the
+ # LockNotAvailable would propagate and no rows would come back.
+ tables, _connect_mock, state = self._run(declare_locks_left=1, batches=[[(1,), (2,), (3,)]])
+
+ assert state["declare_locks_left"] == 0, "the read DECLARE should have hit the lock timeout"
+ assert sum(table.num_rows for table in tables) == 3
+
+ def test_reraises_lock_timeout_after_rows_yielded(self):
+ # A lock timeout 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.
+ with pytest.raises(psycopg.errors.LockNotAvailable, match="canceling statement due to lock timeout"):
+ self._run(declare_locks_left=0, batches=[[(1,), (2,)], psycopg.errors.LockNotAvailable(self._LOCK_TIMEOUT)])
+
+
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