: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(linear): retry truncated JSON responses instead of failing hard (#67443)
Tom Owersd1cefa7869e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linear/linear.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linear/linear.pyindex 981c34289f45..571e0c5d0544 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linear/linear.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linear/linear.py@@ -117,10 +117,16 @@ def _make_paginated_request(try:payload = response.json()- except Exception:+ except Exception as e:if not response.ok:- raise Exception(f"{response.status_code} Client Error: {response.reason} (Linear API: {response.text})")- raise Exception(f"Unexpected Linear response: {response.text}")+ raise Exception(+ f"{response.status_code} Client Error: {response.reason} (Linear API: {response.text})"+ ) from e+ # A 2xx whose body won't parse as JSON is almost always a truncated transfer (the+ # connection dropped mid-body on a large page), not a stable response Linear will keep+ # returning. Ride it out on the same backoff path as other transient failures instead of+ # failing the activity outright. Don't echo response.text — a partial body carries data.+ raise LinearRetryableError(f"Linear: incomplete JSON response ({e})") from eif "errors" in payload:error_messages = [e.get("message", "") for e in payload["errors"]]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linear/test_linear.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linear/test_linear.pyindex 7a0ea1018796..0f442f40b943 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linear/test_linear.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linear/test_linear.py@@ -1,4 +1,5 @@import copy+import jsonfrom collections.abc import Iterablefrom typing import Any, cast@@ -49,6 +50,17 @@ def _make_rate_limited_response(headers: dict[str, str] | None = None) -> MagicMreturn response+def _make_truncated_response(body: str) -> MagicMock:+ """Mimic a large 2xx page cut mid-stream: status is OK but the body fails to JSON-decode."""+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ response.reason = "OK"+ response.text = body+ response.json.side_effect = json.JSONDecodeError("Unterminated string starting at", body, len(body))+ return response++def _retry_state(exc: BaseException) -> RetryCallState:state = RetryCallState(retry_object=MagicMock(), fn=None, args=(), kwargs={})state.outcome = Future.construct(1, exc, has_exception=True)@@ -290,6 +302,63 @@ class TestMakePaginatedRequest:assert session.post.call_count == LINEAR_MAX_RETRY_ATTEMPTS+ @patch("time.sleep", return_value=None)+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.linear.linear.make_tracked_session")+ def test_truncated_2xx_response_is_retried_then_succeeds(+ self, mock_session_cls: MagicMock, _mock_sleep: MagicMock+ ) -> None:+ # A large page cut mid-stream arrives as a 2xx whose body fails to JSON-decode. It must be+ # retried with backoff, not surfaced as a non-retryable JSONDecodeError/Exception.+ session = MagicMock()+ session.post.side_effect = [+ _make_truncated_response('{"data":{"issues":{"nodes":[{"id":"a"'),+ _make_response([{"id": "a"}], False, None),+ ]+ mock_session_cls.return_value = session++ manager = _make_resumable_manager()+ logger = MagicMock()++ pages = list(+ _make_paginated_request(+ access_token="tok",+ endpoint_name="issues",+ logger=logger,+ resumable_source_manager=manager,+ )+ )++ assert pages == [[{"id": "a"}]]+ assert session.post.call_count == 2++ @patch("time.sleep", return_value=None)+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.linear.linear.make_tracked_session")+ def test_persistent_truncated_response_raises_retryable_error_without_leaking_body(+ self, mock_session_cls: MagicMock, _mock_sleep: MagicMock+ ) -> None:+ # The partial body can embed customer data, so the retryable error must describe the failure+ # without echoing response.text.+ body = '{"data":{"issues":{"nodes":[{"title":"secret customer issue"'+ session = MagicMock()+ session.post.side_effect = [_make_truncated_response(body) for _ in range(LINEAR_MAX_RETRY_ATTEMPTS)]+ mock_session_cls.return_value = session++ manager = _make_resumable_manager()+ logger = MagicMock()++ with pytest.raises(LinearRetryableError) as exc_info:+ list(+ _make_paginated_request(+ access_token="tok",+ endpoint_name="issues",+ logger=logger,+ resumable_source_manager=manager,+ )+ )++ assert session.post.call_count == LINEAR_MAX_RETRY_ATTEMPTS+ assert "secret customer issue" not in str(exc_info.value)+class TestRateLimitBackoff:@parameterized.expand(