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): retry schema discovery on a hot-standby recovery conflict (#76114)

Tom Owers3139230df4f7
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 bb4f584cd8ec..c1b8fa991d88 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
@@ -427,9 +427,10 @@ def _is_dropped_or_connect_timeout(error: BaseException) -> bool:
the moment another connection closes, and the server begins accepting connections once
startup/recovery finishes. Used by the read/sync connect retry (`_connect_with_dropped_retry`)
and the `offset_chunking` reconnect. The schema-discovery path retries drops, connection-limit
- refusals and server-startup refusals too (via `_is_dropped_or_connection_limit`) but deliberately
- keeps failing fast on connect-time *timeouts*, where a timeout usually means an unreachable host /
- unconfigured firewall (see `PostgresErrors` and `get_non_retryable_errors`).
+ refusals, server-startup refusals, and recovery conflicts too (via
+ `_is_dropped_or_connection_limit`) but deliberately keeps failing fast on connect-time *timeouts*,
+ where a timeout usually means an unreachable host / unconfigured firewall (see `PostgresErrors`
+ and `get_non_retryable_errors`).
"""
return (
_is_connection_dropped_error(error)
@@ -443,17 +444,24 @@ def _is_dropped_or_connection_limit(error: BaseException) -> bool:
"""Transient conditions the background schema-discovery retry recovers from in process.
A mid-stream drop (`_is_connection_dropped_error`), a connection-limit refusal
- (`_is_connection_limit_error`), or a "server not ready" refusal while the source is still
- starting up / recovering (`_is_server_starting_up_error`). All are transient — a slot frees as
- connections close, a pooler-cached login failure clears once the upstream has capacity, and the
- server begins accepting connections once startup/recovery finishes — so discovery retries them on
- a fresh connection instead of failing the activity and surfacing captured error-tracking noise.
- Unlike the read/sync connect path (`_is_dropped_or_connect_timeout`), a connect-time *timeout* is
- deliberately excluded: during discovery a timeout usually means a now-unreachable host, which
- should fail fast rather than burn the retry budget.
+ (`_is_connection_limit_error`), a "server not ready" refusal while the source is still starting
+ up / recovering (`_is_server_starting_up_error`), or a hot-standby recovery conflict
+ (`_is_recovery_conflict_error`). All are transient — a slot frees as connections close, a
+ pooler-cached login failure clears once the upstream has capacity, the server begins accepting
+ connections once startup/recovery finishes, and a recovery conflict clears once the replica's WAL
+ replay moves past the conflicting row versions — so discovery retries them on a fresh connection
+ instead of failing the activity and surfacing captured error-tracking noise. The import read path
+ already retries the same recovery-conflict condition mid-stream (see `handle_recovery_conflict`);
+ discovery just needed the same treatment. Unlike the read/sync connect path
+ (`_is_dropped_or_connect_timeout`), a connect-time *timeout* is deliberately excluded: during
+ discovery a timeout usually means a now-unreachable host, which should fail fast rather than burn
+ the retry budget.
"""
return (
- _is_connection_dropped_error(error) or _is_connection_limit_error(error) or _is_server_starting_up_error(error)
+ _is_connection_dropped_error(error)
+ or _is_connection_limit_error(error)
+ or _is_server_starting_up_error(error)
+ or _is_recovery_conflict_error(error)
)
@@ -1465,8 +1473,11 @@ def get_schemas(
# captured error-tracking noise even though the next attempt would succeed. Connection-limit
# refusals ("remaining connection slots are reserved", "sorry, too many clients already") are
# retried the same way — the customer's database is momentarily out of slots and frees one as
- # connections close. Permanent errors (auth failures, SSL-required) re-raise immediately because
- # `_is_dropped_or_connection_limit` matches only transient drops and connection-limit refusals.
+ # connections close. A hot-standby recovery conflict ("canceling statement due to conflict with
+ # recovery") is retried too — the same transient condition the import read path already recovers
+ # from mid-stream — since discovery can run against a read replica just like the row-copy path.
+ # Permanent errors (auth failures, SSL-required) re-raise immediately because
+ # `_is_dropped_or_connection_limit` matches only these known-transient conditions.
def _connect_and_discover() -> dict[str, PostgresDiscoveredSchema]:
connection = _connect_to_postgres(
host=host, port=port, database=database, user=user, password=password, require_ssl=require_ssl
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 a55669784f32..e5921a7e4b38 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
@@ -3537,6 +3537,44 @@ class TestPostgresSchemaDiscovery:
# The refused connection was never rolled back — that's what masked the real cause before.
refused_connection.rollback.assert_not_called()
+ def test_get_schemas_retries_recovery_conflict_during_discovery_query(self):
+ # A hot-standby (read replica) can cancel the discovery catalog scan with a
+ # SerializationFailure ("canceling statement due to conflict with recovery") once WAL replay
+ # needs to remove row versions the query is still reading — the same transient condition the
+ # import read path already retries mid-stream. Before the fix, `_is_dropped_or_connection_limit`
+ # didn't recognize it, so the conflict escaped on the first attempt and surfaced as captured
+ # error-tracking noise instead of retrying discovery on a fresh connection.
+ conflict = psycopg.errors.SerializationFailure(
+ "canceling statement due to conflict with recovery\n"
+ "DETAIL: User query might have needed to see row versions that must be removed."
+ )
+ conflicted_connection = self._drop_on_execute_connection(conflict)
+ good_connection = self._mock_connection(
+ [("public", "users")],
+ [("public", "users", "id", "integer", "NO", 1)],
+ )
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect",
+ side_effect=[conflicted_connection, good_connection],
+ ) as connect_mock:
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.time.sleep"
+ ):
+ schemas = get_schemas(
+ host="localhost",
+ port=5432,
+ database="postgres",
+ user="postgres",
+ password="postgres",
+ schema="",
+ )
+
+ assert connect_mock.call_count == 2
+ assert set(schemas.keys()) == {"public.users"}
+ conflicted_connection.close.assert_called_once()
+ good_connection.close.assert_called_once()
+
def test_get_schemas_retries_connection_limit_refused_on_connect(self):
# The customer database can refuse the discovery connect outright once it's out of slots
# ("remaining connection slots are reserved for roles with the SUPERUSER attribute"). It's the