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(data-imports): treat non-JSON REST responses as non-retryable (#72144)

Tom Owerse1c83b0c42a8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
index c0eb9e7bf5f4..8c1d48e7a67b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py
@@ -4,6 +4,7 @@ from collections.abc import Callable, Iterator
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from typing import Any, Optional
+from urllib.parse import urlsplit
from requests import Request, Response, Session
from requests.auth import AuthBase
@@ -30,6 +31,41 @@ class RESTClientRetryableError(Exception):
self.retry_after = retry_after
+class RESTClientNonRetryableError(Exception):
+ """A response that retrying can never turn into usable data.
+
+ Not a subclass of RESTClientRetryableError so the tenacity retry — which only
+ reissues RESTClientRetryableError — stops immediately instead of re-fetching a
+ deterministic failure.
+ """
+
+
+# Bytes that can legally begin a JSON document: an object/array, a string, a
+# number, or one of the literals true/false/null.
+_JSON_START_BYTES = frozenset(b'{["-tfn0123456789')
+
+
+def _looks_like_json(content: bytes) -> bool:
+ stripped = content.lstrip()
+ return bool(stripped) and stripped[0] in _JSON_START_BYTES
+
+
+def _safe_url(url: str) -> str:
+ """Scheme, host, and path only — never the query string, fragment, or userinfo.
+
+ An error message built from a URL can flow into non-retryable-error analytics
+ and error tracking, where tracked-session value redaction doesn't reach. An
+ ``api_key`` auth with ``location: "query"`` carries the secret in the query
+ string, so keep only the parts that are safe to surface."""
+ parts = urlsplit(url)
+ if not parts.scheme:
+ return url
+ host = parts.hostname or ""
+ if parts.port:
+ host = f"{host}:{parts.port}"
+ return f"{parts.scheme}://{host}{parts.path}"
+
+
# Upper bound on how long we'll honor a server-provided retry delay, so a
# misreported header can't stall a worker for an unbounded amount of time.
MAX_RETRY_AFTER_SECONDS = 300.0
@@ -196,7 +232,7 @@ class RESTClient:
if response.status_code == 429 or response.status_code >= 500:
raise RESTClientRetryableError(
- f"HTTP {response.status_code} for {response.url}",
+ f"HTTP {response.status_code} for {_safe_url(response.url)}",
retry_after=_parse_retry_after(response),
)
@@ -215,11 +251,18 @@ class RESTClient:
# An empty body on an otherwise-successful response is a complete "no data"
# answer (e.g. an endpoint with nothing to return), not a truncated page —
# retrying can't conjure rows, so treat it as an empty page and let the
- # paginator stop. A non-empty body that fails to parse is a partial/truncated
- # read, which stays retryable.
+ # paginator stop.
if not response.content or not response.content.strip():
return response, None
- raise RESTClientRetryableError(f"Malformed JSON response from {response.url}: {e}") from e
+ # A body that doesn't even begin with a JSON value is not a truncated page:
+ # the endpoint returned non-JSON content (an HTML or plain-text error page, a
+ # login redirect) on an otherwise-successful response. Re-fetching returns the
+ # same non-JSON body, so fail fast and non-retryably instead of burning the
+ # retry budget. A body that starts as JSON but fails to parse is a partial /
+ # truncated read, which stays retryable.
+ 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
return response, body
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
index 596e8a917ee1..a7a4df0c5cb1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py
@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
MAX_RETRY_AFTER_SECONDS,
RESTClient,
+ RESTClientNonRetryableError,
RESTClientRetryableError,
_parse_retry_after,
)
@@ -55,6 +56,18 @@ def _make_truncated_response(status_code: int = 200) -> Response:
return resp
+def _make_non_json_response(content: bytes, status_code: int = 200) -> Response:
+ # A successful response whose body never begins as JSON — an HTML/plain-text error
+ # page or login redirect returned with a 2xx. `response.json()` raises "Expecting
+ # value: line 1 column 1 (char 0)", identical to a truncated body cut off at the start.
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = content
+ resp.headers["Content-Type"] = "application/json"
+ resp.url = "https://api.example.com/items"
+ return resp
+
+
class TestRESTClient:
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -343,6 +356,58 @@ class TestRESTClient:
assert mock_session.send.call_count == 5
+ @pytest.mark.parametrize(
+ "content",
+ [
+ pytest.param(b"<!DOCTYPE html><html><body>Service unavailable</body></html>", id="html"),
+ pytest.param(b" <html>login required</html>", id="html_leading_whitespace"),
+ pytest.param(b"Not Found", id="plain_text"),
+ ],
+ )
+ @patch("tenacity.nap.time.sleep")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ )
+ def test_non_json_response_body_is_non_retryable(self, MockSession, mock_sleep, content) -> None:
+ # A 2xx whose body never begins as JSON is a deterministic non-JSON response, not a
+ # truncated page: fail fast and non-retryably rather than re-fetching the same body
+ # to the retry cap (contrast the truncated-JSON case, which stays retryable).
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock()
+ mock_session.send.return_value = _make_non_json_response(content)
+
+ client = RESTClient(base_url="https://api.example.com")
+ with pytest.raises(RESTClientNonRetryableError, match="Non-JSON response from"):
+ list(client.paginate(path="/items", paginator=SinglePagePaginator()))
+
+ assert mock_session.send.call_count == 1
+ mock_sleep.assert_not_called()
+
+ @patch("tenacity.nap.time.sleep")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ )
+ def test_non_json_error_message_omits_query_string_secret(self, MockSession, mock_sleep) -> None:
+ # An api_key auth with location="query" puts the secret in the URL. This message flows
+ # into non-retryable-error analytics where session-value redaction doesn't reach, so it
+ # must carry only scheme/host/path — never the query string that holds the key.
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock()
+ resp = _make_non_json_response(b"<html>nope</html>")
+ resp.url = "https://api.example.com/leads?api_key=super-secret-value&page=1"
+ mock_session.send.return_value = resp
+
+ client = RESTClient(base_url="https://api.example.com")
+ with pytest.raises(RESTClientNonRetryableError) as ctx:
+ list(client.paginate(path="/leads", paginator=SinglePagePaginator()))
+
+ message = str(ctx.value)
+ assert "super-secret-value" not in message
+ assert "api_key" not in message
+ assert "https://api.example.com/leads" in message
+
@pytest.mark.parametrize("content", [b"", b" \n\t"], ids=["empty", "whitespace_only"])
@patch("tenacity.nap.time.sleep")
@patch(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
index 7e9b77aeda1a..10b0933269f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
@@ -777,6 +777,12 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
"invalid_client": "The OAuth2 token endpoint rejected the client credentials (invalid_client). Check the configured client_id, client secret, and token URL.",
"invalid_grant": "The OAuth2 token endpoint rejected the grant (invalid_grant) — a refresh token may have expired or been revoked. Re-enter the OAuth2 credentials.",
OAUTH2_PERMANENT_ERROR_MARKER: "The OAuth2 token endpoint rejected the request and the configuration must change before the sync can succeed. Check the configured OAuth2 credentials, token URL, grant type, and scopes.",
+ # The endpoint returned non-JSON content (an HTML or plain-text error page, a
+ # login redirect) on an otherwise-successful response. The request shape is
+ # manifest-driven and deterministic, so retrying re-fetches the same body —
+ # stop and point at the config the user can change. Matches the stable prefix
+ # RESTClientNonRetryableError uses, not the variable URL that follows.
+ "Non-JSON response from": "The upstream API returned a non-JSON response (for example an HTML or plain-text error page) instead of data. Check that the resource's URL and path in the manifest point at a JSON API endpoint and that any required authentication is configured, then try again.",
}
def _assemble_manifest(self, config: CustomSourceConfig) -> dict[str, Any]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
index b2224641aa1a..1f2a35022449 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/test_custom_source.py
@@ -30,6 +30,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
OAuth2AuthRequestError,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_auth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientNonRetryableError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.custom.source import (
MAX_MANIFEST_RESOURCES,
PREVIEW_MAX_FANOUT_PARENTS,
@@ -1750,6 +1753,16 @@ class TestCustomSourceNonRetryableErrors(SimpleTestCase):
non_retryable = CustomSource().get_non_retryable_errors()
assert any(key in str(ctx.exception) for key in non_retryable)
+ def test_non_json_response_message_is_classified_non_retryable(self):
+ # The REST client raises RESTClientNonRetryableError when a configured endpoint
+ # returns non-JSON (an HTML/plain-text error page) on a 2xx. Build the real error the
+ # client raises so this breaks if its stable prefix drifts from the classifier's key.
+ # The URL is a placeholder, never a real customer host.
+ error = RESTClientNonRetryableError("Non-JSON response from https://api.example.com/leads")
+
+ non_retryable = CustomSource().get_non_retryable_errors()
+ assert any(key in str(error) for key in non_retryable)
+
@parameterized.expand(["invalid_client", "invalid_grant"])
def test_oauth2_permanent_errors_are_classified_non_retryable(self, error_code):
# A permanent OAuth2 token rejection (invalid_client / invalid_grant) surfaces the