: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(data-warehouse): add a client deadline to each postgres read round trip (#113543)
Tom Owers4982d9f0166e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.pyindex 2620040ba6f3..af57acfbff7b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/client_deadline.py@@ -19,18 +19,37 @@ from psycopg.abc import Params, Querylogger = structlog.get_logger(__name__)+# Stable prefix of `ClientDeadlineExceededError`. `PostgresSource.get_retryable_errors` matches it,+# and no entry of `get_non_retryable_errors` may.+CLIENT_DEADLINE_ERROR = "Postgres gave no answer to a statement"+# How long the cancel request itself can take.CANCEL_REQUEST_TIMEOUT_SECONDS = 10# How long the statement gets to end after the cancel request, before the socket is shut down.CANCEL_GRACE_SECONDS = 20+class ClientDeadlineExceededError(Exception):+ """A statement was still running at its client-side deadline.++ Not a psycopg error on purpose. The handlers for `QueryCanceled` read a cancel as the server's+ statement timeout, which for an incremental read is a permanent failure. This deadline acts+ only when the server limit did not, so the cause is a pooler or a server that stopped+ answering, and a later attempt can succeed.+ """++ def __init__(self, timeout_seconds: float) -> None:+ super().__init__(f"{CLIENT_DEADLINE_ERROR} within {timeout_seconds:g} seconds, so PostHog ended the statement")+ self.timeout_seconds = timeout_seconds++class _StatementWatchdog:def __init__(self, connection: psycopg.Connection[Any], timeout_seconds: float) -> None:self._connection = connectionself._timeout_seconds = timeout_secondsself._lock = threading.Lock()self._finished = threading.Event()+ self.expired = Falseself._timer = threading.Timer(timeout_seconds, self._expire)self._timer.daemon = True@@ -48,6 +67,7 @@ class _StatementWatchdog:with self._lock:if self._finished.is_set():return+ self.expired = Truelogger.warning("data_imports.postgres_client_deadline", timeout_seconds=self._timeout_seconds)try:self._connection.cancel_safe(timeout=CANCEL_REQUEST_TIMEOUT_SECONDS)@@ -81,16 +101,26 @@ def _shut_down_socket(connection: psycopg.Connection[Any]) -> None:@contextmanager-def client_side_deadline(connection: psycopg.Connection[Any], timeout_seconds: float) -> Iterator[None]:+def client_side_deadline(+ connection: psycopg.Connection[Any], timeout_seconds: float, *, raise_deadline_error: bool = True+) -> Iterator[None]:"""End the statement that runs inside the block when it takes longer than `timeout_seconds`.- At the deadline the statement gets a cancel request, and raises `QueryCanceled`. If it is still- running `CANCEL_GRACE_SECONDS` later, the socket is shut down, and it raises `OperationalError`.+ At the deadline the statement gets a cancel request. If it is still running+ `CANCEL_GRACE_SECONDS` later, the socket is shut down. The error that the statement then raises+ becomes a `ClientDeadlineExceededError`.++ With `raise_deadline_error=False` the statement keeps its own error: `QueryCanceled` after the+ cancel request, `OperationalError` after the shutdown."""watchdog = _StatementWatchdog(connection, timeout_seconds)watchdog.start()try:yield+ except Exception as e:+ if raise_deadline_error and watchdog.expired:+ raise ClientDeadlineExceededError(timeout_seconds) from e+ raisefinally:watchdog.finish()@@ -111,3 +141,43 @@ def deadline_cursor_factory(timeout_seconds: float) -> type[psycopg.Cursor[Any]]return super().execute(query, params, prepare=prepare, binary=binary)return DeadlineCursor+++def deadline_server_cursor_factory(timeout_seconds: float) -> type[psycopg.ServerCursor[Any]]:+ """Return a server cursor class that puts `client_side_deadline` on every round trip.++ Each `FETCH` is one round trip with its own deadline. The limit is thus on one silent wait+ and not on the read as a whole, so a long read that keeps returning rows never reaches it.+ """++ class DeadlineServerCursor(psycopg.ServerCursor[Any]):+ def execute(+ self,+ query: Query,+ params: Params | None = None,+ *,+ binary: bool | None = None,+ **kwargs: Any,+ ) -> Self:+ with client_side_deadline(self.connection, timeout_seconds):+ return super().execute(query, params, binary=binary, **kwargs)++ def fetchone(self) -> Any:+ with client_side_deadline(self.connection, timeout_seconds):+ return super().fetchone()++ def fetchmany(self, size: int = 0) -> list[Any]:+ with client_side_deadline(self.connection, timeout_seconds):+ return super().fetchmany(size)++ def fetchall(self) -> list[Any]:+ with client_side_deadline(self.connection, timeout_seconds):+ return super().fetchall()++ def close(self) -> None:+ # A close runs while the row generator unwinds, where the callers already handle the+ # native errors. A new error class here would hide the outcome of the read.+ with client_side_deadline(self.connection, timeout_seconds, raise_deadline_error=False):+ super().close()++ return DeadlineServerCursordiff --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 aa7902931571..d0a6ff3fece8 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@@ -98,8 +98,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_PostgresSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (+ ClientDeadlineExceededError,client_side_deadline,deadline_cursor_factory,+ deadline_server_cursor_factory,)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import XminUnsupportedErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.partitioned_tables import (@@ -135,6 +137,31 @@ SETUP_STATEMENT_CLIENT_DEADLINE_SECONDS = METADATA_STATEMENT_TIMEOUT_MS / 1000 +# `EXPLAIN` only plans the query, so one that is still running after this long waits on a lock or on# a server that stopped answering. The plan goes to a debug log line and nothing else needs it.EXPLAIN_CLIENT_DEADLINE_SECONDS = 60+# Client-side limit on each round trip of the connection that reads the rows: one keyset page, the+# `DECLARE` of a server cursor, one `FETCH`. It is a limit on one silent wait, not on the read, so a+# long read that keeps returning rows never reaches it. One minute above the server limit, like the+# setup limit, because the first `FETCH` of a sorted read is permitted to use the full server limit.+STREAM_STATEMENT_CLIENT_DEADLINE_SECONDS = SYNC_STATEMENT_TIMEOUT_MS / 1000 + 60+# The session statements that open a streaming connection do no work on the server.+STREAM_SESSION_SETUP_CLIENT_DEADLINE_SECONDS = 60+# The exact `COUNT(*)` of a read with no incremental filter scans the full table, on each attempt,+# before the first row is read. Its result feeds the progress display and the billing limit check+# only, so a count that is not done by this time gives way to the catalog estimate.+UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS = 60++_STREAM_SERVER_CURSOR = deadline_server_cursor_factory(STREAM_STATEMENT_CLIENT_DEADLINE_SECONDS)++# libpq options that end a connection whose peer went away. Keepalives find a dead peer on an idle+# socket in about 80 seconds. `tcp_user_timeout` (milliseconds) does the same for data that the+# peer never acknowledges. Both stay quiet while the peer answers at the TCP level, so neither+# ends a statement that the server is still working on.+_TCP_LIVENESS_KWARGS: dict[str, int] = {+ "keepalives": 1,+ "keepalives_idle": 30,+ "keepalives_interval": 10,+ "keepalives_count": 5,+ "tcp_user_timeout": 60_000,+}# Rows the row-size probe aims to measure. Enough for a stable p95 and a meaningful widest row,# few enough that `octet_length(t::text)` — which de-toasts every value — stays cheap on a table@@ -958,10 +985,7 @@ def _connect_to_postgres(sslrootcert="/tmp/no.txt",sslcert="/tmp/no.txt",sslkey="/tmp/no.txt",- keepalives=1,- keepalives_idle=30,- keepalives_interval=10,- keepalives_count=5,+ **_TCP_LIVENESS_KWARGS,options=options,**kwargs,)@@ -2617,7 +2641,8 @@ def _check_keyset_page_plan(cursor: psycopg.Cursor, query: sql.Composed, logger:is what says whether widening the seek past the flag is safe."""try:- cursor.execute(sql.SQL("EXPLAIN {}").format(query))+ with client_side_deadline(cursor.connection, EXPLAIN_CLIENT_DEADLINE_SECONDS):+ cursor.execute(sql.SQL("EXPLAIN {}").format(query))plan = "\n".join(str(column) for row in cursor.fetchall() for column in row)except Exception as e:# Best-effort, exactly like `_explain_query`: a failed EXPLAIN must never fail the page.@@ -3061,11 +3086,21 @@ def _get_rows_to_sync(logger: FilteringBoundLogger,*,should_use_incremental_field: bool = False,+ estimate_on_timeout: Callable[[], int | None] | None = None,) -> int:+ """Count the rows this run reads. The result feeds progress and the billing limit check only.++ A count with no incremental filter gets `UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS`. When it is+ not done by then, the result is `estimate_on_timeout()`, or 0 (unknown) without one.+ """try:_explain_query(cursor, count_query, logger)logger.debug(f"Running query: {count_query.as_string()}")- cursor.execute(count_query)+ if should_use_incremental_field:+ cursor.execute(count_query)+ else:+ with client_side_deadline(cursor.connection, UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS):+ cursor.execute(count_query)row = cursor.fetchone()if row is None:@@ -3078,6 +3113,16 @@ def _get_rows_to_sync(logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")return int(rows_to_sync)+ except ClientDeadlineExceededError as e:+ if should_use_incremental_field:+ raise+ if cursor.connection.broken or cursor.connection.closed:+ # The cancel request had no effect and the socket was shut down. No statement can run+ # on this connection, so the estimate and the remaining setup cannot run either.+ raise+ estimate = estimate_on_timeout() if estimate_on_timeout is not None else None+ logger.debug(f"_get_rows_to_sync: COUNT not done in time ({e}). Using the estimate: {estimate}")+ return estimate or 0except psycopg.errors.QueryCanceled as e:# QueryCanceled means the COUNT was cancelled — usually the statement_timeout, but possibly a# lock_timeout or an admin cancel (we don't inspect which). On incremental syncs re-raise:@@ -3622,10 +3667,7 @@ def postgres_source(sslrootcert="/tmp/no.txt",sslcert="/tmp/no.txt",sslkey="/tmp/no.txt",- keepalives=1,- keepalives_idle=30,- keepalives_interval=10,- keepalives_count=5,+ **_TCP_LIVENESS_KWARGS,options=FORCE_UTF8_CLIENT_ENCODING,)except psycopg.OperationalError as e:@@ -3837,6 +3879,13 @@ def postgres_source(count_query,logger,should_use_incremental_field=should_use_incremental_field,+ # The estimate covers the full table, so it stands in only+ # for a count of the full table.+ estimate_on_timeout=(+ (lambda: _estimated_row_count(cursor, schema, table_name, logger))+ if xmin_bounds is None+ else None+ ),)if _role_subject_to_rls(cursor, schema, table_name, logger):@@ -4015,10 +4064,7 @@ def postgres_source(sslcert="/tmp/no.txt",sslkey="/tmp/no.txt",cursor_factory=cursor_factory,- keepalives=1,- keepalives_idle=30,- keepalives_interval=10,- keepalives_count=5,+ **_TCP_LIVENESS_KWARGS,options=FORCE_UTF8_CLIENT_ENCODING,)except psycopg.OperationalError as e:@@ -4057,16 +4103,24 @@ def postgres_source(# arrive as YYYY-MM-DD regardless of the server's configured DateStyle.# A non-ISO source (e.g. German/SQL/Postgres styles) would otherwise send# "04/01/2022" or "15.01.2024", which the Safe*Loaders can't parse.+ connection.server_cursor_factory = _STREAM_SERVER_CURSORtry:# Use psycopg.Cursor directly to bypass cursor_factory (which may be# ServerCursor and requires a `name` arg, breaking an unnamed cursor()).- with psycopg.Cursor(connection) as setup_cursor:+ with (+ client_side_deadline(connection, STREAM_SESSION_SETUP_CLIENT_DEADLINE_SECONDS),+ psycopg.Cursor(connection) as setup_cursor,+ ):setup_cursor.execute(sql.SQL("SET DateStyle TO 'ISO, MDY'"))setup_cursor.execute(sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(SYNC_STATEMENT_TIMEOUT_MS)))+ except ClientDeadlineExceededError:+ # A server that does not answer a `SET` does not answer the read either.+ _safe_close_connection(connection)+ raiseexcept Exception as e:logger.debug(f"Failed to set statement_timeout on sync connection: {e}")# The SET above opens an implicit transaction in psycopg's default@@ -4075,7 +4129,12 @@ def postgres_source(# chunking) would otherwise hit "can't change autocommit state:# connection in transaction". SET statement_timeout has session scope,# so committing preserves it.- connection.commit()+ try:+ with client_side_deadline(connection, STREAM_SESSION_SETUP_CLIENT_DEADLINE_SECONDS):+ connection.commit()+ except ClientDeadlineExceededError:+ _safe_close_connection(connection)+ raisereturn connectiondef refreshed_projection() -> TableProjection[PostgreSQLColumn]:@@ -4090,7 +4149,10 @@ def postgres_source(with _connect_with_dropped_retry(get_connection, logger) as probe_connection:# `get_connection` may bind ServerCursor as the factory, which needs a# name, so take an unnamed client cursor directly.- with psycopg.Cursor(probe_connection) as probe_cursor:+ with (+ client_side_deadline(probe_connection, STREAM_STATEMENT_CLIENT_DEADLINE_SECONDS),+ psycopg.Cursor(probe_connection) as probe_cursor,+ ):fresh_table = _get_table(probe_cursor, schema, table_name, logger)except Exception as e:logger.debug(f"Could not re-read the catalog before streaming: {e}", exc_info=e)@@ -4243,7 +4305,9 @@ def postgres_source(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)+ # A client cursor reads the full page inside `execute`.+ with client_side_deadline(connection, STREAM_STATEMENT_CLIENT_DEADLINE_SECONDS):+ cursor.execute(query_with_limit_sql)page_columns = [column.name for column in cursor.description or []]rows: list[tuple[Any, ...]] = cursor.fetchall()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 fcb47509dfcc..76a250b784fa 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@@ -52,6 +52,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.ccdc_pg_connection,drop_slot_and_publication,)+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (+ CLIENT_DEADLINE_ERROR,+)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (_CONNECTION_DROPPED_ERROR_SUBSTRINGS,_CONNECTION_LIMIT_ERROR_SUBSTRINGS,@@ -395,6 +398,13 @@ _CONNECTION_DROPPED_EXHAUSTED_MESSAGE = ("and failovers. This sync is still enabled and will run again on its next schedule.")+_CLIENT_DEADLINE_EXHAUSTED_MESSAGE = (+ "Your database stopped answering in the middle of the sync, and it did so again on every retry. "+ "A connection pooler, a firewall, or an overloaded database can hold a query without an answer. "+ "Check those, and check that your database has capacity for the read. This sync is still "+ "enabled and will run again on its next schedule."+)+_SERVER_UNAVAILABLE_EXHAUSTED_MESSAGE = ("Your database wasn't accepting connections, and it was still unavailable after every retry. It ""reported that it's starting up, recovering, or shutting down. Check that the database is "@@ -1379,7 +1389,12 @@ class PostgresSource(# The bounded lookup in front of every connect raises these two when the resolver does not# answer in time or answers "try again". Neither is a verdict on the host, and a fresh# attempt recovers, so they belong with the other self-recovering connect failures.+ #+ # `CLIENT_DEADLINE_ERROR` is the client-side statement deadline. It acts only when the+ # server's own statement timeout did not, so it reports a pooler or a server that stopped+ # answering, not a query that is too slow for its index.return {+ CLIENT_DEADLINE_ERROR,*_CONNECTION_DROPPED_ERROR_SUBSTRINGS,*_POOLER_CONNECTION_DROPPED_ERROR_SUBSTRINGS,*_SERVER_STARTING_UP_ERROR_SUBSTRINGS,@@ -1405,6 +1420,7 @@ class PostgresSource(**dict.fromkeys(_SERVER_STARTING_UP_ERROR_SUBSTRINGS, _SERVER_UNAVAILABLE_EXHAUSTED_MESSAGE),**dict.fromkeys(_CONNECTION_LIMIT_ERROR_SUBSTRINGS, _CONNECTION_LIMIT_EXHAUSTED_MESSAGE),"conflict with recovery": _RECOVERY_CONFLICT_EXHAUSTED_MESSAGE,+ CLIENT_DEADLINE_ERROR: _CLIENT_DEADLINE_EXHAUSTED_MESSAGE,HOST_RESOLUTION_TIMEOUT_ERROR: HOST_RESOLUTION_EXHAUSTED_MESSAGE,TEMPORARY_HOST_RESOLUTION_ERROR: HOST_RESOLUTION_EXHAUSTED_MESSAGE,}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.pyindex bdf5903403bd..77da927398a9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test/test_client_deadline.py@@ -2,12 +2,24 @@ import socketimport threadingimport pytest-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patch+import psycopg++from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.neon.source import NeonSource+from products.warehouse_sources.backend.temporal.data_imports.sources.planetscale_postgres.source import (+ PlanetScalePostgresSource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres import client_deadlinefrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (+ ClientDeadlineExceededError,client_side_deadline,+ deadline_server_cursor_factory,)+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource+from products.warehouse_sources.backend.temporal.data_imports.sources.supabase.source import SupabaseSourcedef test_a_statement_that_ends_in_time_is_not_cancelled() -> None:@@ -52,3 +64,127 @@ def test_a_statement_that_ignores_the_cancel_request_loses_its_socket(finally:client_end.close()server_end.close()+++def _statement_ended_by_the_deadline(connection: MagicMock, error: Exception, **deadline_kwargs: bool) -> None:+ cancelled = threading.Event()+ connection.cancel_safe.side_effect = lambda timeout: cancelled.set()+ with client_side_deadline(connection, timeout_seconds=0.01, **deadline_kwargs):+ assert cancelled.wait(5)+ raise error+++ "statement_error",+ [+ psycopg.errors.QueryCanceled("canceling statement due to user request"),+ psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly"),+ ],+ ids=["after_the_cancel_request", "after_the_socket_shutdown"],+)+def test_a_statement_ended_by_the_deadline_raises_the_deadline_error(statement_error: Exception) -> None:+ with pytest.raises(ClientDeadlineExceededError) as error:+ _statement_ended_by_the_deadline(MagicMock(), statement_error)++ assert error.value.__cause__ is statement_error+++def test_a_statement_ended_by_the_deadline_can_keep_its_own_error() -> None:+ statement_error = psycopg.errors.QueryCanceled("canceling statement due to user request")++ with pytest.raises(psycopg.errors.QueryCanceled):+ _statement_ended_by_the_deadline(MagicMock(), statement_error, raise_deadline_error=False)+++def test_a_statement_that_fails_before_the_deadline_keeps_its_own_error() -> None:+ with pytest.raises(psycopg.errors.UndefinedTable):+ with client_side_deadline(MagicMock(), timeout_seconds=30):+ raise psycopg.errors.UndefinedTable("relation does not exist")+++class _RecordingTimer:+ started: list[float] = []+ cancelled = 0++ def __init__(self, interval: float, function: object) -> None:+ self.interval = interval+ self.daemon = False++ def start(self) -> None:+ type(self).started.append(self.interval)++ def cancel(self) -> None:+ type(self).cancelled += 1+++ "round_trip",+ [+ lambda cursor: cursor.execute("SELECT 1"),+ lambda cursor: cursor.fetchone(),+ lambda cursor: cursor.fetchmany(100),+ lambda cursor: cursor.fetchall(),+ lambda cursor: cursor.close(),+ ],+ ids=["execute", "fetchone", "fetchmany", "fetchall", "close"],+)+def test_each_server_cursor_round_trip_gets_its_own_deadline(monkeypatch: pytest.MonkeyPatch, round_trip) -> None:+ # A deadline that covered the read as a whole would end a long read that is in good health.+ _RecordingTimer.started = []+ _RecordingTimer.cancelled = 0+ monkeypatch.setattr(client_deadline.threading, "Timer", _RecordingTimer)+ cursor_class = deadline_server_cursor_factory(660)+ cursor = cursor_class.__new__(cursor_class)+ cursor._conn = MagicMock()++ with (+ patch.object(psycopg.ServerCursor, "execute"),+ patch.object(psycopg.ServerCursor, "fetchone"),+ patch.object(psycopg.ServerCursor, "fetchmany"),+ patch.object(psycopg.ServerCursor, "fetchall"),+ patch.object(psycopg.ServerCursor, "close"),+ ):+ for _ in range(3):+ round_trip(cursor)++ assert _RecordingTimer.started == [660, 660, 660]+ assert _RecordingTimer.cancelled == 3+++ "round_trip,expected_error",+ [+ (lambda cursor: cursor.fetchmany(100), ClientDeadlineExceededError),+ # The row generator closes its cursor while it unwinds, and its callers handle the native error.+ (lambda cursor: cursor.close(), psycopg.errors.QueryCanceled),+ ],+ ids=["fetchmany", "close"],+)+def test_a_silent_server_cursor_round_trip_ends_at_the_deadline(round_trip, expected_error) -> None:+ cancelled = threading.Event()+ connection = MagicMock()+ connection.cancel_safe.side_effect = lambda timeout: cancelled.set()+ cursor_class = deadline_server_cursor_factory(0.01)+ cursor = cursor_class.__new__(cursor_class)+ cursor._conn = connection++ def silent_until_cancelled(*args: object) -> None:+ assert cancelled.wait(5)+ raise psycopg.errors.QueryCanceled("canceling statement due to user request")++ with (+ patch.object(psycopg.ServerCursor, "fetchmany", side_effect=silent_until_cancelled),+ patch.object(psycopg.ServerCursor, "close", side_effect=silent_until_cancelled),+ pytest.raises(expected_error),+ ):+ round_trip(cursor)++[email protected]("source_class", [PostgresSource, NeonSource, SupabaseSource, PlanetScalePostgresSource])+def test_the_deadline_error_is_retryable_for_every_postgres_source(source_class: type[PostgresSource]) -> None:+ source = source_class()+ message = str(ClientDeadlineExceededError(660))++ assert not error_message_matches(message, {**Any_Source_Errors, **source.get_non_retryable_errors()})+ assert error_message_matches(message, source.get_retryable_errors())+ assert error_message_matches(message, source.get_retry_exhausted_errors())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 73b59630a1ad..0edd6a0d2aac 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@@ -3,7 +3,7 @@ import errnoimport socketimport threadingfrom collections.abc import Generator, Iterable, Iterator-from contextlib import contextmanager+from contextlib import ExitStack, contextmanagerfrom datetime import UTC, date, datetime, time, timedelta, timezonefrom typing import Any, cast@@ -55,6 +55,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.types import Tablefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import addrinfofrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.client_deadline import (+ CLIENT_DEADLINE_ERROR,+ ClientDeadlineExceededError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import (ForeignServerUnreachableError,XminUnsupportedError,@@ -80,12 +84,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_MAX_SETUP_RECOVERY_CONFLICT_RETRIES,_MIN_RECOVERY_CONFLICT_CHUNK_SIZE,_SSH_HANDSHAKE_EOF_ERROR,+ _STREAM_SERVER_CURSOR,+ _TCP_LIVENESS_KWARGS,+ EXPLAIN_CLIENT_DEADLINE_SECONDS,FORCE_UTF8_CLIENT_ENCODING,METADATA_STATEMENT_TIMEOUT_MS,MIN_SIZE_SAMPLE_PERCENT,SIZE_SAMPLE_MAX_ROWS,SIZE_SAMPLE_TARGET_ROWS,SSL_REQUIRED_AFTER_DATE,+ UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS,XMIN_PROJECTED_COLUMN,JsonAsStringLoader,NetworkAsStringLoader,@@ -3531,8 +3539,8 @@ class TestServerCursorStatementTimeout:"""class _Cursor:- def __init__(self, raise_on_fetch: bool):- self._raise_on_fetch = raise_on_fetch+ def __init__(self, fetch_error: BaseException | None):+ self._fetch_error = fetch_errorcol = mock.Mock()col.name = "id"self.description = [col]@@ -3541,8 +3549,8 @@ class TestServerCursorStatementTimeout:return Nonedef fetchmany(self, _n: int):- if self._raise_on_fetch:- raise psycopg.errors.QueryCanceled("canceling statement due to statement timeout")+ if self._fetch_error is not None:+ raise self._fetch_errorreturn []def __enter__(self):@@ -3552,7 +3560,8 @@ class TestServerCursorStatementTimeout:return Falseclass _Connection:- def __init__(self):+ def __init__(self, fetch_error: BaseException):+ self._fetch_error = fetch_errorself.autocommit = Falseself.closed = False# Real psycopg connections expose `broken`; the setup path probes it via@@ -3563,7 +3572,7 @@ class TestServerCursorStatementTimeout:def cursor(self, *args, **kwargs):# A named cursor (`name=...`) is the streaming server cursor that must# raise the timeout; the unnamed setup cursor stays benign.- return TestServerCursorStatementTimeout._Cursor(raise_on_fetch="name" in kwargs)+ return TestServerCursorStatementTimeout._Cursor(self._fetch_error if "name" in kwargs else None)def commit(self):return None@@ -3577,7 +3586,7 @@ class TestServerCursorStatementTimeout:def __exit__(self, *args):return False- def _run(self, *, should_use_incremental_field: bool):+ def _run(self, *, should_use_incremental_field: bool, fetch_error: BaseException):from contextlib import contextmanager@contextmanager@@ -3592,8 +3601,8 @@ class TestServerCursorStatementTimeout:module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"with (- patch(f"{module}.psycopg.connect", return_value=self._Connection()),- patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(raise_on_fetch=False)),+ patch(f"{module}.psycopg.connect", return_value=self._Connection(fetch_error)),+ patch(f"{module}.psycopg.Cursor", return_value=self._Cursor(None)),patch(f"{module}._get_table", return_value=fake_table),patch(f"{module}._is_read_replica", return_value=False),patch(f"{module}._is_duckdb_connection", return_value=False),@@ -3623,19 +3632,28 @@ class TestServerCursorStatementTimeout:)list(cast(Iterable[Any], response.items()))+ _SERVER_TIMEOUT = psycopg.errors.QueryCanceled("canceling statement due to statement timeout")+ _CLIENT_DEADLINE = ClientDeadlineExceededError(660)+@pytest.mark.parametrize(- "should_use_incremental_field,expected_exception,expected_substr",+ "should_use_incremental_field,fetch_error,expected_exception,expected_substr",[# Incremental syncs map the FETCH timeout to a non-retryable QueryTimeoutException.- (True, QueryTimeoutException, "updated_at"),+ (True, _SERVER_TIMEOUT, QueryTimeoutException, "updated_at"),# Full-table syncs have no stable ORDER BY, so they stay retryable to let a fresh# re-sync reorder rows rather than giving up — with a message that names the fix.- (False, Exception, "incremental replication"),+ (False, _SERVER_TIMEOUT, Exception, "incremental replication"),+ # The client deadline reports a server that stopped answering, so it must reach the+ # activity unchanged for both sync types, and never as the permanent index advice.+ (True, _CLIENT_DEADLINE, ClientDeadlineExceededError, CLIENT_DEADLINE_ERROR),+ (False, _CLIENT_DEADLINE, ClientDeadlineExceededError, CLIENT_DEADLINE_ERROR),],)- def test_statement_timeout_handling(self, should_use_incremental_field, expected_exception, expected_substr):+ def test_statement_timeout_handling(+ self, should_use_incremental_field, fetch_error, expected_exception, expected_substr+ ):with pytest.raises(expected_exception) as exc_info:- self._run(should_use_incremental_field=should_use_incremental_field)+ self._run(should_use_incremental_field=should_use_incremental_field, fetch_error=fetch_error)if expected_substr is not None:assert expected_substr in str(exc_info.value)@@ -4075,6 +4093,101 @@ class TestOffsetChunkingConnectTimeout:assert connect_mock.call_count == 5+class TestStreamingConnectionDeadlines:+ class _PageCursor(TestOffsetChunkingConnectRecoveryConflict._OffsetCursor):+ def execute(self, *args, **kwargs):+ raise ClientDeadlineExceededError(660)++ class _Connection(TestOffsetChunkingConnectRecoveryConflict._Connection):+ def __init__(self, setup_cursor: Any):+ super().__init__()+ self._setup_cursor = setup_cursor+ self.server_cursor_factory: Any = None++ def cursor(self, *args, **kwargs):+ return self._setup_cursor++ def _source(self, page_cursor: type, *, count_error: Exception | None = None) -> SourceResponse:+ @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=False)]+ fake_table.__contains__ = mock.Mock(return_value=False)++ def execute(query: Any, *args: Any, **kwargs: Any) -> None:+ if count_error is not None and "COUNT(*)" in str(query):+ raise count_error++ setup_cursor = mock.MagicMock()+ setup_cursor.__enter__.return_value = setup_cursor+ setup_cursor.connection.broken = False+ setup_cursor.connection.closed = False+ setup_cursor.execute.side_effect = execute+ self.connection = self._Connection(setup_cursor)++ module = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"+ with ExitStack() as stack:+ self.connect_mock = stack.enter_context(patch(f"{module}.psycopg.connect", return_value=self.connection))+ for target, value in {+ "_get_table": fake_table,+ "_is_read_replica": False,+ "_is_duckdb_connection": False,+ "_get_primary_keys": ["id"],+ "_is_partitioned_table": False,+ "_get_table_chunk_size": _TableChunking(batch_rows=1000, fetch_rows=1000),+ "_role_subject_to_rls": False,+ "_get_partition_settings": None,+ "_explain_query": None,+ "_estimated_row_count": 4321,+ }.items():+ stack.enter_context(patch(f"{module}.{target}", return_value=value))+ stack.enter_context(patch(f"{module}.psycopg.Cursor", side_effect=lambda _conn: page_cursor()))+ response = postgres_source(+ tunnel=lambda: fake_tunnel(),+ user="u",+ password="p",+ database="db",+ sslmode="prefer",+ schema="public",+ table_names=["companies"],+ should_use_incremental_field=False,+ logger=structlog.get_logger(),+ db_incremental_field_last_value=None,+ team_id=1,+ )+ list(cast(Iterable[Any], response.items()))+ return response++ def test_keyset_page_deadline_ends_the_attempt_without_an_in_process_retry(self):+ with pytest.raises(ClientDeadlineExceededError):+ self._source(self._PageCursor)++ # 1 setup + 1 catalog re-read + 1 keyset read. A retry on the same silent server would hold+ # the worker for one more deadline each time.+ assert self.connect_mock.call_count == 3+ assert self.connection.closed is True++ def test_every_connection_gets_the_connect_and_tcp_limits_and_the_deadline_cursor(self):+ self._source(TestOffsetChunkingConnectRecoveryConflict._OffsetCursor)++ for call in self.connect_mock.call_args_list:+ assert call.kwargs["connect_timeout"] == 15+ assert {name: call.kwargs[name] for name in _TCP_LIVENESS_KWARGS} == _TCP_LIVENESS_KWARGS+ assert self.connection.server_cursor_factory is _STREAM_SERVER_CURSOR++ def test_full_table_count_past_its_deadline_reports_the_catalog_estimate(self):+ response = self._source(+ TestOffsetChunkingConnectRecoveryConflict._OffsetCursor,+ count_error=ClientDeadlineExceededError(UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS),+ )++ assert response.rows_to_sync == 4321++def _fake_column(name: str):column = mock.Mock()column.name = name@@ -7470,6 +7583,94 @@ class TestGetRowsToSync:mock_capture.assert_not_called()+ @pytest.mark.parametrize(+ "estimate_on_timeout,expected",+ [+ (lambda: 1234, 1234),+ # No statistics yet for the table, and a view has none at all.+ (lambda: None, 0),+ # An xmin count has no catalog estimate, so it stays unknown.+ (None, 0),+ ],+ ids=["catalog_estimate", "no_statistics", "no_estimator"],+ )+ def test_unfiltered_count_past_its_deadline_gives_the_estimate(self, estimate_on_timeout, expected):+ cursor = self._cursor_past_the_count_deadline(connection_lost=False)+ count_query = _build_count_query("public", "users", False, None, None, None)++ rows = _get_rows_to_sync(+ cast(Any, cursor), count_query, structlog.get_logger(), estimate_on_timeout=estimate_on_timeout+ )++ assert rows == expected++ @staticmethod+ def _cursor_past_the_count_deadline(*, connection_lost: bool) -> mock.MagicMock:+ cursor = mock.MagicMock()+ cursor.connection.broken = connection_lost+ cursor.connection.closed = connection_lost+ cursor.execute.side_effect = [None, ClientDeadlineExceededError(UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS)]+ return cursor++ def test_unfiltered_count_deadline_that_cost_the_connection_ends_the_attempt(self):+ # After the socket shutdown no statement can run, so an estimate of 0 here would send the+ # setup into its reconnect loop, which runs the same count again.+ cursor = self._cursor_past_the_count_deadline(connection_lost=True)+ count_query = _build_count_query("public", "users", False, None, None, None)++ with pytest.raises(ClientDeadlineExceededError):+ _get_rows_to_sync(cast(Any, cursor), count_query, structlog.get_logger(), estimate_on_timeout=lambda: 1234)++ def test_incremental_count_past_the_client_deadline_stays_retryable(self):+ # The incremental handlers read `QueryCanceled` as "add an index", which stops the sync.+ cursor = mock.MagicMock()+ cursor.execute.side_effect = [None, ClientDeadlineExceededError(660)]+ count_query = _build_count_query("public", "users", False, None, None, None)++ with pytest.raises(ClientDeadlineExceededError):+ _get_rows_to_sync(+ cast(Any, cursor),+ count_query,+ structlog.get_logger(),+ should_use_incremental_field=True,+ estimate_on_timeout=lambda: 1234,+ )++ @pytest.mark.parametrize(+ "should_use_incremental_field,expected_deadlines",+ [+ # The `EXPLAIN` has its own limit for both. Only the unfiltered count gets the short one.+ (False, [EXPLAIN_CLIENT_DEADLINE_SECONDS, UNFILTERED_COUNT_CLIENT_DEADLINE_SECONDS]),+ (True, [EXPLAIN_CLIENT_DEADLINE_SECONDS]),+ ],+ ids=["full_table", "incremental"],+ )+ def test_only_the_unfiltered_count_gets_the_short_deadline(self, should_use_incremental_field, expected_deadlines):+ deadlines: list[float] = []++ @contextmanager+ def record_deadline(_connection: Any, timeout_seconds: float, **_kwargs: Any) -> Iterator[None]:+ deadlines.append(timeout_seconds)+ yield++ cursor = mock.MagicMock()+ cursor.fetchone.return_value = (7,)+ count_query = _build_count_query("public", "users", False, None, None, None)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.client_side_deadline",+ record_deadline,+ ):+ rows = _get_rows_to_sync(+ cast(Any, cursor),+ count_query,+ structlog.get_logger(),+ should_use_incremental_field=should_use_incremental_field,+ )++ assert rows == 7+ assert deadlines == expected_deadlines+class TestPartitionedTableChunkSizing:"""Incremental reads use per-child partition queries; no parent FETCH chunk cap."""