: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
chore(data-warehouse): drop the server-cursor seek fallback for seekable tables (#110673)
Tom Owers28cab3baa90e
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.pyindex 523e5fa0d832..684b30ddd7a2 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@@ -4504,31 +4504,12 @@ 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):# Paging by OFFSET needs a query whose order is total, the precondition the- # connection-dropped handler below also enforces. A full-table read orders- # nothing, and an xmin read orders on a cursor that every row of one- # transaction shares, so both seek on the primary key instead. Seeking can- # only start from the top, because rows already yielded are already written.- if not should_use_incremental_field:- if keyset_primary_keys is not None and offset == 0:- logger.debug(- f"Falling back to keyset chunking for table due to SerializationFailure error: {e}."- )- yield from offset_chunking(- 0,- chunk_size,- from_recovery_conflict=True,- keyset_primary_keys=keyset_primary_keys,- )- return- # An xmin read still has its cursor to page on, and it appends, so- # restarting it would duplicate the rows it already wrote. Keep paging.- if xmin_bounds is None:- if keyset_primary_keys is None:- raise _unorderable_read_abort_error(schema, table_name) from e- # Retryable, so Temporal restarts the read and the load overwrites- # from the first batch. The next attempt can conflict before any row- # is out, where seeking takes over.- raise+ # connection-dropped handler below also enforces. A full-table read reaches+ # this server cursor only when the table has no seekable key, so it orders+ # nothing and cannot page. An xmin read still has its cursor to page on, and+ # it appends, so restarting it would duplicate the rows it already wrote.+ if not should_use_incremental_field and xmin_bounds is None:+ raise _unorderable_read_abort_error(schema, table_name) from elogger.debug(f"Falling back to offset chunking for table due to SerializationFailure error: {e}."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.pyindex 67b7f3ad3609..69f3b66f20af 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@@ -4111,13 +4111,16 @@ class TestChunkedRereadAfterRecoveryConflict:return self._rows[pivot:] + self._rows[:pivot]class _PageCursor:- def __init__(self, scan, column_names: list[str], column_type: str):+ def __init__(self, scan, column_names: list[str], column_type: str, error: BaseException | None = None):self.description = [_fake_column(name) for name in column_names]self._scan = scanself._column_type = column_type+ self._error = errorself._result: list[tuple[Any, ...]] = []def execute(self, query, *args, **kwargs):+ if self._error is not None:+ raise self._errortext = query.as_string()# Only an ORDER BY that reaches the primary key is total. Anything short of it leaves# rows tied, and each page is its own statement, so the pages overlap and skip.@@ -4205,6 +4208,7 @@ class TestChunkedRereadAfterRecoveryConflict:pages_to_take: int | None = None,arrow_schema: pa.Schema | None = None,column_type: str = "integer",+ page_error: BaseException | None = None,) -> list[int | str]:@contextmanagerdef fake_tunnel():@@ -4233,7 +4237,8 @@ class TestChunkedRereadAfterRecoveryConflict:with (patch(f"{module}.psycopg.connect", return_value=connection),patch(- f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._PageCursor(scan, column_names, column_type)+ f"{module}.psycopg.Cursor",+ side_effect=lambda _conn: self._PageCursor(scan, column_names, column_type, page_error),),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=True),@@ -4323,6 +4328,22 @@ class TestChunkedRereadAfterRecoveryConflict:assert sorted(ids) == [1, 2, 3, 4, 5, 6]+ def test_xmin_reread_that_times_out_is_non_retryable(self):+ # The replica canceled the server cursor with a recovery conflict, and the chunked re-read+ # then hit the statement timeout as well. A whole-activity retry would re-read into the same+ # replica, so the error must be the non-retryable one that names the replica settings.+ with pytest.raises(QueryTimeoutException) as exc_info:+ self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ is_xmin=True,+ page_error=psycopg.errors.QueryCanceled("canceling statement due to statement timeout"),+ )++ assert "max_standby_streaming_delay" in str(exc_info.value)+ assert type(exc_info.value).__name__ in PostgresSource().get_non_retryable_errors()+def test_retried_full_refresh_seeks_instead_of_reopening_the_cursor(self):# The first attempt re-raised past its first row, so a second server cursor conflicts at the# same place. The named cursor here would raise again after two rows; the seek never opens it.