: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(notion): retry responses with an empty or non-JSON body (#80072)
Tom Owers0158d3414443
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.pyindex a13b9ee797ca..321be311bc3e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/notion.py@@ -205,7 +205,15 @@ def _request(logger.error(f"Notion API error: status={response.status_code}, body={response.text}, url={url}")response.raise_for_status()- return response.json()+ try:+ return response.json()+ except requests.exceptions.JSONDecodeError as e:+ # A 2xx with an empty or non-JSON body is a truncated/garbled response (a proxy hiccup, or the+ # connection dropped after the status line) rather than real Notion output — every success+ # path returns JSON. Treat it like the other transient response failures and retry.+ raise NotionRetryableError(+ f"Notion returned a non-JSON response: status={response.status_code}, url={url}"+ ) from edef validate_credentials(token: str, api_version: str) -> tuple[bool, str | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.pyindex 5100f6afa2c7..bd3d6cec6ac3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/source.py@@ -58,6 +58,10 @@ class NotionSource(ResumableSource[NotionSourceConfig, NotionResumeConfig]):return {"Notion API error (retryable)","Notion rate limited",+ # A 2xx whose body is empty or non-JSON is a truncated/garbled response, retried in-process+ # by `_request`. If those retries exhaust, the condition is transient and self-recovering,+ # so let Temporal retry the activity instead of surfacing it as tracked exception noise.+ "Notion returned a non-JSON response",# `_request`'s tenacity retry also covers `requests.ConnectionError` (which# `requests.exceptions.SSLError` subclasses) and `requests.ReadTimeout`. urllib3# wraps both as "... Max retries exceeded with url: ..." regardless of the underlyingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.pyindex e9fb68319c84..e6be2caf0e8f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion.py@@ -36,14 +36,23 @@ MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.notioclass FakeResponse:- def __init__(self, json_data: Any, status_code: int = 200, headers: Optional[dict[str, str]] = None) -> None:+ def __init__(+ self,+ json_data: Any,+ status_code: int = 200,+ headers: Optional[dict[str, str]] = None,+ json_exc: Optional[Exception] = None,+ ) -> None:self._json = json_data+ self._json_exc = json_excself.status_code = status_codeself.headers = headers or {}self.ok = 200 <= status_code < 400self.text = ""def json(self) -> Any:+ if self._json_exc is not None:+ raise self._json_excreturn self._jsondef raise_for_status(self) -> None:@@ -312,6 +321,49 @@ class TestNotion:assert result == {"results": []}assert attempts["count"] == 2+ def test_request_non_json_2xx_raises_retryable(self) -> None:+ # A 2xx whose body is empty or non-JSON makes response.json() raise JSONDecodeError. That is a+ # truncated/garbled response, not real Notion output, so it must surface as the retryable type+ # carrying the stable phrase get_retryable_errors matches — not crash the sync.+ session = FakeSession(+ [+ FakeResponse(+ None,+ status_code=200,+ json_exc=requests.exceptions.JSONDecodeError("Expecting value: line 1 column 1 (char 0)", "", 0),+ )+ ]+ )+ with pytest.raises(NotionRetryableError) as exc_info:+ cast(Any, _request).__wrapped__(+ cast(requests.Session, session), "GET", "/v1/users", mock.MagicMock(), params={}+ )+ assert "Notion returned a non-JSON response" in str(exc_info.value)++ def test_request_retries_non_json_response(self) -> None:+ # An empty/non-JSON 2xx body is transient like a broken connection: the retry must recover+ # rather than propagate JSONDecodeError as a fatal sync error.+ attempts = {"count": 0}++ def request(*_args: Any, **_kwargs: Any) -> FakeResponse:+ attempts["count"] += 1+ if attempts["count"] == 1:+ return FakeResponse(+ None,+ status_code=200,+ json_exc=requests.exceptions.JSONDecodeError("Expecting value: line 1 column 1 (char 0)", "", 0),+ )+ return FakeResponse({"results": []})++ session = mock.MagicMock()+ session.request.side_effect = request++ with mock.patch(f"{MODULE}._wait_strategy", return_value=0):+ result = _request(cast(requests.Session, session), "GET", "/v1/users", mock.MagicMock(), params={})++ assert result == {"results": []}+ assert attempts["count"] == 2+def test_request_404_raises_not_found(self) -> None:# Notion 404s a page/block that was deleted or unshared. It must surface as the typed# NotionNotFoundError so the fan-out streams can skip it instead of crashing.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.pyindex 6e6b3817464e..756dfbb3d785 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/notion/tests/test_notion_source.py@@ -172,6 +172,10 @@ class TestNotionSource:"/v1/search (Caused by ReadTimeoutError(\"HTTPSConnectionPool(host='api.notion.com', "'port=443): Read timed out."))',),+ (+ "non_json_response_after_tenacity_exhausted",+ "Notion returned a non-JSON response: status=200, url=https://api.notion.com/v1/search",+ ),])def test_retryable_marker_matches_raised_message(self, _name: str, error_message: str) -> None: