: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(postgres): stop retrying read-replica recovery-conflict timeouts (#65083)
Tom Owers8b33633b579f
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 5172c2689d1f..536ea2ee95d2 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -2774,7 +2774,7 @@ def postgres_source(connection.commit()return connection- def offset_chunking(offset: int, chunk_size: int):+ def offset_chunking(offset: int, chunk_size: int, *, from_recovery_conflict: bool = False):# If the db is a read replica and we're running into `conflict with recovery errors,# we create a new query for each chunk. This is due to how the primary replicates# over, we often run into errors when vacuums are happening@@ -2879,6 +2879,20 @@ def postgres_source()if timeout_error is not None:raise timeout_error from e+ if from_recovery_conflict:+ # We only reach offset chunking here because the read replica just+ # canceled our reads with a recovery conflict. Hitting the statement+ # timeout on top of that means the chunked fallback can't finish a chunk+ # either, and a whole-activity retry just re-reads from the start into the+ # same conflicting, overloaded replica — so stop retrying. QueryTimeoutException+ # is already non-retryable (see source.py), unlike the raw QueryCanceled.+ raise QueryTimeoutException(+ "Reading from your read replica timed out: Postgres canceled the initial "+ "read with a recovery conflict, and the chunked fallback read still couldn't "+ "finish within the 10 minute statement timeout. Increase "+ "max_standby_streaming_delay or enable hot_standby_feedback on the replica, "+ "or sync from the primary database instead."+ ) from eraiseexcept _CONNECTION_DROPPED_ERROR_TYPES as e:if not _is_connection_dropped_error(e):@@ -3013,7 +3027,7 @@ def postgres_source(# If we hit a SerializationFailure and we're reading from a read replica, we fallback to offset chunkingif 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)+ yield from offset_chunking(offset, chunk_size, from_recovery_conflict=True)returnraisediff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex 7e7de7f8f9a7..f65a7024a1a7 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -1380,6 +1380,124 @@ class TestOffsetChunkingConnectRecoveryConflict:assert connect_mock.call_count == 5+class TestOffsetChunkingRecoveryConflictTimeout:+ """When a read replica cancels the initial read with a recovery conflict, `get_rows` falls+ back to offset chunking. If a chunk then exhausts the 10-min statement_timeout, a full-table+ sync used to re-raise the raw, retryable QueryCanceled — so Temporal re-read from the start+ into the same conflicting, overloaded replica every attempt. The fallback must instead surface+ a non-retryable QueryTimeoutException with actionable replica guidance.+ """++ class _NamedCursor:+ def __init__(self):+ col = mock.Mock()+ col.name = "id"+ self.description = [col]++ def execute(self, *args, **kwargs):+ raise psycopg.errors.SerializationFailure("canceling statement due to conflict with recovery")++ def fetchmany(self, _n):+ return []++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ class _OffsetCursor:+ def __init__(self):+ col = mock.Mock()+ col.name = "id"+ self.description = [col]++ def execute(self, *args, **kwargs):+ raise psycopg.errors.QueryCanceled("canceling statement due to statement timeout")++ def fetchall(self):+ return []++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ class _Connection:+ def __init__(self):+ self.autocommit = False+ self.closed = False+ self.broken = False+ self.adapters = mock.Mock()++ def cursor(self, *args, **kwargs):+ if "name" in kwargs:+ return TestOffsetChunkingRecoveryConflictTimeout._NamedCursor()+ 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 test_statement_timeout_in_recovery_conflict_fallback_is_non_retryable(self):+ @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 = "posthog.temporal.data_imports.sources.postgres.postgres"+ with (+ patch(f"{module}.psycopg.connect", return_value=self._Connection()),+ patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._OffsetCursor()),+ patch(f"{module}._get_table", return_value=fake_table),+ patch(f"{module}._is_read_replica", return_value=True),+ 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=1000),+ 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),+ patch(f"{module}.time.sleep"),+ ):+ 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,+ )+ with pytest.raises(QueryTimeoutException) as exc_info:+ list(cast(Iterable[Any], response.items()))++ message = str(exc_info.value)+ assert "max_standby_streaming_delay" in message+ # Unlike a raw QueryCanceled, QueryTimeoutException is classified non-retryable. It's matched+ # by class name in the Temporal-wrapped error string (see external_data_job.py), so the+ # non-retryable signal here is the type name, not the message text.+ non_retryable = PostgresSource().get_non_retryable_errors()+ assert type(exc_info.value).__name__ in non_retryable++class TestSafeCloseConnection:def test_none_is_a_noop(self):# The offset-chunking path can reach a teardown handler with no connection (a connect that