: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): seek on a retried full-table read from a read replica (#95274)
Daniel RCe4bf75a82c92
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex 0cd32080dc45..f83c31597be7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py@@ -123,3 +123,6 @@ class SourceInputs:# True when extraction batches should be bounded by accumulated bytes rather than by the# sampled row count alone. Evaluated once per run alongside `fanout_warehouse_reuse`.byte_bounded_extraction: bool = False+ # Temporal's attempt number for this activity, starting at 1. A source can read a retry+ # differently from a first run, because the first run has already shown what fails.+ activity_attempt: int = 1diff --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 b51ef5d282b4..15b8591f0538 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@@ -3292,6 +3292,7 @@ def postgres_source(xmin_last_value: Optional[int] = None,xmin_num_wraparound: Optional[int] = None,byte_bounded_extraction: bool = False,+ activity_attempt: int = 1,) -> SourceResponse:table_name = table_names[0]if not table_name:@@ -4075,6 +4076,26 @@ def postgres_source(else None)+ # A server cursor idles in an open transaction through every Delta merge, and a replica+ # that cancels reads during that idle kills each attempt at the same place. The handler+ # below cannot resume past the first row, because the cursor's order is arbitrary, so+ # it re-raises for a restart, and a restart on another cursor repeats the failure. The+ # seek pages in autocommit, so nothing idles and a conflict resumes at the last key.+ # Only from the second attempt, so a replica that never cancels keeps one snapshot.+ if (+ activity_attempt > 1+ and using_read_replica+ and keyset_primary_keys is not None+ and not should_use_incremental_field+ and xmin_bounds is None+ ):+ logger.debug(+ f"Attempt {activity_attempt} of a full-table read on a read replica. Seeking from the "+ f"start instead of reopening a server cursor. keys = {keyset_primary_keys}"+ )+ yield from offset_chunking(0, chunk_size, keyset_primary_keys=keyset_primary_keys)+ return+initial_read_drop_retries = 0initial_read_lock_timeout_retries = 0while True: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 de491b1ab24e..beb5e07d203d 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@@ -1562,6 +1562,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDaxmin_last_value=schema.xmin_last_value,xmin_num_wraparound=schema.xmin_num_wraparound,byte_bounded_extraction=inputs.byte_bounded_extraction,+ activity_attempt=inputs.activity_attempt,)except SqlclientUnableToEstablishSqlconnection as e:# A setup query (e.g. the duplicate-PK probe) touched a postgres_fdw foreign table and thediff --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 ad2e842bbc34..89d59773da54 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@@ -3544,6 +3544,7 @@ class TestChunkedRereadAfterRecoveryConflict:has_id_column: bool = False,has_duplicate_pks: bool = False,is_xmin: bool = False,+ activity_attempt: int = 1,) -> list[int]:@contextmanagerdef fake_tunnel():@@ -3599,6 +3600,7 @@ class TestChunkedRereadAfterRecoveryConflict:team_id=1,is_xmin=is_xmin,xmin_last_value=self._XMIN_BOUNDS.lower if is_xmin else None,+ activity_attempt=activity_attempt,)return [row["id"] for table in cast(Iterable[Any], response.items()) for row in table.to_pylist()]@@ -3650,6 +3652,18 @@ class TestChunkedRereadAfterRecoveryConflict:with pytest.raises(psycopg.errors.SerializationFailure):self._read_ids(should_use_incremental_field=False, rows_before_conflict=2, primary_keys=["id"])+ 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.+ ids = self._read_ids(+ should_use_incremental_field=False,+ rows_before_conflict=2,+ primary_keys=["id"],+ activity_attempt=2,+ )++ assert sorted(ids) == [row[0] for row in self._ROWS]+@pytest.mark.parametrize("rows_before_conflict,nullable_value,has_id_column,has_duplicate_pks",[diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.pyindex 92d3513cd15c..9fe451bbcb07 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py@@ -119,6 +119,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):xmin_last_value=None,xmin_num_wraparound=None,byte_bounded_extraction=False,+ activity_attempt=1,)@@ -173,6 +174,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **xmin_last_value=None,xmin_num_wraparound=None,byte_bounded_extraction=False,+ activity_attempt=1,)@@ -239,6 +241,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, texmin_last_value=None,xmin_num_wraparound=None,byte_bounded_extraction=False,+ activity_attempt=1,)@@ -320,6 +323,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, teaxmin_last_value=None,xmin_num_wraparound=None,byte_bounded_extraction=False,+ activity_attempt=1,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex 674db365165f..2f66013c024c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -515,6 +515,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:api_version=new_source.resolve_api_version(schema.api_version or model.pipeline.api_version),fanout_warehouse_reuse=fanout_warehouse_reuse,byte_bounded_extraction=byte_bounded_extraction,+ activity_attempt=activity.info().attempt if activity.in_activity() else 1,)try: