: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(intercom): retry transient companies scroll 5xx inline (#64860)
Tom Owersd31e9da97f18
diff --git a/posthog/temporal/data_imports/sources/intercom/intercom.py b/posthog/temporal/data_imports/sources/intercom/intercom.pyindex 3761eb7c4929..94786f913793 100644--- a/posthog/temporal/data_imports/sources/intercom/intercom.py+++ b/posthog/temporal/data_imports/sources/intercom/intercom.py@@ -50,6 +50,16 @@ def _is_scroll_exists(exc: HTTPError) -> bool:return any(isinstance(e, dict) and e.get("code") == "scroll_exists" for e in errors or [])+def _is_server_error(exc: HTTPError) -> bool:+ """Intercom's companies Scroll API intermittently returns a 5xx mid-walk —+ a transient backend blip, not a poisoned cursor. Retrying the identical+ scroll request clears it, so back off and retry inline rather than failing+ the whole sync. Distinct from the short transport-level retry: this gives+ the flaky endpoint a wider window before a Temporal activity retry."""+ resp = exc.response+ return resp is not None and 500 <= resp.status_code < 600++def _default_headers() -> dict[str, str]:return {"Accept": "application/json",@@ -285,6 +295,39 @@ def _conversation_parts_generator(_SCROLL_EXISTS_BACKOFF_SECONDS = 60_SCROLL_EXISTS_MAX_RETRIES = 2+# Transient 5xx from the companies Scroll API (see `_is_server_error`). Retry the+# identical request inline with exponential backoff, then let it surface so+# Temporal retries the activity (which re-opens a fresh scroll).+_SCROLL_SERVER_ERROR_BACKOFF_SECONDS = 2.0+_SCROLL_SERVER_ERROR_MAX_RETRIES = 3+++def _scroll_companies_get(session: Session, scroll_param: str | None = None) -> dict[str, Any]:+ """Fetch one `/companies/scroll` page, retrying a transient 5xx inline.++ `scroll_param` is None to open the scroll, or the cursor from the prior page+ to continue it. Retrying the same request is safe — the cursor doesn't+ advance until a page is returned, so a retried call yields the same page+ without duplicating or skipping rows."""+ params = {"scroll_param": scroll_param} if scroll_param is not None else None+ for attempt in range(_SCROLL_SERVER_ERROR_MAX_RETRIES + 1):+ try:+ return _intercom_get(session, "/companies/scroll", params=params)+ except HTTPError as exc:+ if _is_server_error(exc) and attempt < _SCROLL_SERVER_ERROR_MAX_RETRIES:+ wait = _SCROLL_SERVER_ERROR_BACKOFF_SECONDS * (2**attempt)+ logger.warning(+ "intercom_companies_scroll_server_error_retry",+ attempt=attempt + 1,+ backoff_seconds=wait,+ status_code=exc.response.status_code if exc.response is not None else None,+ )+ time.sleep(wait)+ continue+ raise+ # Unreachable: the final attempt either returns or re-raises above.+ raise AssertionError("unreachable")+def _open_companies_scroll(session: Session) -> dict[str, Any]:"""Open a fresh companies scroll, waiting out a stale `scroll_exists` lock.@@ -297,7 +340,7 @@ def _open_companies_scroll(session: Session) -> dict[str, Any]:yet at this stage)."""for attempt in range(_SCROLL_EXISTS_MAX_RETRIES + 1):try:- return _intercom_get(session, "/companies/scroll")+ return _scroll_companies_get(session)except HTTPError as exc:if _is_scroll_exists(exc) and attempt < _SCROLL_EXISTS_MAX_RETRIES:logger.warning(@@ -327,7 +370,7 @@ def _iter_companies(session: Session) -> Iterator[dict[str, Any]]:if scroll_param is None:payload = _open_companies_scroll(session)else:- payload = _intercom_get(session, "/companies/scroll", params={"scroll_param": scroll_param})+ payload = _scroll_companies_get(session, scroll_param)data = payload.get("data") or []if not data:returndiff --git a/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.pyindex 1646a99cb990..8d1b9ef17a33 100644--- a/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py+++ b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py@@ -22,6 +22,7 @@ from posthog.temporal.data_imports.sources.intercom.intercom import (_company_segments_generator,_conversation_parts_generator,_is_scroll_exists,+ _is_server_error,_iter_companies,_make_intercom_session,get_resource,@@ -452,6 +453,77 @@ class TestCompaniesScrollExists:assert mock_session.get.call_count == 1+class TestCompaniesScrollServerError:+ @pytest.mark.parametrize(+ "status_code,expected",+ [+ (500, True),+ (502, True),+ (503, True),+ (504, True),+ (400, False),+ (404, False),+ (429, False),+ (200, False),+ ],+ )+ def test_is_server_error(self, status_code: int, expected: bool):+ assert _is_server_error(_http_error(None, status_code=status_code, text="boom")) is expected++ def test_iter_companies_retries_continuation_server_error(self):+ # A transient 5xx mid-walk (the observed error: 500 on+ # `/companies/scroll?scroll_param=...`) is retried inline against the same+ # scroll_param, so the walk continues without re-opening or duplicating rows.+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),+ _make_response(None, status_code=500, text="Server Error"),+ _make_response({"data": [{"id": "co2"}], "scroll_param": "s2"}),+ _make_response({"data": []}),+ ]++ with mock.patch.object(intercom_module.time, "sleep") as sleep:+ companies = list(_iter_companies(mock_session))++ assert [c["id"] for c in companies] == ["co1", "co2"]+ sleep.assert_called_once_with(intercom_module._SCROLL_SERVER_ERROR_BACKOFF_SECONDS)+ # The retried continuation reuses the same scroll_param — the cursor only+ # advances once a page is returned.+ assert mock_session.get.call_args_list[2].kwargs["params"] == {"scroll_param": "s1"}++ def test_iter_companies_retries_open_server_error(self):+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response(None, status_code=503, text="Service Unavailable"),+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),+ _make_response({"data": []}),+ ]++ with mock.patch.object(intercom_module.time, "sleep"):+ companies = list(_iter_companies(mock_session))++ assert [c["id"] for c in companies] == ["co1"]+ # The retried open carries no scroll_param.+ assert mock_session.get.call_args_list[1].kwargs["params"] is None++ def test_iter_companies_reraises_server_error_after_max_retries(self):+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),+ *[+ _make_response(None, status_code=500, text="Server Error")+ for _ in range(intercom_module._SCROLL_SERVER_ERROR_MAX_RETRIES + 1)+ ],+ ]++ with mock.patch.object(intercom_module.time, "sleep"):+ with pytest.raises(HTTPError):+ list(_iter_companies(mock_session))++ # One open + every continuation attempt (initial + retries) before surfacing.+ assert mock_session.get.call_count == intercom_module._SCROLL_SERVER_ERROR_MAX_RETRIES + 2++class TestSubstreamSessionRetries:def test_idempotent_search_posts_are_retryable(self):# The substream walk reaches `/conversations/search` and `/companies/list`