: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(redshift): retry a dropped connection during sync setup (#87622)
Tom Owers097e5d2e1052
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.pyindex 9f2216ffffcf..fd7c86f6cc59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py@@ -10,11 +10,12 @@ credentials.from __future__ import annotations+import timeimport collections-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom contextlib import contextmanagerfrom datetime import date-from typing import Any, Literal, LiteralString, Optional, cast+from typing import Any, Literal, LiteralString, Optional, TypeVar, castimport psycopgimport pyarrow as pa@@ -69,7 +70,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_RedshiftSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException-from products.warehouse_sources.backend.types import IncrementalFieldType+from products.warehouse_sources.backend.types import IncrementalFieldType, PartitionSettings__all__ = ["JsonAsStringLoader",@@ -392,6 +393,49 @@ def _recover_after_failed_probe(connection: psycopg.Connection) -> None:pass+_T = TypeVar("_T")++_MAX_SETUP_CONNECTION_DROP_ATTEMPTS = 3+++def _is_transient_connection_drop_error(error: BaseException) -> bool:+ """True if a freshly opened connection died before `build_pipeline`'s setup phase finished.++ psycopg raises this exact OperationalError message when libpq finds the socket already gone+ (a network blip or a cluster pause/resize) — the keepalives configured on connect only detect+ a dead peer during a query, not this class of drop between connecting and the first query.+ """+ return isinstance(error, psycopg.OperationalError) and "the connection is lost" in str(error)+++def _retry_on_transient_connection_drop(+ operation: Callable[[], _T],+ logger: FilteringBoundLogger,+ *,+ max_attempts: int = _MAX_SETUP_CONNECTION_DROP_ATTEMPTS,+) -> _T:+ """Run `operation`, retrying the whole thing (including reopening the connection) on a+ transient connection drop rather than failing sync setup on the first blip and burning a+ full Temporal activity retry — which re-runs from the very start of the sync — to recover+ from something a cheap in-process reconnect fixes in seconds.+ """+ attempt = 0+ while True:+ try:+ return operation()+ except psycopg.OperationalError as e:+ attempt += 1+ if attempt >= max_attempts or not _is_transient_connection_drop_error(e):+ raise+ logger.warning(+ "Transient Redshift connection drop during pipeline setup; retrying",+ attempt=attempt,+ max_attempts=max_attempts,+ exc_info=e,+ )+ time.sleep(min(2 * attempt, 30))++def _reads_primary_keys(cursor: psycopg.Cursor, schema: str) -> bool | None:"""Can this connection read primary-key constraints in `schema` at all?@@ -735,6 +779,19 @@ class QualifiedRelation:name: str+@frozen+class RedshiftTableSetup:+ """Everything `build_pipeline` learns about a table before it can stream rows."""++ full_table: Table[RedshiftColumn]+ primary_keys: list[str] | None+ projected_table: Table[RedshiftColumn]+ chunk_size: int+ rows_to_sync: int+ partition_settings: PartitionSettings | None+ duplicate_primary_keys: bool++class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycopg.Connection, Any]):# `psycopg.Cursor` does not satisfy `_CursorLike` (its `execute`# signature uses `params` instead of `args`, and accepts `Query`@@ -1465,96 +1522,122 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoenabled_columns = inputs.enabled_columnsrow_filters = inputs.row_filters- with self.connect(config) as connection:- # Autocommit so each best-effort discovery probe runs in its own transaction. A probe- # that fails — a permission error, an EXPLAIN the cluster rejects, a cancelled COUNT(*) —- # otherwise leaves the shared transaction aborted (INERROR), and every probe after it- # raises `InFailedSqlTransaction` until a rollback. Mirrors the postgres source.- connection.autocommit = True- with connection.cursor() as cursor:- logger.debug("Getting table types...")- full_table = self.get_table_metadata(cursor, schema, table_name, logger)-- cursor.execute(- sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 60 * 10)) # 10 mins- )- try:- logger.debug("Getting primary keys...")- primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name, logger, full_table.type)- if primary_keys:- logger.debug(f"Found primary keys: {primary_keys}")-- # Resolve PKs before projection so SELECT and Arrow schema agree.- if primary_keys is None and "id" in full_table:- logger.debug("Falling back to ['id'] for primary keys...")- primary_keys = ["id"]-- projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)- table = project_arrow_columns(full_table, projected)- logger.debug(f"Source schema: {table.to_arrow_schema()}")-- inner_query_with_limit = _build_query(- schema,- table_name,- should_use_incremental_field,- table.type,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- add_sampling=True,- enabled_columns=enabled_columns,- primary_keys=primary_keys,+ def _discover_and_probe() -> RedshiftTableSetup:+ with self.connect(config) as connection:+ # Autocommit so each best-effort discovery probe runs in its own transaction. A probe+ # that fails — a permission error, an EXPLAIN the cluster rejects, a cancelled COUNT(*) —+ # otherwise leaves the shared transaction aborted (INERROR), and every probe after it+ # raises `InFailedSqlTransaction` until a rollback. Mirrors the postgres source.+ connection.autocommit = True+ with connection.cursor() as cursor:+ logger.debug("Getting table types...")+ full_table = self.get_table_metadata(cursor, schema, table_name, logger)++ cursor.execute(+ sql.SQL("SET statement_timeout = {timeout}").format(+ timeout=sql.Literal(1000 * 60 * 10)+ ) # 10 mins)+ try:+ logger.debug("Getting primary keys...")+ primary_keys = self.get_primary_keys_for_table(+ cursor, schema, table_name, logger, full_table.type+ )+ if primary_keys:+ logger.debug(f"Found primary keys: {primary_keys}")- inner_query_without_limit = _build_query(- schema,- table_name,- should_use_incremental_field,- table.type,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- enabled_columns=enabled_columns,- primary_keys=primary_keys,- row_filters=row_filters,- )- logger.debug("Getting table chunk size...")- if chunk_size_override is not None:- chunk_size = chunk_size_override- logger.debug(f"Using chunk_size_override: {chunk_size_override}")- else:- # `inner_query_with_limit` is a `psycopg.sql.Composed`- # rather than a `str`; the override on- # `fetch_average_row_size` accepts it via `Any`.- chunk_size = self.get_chunk_size(- cursor,+ # Resolve PKs before projection so SELECT and Arrow schema agree.+ if primary_keys is None and "id" in full_table:+ logger.debug("Falling back to ['id'] for primary keys...")+ primary_keys = ["id"]++ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ table = project_arrow_columns(full_table, projected)+ logger.debug(f"Source schema: {table.to_arrow_schema()}")++ inner_query_with_limit = _build_query(schema,table_name,- inner_query_with_limit, # type: ignore[arg-type]- None,- logger,+ should_use_incremental_field,+ table.type,+ incremental_field,+ incremental_field_type,+ db_incremental_field_last_value,+ add_sampling=True,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)- logger.debug("Getting rows to sync...")- rows_to_sync = self.get_rows_to_sync(cursor, inner_query_without_limit, None, logger)- logger.debug("Getting partition settings...")- partition_settings = (- self.get_partition_settings(cursor, schema, table_name, logger)- if should_use_incremental_field- else None- )- duplicate_primary_keys = False- if primary_keys == ["id"] and "id" in full_table:- # Only check dupes when we fell back to the `id` PK above.- logger.debug("Checking duplicate primary keys...")- duplicate_primary_keys = self.has_duplicate_primary_keys(- cursor, schema, table_name, primary_keys, logger++ inner_query_without_limit = _build_query(+ schema,+ table_name,+ should_use_incremental_field,+ table.type,+ incremental_field,+ incremental_field_type,+ db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,+ row_filters=row_filters,)- except psycopg.errors.QueryCanceled:- if should_use_incremental_field:- raise QueryTimeoutException(- f"10 min timeout statement reached. Please ensure your incremental field ({incremental_field}) is set as a SORTKEY on the table"+ logger.debug("Getting table chunk size...")+ if chunk_size_override is not None:+ chunk_size = chunk_size_override+ logger.debug(f"Using chunk_size_override: {chunk_size_override}")+ else:+ # `inner_query_with_limit` is a `psycopg.sql.Composed`+ # rather than a `str`; the override on+ # `fetch_average_row_size` accepts it via `Any`.+ chunk_size = self.get_chunk_size(+ cursor,+ schema,+ table_name,+ inner_query_with_limit, # type: ignore[arg-type]+ None,+ logger,+ )+ logger.debug("Getting rows to sync...")+ rows_to_sync = self.get_rows_to_sync(cursor, inner_query_without_limit, None, logger)+ logger.debug("Getting partition settings...")+ partition_settings = (+ self.get_partition_settings(cursor, schema, table_name, logger)+ if should_use_incremental_field+ else None)- raise+ duplicate_primary_keys = False+ if primary_keys == ["id"] and "id" in full_table:+ # Only check dupes when we fell back to the `id` PK above.+ logger.debug("Checking duplicate primary keys...")+ duplicate_primary_keys = self.has_duplicate_primary_keys(+ cursor, schema, table_name, primary_keys, logger+ )+ except psycopg.errors.QueryCanceled:+ if should_use_incremental_field:+ raise QueryTimeoutException(+ f"10 min timeout statement reached. Please ensure your incremental field ({incremental_field}) is set as a SORTKEY on the table"+ )+ raise+ return RedshiftTableSetup(+ full_table=full_table,+ primary_keys=primary_keys,+ projected_table=table,+ chunk_size=chunk_size,+ rows_to_sync=rows_to_sync,+ partition_settings=partition_settings,+ duplicate_primary_keys=duplicate_primary_keys,+ )++ # A fresh connection can still drop before setup finishes (network blip, cluster+ # pause/resize) — retry the whole discovery+probe phase (reopening the connection) rather+ # than let it fail through to a full Temporal activity retry, which restarts the sync+ # from scratch. See `_retry_on_transient_connection_drop`.+ setup = _retry_on_transient_connection_drop(_discover_and_probe, logger)+ primary_keys = setup.primary_keys+ table = setup.projected_table+ chunk_size = setup.chunk_size+ rows_to_sync = setup.rows_to_sync+ partition_settings = setup.partition_settings+ duplicate_primary_keys = setup.duplicate_primary_keysdef get_rows() -> Iterator[Any]:arrow_schema = table.to_arrow_schema()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.pyindex 27e7e9ebeef5..a426273f5c54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.redshift.r_build_query,_explain_query,_fetch_arrow_batches,+ _is_transient_connection_drop_error,_libpq_rows_per_chunk,_stream_arrow_batches,_stream_rows_as_arrow_batches,@@ -1375,7 +1376,65 @@ def build_pipeline_mocks(mocker):return mock_connect, streaming_cursor+class TestIsTransientConnectionDropError:+ def test_matches_connection_is_lost(self):+ assert _is_transient_connection_drop_error(psycopg.OperationalError("the connection is lost")) is True++ def test_does_not_match_unrelated_operational_error(self):+ # A permanent, non-actionable failure that also raises OperationalError must not be+ # swept up by the narrow "the connection is lost" match and retried in-process.+ assert (+ _is_transient_connection_drop_error(+ psycopg.OperationalError("password authentication failed for user testuser")+ )+ is False+ )++ def test_does_not_match_non_operational_error(self):+ assert _is_transient_connection_drop_error(ValueError("the connection is lost")) is False++class TestBuildPipeline:+ def test_retries_once_on_transient_connection_drop_during_setup(self, build_pipeline_mocks, mocker):+ # Regression: `get_table_metadata` hit a freshly opened connection that dropped+ # (`psycopg.OperationalError: the connection is lost`) before setup finished. Without an+ # in-process retry this failed the whole sync out to Temporal's activity-level retry, which+ # restarts the entire setup phase from scratch instead of reconnecting once.+ mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.time.sleep")+ attempts = {"n": 0}+ fake_table = Table(+ name="messages",+ parents=("public",),+ columns=[RedshiftColumn(name="id", data_type="integer", nullable=False)],+ type="table",+ )++ def flaky_get_table_metadata(*args, **kwargs):+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise psycopg.OperationalError("the connection is lost")+ return fake_table++ mocker.patch.object(RedshiftImplementation, "get_table_metadata", side_effect=flaky_get_table_metadata)++ impl = RedshiftImplementation()+ response = impl.build_pipeline(_make_config(), _make_inputs())++ assert attempts["n"] == 2+ assert response.primary_keys == ["id"]++ def test_gives_up_after_max_attempts_on_persistent_connection_drop(self, build_pipeline_mocks, mocker):+ mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.redshift.redshift.time.sleep")+ mocker.patch.object(+ RedshiftImplementation,+ "get_table_metadata",+ side_effect=psycopg.OperationalError("the connection is lost"),+ )++ impl = RedshiftImplementation()+ with pytest.raises(psycopg.OperationalError):+ impl.build_pipeline(_make_config(), _make_inputs())+def test_returns_source_response(self, build_pipeline_mocks):mock_connect, _ = build_pipeline_mocksimpl = RedshiftImplementation()