: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(warehouse): page a full-refresh replica re-read by primary key (#93764)
Daniel RC75a989f93447
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 92799ba7c9a2..b4a11a364d51 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@@ -659,6 +659,18 @@ def _recovery_conflict_abort_error(retries: int) -> Exception:)+def _unorderable_read_abort_error(schema: str, table_name: str) -> Exception:+ # Non-retryable (see source.py): a full-table read orders nothing, so a re-read can only be paged+ # by seeking on a key that is unique and never NULL. Without one there is no safe page order at+ # all, and every whole-activity retry re-reads into the same wall.+ return Exception(+ f"Read replica canceled the read of {schema}.{table_name} due to conflict with recovery, and "+ f"the table has no key that can resume a canceled read. Resuming needs a key that is unique "+ f"and never NULL. Add a primary key to the table, increase max_standby_streaming_delay or "+ f"enable hot_standby_feedback on the replica, or sync from the primary database instead."+ )++def _statement_timeout_as_non_retryable(error: BaseException,*,@@ -2218,6 +2230,44 @@ def _build_xmin_query(return ordered+def _build_keyset_query(+ schema: str,+ table_name: str,+ primary_keys: list[str],+ after: Optional[tuple[Any, ...]],+ *,+ incremental_field: Optional[str] = None,+ enabled_columns: Optional[list[str]] = None,+ row_filters: Optional[list[ValidatedRowFilter]] = None,+) -> sql.Composed:+ """One page of a full-table read, seeking past the last primary key already read.++ A full-table read has no ORDER BY, so LIMIT/OFFSET cannot page it: every page is its own scan+ and may come back in a different order, which both repeats and drops rows. Ordering by the+ primary key gives the pages one sequence to walk, and seeking past the last key keeps each page+ an index range scan. The key must be unique, or a page boundary inside a run of equal keys+ drops the rest of that run.+ """+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ select_clause: sql.Composable = (+ sql.SQL("*") if projected is None else sql.SQL(", ").join(sql.Identifier(c) for c in projected)+ )+ key_columns = sql.SQL(", ").join(sql.Identifier(key) for key in primary_keys)++ conditions = render_psycopg_row_filter_conditions(row_filters or [])+ if after is not None:+ conditions.append(+ sql.SQL("({keys}) > ({values})").format(+ keys=key_columns, values=sql.SQL(", ").join(sql.Literal(value) for value in after)+ )+ )++ query = sql.SQL("SELECT {cols} FROM {table}").format(cols=select_clause, table=sql.Identifier(schema, table_name))+ if conditions:+ query = query + sql.SQL(" WHERE ") + and_join(conditions)+ return query + sql.SQL(" ORDER BY {keys} ASC").format(keys=key_columns)++def _build_count_query(schema: str,table_name: str,@@ -3631,13 +3681,28 @@ def postgres_source(connection.commit()return connection- def offset_chunking(offset: int, chunk_size: int, *, from_recovery_conflict: bool = False):+ def offset_chunking(+ offset: int,+ chunk_size: int,+ *,+ from_recovery_conflict: bool = False,+ keyset_primary_keys: list[str] | None = None,+ ):# 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- logger.debug(- f"Using offset chunking to read from read replica. offset = {offset}, chunk_size = {chunk_size}"- )+ # over, we often run into errors when vacuums are happening.+ #+ # `keyset_primary_keys` pages by seeking past the last key read instead of by OFFSET,+ # for a read whose own query orders nothing (see `_build_keyset_query`).+ if keyset_primary_keys is not None:+ logger.debug(+ f"Using keyset chunking to read from read replica. keys = {keyset_primary_keys}, "+ f"chunk_size = {chunk_size}"+ )+ else:+ logger.debug(+ f"Using offset chunking to read from read replica. offset = {offset}, chunk_size = {chunk_size}"+ )query = _build_query(schema,@@ -3653,6 +3718,25 @@ def postgres_source(xmin_bounds=xmin_bounds,)+ last_key: tuple[Any, ...] | None = None++ def build_page_query() -> sql.Composed:+ if keyset_primary_keys is not None:+ page = _build_keyset_query(+ schema,+ table_name,+ keyset_primary_keys,+ last_key,+ incremental_field=incremental_field,+ enabled_columns=enabled_columns,+ row_filters=row_filters,+ )+ return page + sql.SQL(" LIMIT {limit}").format(limit=sql.Literal(chunk_size))+ return query + sql.SQL(" LIMIT {limit} OFFSET {offset}").format(+ limit=sql.Literal(chunk_size),+ offset=sql.Literal(offset),+ )+successive_errors = 0successive_conn_errors = 0floor_retries = 0@@ -3701,10 +3785,7 @@ def postgres_source(# argument: 'name'". This LIMIT/OFFSET fetchall path wants an# unnamed client cursor.with psycopg.Cursor(connection) as cursor:- query_with_limit_sql = query + sql.SQL(" LIMIT {limit} OFFSET {offset}").format(- limit=sql.Literal(chunk_size),- offset=sql.Literal(offset),- )+ query_with_limit_sql = build_page_query()logger.debug(f"Postgres query: {query_with_limit_sql}")cursor.execute(query_with_limit_sql)@@ -3714,7 +3795,11 @@ def postgres_source(if not rows or len(rows) == 0:break- offset += len(rows)+ if keyset_primary_keys is not None:+ key_positions = [column_names.index(key) for key in keyset_primary_keys]+ last_key = tuple(rows[-1][position] for position in key_positions)+ else:+ offset += len(rows)yield table_from_iterator((dict(zip(column_names, row)) for row in rows),@@ -3896,6 +3981,21 @@ def postgres_source()return+ # Seeking needs a key that is unique and never NULL. A page boundary inside a run of+ # equal keys drops the rest of that run, and `key > last` never matches NULL, so a NULL+ # row is dropped unless it lands on the first page. A declared primary key is both. The+ # assumed `id` is neither until checked, and its duplicate probe groups NULLs together,+ # so a single NULL row passes it. A partitioned parent's key is unique only per child.+ not_null_columns = {column.name for column in full_table.columns if not column.nullable}+ keyset_primary_keys = (+ primary_keys+ if primary_keys+ and not is_partitioned+ and not (used_id_pk_fallback and has_duplicate_primary_keys)+ and all(key in not_null_columns for key in primary_keys)+ else None+ )+initial_read_drop_retries = 0initial_read_lock_timeout_retries = 0while True:@@ -3949,6 +4049,29 @@ def postgres_source(except psycopg.errors.SerializationFailure as e:# 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 that orders its rows, the precondition the+ # connection-dropped handler below also enforces. A full-table read orders+ # nothing, so seek on the primary key instead, and only from the start,+ # because rows already yielded are already written.+ if not should_use_incremental_field and xmin_bounds is None:+ if keyset_primary_keys is None:+ raise _unorderable_read_abort_error(schema, table_name) from e+ if offset > 0:+ # 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+ 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+logger.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/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex e4b7a47c6be1..855916028b22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -775,6 +775,19 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa"max_standby_streaming_delay on the replica, enable hot_standby_feedback, or point the ""connection at the primary database, then re-enable the sync."),+ # A recovery conflict on a full-table read of a table with no unique, non-NULL key. The+ # re-read can only be paged by seeking on such a key, so there is no safe page order and+ # a whole-activity retry re-reads into the same wall. Non-retryable for that reason,+ # unlike the same conflict on a table that has a key, which stays retryable.+ "no key that can resume a canceled read": (+ "Your read replica canceled the sync's read of this table "+ '("canceling statement due to conflict with recovery"). To resume the read, PostHog '+ "needs a column that is unique and never null, and this table doesn't have one. "+ "Without it, reading the table again would duplicate or miss rows. Add a primary key "+ "to the table, increase max_standby_streaming_delay on the replica, enable "+ "hot_standby_feedback, or point the connection at the primary database, then "+ "re-enable the sync."+ ),# Activity-layer twin of the `QueryTimeoutException` key above, for the read-replica path:# when a recovery conflict forces the offset-chunking fallback and a chunk then hits the# 10-minute statement_timeout, `get_rows` raises `QueryTimeoutException` with this message.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 001abd9c5f58..b16d0263ff63 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@@ -1,3 +1,4 @@+import reimport errnoimport socketimport threading@@ -3159,7 +3160,7 @@ class TestOffsetChunkingConnectRecoveryConflict: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.columns = [PostgreSQLColumn(name="id", data_type="integer", nullable=False)]fake_table.__contains__ = mock.Mock(return_value=False)connection = self._Connection()@@ -3223,7 +3224,7 @@ class TestOffsetChunkingConnectTimeout: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.columns = [PostgreSQLColumn(name="id", data_type="integer", nullable=False)]fake_table.__contains__ = mock.Mock(return_value=False)# Reuse the connect-conflict scaffolding: the named server cursor raises a recovery conflict@@ -3353,7 +3354,7 @@ class TestOffsetChunkingRecoveryConflictTimeout: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.columns = [PostgreSQLColumn(name="id", data_type="integer", nullable=False)]fake_table.__contains__ = mock.Mock(return_value=False)module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"@@ -3396,6 +3397,199 @@ class TestOffsetChunkingRecoveryConflictTimeout:assert type(exc_info.value).__name__ in non_retryable+class TestChunkedRereadAfterRecoveryConflict:+ """A read replica cancelling the initial read with "conflict with recovery" routes `get_rows`+ into a chunked re-read. Paging by LIMIT/OFFSET is only correct when the query orders its rows:+ a full-table read has no ORDER BY, so every page is a fresh scan Postgres may return in a+ different order, which both repeats and drops rows. Such a read must page by seeking past the+ last primary key it read, and must refuse to page at all when it cannot.++ `_Scan` rotates an unordered result per statement to model that freedom deterministically.+ """++ _CONFLICT = "canceling statement due to conflict with recovery"+ _ROWS: list[tuple[int]] = [(1,), (2,), (3,), (4,), (5,), (6,)]++ class _Scan:+ def __init__(self, rows: list[tuple[int]]):+ self._rows = rows+ self._statements = 0++ def rows_for(self, ordered: bool) -> list[tuple[int]]:+ if ordered:+ return sorted(self._rows)+ self._statements += 1+ pivot = self._statements % len(self._rows)+ return self._rows[pivot:] + self._rows[:pivot]++ class _PageCursor:+ def __init__(self, scan):+ column = mock.Mock()+ column.name = "id"+ self.description = [column]+ self._scan = scan+ self._result: list[tuple[int]] = []++ def execute(self, query, *args, **kwargs):+ text = query.as_string()+ rows = self._scan.rows_for("ORDER BY" in text)+ seek = re.search(r'\("id"\) > \((\d+)\)', text)+ if seek:+ rows = [row for row in rows if row[0] > int(seek.group(1))]+ offset = re.search(r"OFFSET (\d+)", text)+ if offset:+ rows = rows[int(offset.group(1)) :]+ limit = re.search(r"LIMIT (\d+)", text)+ self._result = rows[: int(limit.group(1))] if limit else rows++ def fetchall(self):+ return self._result++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ class _NamedCursor:+ def __init__(self, rows_before_conflict: int, scan):+ column = mock.Mock()+ column.name = "id"+ self.description = [column]+ self._pending = scan.rows_for(True)[:rows_before_conflict]++ def execute(self, *args, **kwargs):+ return None++ def fetchmany(self, _n):+ if self._pending:+ page, self._pending = self._pending, []+ return page+ raise psycopg.errors.SerializationFailure(TestChunkedRereadAfterRecoveryConflict._CONFLICT)++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ class _Connection:+ def __init__(self, named_cursor):+ self.autocommit = False+ self.closed = False+ self.broken = False+ self.adapters = mock.Mock()+ self._named_cursor = named_cursor++ def cursor(self, *args, **kwargs):+ if "name" in kwargs:+ return self._named_cursor+ 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 _read_ids(+ self,+ *,+ should_use_incremental_field: bool,+ rows_before_conflict: int,+ primary_keys: list[str] | None = None,+ key_is_nullable: bool = False,+ ) -> list[int]:+ @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 = [PostgreSQLColumn(name="id", data_type="integer", nullable=key_is_nullable)]+ fake_table.__contains__ = mock.Mock(return_value=False)++ scan = self._Scan(list(self._ROWS))+ connection = self._Connection(self._NamedCursor(rows_before_conflict, scan))++ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"+ with (+ patch(f"{module}.psycopg.connect", return_value=connection),+ patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: self._PageCursor(scan)),+ patch(f"{module}._get_table", return_value=fake_table),+ patch(f"{module}._is_read_replica", return_value=True),+ patch(f"{module}._is_duckdb_connection", return_value=False),+ patch(f"{module}._get_primary_keys", return_value=primary_keys),+ patch(f"{module}._is_partitioned_table", return_value=False),+ patch(f"{module}._get_table_chunk_size", return_value=_TableChunking(batch_rows=2, fetch_rows=2)),+ patch(f"{module}._get_rows_to_sync", return_value=len(self._ROWS)),+ 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=should_use_incremental_field,+ incremental_field="id" if should_use_incremental_field else None,+ incremental_field_type=IncrementalFieldType.Integer if should_use_incremental_field else None,+ logger=structlog.get_logger(),+ db_incremental_field_last_value=0 if should_use_incremental_field else None,+ team_id=1,+ )+ return [row["id"] for table in cast(Iterable[Any], response.items()) for row in table.to_pylist()]++ @pytest.mark.parametrize(+ "should_use_incremental_field,rows_before_conflict",+ [(False, 0), (True, 2)],+ ids=["full_refresh_has_no_order_of_its_own", "incremental_read_is_ordered_by_its_cursor"],+ )+ def test_chunked_reread_yields_every_row_exactly_once(self, should_use_incremental_field, rows_before_conflict):+ ids = self._read_ids(+ should_use_incremental_field=should_use_incremental_field,+ rows_before_conflict=rows_before_conflict,+ primary_keys=["id"],+ )++ assert sorted(ids) == [row[0] for row in self._ROWS]++ def test_full_refresh_stays_retryable_when_rows_are_already_written(self):+ with pytest.raises(psycopg.errors.SerializationFailure):+ self._read_ids(should_use_incremental_field=False, rows_before_conflict=2, primary_keys=["id"])++ @pytest.mark.parametrize(+ "rows_before_conflict,primary_keys,key_is_nullable",+ [(0, None, False), (2, None, False), (0, ["id"], True)],+ ids=["no_key_at_all", "no_key_at_all_after_rows_written", "key_column_is_nullable"],+ )+ def test_full_refresh_without_a_seekable_key_fails_non_retryably(+ self, rows_before_conflict, primary_keys, key_is_nullable+ ):+ with pytest.raises(Exception) as exc_info:+ self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=rows_before_conflict,+ primary_keys=primary_keys,+ key_is_nullable=key_is_nullable,+ )++ message = str(exc_info.value)+ assert "no key that can resume a canceled read" in message+ assert any(fragment in message for fragment in PostgresSource().get_non_retryable_errors())++class TestSafeCloseConnection:def test_none_is_a_noop(self):# The offset-chunking path can reach a teardown handler with no connection (a connect that