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 connection-limit refusals during schema discovery (#68599)

Tom Owerse8acb8a48808
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 2a05f6c4e34d..59677c62b346 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
@@ -322,13 +322,16 @@ def _is_connection_dropped_error(error: BaseException) -> bool:
def _is_connection_limit_error(error: BaseException) -> bool:
- """True if the source refused a new connection because it's at a connection limit.
-
- Distinct from `_is_connection_dropped_error`: the connection was never established, so this is
- only meaningful on the connect path (`_connect_with_dropped_retry`), not for mid-stream fetch
- failures on an already-open connection.
+ """True if the source refused a connection because it's at a connection limit.
+
+ Usually a connect-time refusal (`psycopg.OperationalError`), but a pooler that caches an
+ upstream login failure instead reveals the limit on the first query as a `ProtocolViolation`
+ ("server login has been failing, cached error: remaining connection slots are reserved ..."),
+ so match that type too. Distinct from `_is_connection_dropped_error` — the backend connection
+ was never usable — but the same transient capacity class: a slot frees the moment another
+ connection closes, so it stays retryable and is never a `NonRetryableError`.
"""
- if not isinstance(error, psycopg.OperationalError):
+ if not isinstance(error, psycopg.OperationalError | psycopg.errors.ProtocolViolation):
return False
message = " ".join(str(arg) for arg in error.args).lower()
return any(substring in message for substring in _CONNECTION_LIMIT_ERROR_SUBSTRINGS)
@@ -344,9 +347,10 @@ def _is_dropped_or_connect_timeout(error: BaseException) -> bool:
the reconnect just needs retrying. Connection-limit refusals ("sorry, too many clients already",
etc.) are likewise transient — a slot frees the moment another connection closes. Used by the
read/sync connect retry (`_connect_with_dropped_retry`) and the `offset_chunking` reconnect. The
- user-facing validation path (`get_schemas`, via `_retry_on_connection_dropped` directly)
- deliberately keeps failing fast on the same connect-time conditions, where a timeout usually means
- an unreachable host / unconfigured firewall (see `PostgresErrors` and `get_non_retryable_errors`).
+ schema-discovery path retries drops and connection-limit 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`).
"""
return (
_is_connection_dropped_error(error)
@@ -355,6 +359,20 @@ def _is_dropped_or_connect_timeout(error: BaseException) -> bool:
)
+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`) or a connection-limit refusal
+ (`_is_connection_limit_error`). Both are transient — a slot frees as connections close, and a
+ pooler-cached login failure clears once the upstream has capacity — 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.
+ """
+ return _is_connection_dropped_error(error) or _is_connection_limit_error(error)
+
+
def _raise_if_setup_connection_broken(connection: psycopg.Connection) -> None:
"""Surface a connection dropped during metadata discovery as a retryable error.
@@ -1194,7 +1212,15 @@ def _schemas_from_conn(
cursor.execute(
sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(METADATA_STATEMENT_TIMEOUT_MS))
)
- except psycopg.Error:
+ except psycopg.Error as e:
+ # A dropped or connection-limit-refused upstream fails on this first query too — a pooler
+ # surfacing "remaining connection slots are reserved ..." on the first statement. Rolling
+ # that back raises a misleading "the connection is lost" that buries the real cause, so
+ # re-raise the true error and let the discovery retry recover on a fresh connection. A
+ # live engine that merely rejects the SET (e.g. DuckDB) is not a drop/limit: clear the
+ # aborted transaction and fall back to the default timeout.
+ if _is_connection_dropped_error(e) or _is_connection_limit_error(e):
+ raise
connection.rollback()
discovered_tables, _qualify_with_schema = _get_discovered_tables(cursor, schema, names)
@@ -1284,9 +1310,11 @@ def get_schemas(
# either on connect or on the first discovery query (e.g. `SELECT version()` in
# `_is_duckdb_connection`). Retry the whole connect-and-discover cycle on a fresh connection so
# the retry spans both — otherwise the blip fails the discovery activity and surfaces as
- # captured error-tracking noise even though the next attempt would succeed. Permanent errors
- # (auth failures, SSL-required) re-raise immediately because `_is_connection_dropped_error` only
- # matches transient drops.
+ # 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.
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
@@ -1297,7 +1325,10 @@ def get_schemas(
connection.close()
return _retry_on_connection_dropped(
- _connect_and_discover, structlog.get_logger(), max_attempts=_MAX_SETUP_CONNECTION_DROPPED_RETRIES
+ _connect_and_discover,
+ structlog.get_logger(),
+ max_attempts=_MAX_SETUP_CONNECTION_DROPPED_RETRIES,
+ is_retryable=_is_dropped_or_connection_limit,
)
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 356572251dda..ef655797519e 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
@@ -1233,6 +1233,13 @@ class TestIsConnectionLimitError:
'connection failed: connection to server at "10.0.0.1", port 5432 failed: '
"FATAL: (EMAXCONNSESSION) max clients reached in session mode - max clients are limited to pool_size: 15"
),
+ # A pooler (PgBouncer-style) that caches an upstream login failure reveals the limit on
+ # the first query as a ProtocolViolation, not an OperationalError — it must still be
+ # recognised so the discovery retry recovers instead of surfacing it as captured noise.
+ psycopg.errors.ProtocolViolation(
+ "server login has been failing, cached error: remaining connection slots are "
+ "reserved for roles with the SUPERUSER attribute (server_login_retry)"
+ ),
],
)
def test_connection_limit_errors_are_detected(self, error):
@@ -2859,6 +2866,82 @@ class TestPostgresSchemaDiscovery:
dropped_connection.close.assert_called_once()
good_connection.close.assert_called_once()
+ def test_get_schemas_retries_pooler_connection_limit_on_discovery_query(self):
+ # A pooler can accept the connect and then reveal, on the first discovery query, that the
+ # customer database is out of connection slots — caching the upstream login failure as a
+ # ProtocolViolation ("server login has been failing, cached error: remaining connection slots
+ # are reserved ..."). It's a transient capacity condition (a slot frees as connections close),
+ # so discovery must retry on a fresh connection. Before the fix the SET-timeout `except` rolled
+ # the refused connection back — raising a misleading "the connection is lost" — and the
+ # discovery retry didn't cover connection-limit refusals, so it surfaced as captured noise.
+ refusal = psycopg.errors.ProtocolViolation(
+ "server login has been failing, cached error: remaining connection slots are reserved "
+ "for roles with the SUPERUSER attribute (server_login_retry)"
+ )
+ refused_connection = self._drop_on_execute_connection(refusal)
+ 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=[refused_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"}
+ refused_connection.close.assert_called_once()
+ good_connection.close.assert_called_once()
+ # 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_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
+ # same transient capacity class as a dropped connection, so discovery must retry on a fresh
+ # connect rather than fail the activity on the first blip — before the fix the discovery retry
+ # only covered drops, so a connection-limit refusal escaped on the first attempt.
+ refusal = psycopg.OperationalError(
+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: '
+ "FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute"
+ )
+ 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=[refusal, 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"}
+ good_connection.close.assert_called_once()
+
def test_get_schemas_does_not_retry_non_drop_error_during_discovery_query(self):
# A genuine XX000 internal error that isn't the pooler drop must propagate on the first
# discovery attempt — the discovery retry is scoped strictly to transient drops.