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(zoho_crm): classify a 2xx body that is not JSON (#97268)

posthog[bot]a94f8a6f2ab4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py
index 1f6ef97dd7b6..cf6da156afd5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py
@@ -60,6 +60,7 @@ class ZohoCRMSource(ResumableSource[ZohoCRMSourceConfig, ZohoCRMResumeConfig]):
"400 Client Error: for url: https://accounts.zoho": "Zoho CRM rejected your OAuth credentials. Check that the client ID, client secret, and refresh token all belong to the same self client.",
"401 Client Error: Unauthorized for url": "Your Zoho CRM access token is invalid or expired. Reconnect the source to issue a new one.",
"403 Client Error: Forbidden for url": "Your Zoho CRM token is missing a scope for this module. Re-authorize with the ZohoCRM.modules.ALL, ZohoCRM.settings.fields.READ, and ZohoCRM.settings.modules.READ scopes.",
+ "Non-JSON response from": "Zoho CRM returned a non-JSON response, for example an HTML error or login page, instead of data. Check that the data center you picked matches your Zoho account, then try again.",
}
@property
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py
index d3e912d65219..d6d40b335f90 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py
@@ -7,6 +7,10 @@ from unittest import mock
import requests
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientNonRetryableError,
+ RESTClientRetryableError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.settings import ZOHO_CRM_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.zoho_crm import (
@@ -59,6 +63,15 @@ def _response(status_code: int = 200, body: Optional[dict[str, Any]] = None) ->
return response
+def _undecodable_response(content: bytes, url: str = "https://www.zohoapis.com/crm/v8/Leads?page=1") -> mock.MagicMock:
+ """A 2xx whose body `response.json()` refuses, as `requests` reports it."""
+ response = _response(200)
+ response.json.side_effect = requests.exceptions.JSONDecodeError("Expecting value", "", 0)
+ response.content = content
+ response.url = url
+ return response
+
+
def _no_content_response(status_code: int) -> mock.MagicMock:
"""An empty-bodied Zoho response: reading it as JSON fails, as it does against the real API."""
response = _response(status_code)
@@ -176,6 +189,18 @@ class TestZohoCRMClient:
with pytest.raises(ZohoCRMAuthError, match="invalid_code"):
client.mint_access_token()
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_json_token_body_is_non_retryable(self, make_session: mock.MagicMock) -> None:
+ make_session.return_value = _session(
+ [],
+ post_responses=[
+ _undecodable_response(b"<html><body>Sign in</body></html>", "https://accounts.zoho.com/oauth/v2/token")
+ ],
+ )
+
+ with pytest.raises(RESTClientNonRetryableError):
+ _client().mint_access_token()
+
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_authorization_header_uses_the_zoho_scheme(self, make_session: mock.MagicMock) -> None:
session = _session([_response(200, {"modules": []})])
@@ -246,6 +271,12 @@ class TestReadableFieldNames:
assert readable_field_names(_client(), "v8", "Leads") == []
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_metadata_body_yields_no_projection(self, make_session: mock.MagicMock) -> None:
+ make_session.return_value = _session([_undecodable_response(b"")])
+
+ assert readable_field_names(_client(), "v8", "Leads") == []
+
class TestGetRows:
@mock.patch(f"{_MODULE}.make_tracked_session")
@@ -430,6 +461,34 @@ class TestGetRows:
assert "sort_by" not in _get_params(session, 0)
assert "fields" not in _get_params(session, 0)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_records_body_stops_pagination_without_crashing(self, make_session: mock.MagicMock) -> None:
+ session = _session([_fields_response(1), _undecodable_response(b"")])
+ make_session.return_value = session
+ manager = FakeResumeManager()
+
+ assert list(get_rows(_client(), "v8", "Leads", manager, mock.MagicMock())) == []
+ assert manager.cleared is True
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_non_json_records_body_is_non_retryable(self, make_session: mock.MagicMock) -> None:
+ # The fixture URL carries a query string, which holds the page token and the field list.
+ make_session.return_value = _session(
+ [_fields_response(1), _undecodable_response(b"<!DOCTYPE html><html><body>Sign in</body></html>")]
+ )
+
+ with pytest.raises(RESTClientNonRetryableError) as exc:
+ list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock()))
+
+ assert str(exc.value) == "Non-JSON response from https://www.zohoapis.com/crm/v8/Leads"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_truncated_records_body_stays_retryable(self, make_session: mock.MagicMock) -> None:
+ make_session.return_value = _session([_fields_response(1), _undecodable_response(b'{"data": [{"id": "1"}')])
+
+ with pytest.raises(RESTClientRetryableError):
+ list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock()))
+
class TestValidateCredentials:
@mock.patch(f"{_MODULE}.make_tracked_session")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.py
index 19baafba1beb..2b1c28ebcc68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.py
@@ -51,6 +51,13 @@ class TestZohoCRMSource:
assert self.source.default_version == "v8"
assert self.source.api_docs_url.startswith("https://")
+ def test_non_json_response_message_matches_non_retryable_error(self) -> None:
+ # The classifier matches a prefix, so the variable URL must not stop the match.
+ raised = "Non-JSON response from https://www.zohoapis.com/crm/v8/Leads"
+ matches = [friendly for key, friendly in self.source.get_non_retryable_errors().items() if key in raised]
+
+ assert matches and matches[0] is not None
+
def test_source_config_documents_scopes_the_requests_require(self) -> None:
# `settings.modules.READ` is the easy one to drop, because nothing in the sync path uses it:
# it exists only so `validate_credentials` can probe /settings/modules. Zoho answers that
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
index 85832c9bbda9..9796ba84ab1f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py
@@ -9,6 +9,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.dat
coerce_datetime_to_utc,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientNonRetryableError,
+ RESTClientRetryableError,
+ _looks_like_json,
+ _safe_url,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.settings import (
@@ -89,6 +95,24 @@ def format_modified_since(value: Any) -> str:
return parsed.strftime("%Y-%m-%dT%H:%M:%S+00:00")
+def _parse_json_body(response: requests.Response) -> Optional[Any]:
+ """Decode a 2xx JSON body, or classify a body that does not decode.
+
+ An empty body is a complete "no data" answer, so it becomes `None`. A body that starts as a
+ JSON value is a truncated read and stays retryable. A body that never starts as JSON is an
+ error, login, or maintenance page, which a retry can only fetch again, so it is non-retryable.
+ """
+ try:
+ return response.json()
+ except requests.exceptions.JSONDecodeError as e:
+ if not response.content or not response.content.strip():
+ return None
+ # `_safe_url` drops the query string, which carries the page token and the field list.
+ if not _looks_like_json(response.content):
+ raise RESTClientNonRetryableError(f"Non-JSON response from {_safe_url(response.url)}") from e
+ raise RESTClientRetryableError(f"Malformed JSON response from {_safe_url(response.url)}: {e}") from e
+
+
def chunk_fields(names: list[str], size: int = MAX_FIELDS_PER_REQUEST) -> list[list[str]]:
"""Split field API names into request-sized slices. An empty list means "no projection"."""
if not names:
@@ -140,7 +164,7 @@ class ZohoCRMClient:
timeout=REQUEST_TIMEOUT_SECONDS,
)
response.raise_for_status()
- body = response.json()
+ body = _parse_json_body(response) or {}
access_token = body.get("access_token")
if not access_token:
@@ -192,8 +216,12 @@ def readable_field_names(client: ZohoCRMClient, api_version: str, module: str) -
if response.status_code in NO_CONTENT_STATUSES:
return []
+ body = _parse_json_body(response)
+ if body is None:
+ return []
+
names: list[str] = []
- for field in response.json().get("fields") or []:
+ for field in body.get("fields") or []:
api_name = field.get("api_name")
if not api_name:
continue
@@ -216,7 +244,10 @@ def _fetch_page(
if response.status_code in NO_CONTENT_STATUSES:
return [], {}
- body = response.json()
+ body = _parse_json_body(response)
+ if body is None:
+ return [], {}
+
return list(body.get(config.data_key) or []), dict(body.get("info") or {})