: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): retry recovery conflicts that surface as QueryCanceled during setup (#66651)
Tom Owersb0b78e6c4763
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 f99ec8ab1219..4f54a2c2e7f6 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@@ -2617,11 +2617,11 @@ def postgres_source(conn.autocommit = Truereturn conn- # A hot-standby recovery conflict ("terminating connection due to conflict with recovery")- # terminates the whole connection mid-probe, so autocommit alone can't isolate it — every- # subsequent probe on the dead connection fails too. Reconnect and retry the metadata- # probes a bounded number of times with backoff, mirroring how the read loop recovers from- # the same conflict. Only once the conflicts are sustained do we raise the non-retryable+ # A hot-standby recovery conflict ("conflict with recovery") cancels or terminates the probe+ # mid-flight, so autocommit alone can't isolate it — the connection is left unusable and+ # every subsequent probe on it fails too. Reconnect and retry the metadata probes a bounded+ # number of times with backoff, mirroring how the read loop recovers from the same conflict.+ # Only once the conflicts are sustained do we raise the non-retryable# "successive SerializationFailure errors" abort the read path already uses, rather than# letting Temporal re-run setup straight back into the same wall.setup_recovery_conflicts = 0@@ -2864,7 +2864,14 @@ def postgres_source(# retryable dropped-connection error instead._raise_if_setup_connection_broken(connection)break- except psycopg.errors.SerializationFailure as e:+ except (psycopg.errors.SerializationFailure, psycopg.errors.QueryCanceled) as e:+ # A hot-standby recovery conflict surfaces as either SerializationFailure (the+ # transaction was aborted — "terminating connection due to conflict with recovery")+ # or QueryCanceled (the statement was canceled — "canceling statement due to conflict+ # with recovery", e.g. a replica reconnect) depending on the conflict and the server.+ # Both are the same transient condition and recover on reconnect. Any other+ # QueryCanceled here is a statement_timeout and must re-raise. QueryCanceled subclasses+ # OperationalError, so this clause must precede the connection-dropped handler below.if "conflict with recovery" not in "".join(e.args):raise# Connection is dead; close defensively before reconnecting.@@ -2873,7 +2880,7 @@ def postgres_source(if setup_recovery_conflicts >= _MAX_SETUP_RECOVERY_CONFLICT_RETRIES:raise _recovery_conflict_abort_error(setup_recovery_conflicts) from elogger.debug(- f"SerializationFailure during table setup ({e}). Reconnecting and retrying "+ f"Recovery conflict during table setup ({e}). Reconnecting and retrying "f"(attempt {setup_recovery_conflicts}/{_MAX_SETUP_RECOVERY_CONFLICT_RETRIES})")time.sleep(min(2 * setup_recovery_conflicts, 30))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 16f38d3739f4..65f3251405d9 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@@ -879,8 +879,22 @@ class TestPostgresSourceSetupRecoveryConflictRetry:db_incremental_field_last_value=None,)- def test_sustained_recovery_conflict_during_setup_aborts_non_retryably(self):- err = psycopg.errors.SerializationFailure("terminating connection due to conflict with recovery")+ @pytest.mark.parametrize(+ "err",+ [+ # A hot-standby recovery conflict surfaces as either SerializationFailure (the+ # transaction was aborted) or QueryCanceled (the statement was canceled, e.g. a replica+ # reconnect) — the same transient condition. Both must be retried in-process during setup+ # and end in the non-retryable abort once sustained; before the QueryCanceled fix that+ # flavor escaped on the first probe and failed the whole activity.+ psycopg.errors.SerializationFailure("terminating connection due to conflict with recovery"),+ psycopg.errors.QueryCanceled(+ "canceling statement due to conflict with recovery\n"+ "DETAIL: User query might have conflicted with replica reconnect."+ ),+ ],+ )+ def test_sustained_recovery_conflict_during_setup_aborts_non_retryably(self, err):connection = self._make_failing_connection(err)with patch(@@ -898,17 +912,24 @@ class TestPostgresSourceSetupRecoveryConflictRetry:# Each retry reconnects, so connect is called once per attempt.assert connect_mock.call_count == _MAX_SETUP_RECOVERY_CONFLICT_RETRIES- def test_non_recovery_serialization_failure_during_setup_is_not_retried(self):- # A serialization failure unrelated to standby recovery must propagate immediately —- # the retry is scoped strictly to "conflict with recovery".- err = psycopg.errors.SerializationFailure("could not serialize access due to concurrent update")+ @pytest.mark.parametrize(+ "err",+ [+ # The in-process retry is scoped strictly to "conflict with recovery": a serialization+ # failure from a concurrent update, and a QueryCanceled from a statement_timeout, are+ # both unrelated to standby recovery and must propagate on the first probe.+ psycopg.errors.SerializationFailure("could not serialize access due to concurrent update"),+ psycopg.errors.QueryCanceled("canceling statement due to statement timeout"),+ ],+ )+ def test_non_recovery_conflict_during_setup_is_not_retried(self, err):connection = self._make_failing_connection(err)with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect",return_value=connection,) as connect_mock:- with pytest.raises(psycopg.errors.SerializationFailure):+ with pytest.raises(type(err)):self._call_postgres_source()assert connect_mock.call_count == 1