: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(salesforce): stop retrying a sync whose instance host no longer exists (#113259)
Tom Owers808be60e41e9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.pyindex ab0a0e16fba5..54e00c31274b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py@@ -1,6 +1,8 @@import time+import socketfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional+from urllib.parse import urlparsefrom requests import Responsefrom requests.exceptions import (@@ -10,6 +12,10 @@ from requests.exceptions import ()from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets+from products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (+ DeadlineExceededError,+ run_with_deadline,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth@@ -79,6 +85,40 @@ class SalesforceAuthRequestError(Exception):raise cls(error_message, response=response)+# Matched by `SalesforceSource.get_non_retryable_errors`. It carries no host, so it is safe to store.+INSTANCE_HOST_NOT_FOUND_ERROR = "Salesforce instance host does not resolve"+_INSTANCE_HOST_LOOKUP_TIMEOUT_SECONDS = 10+++class SalesforceInstanceNotFoundError(Exception):+ """The org's instance host has no DNS record, so no attempt can reach the token endpoint."""+++def _instance_host_missing(instance_url: str) -> bool:+ """Whether DNS answers that the instance host does not exist.++ The egress proxy reports a host it cannot resolve as a 502 on CONNECT, the same as a real proxy+ blip. A lookup of our own tells the two apart. A resolver that fails or times out is no answer,+ so it counts as not missing and the error stays retryable.+ """+ host = urlparse(instance_url).hostname+ if not host:+ return False+ try:+ run_with_deadline(+ lambda: socket.getaddrinfo(host, 443, proto=socket.IPPROTO_TCP),+ timeout_seconds=_INSTANCE_HOST_LOOKUP_TIMEOUT_SECONDS,+ thread_name="salesforce-instance-resolve",+ )+ except socket.gaierror as e:+ # Only NXDOMAIN is an answer about the name. Every other errno, EAI_FAIL included, is the+ # resolver failing, which says nothing about the org.+ return e.errno == socket.EAI_NONAME+ except (DeadlineExceededError, UnicodeError):+ return False+ return False++# Salesforce serializes OAuth token requests per connected app: when a refresh for the same app# arrives while another is still in flight (parallel schema syncs sharing one connection commonly# do this), it rejects the duplicate with a 400 "token request is already being processed". The@@ -123,6 +163,10 @@ def salesforce_refresh_access_token(refresh_token: str, instance_url: str, *, ca# activity before it reads a row, and the sync restarts from scratch.attempt += 1if attempt >= _MAX_TOKEN_REFRESH_ATTEMPTS:+ # A deleted org, or one whose My Domain was renamed, leaves an instance host with no+ # DNS record. That fails the same way on every run, so it must not stay retryable.+ if _instance_host_missing(instance_url):+ raise SalesforceInstanceNotFoundError(INSTANCE_HOST_NOT_FOUND_ERROR) from Noneraisetime.sleep(min(0.5 * attempt, 5))continuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/source.pyindex 2a033c65ef23..de23a6b9fa4e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/source.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_SalesforceSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth import (+ INSTANCE_HOST_NOT_FOUND_ERROR,salesforce_refresh_access_token,)from products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.salesforce import (@@ -81,6 +82,10 @@ class SalesforceSource(ResumableSource[SalesforceSourceConfig, SalesforceResumeC# above never match it. Key off the stable error_description returned by Salesforce# when the refresh token is expired/revoked — reconnecting is the only fix."expired access/refresh token": "Your Salesforce connection has expired or been revoked. Please reconnect the source.",+ INSTANCE_HOST_NOT_FOUND_ERROR: (+ "Your Salesforce org's address no longer exists, so the org may be deleted or its My Domain "+ "renamed. Reconnect your Salesforce account, then re-enable the sync."+ ),}def get_schemas(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.pyindex 33aa1ce4009d..8196e9e8271a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/test/test_auth.py@@ -1,4 +1,5 @@import json+import socketimport pytestimport unittest.mock@@ -158,7 +159,16 @@ def test_refresh_retries_transient_transport_error_then_succeeds():assert mock_sleep.call_count == 2-def test_refresh_raises_transport_error_after_exhausting_retries():+ "lookup_error",+ [+ None,+ socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution"),+ socket.gaierror(socket.EAI_FAIL, "Non-recoverable failure in name resolution"),+ ],+ ids=["host_resolves", "resolver_blip", "resolver_failure"],+)+def test_refresh_raises_transport_error_after_exhausting_retries(lookup_error):items = [requests.exceptions.ProxyError("Cannot connect to proxy") for _ in range(auth._MAX_TOKEN_REFRESH_ATTEMPTS)]with (@@ -169,6 +179,10 @@ def test_refresh_raises_transport_error_after_exhausting_retries():unittest.mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep") as mock_sleep,+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.socket.getaddrinfo",+ side_effect=lookup_error,+ ),pytest.raises(requests.exceptions.ProxyError),):_ = auth.salesforce_refresh_access_token("something", "https://login.salesforce.com")@@ -176,6 +190,32 @@ def test_refresh_raises_transport_error_after_exhausting_retries():assert mock_sleep.call_count == auth._MAX_TOKEN_REFRESH_ATTEMPTS - 1+def test_refresh_stops_retrying_when_instance_host_does_not_exist():+ from products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.source import SalesforceSource++ items = [requests.exceptions.ProxyError("Cannot connect to proxy") for _ in range(auth._MAX_TOKEN_REFRESH_ATTEMPTS)]++ with (+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.make_tracked_session",+ return_value=_session_with_side_effects(items),+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep"+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.socket.getaddrinfo",+ side_effect=socket.gaierror(socket.EAI_NONAME, "Name or service not known"),+ ),+ pytest.raises(auth.SalesforceInstanceNotFoundError) as exc,+ ):+ _ = auth.salesforce_refresh_access_token("something", "https://deleted-org.my.salesforce.com")++ patterns = SalesforceSource().get_non_retryable_errors()+ assert any(pattern in str(exc.value) for pattern in patterns)+ assert "deleted-org" not in str(exc.value)++def test_refresh_retries_transient_token_request_then_succeeds():# Salesforce locks concurrent token requests with a 400 "token request is already being# processed"; the lock clears, so a retry should recover instead of failing the sync.