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 truncated JSON responses instead of crashing (#64252)

Tom Owersc4f45cd677cb
diff --git a/posthog/temporal/data_imports/sources/hubspot/hubspot.py b/posthog/temporal/data_imports/sources/hubspot/hubspot.py
index a678369257fe..fd6f055cddc5 100644
--- a/posthog/temporal/data_imports/sources/hubspot/hubspot.py
+++ b/posthog/temporal/data_imports/sources/hubspot/hubspot.py
@@ -21,6 +21,7 @@ from datetime import UTC, datetime
from typing import Any, Optional
import requests
+from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
@@ -328,7 +329,13 @@ def get_rows(
logger.error(f"Hubspot API error: status={response.status_code}, body={response.text}, url={page_url}")
response.raise_for_status()
- return response.json()
+ # Parse inside the retry so a truncated/partial body (JSONDecodeError, e.g. an
+ # "Unterminated string" mid-stream) is reissued like a 429/5xx instead of bubbling
+ # up uncaught and failing the whole import.
+ try:
+ return response.json()
+ except RequestsJSONDecodeError as e:
+ raise HubspotRetryableError(f"Hubspot API malformed JSON response (retryable): url={page_url}") from e
while True:
data = fetch_page(url)
@@ -422,7 +429,13 @@ def _batch_read_associations(
)
response.raise_for_status()
- return response.json()
+ # See fetch_page: a truncated/partial body is transient, so retry rather than crash.
+ try:
+ return response.json()
+ except RequestsJSONDecodeError as e:
+ raise HubspotRetryableError(
+ f"Hubspot v4 associations malformed JSON response (retryable): url={url}"
+ ) from e
for start in range(0, len(ids), ASSOCIATIONS_BATCH_SIZE):
chunk = ids[start : start + ASSOCIATIONS_BATCH_SIZE]
@@ -564,7 +577,11 @@ def get_rows_via_search(
logger.error(f"Hubspot search error: status={response.status_code}, body={response.text}, url={search_url}")
response.raise_for_status()
- return response.json()
+ # See fetch_page: a truncated/partial body is transient, so retry rather than crash.
+ try:
+ return response.json()
+ except RequestsJSONDecodeError as e:
+ raise HubspotRetryableError(f"Hubspot search malformed JSON response (retryable): url={search_url}") from e
def save_progress() -> None:
resumable_source_manager.save_state(
diff --git a/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
index 739447117192..8f35b5aaa09c 100644
--- a/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
+++ b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
@@ -5,6 +5,8 @@ from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
+
from posthog.temporal.data_imports.sources.hubspot.hubspot import (
HubspotPathologicalWindowError,
HubspotResumeConfig,
@@ -943,6 +945,46 @@ class TestGetRowsFullRefresh:
assert captured_urls[0] == "https://api.hubapi.com/resume-here"
+ def test_truncated_json_body_is_retried(self) -> None:
+ # Regression: a truncated/partial page body raises requests' JSONDecodeError
+ # ("Unterminated string"). It must be treated as transient and retried, not crash
+ # the whole import.
+ from posthog.temporal.data_imports.sources.hubspot.hubspot import get_rows
+
+ manager = _make_manager()
+ logger = MagicMock()
+
+ truncated = _make_response(200, {"results": [{"id": "1", "properties": {"hs_object_id": "1"}}]})
+ truncated.json.side_effect = RequestsJSONDecodeError("Unterminated string starting at", "doc", 42)
+ good = _make_response(200, {"results": [{"id": "1", "properties": {"hs_object_id": "1"}}]})
+
+ iter_resp = iter([truncated, good])
+ captured_urls: list[str] = []
+
+ def _get(url, headers=None, timeout=None): # noqa: ARG001
+ captured_urls.append(url)
+ return next(iter_resp)
+
+ with patch(
+ "posthog.temporal.data_imports.sources.hubspot.hubspot.make_tracked_session",
+ new=lambda *_a, **_k: type("_S", (), {"get": staticmethod(_get)})(),
+ ):
+ tables = list(
+ get_rows(
+ api_key="k",
+ refresh_token="r",
+ endpoint="deals",
+ logger=logger,
+ resumable_source_manager=manager,
+ include_custom_props=False,
+ )
+ )
+
+ # The truncated response was reissued (same URL) and the retry yielded the row.
+ assert len(captured_urls) == 2
+ assert captured_urls[0] == captured_urls[1]
+ assert sum(t.num_rows for t in tables) == 1
+
class TestExpectedPropertiesBackfill:
def test_cursor_column_present_on_row_after_flatten(self) -> None: