: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): retry transient token-request lock with in-process backoff (#66872)
Tom Owers2e6941b3e9ac
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 8e6058212957..d39188d78af9 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,3 +1,4 @@+import timefrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional@@ -75,20 +76,38 @@ class SalesforceAuthRequestError(Exception):raise cls(error_message, response=response)-def salesforce_refresh_access_token(refresh_token: str, instance_url: str) -> str:- res = make_tracked_session().post(- f"{instance_url}/services/oauth2/token",- data={- "grant_type": "refresh_token",- "client_id": settings.SALESFORCE_CONSUMER_KEY,- "client_secret": settings.SALESFORCE_CONSUMER_SECRET,- "refresh_token": refresh_token,- },- )+# 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+# lock clears in moments, so a short in-process backoff recovers without failing the whole import+# activity — which would otherwise restart pagination and surface captured error-tracking noise.+_TRANSIENT_TOKEN_REQUEST_ERROR = "token request is already being processed"+_MAX_TOKEN_REFRESH_ATTEMPTS = 4- SalesforceAuthRequestError.raise_from_response(res)- return res.json()["access_token"]+def salesforce_refresh_access_token(refresh_token: str, instance_url: str) -> str:+ attempt = 0+ while True:+ res = make_tracked_session().post(+ f"{instance_url}/services/oauth2/token",+ data={+ "grant_type": "refresh_token",+ "client_id": settings.SALESFORCE_CONSUMER_KEY,+ "client_secret": settings.SALESFORCE_CONSUMER_SECRET,+ "refresh_token": refresh_token,+ },+ )++ try:+ SalesforceAuthRequestError.raise_from_response(res)+ except SalesforceAuthRequestError as err:+ attempt += 1+ if attempt >= _MAX_TOKEN_REFRESH_ATTEMPTS or _TRANSIENT_TOKEN_REQUEST_ERROR not in str(err):+ raise+ time.sleep(min(0.5 * attempt, 5))+ continue++ return res.json()["access_token"]def get_salesforce_access_token_from_code(code: str, redirect_uri: str, instance_url: str) -> tuple[str, str]: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 d100bc625aa9..2a139df0c7be 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@@ -100,6 +100,88 @@ def test_get_salesforce_access_token_from_code_raises_on_server_failure():assert response_body in str(exc.value)+def _token_response(status_code: int, body: dict) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode("utf-8")+ return response+++def _session_returning(responses: list[requests.Response]):+ it = iter(responses)+ return type("_S", (), {"post": staticmethod(lambda *a, **k: next(it))})()+++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.+ responses = [+ _token_response(400, {"error_description": "token request is already being processed"}),+ _token_response(400, {"error_description": "token request is already being processed"}),+ _token_response(200, {"access_token": "fresh-token"}),+ ]++ with (+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.make_tracked_session",+ return_value=_session_returning(responses),+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep"+ ) as mock_sleep,+ ):+ token = auth.salesforce_refresh_access_token("something", "https://login.salesforce.com")++ assert token == "fresh-token"+ assert mock_sleep.call_count == 2+++def test_refresh_raises_transient_token_request_after_exhausting_retries():+ responses = [+ _token_response(400, {"error_description": "token request is already being processed"})+ 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_returning(responses),+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep"+ ) as mock_sleep,+ pytest.raises(auth.SalesforceAuthRequestError) as exc,+ ):+ _ = auth.salesforce_refresh_access_token("something", "https://login.salesforce.com")++ assert "token request is already being processed" in str(exc.value)+ assert mock_sleep.call_count == auth._MAX_TOKEN_REFRESH_ATTEMPTS - 1+++def test_refresh_does_not_retry_non_transient_error():+ # A permanent auth failure must not be retried — it surfaces immediately for the+ # non-retryable classifier to catch.+ responses = [+ _token_response(400, {"error_description": "expired access/refresh token"}),+ _token_response(200, {"access_token": "should-not-be-reached"}),+ ]++ with (+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.make_tracked_session",+ return_value=_session_returning(responses),+ ),+ unittest.mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.salesforce.auth.time.sleep"+ ) as mock_sleep,+ pytest.raises(auth.SalesforceAuthRequestError) as exc,+ ):+ _ = auth.salesforce_refresh_access_token("something", "https://login.salesforce.com")++ assert "expired access/refresh token" in str(exc.value)+ assert mock_sleep.call_count == 0++@pytest.mark.parametrize("error_description",[