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(hubspot): retry transient errors during property discovery (#65027)

Tom Owers9e37be62c496
diff --git a/posthog/temporal/data_imports/sources/hubspot/helpers.py b/posthog/temporal/data_imports/sources/hubspot/helpers.py
index 9ded90d2dd3d..b1acf7f6733d 100644
--- a/posthog/temporal/data_imports/sources/hubspot/helpers.py
+++ b/posthog/temporal/data_imports/sources/hubspot/helpers.py
@@ -2,18 +2,38 @@
import urllib.parse
from collections.abc import Iterator
+from http import HTTPStatus
from typing import Any, Optional
-from requests.exceptions import HTTPError
+import requests
+from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
-from .auth import hubspot_refresh_access_token
+from .auth import HubspotRetryableError, hubspot_refresh_access_token
from .settings import OBJECT_TYPE_PLURAL
BASE_URL = "https://api.hubapi.com/"
+def _is_retryable_status(status_code: int) -> bool:
+ """Transient HubSpot statuses that warrant a backoff-and-retry rather than failing the sync.
+
+ 429 and 5xx are the usual transient signals. Unrecognised 4xx codes (e.g. the non-standard 477
+ HubSpot's edge has been observed returning during brief incidents) aren't actionable client
+ errors, so treat any unknown 4xx as transient too instead of crashing the import on it.
+ """
+ if status_code == 429 or status_code >= 500:
+ return True
+ if 400 <= status_code < 500:
+ try:
+ HTTPStatus(status_code)
+ except ValueError:
+ return True
+ return False
+
+
def get_url(endpoint: str) -> str:
"""Get absolute hubspot endpoint URL"""
return urllib.parse.urljoin(BASE_URL, endpoint)
@@ -117,35 +137,44 @@ def fetch_data(
Notes:
This function uses the `requests` library to make a GET request to the specified endpoint, with
- the API key included in the headers. If the API returns a non-successful HTTP status code (e.g.
- 404 Not Found), a `requests.exceptions.HTTPError` exception will be raised.
+ the API key included in the headers. A 401 refreshes the access token; transient statuses
+ (429, 5xx, and unrecognised non-standard 4xx codes) back off and retry. A permanent client
+ error (e.g. 404 Not Found) raises `requests.exceptions.HTTPError`.
The `endpoint` argument should be a relative URL, which will be appended to the base URL for the
- API. The `params` argument is used to pass additional query parameters to the request
-
- This function also includes a retry decorator that will automatically retry the API call up to
- 3 times with a 5-second delay between retries, using an exponential backoff strategy.
+ API. The `params` argument is used to pass additional query parameters to the request.
"""
# Construct the URL and headers for the API request
url = get_url(endpoint)
headers = _get_headers(api_key)
- # Make the API request
- r = make_tracked_session().get(url, headers=headers, params=params)
- try:
- r.raise_for_status()
- except HTTPError as e:
- if e.response.status_code == 401:
+ @retry(
+ retry=retry_if_exception_type((HubspotRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def _get(page_url: str, query_params: Optional[dict[str, Any]]) -> dict:
+ nonlocal api_key, headers
+ r = make_tracked_session().get(page_url, headers=headers, params=query_params)
+
+ if r.status_code == 401:
api_key = hubspot_refresh_access_token(refresh_token, source_id=source_id)
headers = _get_headers(api_key)
- r = make_tracked_session().get(url, headers=headers, params=params)
- r.raise_for_status()
- else:
- raise
- # Parse the API response and yield the properties of each result
- # Parse the response JSON data
+ raise HubspotRetryableError(f"Hubspot API 401 - refreshed token, retrying: url={page_url}")
- _data = r.json()
+ if _is_retryable_status(r.status_code):
+ raise HubspotRetryableError(f"Hubspot API error (retryable): status={r.status_code}, url={page_url}")
+
+ r.raise_for_status()
+
+ # See hubspot.fetch_page: a truncated/partial body is transient, so retry rather than crash.
+ try:
+ return r.json()
+ except RequestsJSONDecodeError as e:
+ raise HubspotRetryableError(f"Hubspot API malformed JSON response (retryable): url={page_url}") from e
+
+ _data: Optional[dict[str, Any]] = _get(url, params)
# Yield the properties of each result in the API response
while _data is not None:
if "results" in _data:
@@ -176,20 +205,7 @@ def fetch_data(
# Follow pagination links if they exist
_next = _data.get("paging", {}).get("next", None)
if _next:
- next_url = _next["link"]
- # Get the next page response
- r = make_tracked_session().get(next_url, headers=headers)
- try:
- r.raise_for_status()
- except HTTPError as e:
- if e.response.status_code == 401:
- api_key = hubspot_refresh_access_token(refresh_token, source_id=source_id)
- headers = _get_headers(api_key)
- r = make_tracked_session().get(next_url, headers=headers)
- r.raise_for_status()
- else:
- raise
- _data = r.json()
+ _data = _get(_next["link"], None)
else:
_data = None
diff --git a/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_helpers.py b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_helpers.py
new file mode 100644
index 000000000000..99065c45baee
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_helpers.py
@@ -0,0 +1,129 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests.exceptions import HTTPError
+
+from posthog.temporal.data_imports.sources.hubspot.helpers import (
+ HubspotRetryableError,
+ _get_property_names,
+ _is_retryable_status,
+ fetch_data,
+)
+
+
+def _make_response(status: int, payload: dict[str, Any] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.json.return_value = payload or {}
+ response.raise_for_status.side_effect = (
+ None if 200 <= status < 300 else HTTPError(f"{status} Client Error", response=response)
+ )
+ return response
+
+
+def _patch_session(responses: list[MagicMock]) -> tuple[Any, list[str]]:
+ iter_resp = iter(responses)
+ captured: list[str] = []
+
+ def _get(url: str, headers: Any = None, params: Any = None, timeout: Any = None) -> MagicMock: # noqa: ARG001
+ captured.append(url)
+ return next(iter_resp)
+
+ session = type("_S", (), {"get": staticmethod(_get)})()
+ return (
+ patch(
+ "posthog.temporal.data_imports.sources.hubspot.helpers.make_tracked_session",
+ new=lambda *_a, **_k: session,
+ ),
+ captured,
+ )
+
+
[email protected](autouse=True)
+def _no_backoff_sleep() -> Any:
+ # fetch_data backs off on transient errors; skip the real waits in tests.
+ with patch("time.sleep"):
+ yield
+
+
+ "status,expected",
+ [
+ (200, False),
+ (400, False),
+ (401, False),
+ (403, False),
+ (404, False),
+ (409, False),
+ (422, False),
+ (451, False),
+ (429, True),
+ (477, True), # non-standard 4xx HubSpot's edge returns during transient incidents
+ (499, True),
+ (500, True),
+ (502, True),
+ (503, True),
+ ],
+)
+def test_is_retryable_status(status: int, expected: bool) -> None:
+ assert _is_retryable_status(status) is expected
+
+
+def test_fetch_data_retries_non_standard_477_then_succeeds() -> None:
+ # Regression: HubSpot's property endpoint briefly returned a non-standard 477; the discovery
+ # path must back off and retry rather than crashing the whole import on an unknown code.
+ good = _make_response(200, {"results": [{"id": "1", "properties": {"name": "deal_stage"}}]})
+ ctx, captured = _patch_session([_make_response(477), _make_response(477), good])
+ with ctx:
+ pages = list(fetch_data("/crm/v3/properties/deals", "key", "refresh"))
+
+ assert len(captured) == 3
+ assert pages == [[{"name": "deal_stage", "id": "1"}]]
+
+
+def test_fetch_data_reraises_retryable_after_exhausting_retries() -> None:
+ ctx, captured = _patch_session([_make_response(477) for _ in range(5)])
+ with ctx:
+ with pytest.raises(HubspotRetryableError, match="status=477"):
+ list(fetch_data("/crm/v3/properties/deals", "key", "refresh"))
+
+ assert len(captured) == 5
+
+
+def test_fetch_data_permanent_client_error_is_not_retried() -> None:
+ # A genuine permanent client error (404) must surface immediately, not be retried.
+ ctx, captured = _patch_session([_make_response(404)])
+ with ctx:
+ with pytest.raises(HTTPError):
+ list(fetch_data("/crm/v3/properties/deals", "key", "refresh"))
+
+ assert len(captured) == 1
+
+
+def test_fetch_data_refreshes_token_on_401_then_succeeds() -> None:
+ good = _make_response(200, {"results": [{"id": "1", "properties": {"name": "deal_stage"}}]})
+ ctx, captured = _patch_session([_make_response(401), good])
+ with (
+ ctx,
+ patch(
+ "posthog.temporal.data_imports.sources.hubspot.helpers.hubspot_refresh_access_token",
+ return_value="new-token",
+ ) as refresh,
+ ):
+ pages = list(fetch_data("/crm/v3/properties/deals", "key", "refresh"))
+
+ refresh.assert_called_once()
+ assert len(captured) == 2
+ assert pages == [[{"name": "deal_stage", "id": "1"}]]
+
+
+def test_get_property_names_recovers_from_transient_477() -> None:
+ good = _make_response(200, {"results": [{"name": "deal_stage"}, {"name": "amount"}]})
+ ctx, captured = _patch_session([_make_response(477), good])
+ with ctx:
+ names = _get_property_names("key", "refresh", "deal")
+
+ assert names == ["deal_stage", "amount"]
+ assert len(captured) == 2