Skip to content

: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.

fix(postgres): degrade rows-to-sync count timeout on full-table syncs (#67234)

Tom Owers02d225d1777e
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.py
index edc959f71067..aedc0b8229b1 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
@@ -2074,7 +2074,13 @@ def _role_subject_to_rls(cursor: psycopg.Cursor, schema: str, table_name: str, l
return False
-def _get_rows_to_sync(cursor: psycopg.Cursor, count_query: sql.Composed, logger: FilteringBoundLogger) -> int:
+def _get_rows_to_sync(
+ cursor: psycopg.Cursor,
+ count_query: sql.Composed,
+ logger: FilteringBoundLogger,
+ *,
+ should_use_incremental_field: bool = False,
+) -> int:
try:
_explain_query(cursor, count_query, logger)
logger.debug(f"Running query: {count_query.as_string()}")
@@ -2091,8 +2097,20 @@ def _get_rows_to_sync(cursor: psycopg.Cursor, count_query: sql.Composed, logger:
logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")
return int(rows_to_sync)
- except psycopg.errors.QueryCanceled:
- raise
+ except 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:
+ # this COUNT shares its WHERE with the real chunked read, so a cancellation here predicts the
+ # extraction will hit the same wall — the caller maps it to the actionable "add an index on
+ # your incremental field" message. On full-table syncs the COUNT is a full scan while
+ # extraction streams sequentially via a server cursor, so a cancelled count says nothing
+ # about whether extraction will succeed. Fall back to an unknown total (0) like the sibling
+ # `_get_table_chunk_size` probe rather than failing the whole sync at setup on a best-effort
+ # estimate.
+ if should_use_incremental_field:
+ raise
+ logger.debug(f"_get_rows_to_sync: COUNT cancelled on a full-table sync ({e}). Using 0 as rows to sync")
+ return 0
except Exception as e:
# This COUNT(*) is a best-effort estimate for progress reporting and partition sizing.
# It shares its FROM/WHERE with the real extraction query, so any genuine problem
@@ -2804,7 +2822,12 @@ def postgres_source(
except Exception as e:
logger.debug(f"Estimated row count failed, falling back to exact count: {e}")
if rows_to_sync is None:
- rows_to_sync = _get_rows_to_sync(cursor, count_query, logger)
+ rows_to_sync = _get_rows_to_sync(
+ cursor,
+ count_query,
+ logger,
+ should_use_incremental_field=should_use_incremental_field,
+ )
if _role_subject_to_rls(cursor, schema, table_name, logger):
logger.warning(
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.py
index 1d7c01a67b42..505fb93df696 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
@@ -3944,6 +3944,52 @@ class TestGetRowsToSync:
# The temp-file signal is actionable, so it propagates rather than being swallowed.
mock_capture.assert_not_called()
+ @pytest.mark.parametrize(
+ "should_use_incremental_field,expect_raise",
+ [
+ # Full-table sync: the COUNT is a full scan while extraction streams sequentially via a
+ # server cursor, so a statement_timeout here says nothing about whether extraction will
+ # succeed. It must degrade to an unknown total (0), not fail setup with a raw, retryable
+ # QueryCanceled that floods error tracking and Temporal re-attempts forever.
+ (False, False),
+ # Incremental sync: the COUNT shares its WHERE with the chunked read, so the timeout is
+ # predictive — re-raise so the caller surfaces the "add an index" guidance.
+ (True, True),
+ ],
+ )
+ def test_statement_timeout_degrades_for_full_table_but_re_raises_for_incremental(
+ self, should_use_incremental_field, expect_raise
+ ):
+ logger = structlog.get_logger()
+
+ cursor = mock.MagicMock()
+ cursor.execute.side_effect = psycopg.errors.QueryCanceled("canceling statement due to statement timeout")
+ count_query = _build_count_query("public", "users", False, None, None, None)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.capture_exception"
+ ) as mock_capture:
+ if expect_raise:
+ with pytest.raises(psycopg.errors.QueryCanceled):
+ _get_rows_to_sync(
+ cast(Any, cursor),
+ count_query,
+ logger,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ else:
+ assert (
+ _get_rows_to_sync(
+ cast(Any, cursor),
+ count_query,
+ logger,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ == 0
+ )
+
+ mock_capture.assert_not_called()
+
class TestPartitionedTableChunkSizing:
"""Incremental reads use per-child partition queries; no parent FETCH chunk cap."""