: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-sources): bound postgres keyset pages by bytes (#110815)
Daniel RCdaf77bf4d1c3
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 684b30ddd7a2..e6cd91a49dce 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@@ -4127,7 +4127,7 @@ def postgres_source(else keyset_primary_keys)- def build_page_query() -> sql.Composed:+ def build_page_query(limit: int) -> sql.Composed:if keyset_primary_keys is not None:page = _build_keyset_query(schema,@@ -4139,12 +4139,14 @@ def postgres_source(row_filters=row_filters,xmin_bounds=xmin_bounds,)- return page + sql.SQL(" LIMIT {limit}").format(limit=sql.Literal(chunk_size))+ return page + sql.SQL(" LIMIT {limit}").format(limit=sql.Literal(limit))return query + sql.SQL(" LIMIT {limit} OFFSET {offset}").format(- limit=sql.Literal(chunk_size),+ limit=sql.Literal(limit),offset=sql.Literal(offset),)+ # The most rows one page may ask for. A sustained recovery conflict shrinks it.+ page_limit = chunk_sizesuccessive_errors = 0successive_conn_errors = 0floor_retries = 0@@ -4156,191 +4158,214 @@ def postgres_source(# mid-recovery — opening outside the loop let that escape the whole fallback even# though it's the same transient condition the loop already retries.connection: psycopg.Connection | None = None+ column_names: list[str] = []def handle_recovery_conflict(e: BaseException) -> None:# Shared bookkeeping for a recovery conflict hit either while reading a chunk# (SerializationFailure) or while (re)connecting for one (the standby cancels the# connection's own startup). Shrink the chunk toward the floor first; only once# stuck at the floor count down to the non-retryable abort.- nonlocal chunk_size, successive_errors, floor_retries+ nonlocal page_limit, successive_errors, floor_retriessuccessive_errors += 1- reduced_chunk_size = _next_recovery_conflict_chunk_size(chunk_size, successive_errors)- if reduced_chunk_size < chunk_size:- chunk_size = reduced_chunk_size- logger.debug(f"Reducing chunk size to {chunk_size} to reduce load on read replica")+ reduced_page_limit = _next_recovery_conflict_chunk_size(page_limit, successive_errors)+ if reduced_page_limit < page_limit:+ page_limit = reduced_page_limit+ logger.debug(f"Reducing chunk size to {page_limit} to reduce load on read replica")floor_retries = 0- elif chunk_size <= _MIN_RECOVERY_CONFLICT_CHUNK_SIZE:+ elif page_limit <= _MIN_RECOVERY_CONFLICT_CHUNK_SIZE:floor_retries += 1if floor_retries >= _MAX_READ_RECOVERY_CONFLICT_RETRIES:_safe_close_connection(connection)raise _recovery_conflict_abort_error(floor_retries) from etime.sleep(min(2 * successive_errors, 30))- while True:- try:- if connection is None or connection.closed:- logger.debug("Opening Postgres connection for offset chunking...")- connection = get_connection()- # Autocommit so each LIMIT/OFFSET query runs as its own statement and no- # transaction stays open across the slow delta-merge that happens between- # yields. A held transaction is what gets the backend culled by- # idle_in_transaction_session_timeout, producing the "server conn- # crashed?" ProtocolViolation on the next fetch.- connection.autocommit = True-- # Use psycopg.Cursor directly to bypass cursor_factory: on a- # non-read-replica source it is ServerCursor (set in get_rows),- # which requires a `name` and makes an unnamed connection.cursor()- # raise "ServerCursor.__init__() missing 1 required positional- # argument: 'name'". This LIMIT/OFFSET fetchall path wants an- # unnamed client cursor.- with psycopg.Cursor(connection) as cursor:- query_with_limit_sql = build_page_query()- logger.debug(f"Postgres query: {query_with_limit_sql}")- # Check the first page that actually seeks. Page 1 carries no `key >`- # predicate, so its plan says nothing about how the walk behaves.- if keyset_primary_keys is not None and last_key is not None and not plan_checked:- plan_checked = True- _check_keyset_page_plan(cursor, query_with_limit_sql, logger)- cursor.execute(query_with_limit_sql)-- column_names = [column.name for column in cursor.description or []]- rows = cursor.fetchall()+ def keyset_key_of(row: tuple[Any, ...]) -> tuple[Any, ...]:+ return checked_keyset_key(+ tuple(row[column_names.index(key)] for key in keyset_result_columns),+ keyset_result_columns,+ )- if not rows or len(rows) == 0:- break+ def fetch_page(requested_rows: int) -> list[tuple[Any, ...]]:+ """Read the next page and move the read position past it. Empty at the end."""+ nonlocal connection, last_key, offset, column_names, plan_checked+ nonlocal successive_errors, successive_conn_errors, floor_retries, lock_retries+ while True:+ try:+ if connection is None or connection.closed:+ logger.debug("Opening Postgres connection for offset chunking...")+ connection = get_connection()+ # Autocommit so each LIMIT/OFFSET query runs as its own statement and no+ # transaction stays open across the slow delta-merge that happens between+ # yields. A held transaction is what gets the backend culled by+ # idle_in_transaction_session_timeout, producing the "server conn+ # crashed?" ProtocolViolation on the next fetch.+ connection.autocommit = True++ # Use psycopg.Cursor directly to bypass cursor_factory: on a+ # non-read-replica source it is ServerCursor (set in get_rows),+ # which requires a `name` and makes an unnamed connection.cursor()+ # raise "ServerCursor.__init__() missing 1 required positional+ # argument: 'name'". This LIMIT/OFFSET fetchall path wants an+ # unnamed client cursor.+ with psycopg.Cursor(connection) as cursor:+ query_with_limit_sql = build_page_query(min(requested_rows, page_limit))+ logger.debug(f"Postgres query: {query_with_limit_sql}")+ # Check the first page that actually seeks. Page 1 carries no `key >`+ # predicate, so its plan says nothing about how the walk behaves.+ if keyset_primary_keys is not None and last_key is not None and not plan_checked:+ plan_checked = True+ _check_keyset_page_plan(cursor, query_with_limit_sql, logger)+ cursor.execute(query_with_limit_sql)++ page_columns = [column.name for column in cursor.description or []]+ rows: list[tuple[Any, ...]] = cursor.fetchall()++ if not rows:+ return []++ if not column_names:+ column_names = page_columns+ elif page_columns != column_names:+ # One batch can hold rows from several pages, and it reads every row+ # with the columns of the first page.+ positions = [+ page_columns.index(name) if name in page_columns else None for name in column_names+ ]+ rows = [+ tuple(row[position] if position is not None else None for position in positions)+ for row in rows+ ]- page_last_key = Noneif keyset_primary_keys is not None:- key_positions = [column_names.index(key) for key in keyset_result_columns]- page_last_key = checked_keyset_key(- tuple(rows[-1][position] for position in key_positions),- keyset_result_columns,- )-- yield table_from_iterator(- (dict(zip(column_names, row)) for row in rows),- restrict_schema_to_columns(arrow_schema, column_names),- primary_keys=primary_keys,- binary_reporter=binary_reporter,- )-- # Advance and checkpoint only once the consumer comes back for the next- # page, never before the yield. An abandoned walk unwinds at the yield- # above — `GeneratorExit` derives from `BaseException`, so none of the- # handlers below catch it — which leaves the checkpoint on the last page- # the consumer actually took. Publishing the key first would have a- # drained worker commit a page it never read, skipping those rows for- # good, because a resume appends rather than re-reading.- if page_last_key is not None:- last_key = page_last_key- if checkpoint is not None:- checkpoint(page_last_key)+ last_key = keyset_key_of(rows[-1])else:offset += len(rows)successive_errors = 0successive_conn_errors = 0floor_retries = 0- except psycopg.errors.SerializationFailure as e:- if "due to conflict with recovery" not in "".join(e.args):- raise- logger.debug(f"SerializationFailure error: {e}. Retrying chunk at offset {offset}")- handle_recovery_conflict(e)- except psycopg.errors.QueryCanceled as e:- # A chunk hit the 10-min statement_timeout. QueryCanceled- # subclasses OperationalError, so this clause must precede the- # connection-dropped handler below.- if _raised_while_closing_generator(e):- # The generator is being closed and the cursor teardown- # round-trip hit the statement_timeout — irrelevant to the- # sync outcome, so swallow it and let close() complete cleanly.+ lock_retries = 0+ return rows+ except psycopg.errors.SerializationFailure as e:+ if "due to conflict with recovery" not in "".join(e.args):+ raise+ logger.debug(f"SerializationFailure error: {e}. Retrying chunk at offset {offset}")+ handle_recovery_conflict(e)+ except psycopg.errors.QueryCanceled as e:+ # A chunk hit the 10-min statement_timeout. QueryCanceled+ # subclasses OperationalError, so this clause must precede the+ # connection-dropped handler below.+ # Retrying won't help, so map it to the same non-retryable+ # QueryTimeoutException the server-cursor and windowed paths+ # raise instead of leaking a raw, retryable QueryCanceled that+ # Temporal keeps re-attempting._safe_close_connection(connection)- return- # Retrying won't help, so map it to the same non-retryable- # QueryTimeoutException the server-cursor and windowed paths- # raise instead of leaking a raw, retryable QueryCanceled that- # Temporal keeps re-attempting.- _safe_close_connection(connection)- 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- 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 e- if keyset_primary_keys is not None:- raise _keyset_page_timeout_error(keyset_primary_keys) from e- raise _full_table_timeout_error() from e- except psycopg.errors.LockNotAvailable as e:- # A server cursor takes ACCESS SHARE once, at its DECLARE. A seek walk takes- # it per page, so its cumulative chance of landing on a concurrent ACCESS- # EXCLUSIVE is far higher. Without this clause `LockNotAvailable` reaches the- # dropped-connection handler as an `OperationalError`, matches neither of its- # predicates, and fails the whole activity. Retrying the same page is safe- # because `last_key` does not advance until after the page is yielded.- _safe_close_connection(connection)- lock_retries += 1- if lock_retries > _MAX_KEYSET_PAGE_LOCK_RETRIES:- raise- logger.debug(- f"Keyset page blocked on a lock ({e}). Retrying the same page "- f"({lock_retries}/{_MAX_KEYSET_PAGE_LOCK_RETRIES})"- )- time.sleep(min(2 * lock_retries, 30))- continue- except _CONNECTION_DROPPED_ERROR_TYPES as e:- if _is_recovery_conflict_error(e):- # A recovery conflict raised by the (re)connect itself surfaces as a plain- # OperationalError ("connection failed: ... conflict with recovery"), not a- # SerializationFailure, so it bypasses the handler above. Same transient- # condition — drop the dead connection so the loop reopens at the same- # offset, and route it through the shared recovery-conflict retry.- logger.debug(f"Recovery conflict on connect ({e}). Retrying chunk at offset {offset}")+ 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+ 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 e+ if keyset_primary_keys is not None:+ raise _keyset_page_timeout_error(keyset_primary_keys) from e+ raise _full_table_timeout_error() from e+ except psycopg.errors.LockNotAvailable as e:+ # A server cursor takes ACCESS SHARE once, at its DECLARE. A seek walk takes+ # it per page, so its cumulative chance of landing on a concurrent ACCESS+ # EXCLUSIVE is far higher. Without this clause `LockNotAvailable` reaches the+ # dropped-connection handler as an `OperationalError`, matches neither of its+ # predicates, and fails the whole activity. Retrying the same page is safe+ # because the read position does not move until a page is fetched in full._safe_close_connection(connection)- connection = None- handle_recovery_conflict(e)+ lock_retries += 1+ if lock_retries > _MAX_KEYSET_PAGE_LOCK_RETRIES:+ raise+ logger.debug(+ f"Keyset page blocked on a lock ({e}). Retrying the same page "+ f"({lock_retries}/{_MAX_KEYSET_PAGE_LOCK_RETRIES})"+ )+ time.sleep(min(2 * lock_retries, 30))continue- if not _is_dropped_or_connect_timeout(e):+ except _CONNECTION_DROPPED_ERROR_TYPES as e:+ if _is_recovery_conflict_error(e):+ # A recovery conflict raised by the (re)connect itself surfaces as a plain+ # OperationalError ("connection failed: ... conflict with recovery"), not a+ # SerializationFailure, so it bypasses the handler above. Same transient+ # condition — drop the dead connection so the loop reopens at the same+ # offset, and route it through the shared recovery-conflict retry.+ logger.debug(f"Recovery conflict on connect ({e}). Retrying chunk at offset {offset}")+ _safe_close_connection(connection)+ connection = None+ handle_recovery_conflict(e)+ continue+ if not _is_dropped_or_connect_timeout(e):+ _safe_close_connection(connection)+ raise++ # The upstream connection died (idle cull, failover, etc.) or the+ # reconnect that bootstraps this fallback timed out establishing the+ # socket. The read position only moves after a fully fetched page,+ # so reopening and retrying the same page resumes cleanly.+ successive_conn_errors += 1+ _safe_close_connection(connection)+ if successive_conn_errors >= 10:+ raise Exception(+ f"Hit {successive_conn_errors} successive connection errors. Aborting."+ ) from e+ logger.debug(+ f"Transient connection error ({e}). Reconnecting and retrying chunk at offset {offset} "+ f"(attempt {successive_conn_errors})"+ )+ time.sleep(min(2 * successive_conn_errors, 30))+ connection = _connect_with_dropped_retry(get_connection, logger)+ connection.autocommit = True+ except Exception:_safe_close_connection(connection)raise- # The upstream connection died (idle cull, failover, etc.) or the- # reconnect that bootstraps this fallback timed out establishing the- # socket. offset only advances after a fully fetched+yielded chunk,- # so reopening and retrying the same offset resumes cleanly.- successive_conn_errors += 1- _safe_close_connection(connection)- if successive_conn_errors >= 10:- raise Exception(- f"Hit {successive_conn_errors} successive connection errors. Aborting."- ) from e- logger.debug(- f"Transient connection error ({e}). Reconnecting and retrying chunk at offset {offset} "- f"(attempt {successive_conn_errors})"+ try:+ # A page is one statement and it is resident in full, so it is sized like any+ # other fetch. A batch then spans as many pages as its byte budget holds.+ for rows in fetch_row_batches(+ fetch_page,+ max_rows=chunk_size,+ max_page_rows=fetch_page_rows,+ ):+ batch_last_key = keyset_key_of(rows[-1]) if keyset_primary_keys is not None else None++ yield table_from_iterator(+ (dict(zip(column_names, row)) for row in rows),+ restrict_schema_to_columns(arrow_schema, column_names),+ primary_keys=primary_keys,+ binary_reporter=binary_reporter,)- time.sleep(min(2 * successive_conn_errors, 30))- connection = _connect_with_dropped_retry(get_connection, logger)- connection.autocommit = True- except Exception:- _safe_close_connection(connection)- raise- _safe_close_connection(connection)+ # Checkpoint only once the consumer comes back for the next batch, never+ # before the yield. An abandoned walk unwinds at the yield above, which+ # leaves the checkpoint on the last batch the consumer actually took.+ # Publishing the key first would have a drained worker commit a batch it+ # never read, skipping those rows for good, because a resume appends rather+ # than re-reading. The key is the last row of this batch and not the read+ # position, which can already be past rows that wait for the next batch.+ if batch_last_key is not None and checkpoint is not None:+ checkpoint(batch_last_key)+ finally:+ _safe_close_connection(connection)def connect_for_partition_iteration() -> psycopg.Connection:# Each window/partition opens its own connection. A transient drop on that connect —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 02370b076ec1..0f134f0ad9e0 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@@ -4102,6 +4102,15 @@ class TestChunkedRereadAfterRecoveryConflict:def __init__(self, rows: list[tuple[Any, ...]]):self._rows = rowsself._statements = 0+ self.limits: list[int] = []+ self.lock_timeout_before_each_page = False+ self._lock_timeout_due = True++ def take_lock_timeout(self) -> bool:+ if not self.lock_timeout_before_each_page:+ return False+ due, self._lock_timeout_due = self._lock_timeout_due, not self._lock_timeout_due+ return duedef rows_for(self, totally_ordered: bool) -> list[tuple[Any, ...]]:if totally_ordered:@@ -4122,6 +4131,8 @@ class TestChunkedRereadAfterRecoveryConflict:if self._error is not None:raise self._errortext = query.as_string()+ if "LIMIT" in text and "EXPLAIN" not in text and self._scan.take_lock_timeout():+ raise psycopg.errors.LockNotAvailable("canceling statement due to lock timeout")# 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.rows = self._scan.rows_for('"id"' in text.partition("ORDER BY")[2])@@ -4137,6 +4148,8 @@ class TestChunkedRereadAfterRecoveryConflict:if offset:rows = rows[int(offset.group(1)) :]limit = re.search(r"LIMIT (\d+)", text)+ if limit:+ self._scan.limits.append(int(limit.group(1)))self._result = rows[: int(limit.group(1))] if limit else rowsdef fetchall(self):@@ -4208,6 +4221,8 @@ class TestChunkedRereadAfterRecoveryConflict:pages_to_take: int | None = None,arrow_schema: pa.Schema | None = None,column_type: str = "integer",+ chunking: _TableChunking | None = None,+ lock_timeout_before_each_page: bool = False,page_error: BaseException | None = None,) -> list[int | str]:@contextmanager@@ -4231,6 +4246,8 @@ class TestChunkedRereadAfterRecoveryConflict:# `get_rows` inserts `_ph_xmin` ahead of the discovered columns, matching the SELECT.column_names = [XMIN_PROJECTED_COLUMN, "id"] if is_xmin else ["id"]scan = self._Scan(list(rows))+ scan.lock_timeout_before_each_page = lock_timeout_before_each_page+ self.last_scan = scanconnection = self._Connection(self._NamedCursor(rows_before_conflict, scan, column_names))module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"@@ -4246,7 +4263,10 @@ class TestChunkedRereadAfterRecoveryConflict:patch(f"{module}._get_primary_keys", return_value=primary_keys),patch(f"{module}._has_duplicate_primary_keys", return_value=has_duplicate_pks),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_table_chunk_size",+ return_value=chunking or _TableChunking(batch_rows=2, fetch_rows=2),+ ),patch(f"{module}._get_rows_to_sync", return_value=len(rows)),patch(f"{module}._capture_xmin_ceiling", return_value=self._XMIN_BOUNDS),patch(f"{module}._role_subject_to_rls", return_value=False),@@ -4539,6 +4559,57 @@ class TestChunkedRereadAfterRecoveryConflict:# append-safe: the pipeline appends after batch 0 rather than overwriting.assert ids and all(isinstance(row_id, int) and row_id > 2 for row_id in ids)+ # One id column measures 16 bytes, so a 40-byte budget holds two rows per batch.+ _TWO_ROW_BUDGET = 40++ def test_a_seek_page_never_asks_for_more_than_the_measured_page_size(self):+ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", self._TWO_ROW_BUDGET):+ ids = self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ chunking=_TableChunking(batch_rows=6, fetch_rows=4),+ )++ assert ids == [row[0] for row in self._ROWS]+ # A page of the 6-row batch size would hold the whole table in one statement.+ assert self.last_scan.limits[0] == 4+ assert max(self.last_scan.limits) == 4+ # Once a page shows what a row weighs, a page holds no more than one batch budget.+ assert self.last_scan.limits[-1] == 2++ def test_a_batch_that_ends_inside_a_page_checkpoints_its_own_last_row(self):+ # The first page reads rows 1 to 4, and the byte budget closes the first batch after row 2.+ # A checkpoint on the read position would resume past rows 3 and 4, which nothing wrote.+ manager = MagicMock()+ manager.can_resume.return_value = False++ with patch.object(batching, "EXTRACT_BATCH_MAX_BYTES", self._TWO_ROW_BUDGET):+ ids = self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ resumable_source_manager=manager,+ chunking=_TableChunking(batch_rows=6, fetch_rows=4),+ pages_to_take=2,+ )++ assert ids == [1, 2, 3, 4]+ assert [saved.args[0] for saved in manager.save_state.call_args_list] == [+ KeysetResumeState(last_key=2, last_keys=[2])+ ]++ def test_a_lock_timeout_on_every_page_does_not_exhaust_the_retries_of_a_long_walk(self):+ ids = self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=0,+ primary_keys=["id"],+ chunking=_TableChunking(batch_rows=1, fetch_rows=1),+ lock_timeout_before_each_page=True,+ )++ assert ids == [row[0] for row in self._ROWS]+class TestCheckKeysetPagePlan:"""The signal that says whether widening the seek is safe for a table."""