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): treat offset-chunking statement timeout as non-retryable (#63063)

Tom Owers34ac2067de84
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 9b509e9787f9..0dcf58efc5be 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -175,6 +175,30 @@ def _connect_with_dropped_retry(
time.sleep(min(2 * attempt, 30))
+def _statement_timeout_as_non_retryable(
+ error: BaseException,
+ *,
+ should_use_incremental_field: bool,
+ incremental_field: str | None,
+) -> QueryTimeoutException | None:
+ """Classify a statement_timeout (QueryCanceled) hit while streaming rows.
+
+ A chunk/fetch that exhausts the 10-min statement_timeout cannot complete in
+ time — usually a missing index on the incremental field or a deep OFFSET scan —
+ so retrying is futile. On incremental syncs, map it to the same non-retryable
+ QueryTimeoutException the server-cursor and windowed read paths already raise,
+ with an actionable message. Returns None when the error is not a statement
+ timeout, or the sync is non-incremental (the caller should re-raise the original
+ error so a full re-sync can reorder rows safely).
+ """
+ if not isinstance(error, psycopg.errors.QueryCanceled) or not should_use_incremental_field:
+ return None
+ return QueryTimeoutException(
+ f"10 min timeout statement reached. Please ensure your incremental field "
+ f"({incremental_field}) has an appropriate index created"
+ )
+
+
@dataclasses.dataclass(frozen=True)
class PostgresDiscoveredSchema:
source_catalog: str | None
@@ -2106,6 +2130,22 @@ def postgres_source(
else:
# Linear backoff on successive errors to make sure we give the read replica time to catch up
time.sleep(2 * successive_errors)
+ 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.
+ _safe_close_connection(connection)
+ timeout_error = _statement_timeout_as_non_retryable(
+ e,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ )
+ if timeout_error is not None:
+ raise timeout_error from e
+ raise
except (psycopg.errors.ProtocolViolation, psycopg.OperationalError) as e:
if not _is_connection_dropped_error(e):
_safe_close_connection(connection)
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 09be09e1968b..fb4ff76823a7 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -63,6 +63,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
_normalize_function_names,
_rls_active_from_conn,
_role_subject_to_rls,
+ _statement_timeout_as_non_retryable,
filter_postgres_incremental_fields,
get_foreign_keys,
get_leading_index_columns,
@@ -285,6 +286,49 @@ class TestConnectWithDroppedRetry:
assert connect.call_count == 3
+class TestStatementTimeoutAsNonRetryable:
+ @pytest.mark.parametrize(
+ "should_use_incremental_field,incremental_field,expected_substr",
+ [
+ # Incremental syncs map the timeout to a non-retryable QueryTimeoutException.
+ (True, "updated_at", "updated_at"),
+ # Full-table syncs must re-raise the raw QueryCanceled so a fresh re-sync can
+ # reorder rows; we only short-circuit incremental reads.
+ (False, None, None),
+ ],
+ )
+ def test_statement_timeout_mapping(self, should_use_incremental_field, incremental_field, expected_substr):
+ result = _statement_timeout_as_non_retryable(
+ psycopg.errors.QueryCanceled("canceling statement due to statement timeout"),
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ )
+ if expected_substr is None:
+ assert result is None
+ else:
+ assert isinstance(result, QueryTimeoutException)
+ assert expected_substr in str(result)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ psycopg.errors.ProtocolViolation("server conn crashed?"),
+ psycopg.OperationalError("server closed the connection unexpectedly"),
+ psycopg.errors.SerializationFailure("due to conflict with recovery"),
+ Exception("canceling statement due to statement timeout"),
+ ],
+ )
+ def test_non_statement_timeout_errors_are_not_mapped(self, error):
+ assert (
+ _statement_timeout_as_non_retryable(
+ error,
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ )
+ is None
+ )
+
+
class TestPostgresSourceForPipelineSchemaResolution:
@pytest.fixture
def source(self):