: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(warehouse-sources): drop unroutable addresses before connecting (#88582)
Daniel RCce3fa263c151
diff --git a/posthog/psycopg_helpers.py b/posthog/psycopg_helpers.pyindex c144353b684e..8d133689a4fc 100644--- a/posthog/psycopg_helpers.py+++ b/posthog/psycopg_helpers.py@@ -2,11 +2,56 @@ import socketimport ipaddressimport threadingfrom collections.abc import Callable+from functools import lru_cachefrom time import monotonicfrom typing import Anyimport psycopg+# A public address that is only ever connected to on a connectionless socket, so no packet is sent.+# Any global unicast v6 address would do — this one is a root nameserver.+_IPV6_ROUTE_PROBE_ADDRESS = "2001:500:2f::f"+++@lru_cache(maxsize=1)+def has_ipv6_route() -> bool:+ """Whether this host can route to the public IPv6 internet.++ A UDP `connect` picks a source address from the routing table without sending anything, so this+ costs a syscall and no network round trip. Cached: a pod's routing table does not change under+ it, and this sits in front of every outbound database connection.+ """+ try:+ with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as probe:+ probe.connect((_IPV6_ROUTE_PROBE_ADDRESS, 53))+ return True+ except OSError:+ return False+++def prefer_routable_addresses(addresses: list[str]) -> list[str]:+ """Drop addresses in a family this host cannot route to, unless that would leave nothing.++ A dual-stack hostname resolves IPv6-first by RFC 6724, so on an IPv4-only host every v6 address+ fails with ENETUNREACH. Keeping them costs more than latency: psycopg reports only the LAST+ attempt's error, so a trailing unroutable address masks the real, actionable error raised by an+ address that did reach the server — and a caller that decides what to do next by reading that+ message (see the libpq `options` fallback in the postgres source) then decides on the wrong one.++ A v6-only host keeps its addresses: unroutable beats nothing to connect to.+ """+ if has_ipv6_route():+ return addresses++ def _is_ipv6(address: str) -> bool:+ try:+ return ipaddress.ip_address(address.strip("[]")).version == 6+ except ValueError:+ return False++ routable = [a for a in addresses if not _is_ipv6(a)]+ return routable or addresses+def resolve_psycopg_hostaddr_with_timeout(host: str,@@ -66,4 +111,4 @@ def resolve_psycopg_hostaddr_with_timeout(if address not in seen:seen.add(address)addresses.append(address)- return addresses+ return prefer_routable_addresses(addresses)diff --git a/posthog/test/test_psycopg_helpers.py b/posthog/test/test_psycopg_helpers.pynew file mode 100644index 000000000000..5fb4f09c7fd3--- /dev/null+++ b/posthog/test/test_psycopg_helpers.py@@ -0,0 +1,38 @@+from unittest.mock import patch++from parameterized import parameterized++from posthog.psycopg_helpers import prefer_routable_addresses++_V6 = ["2600:1f16:1c4:661c:d148:b481:5246:e29d", "2600:1f16:1c4:6621:c8f:607d:ea25:4345"]+_V4 = ["13.58.18.166", "16.59.10.57"]+_HELPERS = "posthog.psycopg_helpers"+++class TestPreferRoutableAddresses:+ @parameterized.expand(+ [+ ("v6_first", [*_V6, *_V4]),+ ("interleaved", [_V6[0], _V4[0], _V6[1], _V4[1]]),+ ("v6_last", [*_V4, *_V6]),+ ]+ )+ def test_unroutable_addresses_are_dropped_when_ipv6_has_no_route(self, _name, addresses):+ # An unroutable address left at the end of the list is not just wasted latency: psycopg+ # reports only the last attempt's error, so it overwrites the real one from an address+ # that reached the server.+ with patch(f"{_HELPERS}.has_ipv6_route", return_value=False):+ assert prefer_routable_addresses(addresses) == _V4++ def test_every_address_stands_when_ipv6_routes(self):+ with patch(f"{_HELPERS}.has_ipv6_route", return_value=True):+ assert prefer_routable_addresses([*_V6, *_V4]) == [*_V6, *_V4]++ def test_a_v6_only_host_keeps_its_addresses(self):+ # Unroutable beats nothing to connect to — and the route probe can be wrong.+ with patch(f"{_HELPERS}.has_ipv6_route", return_value=False):+ assert prefer_routable_addresses(_V6) == _V6++ def test_anything_that_is_not_an_ipv6_address_survives(self):+ with patch(f"{_HELPERS}.has_ipv6_route", return_value=False):+ assert prefer_routable_addresses(["db.example.com", _V6[0]]) == ["db.example.com"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex f517db523d7b..0fe973b986fd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py@@ -12,6 +12,7 @@ import structlogfrom posthog.cloud_utils import is_cloudfrom posthog.models.integration import Integration+from posthog.psycopg_helpers import prefer_routable_addressesfrom posthog.utils import get_instance_regionfrom products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel@@ -160,7 +161,11 @@ def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:# connect would try them in. Pinning the first one gives up that fallback: if it is down,# nothing tries the next. Every address in the list passed the check above, so this costs# availability on multi-address hosts, not safety.- return HostResolution(connect_host=resolved_ips[0], error=None)+ #+ # That order is IPv6-first for a dual-stack host (RFC 6724), so on an IPv4-only worker the+ # pinned address is one nothing can route to and the connection can never succeed. Order by+ # what this host can actually reach before pinning.+ return HostResolution(connect_host=prefer_routable_addresses(resolved_ips)[0], error=None)def log_connection_open(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.pyindex 3eac1c632409..5669d3dd3cf0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix_is_host_safe,make_ssh_tunnel_factory,open_ssh_tunnel,+ resolve_safe_host,)_MIXINS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"@@ -127,6 +128,24 @@ class TestIsHostSafe(SimpleTestCase):valid, _ = _is_host_safe("good.example.com", team_id=999)assert valid+ @override_settings(CLOUD_DEPLOYMENT="US")+ def test_a_dual_stack_host_pins_an_address_the_worker_can_route_to(self):+ # A dual-stack name resolves IPv6-first, and the pinned address is the only one anything+ # connects to — so on an IPv4-only worker, pinning the resolver's choice can never connect.+ with (+ patch(+ f"{_MIXINS_MODULE}.socket.getaddrinfo",+ return_value=[+ (None, None, None, None, ("2600:1f16:1c4:661c:d148:b481:5246:e29d", 0)),+ (None, None, None, None, ("52.1.2.3", 0)),+ ],+ ),+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=False),+ ):+ resolution = resolve_safe_host("dual-stack.example.com", team_id=999)++ assert resolution.connect_host == "52.1.2.3"+@override_settings(CLOUD_DEPLOYMENT="US")def test_unresolvable_host_blocked(self):import socketdiff --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 b5d8d283aba3..39dcc3c383ce 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@@ -2290,20 +2290,28 @@ class TestResolveHostaddrWithTimeout:assert _resolve_hostaddr_with_timeout(host, 5432, 15) is Nonegetaddrinfo_mock.assert_not_called()- def test_resolved_hostname_returns_every_address_in_order(self):+ @pytest.mark.parametrize(+ "ipv6_routes,expected",+ [+ (True, ["2001:db8::5", "10.0.0.5"]),+ (False, ["10.0.0.5"]),+ ],+ )+ def test_resolved_hostname_returns_the_addresses_this_host_can_reach(self, ipv6_routes, expected):# 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.+ # collapsing to just the first would defeat psycopg's own per-address failover. An address+ # family with no route is worse than useless though: psycopg reports only the last attempt's+ # error, so a trailing unreachable address overwrites the real one from an address that did+ # reach the server, and callers that read that message decide on the wrong error.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)),]- with patch(- "posthog.psycopg_helpers.socket.getaddrinfo",- return_value=addrinfo,+ with (+ patch("posthog.psycopg_helpers.socket.getaddrinfo", return_value=addrinfo),+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=ipv6_routes),):- assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == ["2001:db8::5", "10.0.0.5"]+ assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == expecteddef test_resolved_hostname_dedupes_repeated_addresses(self):# getaddrinfo can repeat an address across otherwise-distinct tuples (e.g. differing canonical@@ -2405,6 +2413,7 @@ class TestConnectToPostgresMultiAddressFailover:"posthog.psycopg_helpers.socket.getaddrinfo",return_value=addrinfo,),+ patch("posthog.psycopg_helpers.has_ipv6_route", return_value=True),patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.psycopg.connect") as connect_mock,