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): keep every resolved Postgres address for connection failover (#77483)

Tom Owers6cd5f38e3130
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 98763dd21712..bb4f584cd8ec 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
@@ -701,18 +701,24 @@ def _is_ip_literal(host: str) -> bool:
return False
-def _resolve_hostaddr_with_timeout(host: str, port: int, timeout: float) -> str | None:
- """Resolve `host` to an IP under a wall-clock `timeout`, to hand psycopg as `hostaddr`.
+def _resolve_hostaddr_with_timeout(host: str, port: int, timeout: float) -> list[str] | None:
+ """Resolve `host` to its addresses under a wall-clock `timeout`, to hand psycopg as `hostaddr`.
psycopg3 resolves hostnames in Python before libpq ever connects — `conninfo_attempts` calls
- `socket.getaddrinfo` (see psycopg/_conninfo_attempts.py) and only then passes the resolved address
- to libpq. `connect_timeout` bounds establishing the socket, never that name lookup, so a stalled
- or unresponsive resolver blocks the (threaded, non-interruptible) sync activity for as long as the
- OS resolver takes. It never trips `connect_timeout`; the activity instead runs until Temporal's
- `start_to_close_timeout` cancels the worker thread mid-`getaddrinfo`, surfacing a misleading
- `CancelledError` and burning the whole activity's retry budget. Resolving here and passing the
- address via `hostaddr` (which makes psycopg skip its own lookup) turns a stalled resolver into a
- fast, retryable error instead.
+ `socket.getaddrinfo` (see psycopg/_conninfo_attempts.py) and only then passes the resolved
+ address(es) to libpq. `connect_timeout` bounds establishing the socket, never that name lookup, so
+ a stalled or unresponsive resolver blocks the (threaded, non-interruptible) sync activity for as
+ long as the OS resolver takes. It never trips `connect_timeout`; the activity instead runs until
+ Temporal's `start_to_close_timeout` cancels the worker thread mid-`getaddrinfo`, surfacing a
+ misleading `CancelledError` and burning the whole activity's retry budget. Resolving here turns a
+ stalled resolver into a fast, retryable error instead.
+
+ Returns every resolved address, not just one: when a host resolves to more than one address (most
+ commonly a dual-stack host with both an AAAA and an A record), `Connection.connect` tries each
+ `hostaddr` attempt in turn and only fails once all of them do (see `conninfo_attempts` /
+ `Connection.connect`'s attempt loop) — a network that can't route one address family (e.g. no IPv6
+ egress) still connects via the other. Handing psycopg a single pre-resolved `hostaddr` would
+ collapse that to one attempt and turn an unreachable-address-family blip into a hard failure.
Returns None when there is nothing to bound — an empty host, a Unix-socket path, or a host that is
already an IP literal — and also on a genuine resolution failure, so psycopg connects (and
@@ -749,8 +755,17 @@ def _resolve_hostaddr_with_timeout(host: str, port: int, timeout: float) -> str
if not addrinfo:
return None
# sockaddr[0] is the address string (getaddrinfo types it as str | int across the IPv4/IPv6
- # tuple variants, so coerce to satisfy the str return type).
- return str(addrinfo[0][4][0])
+ # tuple variants, so coerce to satisfy the str return type). Dedupe while preserving order —
+ # getaddrinfo can repeat an address across otherwise-distinct tuples (e.g. differing canonical
+ # names), and a duplicate `hostaddr` attempt would just fail the same way twice.
+ seen: set[str] = set()
+ addresses: list[str] = []
+ for info in addrinfo:
+ address = str(info[4][0])
+ if address not in seen:
+ seen.add(address)
+ addresses.append(address)
+ return addresses
def _connect_with_options_fallback(**connect_kwargs: Any) -> psycopg.Connection:
@@ -793,9 +808,14 @@ def _connect_to_postgres(
# Bound psycopg's Python-side DNS lookup in production (see `_resolve_hostaddr_with_timeout`).
# Dev/test connect to local or fake hosts, so skip the real lookup there — mirrors `_get_sslmode`.
if not (settings.TEST or settings.DEBUG or settings.E2E_TESTING):
- hostaddr = _resolve_hostaddr_with_timeout(host, port, connect_timeout)
- if hostaddr is not None:
- kwargs["hostaddr"] = hostaddr
+ addresses = _resolve_hostaddr_with_timeout(host, port, connect_timeout)
+ if addresses:
+ # A comma-separated `host`/`hostaddr` pair of matching length is how psycopg/libpq
+ # represent multiple attempts (see `split_attempts` in psycopg/_conninfo_utils.py) — this
+ # keeps its per-address failover intact for a dual-stack host instead of pinning the
+ # connection to whichever single address `getaddrinfo` happened to return first.
+ host = ",".join([host] * len(addresses))
+ kwargs["hostaddr"] = ",".join(addresses)
try:
return _connect_with_options_fallback(
host=host,
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 14abe094a019..a55669784f32 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
@@ -1945,16 +1945,33 @@ class TestResolveHostaddrWithTimeout:
assert _resolve_hostaddr_with_timeout(host, 5432, 15) is None
getaddrinfo_mock.assert_not_called()
- def test_resolved_hostname_returns_first_address(self):
+ def test_resolved_hostname_returns_every_address_in_order(self):
+ # A dual-stack host resolving to more than one address must return all of them, in order —
+ # collapsing to just the first would defeat psycopg's own per-address failover and turn an
+ # unreachable address family (e.g. no IPv6 egress) into a hard connection failure instead of
+ # falling back to the other address.
addrinfo = [
+ (socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("2001:db8::5", 5432)),
(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.5", 5432)),
- (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.6", 5432)),
]
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",
return_value=addrinfo,
):
- assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == "10.0.0.5"
+ assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == ["2001:db8::5", "10.0.0.5"]
+
+ def test_resolved_hostname_dedupes_repeated_addresses(self):
+ # getaddrinfo can repeat an address across otherwise-distinct tuples (e.g. differing canonical
+ # names); a duplicate must not produce a duplicate connection attempt.
+ addrinfo = [
+ (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.5", 5432)),
+ (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.5", 5432)),
+ ]
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",
+ return_value=addrinfo,
+ ):
+ assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == ["10.0.0.5"]
def test_genuine_resolution_failure_falls_through(self):
# A host that doesn't resolve must return None (not raise) so psycopg connects as before and
@@ -1984,6 +2001,73 @@ class TestResolveHostaddrWithTimeout:
assert "Name or service not known" not in message
+# A dual-stack host (e.g. Neon) can resolve to both an IPv6 and an IPv4 address. Passing psycopg a
+# single pre-resolved `hostaddr` collapses its connection attempt to just that one address, so a
+# network that can't route that address family (no IPv6 egress) fails outright instead of falling
+# back to the other address the way an unresolved `host` would. `_connect_to_postgres` must expand
+# every resolved address into a matching-length comma-separated `host`/`hostaddr` pair so psycopg's
+# own attempt loop (`Connection.connect`) still tries each one in turn.
+class TestConnectToPostgresMultiAddressFailover:
+ def test_expands_every_resolved_address_for_psycopg_failover(self):
+ addrinfo = [
+ (socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("2001:db8::1", 5432)),
+ (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("203.0.113.5", 5432)),
+ ]
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.settings"
+ ) as mock_settings,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",
+ return_value=addrinfo,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect"
+ ) as connect_mock,
+ ):
+ mock_settings.TEST = False
+ mock_settings.DEBUG = False
+ mock_settings.E2E_TESTING = False
+ _connect_to_postgres(
+ host="db.example.com",
+ port=5432,
+ database="postgres",
+ user="user",
+ password="password",
+ )
+
+ assert connect_mock.call_args.kwargs["host"] == "db.example.com,db.example.com"
+ assert connect_mock.call_args.kwargs["hostaddr"] == "2001:db8::1,203.0.113.5"
+
+ def test_single_resolved_address_keeps_plain_host_and_hostaddr(self):
+ addrinfo = [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("203.0.113.5", 5432))]
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.settings"
+ ) as mock_settings,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",
+ return_value=addrinfo,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect"
+ ) as connect_mock,
+ ):
+ mock_settings.TEST = False
+ mock_settings.DEBUG = False
+ mock_settings.E2E_TESTING = False
+ _connect_to_postgres(
+ host="db.example.com",
+ port=5432,
+ database="postgres",
+ user="user",
+ password="password",
+ )
+
+ assert connect_mock.call_args.kwargs["host"] == "db.example.com"
+ assert connect_mock.call_args.kwargs["hostaddr"] == "203.0.113.5"
+
+
# Transaction-mode poolers (Supabase Supavisor on :6543, PgBouncer transaction mode, AWS RDS Proxy)
# reject the libpq `options` startup parameter we send to pin client_encoding=UTF8. When they do, we
# drop `options` and retry rather than failing the connection.