: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): bound DNS resolution so stalled lookups fail fast (#67238)
Tom Owersfe91e1b443bf
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 aedc0b8229b1..3cc9b4356f6a 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,9 @@ from __future__ import annotationsimport reimport mathimport time+import socket+import ipaddress+import threadingimport collectionsimport dataclassesfrom collections.abc import Callable, Iterator@@ -557,6 +560,66 @@ def _is_invalid_ssl_negotiation_response(error: BaseException) -> bool:return _INVALID_SSL_NEGOTIATION_RESPONSE_SUBSTRING in " ".join(str(arg) for arg in error.args).lower()+def _is_ip_literal(host: str) -> bool:+ try:+ ipaddress.ip_address(host.strip("[]"))+ return True+ except ValueError:+ 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`.++ 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.++ 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+ re-raises that failure) exactly as before and the existing "Name or service not known"+ classification still applies. Only a resolver that exceeds `timeout` becomes an `OperationalError`;+ its message deliberately avoids the non-retryable "could not translate host name" /+ "Name or service not known" fragments because a stalled resolver is usually transient.+ """+ if not host or host.startswith("/") or _is_ip_literal(host):+ return None++ addrinfo: list[Any] = []+ lookup_error: list[BaseException] = []++ def _lookup() -> None:+ try:+ addrinfo.extend(socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM))+ except BaseException as e: # noqa: BLE001 — surfaced to the caller below via lookup_error+ lookup_error.append(e)++ # Daemon thread so a stalled getaddrinfo can be abandoned without blocking worker shutdown or+ # piling up non-daemon threads — the OS resolver bounds the orphaned lookup on its own.+ thread = threading.Thread(target=_lookup, daemon=True)+ thread.start()+ thread.join(timeout)+ if thread.is_alive():+ raise psycopg.OperationalError(f"Timed out resolving database host name after {timeout}s")+ # A genuine resolution failure falls through to None so psycopg connects and re-raises it,+ # preserving the existing "Name or service not known" classification.+ if lookup_error:+ if isinstance(lookup_error[0], OSError):+ return None+ raise lookup_error[0]+ 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])++def _connect_with_options_fallback(**connect_kwargs: Any) -> psycopg.Connection:"""`psycopg.connect` that retries without the libpq `options` startup parameter when theserver rejects it.@@ -594,6 +657,12 @@ def _connect_to_postgres(# cleanly. We always force UTF8 and append any caller-supplied `options` after it.caller_options = kwargs.pop("options", None)options = f"{FORCE_UTF8_CLIENT_ENCODING} {caller_options}" if caller_options else FORCE_UTF8_CLIENT_ENCODING+ # 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"] = hostaddrtry: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.pyindex 505fb93df696..a6a6c1891088 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,5 @@+import socket+import threadingfrom collections.abc import Generator, Iterable, Iteratorfrom contextlib import contextmanagerfrom datetime import UTC, date, datetime, time, timedelta, timezone@@ -99,6 +101,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_pk_uniqueness_probe_timeout_error,_raise_if_setup_connection_broken,_recovery_conflict_abort_error,+ _resolve_hostaddr_with_timeout,_rls_active_from_conn,_role_subject_to_rls,_safe_close_connection,@@ -1384,6 +1387,67 @@ class TestConnectForcesUtf8ClientEncoding:assert connect_mock.call_args.kwargs["options"] == f"{FORCE_UTF8_CLIENT_ENCODING} -c statement_timeout=5000"+# psycopg3 resolves hostnames Python-side (`socket.getaddrinfo`) before libpq's `connect_timeout`+# applies, so a stalled resolver hangs the threaded sync activity until Temporal's+# `start_to_close_timeout` cancels it, surfacing a misleading `CancelledError`. We bound the lookup+# and hand psycopg the address via `hostaddr`.+class TestResolveHostaddrWithTimeout:+ @pytest.mark.parametrize(+ "host",+ [+ "127.0.0.1", # already an IP (also the SSH-tunnel local endpoint) — nothing to resolve+ "::1",+ "[::1]", # bracketed IPv6 literal — exercises the host.strip("[]") path in _is_ip_literal+ "/var/run/postgresql", # Unix-socket path+ "",+ ],+ )+ def test_hosts_that_need_no_lookup_short_circuit(self, host):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo"+ ) as getaddrinfo_mock:+ assert _resolve_hostaddr_with_timeout(host, 5432, 15) is None+ getaddrinfo_mock.assert_not_called()++ def test_resolved_hostname_returns_first_address(self):+ 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.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"++ 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+ # its own "Name or service not known" error still reaches the non-retryable classifier.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ side_effect=socket.gaierror(-2, "Name or service not known"),+ ):+ assert _resolve_hostaddr_with_timeout("does-not-exist.example.com", 5432, 15) is None++ def test_stalled_resolver_raises_fast_retryable_error(self):+ release = threading.Event()+ try:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ side_effect=lambda *a, **k: release.wait(),+ ):+ with pytest.raises(psycopg.OperationalError) as exc_info:+ _resolve_hostaddr_with_timeout("db.example.com", 5432, 0.1)+ finally:+ release.set() # let the orphaned lookup thread exit++ message = str(exc_info.value)+ assert "Timed out resolving database host name" in message+ # Must stay retryable: it must not carry any of the non-retryable resolution fragments.+ assert "could not translate host name" not in message+ assert "Name or service not known" not in message++# 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.