: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(postgres): swallow statement timeout raised during generator close (#66678)
Tom Owers5d6bfffafad3
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 f3b7889a371c..f99ec8ab1219 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@@ -436,6 +436,28 @@ def _statement_timeout_as_non_retryable()+def _raised_while_closing_generator(error: BaseException) -> bool:+ """True when `error` surfaced while the row generator was being closed.++ Closing a suspended generator raises GeneratorExit at the yield; the server+ cursor / connection `__exit__` then runs and can itself issue a round-trip+ (closing the server cursor, the implicit rollback) that hits the+ statement_timeout and raises QueryCanceled, with the GeneratorExit left as+ its `__context__`. The consumer is already done — the sync finished, or the+ activity is being cancelled — so a teardown error here is irrelevant to the+ sync outcome and must not be re-raised: doing so masks the real cause (e.g.+ the cancellation) and floods error tracking with phantom statement timeouts.+ """+ seen: set[int] = set()+ ctx: BaseException | None = error.__context__+ while ctx is not None and id(ctx) not in seen:+ if isinstance(ctx, GeneratorExit):+ return True+ seen.add(id(ctx))+ ctx = ctx.__context__+ return False++def _pk_uniqueness_probe_timeout_error() -> QueryTimeoutException:"""Build the timeout error for the fallback `id` primary-key uniqueness probe.@@ -3047,10 +3069,17 @@ def postgres_source(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.+ # 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.+ _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,@@ -3226,6 +3255,13 @@ def postgres_source(# A FETCH against the server cursor exhausted the 10-min# statement_timeout. QueryCanceled subclasses OperationalError, so# this clause must precede the connection-dropped handler below.+ if _raised_while_closing_generator(e):+ # Not a real read timeout: the generator is being closed and the+ # cursor/connection teardown round-trip hit the statement_timeout.+ # Swallow it so close() completes cleanly instead of masking the+ # real outcome (e.g. an activity cancellation) with a phantom timeout.+ _safe_close_connection(connection)+ return# Retrying is futile (usually a missing index on the incremental# field or a scan too large to finish in time), so map it to the# same non-retryable QueryTimeoutException the offset-chunking anddiff --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 33d6ad06b56c..16f38d3739f4 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,4 +1,4 @@-from collections.abc import Iterable, Iterator+from collections.abc import Generator, Iterable, Iteratorfrom contextlib import contextmanagerfrom datetime import UTC, date, datetime, time, timedelta, timezonefrom typing import Any, cast@@ -1670,6 +1670,122 @@ class TestServerCursorStatementTimeout:assert expected_substr in str(exc_info.value)+class TestServerCursorCloseStatementTimeout:+ """Closing the `get_rows` generator (the sync finished, or the activity was cancelled) tears+ down the open server cursor; that teardown round-trip can itself hit the statement_timeout and+ raise QueryCanceled. It must be swallowed so close() completes cleanly — re-raising it (or+ mapping it to a non-retryable QueryTimeoutException) masks the real outcome and floods error+ tracking with phantom statement timeouts.+ """++ class _Cursor:+ def __init__(self, *, named: bool):+ self._named = named+ self._yielded = False+ col = mock.Mock()+ col.name = "id"+ self.description = [col]++ def execute(self, *args, **kwargs):+ return None++ def fetchmany(self, _n: int):+ # Yield one chunk once so the generator suspends at the yield inside the+ # `with cursor` block, then report end-of-rows on the next call.+ if self._yielded:+ return []+ self._yielded = True+ return [(1,)]++ def __enter__(self):+ return self++ def __exit__(self, *args):+ # Only the named server cursor's close round-trip trips the timeout, and+ # only while the generator is being closed (GeneratorExit unwinding).+ if self._named and any(isinstance(a, GeneratorExit) for a in args):+ raise psycopg.errors.QueryCanceled("canceling statement due to statement timeout")+ return False++ class _Connection:+ def __init__(self):+ self.autocommit = False+ self.closed = False+ self.broken = False+ self.adapters = mock.Mock()++ def cursor(self, *args, **kwargs):+ return TestServerCursorCloseStatementTimeout._Cursor(named="name" in kwargs)++ def commit(self):+ return None++ def close(self):+ self.closed = True++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ def _open(self, *, should_use_incremental_field: bool) -> tuple[Generator[Any], Any]:+ from contextlib import contextmanager++ @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 = []+ fake_table.__contains__ = mock.Mock(return_value=False)++ connection = self._Connection()+ 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", return_value=self._Cursor(named=False)),+ patch(f"{module}._get_table", return_value=fake_table),+ patch(f"{module}._is_read_replica", return_value=False),+ patch(f"{module}._get_primary_keys", return_value=["id"]),+ patch(f"{module}._is_partitioned_table", return_value=False),+ patch(f"{module}._get_table_chunk_size", return_value=100),+ patch(f"{module}._get_rows_to_sync", return_value=10),+ patch(f"{module}._role_subject_to_rls", return_value=False),+ patch(f"{module}._get_partition_settings", return_value=None),+ ):+ 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,+ logger=structlog.get_logger(),+ db_incremental_field_last_value=datetime(2026, 6, 15, tzinfo=UTC)+ if should_use_incremental_field+ else None,+ team_id=1,+ incremental_field="updated_at" if should_use_incremental_field else None,+ incremental_field_type=IncrementalFieldType.Timestamp if should_use_incremental_field else None,+ )+ gen = cast(Generator[Any], response.items())+ next(gen) # one chunk; generator now suspended at the yield inside `with cursor`+ return gen, connection++ @pytest.mark.parametrize("should_use_incremental_field", [True, False])+ def test_close_swallows_statement_timeout(self, should_use_incremental_field):+ gen, connection = self._open(should_use_incremental_field=should_use_incremental_field)+ # close() must not raise — neither the raw QueryCanceled nor a converted+ # QueryTimeoutException should escape teardown.+ gen.close()+ assert connection.closed++class TestOffsetChunkingConnectRecoveryConflict:"""A recovery conflict raised by the connect itself in the offset-chunking fallback — a hotstandby cancelling the new connection's startup with "conflict with recovery" — must be retried