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(data-imports): retry postgres connects that fail with too many open files (#79818)

Tom Owersa392e697dd47
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 9ce7725b8a76..f3d965064053 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
@@ -3,6 +3,7 @@ from __future__ import annotations
import re
import math
import time
+import errno
import socket
import ipaddress
import threading
@@ -331,12 +332,16 @@ _CONNECTION_LIMIT_ERROR_SUBSTRINGS = (
# yields — psycopg maps it to InternalError, not OperationalError, so it must be
# named explicitly or the type-based catch below would miss it. InternalError_ is the
# generic XX000 class Supavisor's "DbHandler exited" pooler drop arrives as; it's only
-# treated as a drop when its message matches the narrow pooler signature above.
+# treated as a drop when its message matches the narrow pooler signature above. OSError
+# is not psycopg-specific — it's the bare exception the connect-path socket setup raises on
+# EMFILE/ENFILE (see `_is_too_many_open_files_error`) — but every site below narrows it with
+# a message/errno-based predicate before retrying, so an unrelated OSError still re-raises.
_CONNECTION_DROPPED_ERROR_TYPES = (
psycopg.errors.ProtocolViolation,
psycopg.OperationalError,
psycopg.errors.IdleInTransactionSessionTimeout,
psycopg.errors.InternalError_,
+ OSError,
)
@@ -397,6 +402,21 @@ def _is_connection_limit_error(error: BaseException) -> bool:
return any(substring in message for substring in _CONNECTION_LIMIT_ERROR_SUBSTRINGS)
+def _is_too_many_open_files_error(error: BaseException) -> bool:
+ """True if the connect attempt failed because this worker process is out of file descriptors.
+
+ The tunnel/TLS socket setup on the connect path (`_tunnel_with_handshake_translation`,
+ psycopg's own socket creation before libpq takes over) raises a bare `OSError` — not a
+ psycopg exception — when `socket()` hits EMFILE (this process's fd table is full) or ENFILE
+ (the system-wide table is full). Same transient-capacity class as `_is_connection_limit_error`:
+ a descriptor frees the moment another connection/cursor/tunnel in this worker closes, so a
+ fresh connect after backoff usually succeeds. It's fd pressure on our own worker, never a
+ customer database or config problem, so it stays retryable and must never become a
+ `NonRetryableError`.
+ """
+ return isinstance(error, OSError) and error.errno in (errno.EMFILE, errno.ENFILE)
+
+
# Connect-time "server not ready" refusals: PostgreSQL rejects a *new* connection with SQLSTATE
# 57P03 (cannot_connect_now) while it is still coming up — a primary or standby booting ("the
# database system is starting up"), a server replaying WAL after a crash ("the database system is
@@ -432,25 +452,28 @@ def _is_dropped_or_connect_timeout(error: BaseException) -> bool:
"""Transient connect-path failures the import/read reconnect recovers from in process.
A mid-stream drop (`_is_connection_dropped_error`), a connect-time timeout, a connect-time
- connection-limit refusal (`_is_connection_limit_error`), or a connect-time "server not ready"
- refusal while the source is still starting up / recovering (`_is_server_starting_up_error`).
- psycopg raises `ConnectionTimeout` ("connection timeout expired") only while *establishing* a
- connection, never mid-query, so on the import/read path it's transient: the source was reachable
- moments earlier in the same sync, and the reconnect just needs retrying. Connection-limit
- refusals ("sorry, too many clients already", etc.) and server-still-starting-up refusals ("the
- database system is not yet accepting connections", etc.) are likewise transient — a slot frees
- 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, 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`).
+ connection-limit refusal (`_is_connection_limit_error`), a connect-time "server not ready"
+ refusal while the source is still starting up / recovering (`_is_server_starting_up_error`), or
+ this worker process running out of file descriptors while opening the socket
+ (`_is_too_many_open_files_error`). psycopg raises `ConnectionTimeout` ("connection timeout
+ expired") only while *establishing* a connection, never mid-query, so on the import/read path
+ it's transient: the source was reachable moments earlier in the same sync, and the reconnect
+ just needs retrying. Connection-limit refusals ("sorry, too many clients already", etc.) and
+ server-still-starting-up refusals ("the database system is not yet accepting connections", etc.)
+ are likewise transient — a slot frees the moment another connection closes, and the server
+ begins accepting connections once startup/recovery finishes. A file-descriptor exhaustion is the
+ same shape on our side of the wire: a descriptor frees the moment another connection/cursor in
+ this worker closes. 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,
+ 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)
or _is_connection_limit_error(error)
or _is_server_starting_up_error(error)
+ or _is_too_many_open_files_error(error)
or isinstance(error, psycopg.errors.ConnectionTimeout)
)
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 ea0abdec9801..7b6274eae230 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
@@ -1,3 +1,4 @@
+import errno
import socket
import threading
from collections.abc import Generator, Iterable, Iterator
@@ -1772,6 +1773,12 @@ class TestDroppedOrConnectTimeout:
'connection failed: connection to server at "10.0.0.1", port 5432 failed: '
"FATAL: the database system is shutting down"
),
+ # This worker's process-wide (EMFILE) or system-wide (ENFILE) file-descriptor table is
+ # full while opening the socket for a fresh connect. Transient on our side of the wire —
+ # a descriptor frees the moment another connection/cursor in this worker closes — so the
+ # connect retry must recover instead of failing the whole activity on the first blip.
+ OSError(errno.EMFILE, "Too many open files"),
+ OSError(errno.ENFILE, "Too many open files in system"),
],
)
def test_transient_connect_path_errors_are_retryable(self, error):
@@ -1794,6 +1801,9 @@ class TestDroppedOrConnectTimeout:
"FATAL: the database system is not accepting connections "
"DETAIL: Hot standby mode is disabled."
),
+ # An unrelated OSError must not be absorbed just because OSError is now one of the
+ # caught types — only the EMFILE/ENFILE fd-exhaustion errno is retryable.
+ OSError(errno.ENOSPC, "No space left on device"),
],
)
def test_permanent_and_non_connect_errors_are_not_retryable(self, error):