: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 companies scroll past stale scroll_exists lock (#63783)
Tom Owers134b74e438f5
diff --git a/posthog/temporal/data_imports/sources/intercom/intercom.py b/posthog/temporal/data_imports/sources/intercom/intercom.pyindex c75e0243c0e0..3761eb7c4929 100644--- a/posthog/temporal/data_imports/sources/intercom/intercom.py+++ b/posthog/temporal/data_imports/sources/intercom/intercom.py@@ -1,3 +1,4 @@+import timefrom collections.abc import AsyncIterable, Callable, Iterable, Iteratorfrom typing import Any, Optional@@ -31,6 +32,24 @@ def _is_not_found(exc: HTTPError) -> bool:return exc.response is not None and exc.response.status_code == 404+def _is_scroll_exists(exc: HTTPError) -> bool:+ """Intercom permits only one open companies scroll per workspace; opening a+ new scroll while another is still alive returns `400` with `code:+ scroll_exists`. A scroll left behind by an interrupted or concurrent sync+ clears itself once it expires (~1 min idle), so the lock is transient —+ wait it out and retry rather than failing the whole sync. Match on the+ stable error `code`, not the message text or URL."""+ resp = exc.response+ if resp is None or resp.status_code != 400:+ return False+ try:+ body = resp.json()+ except Exception:+ return False+ errors = body.get("errors") if isinstance(body, dict) else None+ return any(isinstance(e, dict) and e.get("code") == "scroll_exists" for e in errors or [])++def _default_headers() -> dict[str, str]:return {"Accept": "application/json",@@ -259,6 +278,40 @@ def _conversation_parts_generator(yield part+# Intercom expires an idle companies scroll after ~1 minute, so a stale scroll+# left by an interrupted or concurrent sync clears within that window. Wait+# past it before retrying the open, and cap the retries so a genuinely stuck+# lock still surfaces instead of looping forever.+_SCROLL_EXISTS_BACKOFF_SECONDS = 60+_SCROLL_EXISTS_MAX_RETRIES = 2+++def _open_companies_scroll(session: Session) -> dict[str, Any]:+ """Open a fresh companies scroll, waiting out a stale `scroll_exists` lock.++ See `_is_scroll_exists`: a scroll left open by an interrupted or concurrent+ sync blocks a new one with `400 scroll_exists` until it expires. Back off+ and retry the open instead of failing — re-opening is the only recovery, as+ a scroll can't be resumed from a point, only restarted from the beginning+ (which is exactly what opening again does, and no rows have been yielded+ yet at this stage)."""+ for attempt in range(_SCROLL_EXISTS_MAX_RETRIES + 1):+ try:+ return _intercom_get(session, "/companies/scroll")+ except HTTPError as exc:+ if _is_scroll_exists(exc) and attempt < _SCROLL_EXISTS_MAX_RETRIES:+ logger.warning(+ "intercom_companies_scroll_exists_retry",+ attempt=attempt + 1,+ backoff_seconds=_SCROLL_EXISTS_BACKOFF_SECONDS,+ )+ time.sleep(_SCROLL_EXISTS_BACKOFF_SECONDS)+ continue+ raise+ # Unreachable: the final attempt either returns or re-raises above.+ raise AssertionError("unreachable")++def _iter_companies(session: Session) -> Iterator[dict[str, Any]]:"""Walk every company via `GET /companies/scroll` (full refresh).@@ -267,12 +320,14 @@ def _iter_companies(session: Session) -> Iterator[dict[str, Any]]:please use scroll API`. The Scroll API has no such ceiling: each responsecarries a `scroll_param` to feed into the next request, and the walk endswhen `data` comes back empty (the scroll param then expires). Only one- scroll can be open per workspace at a time — fine here, since this is the- sole scroll user and a schema never syncs concurrently with itself."""+ scroll can be open per workspace at a time, so the initial open backs off+ past a stale `scroll_exists` lock (see `_open_companies_scroll`)."""scroll_param: str | None = Nonewhile True:- params = {"scroll_param": scroll_param} if scroll_param else None- payload = _intercom_get(session, "/companies/scroll", params=params)+ if scroll_param is None:+ payload = _open_companies_scroll(session)+ else:+ payload = _intercom_get(session, "/companies/scroll", params={"scroll_param": 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 76f762324126..1646a99cb990 100644--- a/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py+++ b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py@@ -21,6 +21,7 @@ from posthog.temporal.data_imports.sources.intercom.intercom import (_build_search_body,_company_segments_generator,_conversation_parts_generator,+ _is_scroll_exists,_iter_companies,_make_intercom_session,get_resource,@@ -43,6 +44,16 @@ def _endpoint(resource: Any) -> dict[str, Any]:return cast(dict[str, Any], resource["endpoint"])+SCROLL_EXISTS_BODY = {+ "type": "error.list",+ "errors": [{"code": "scroll_exists", "message": "scroll already exists for this workspace"}],+}+++def _http_error(json_body: Any, status_code: int = 400, text: str = "") -> HTTPError:+ return HTTPError(response=_make_response(json_body, status_code=status_code, text=text))++class TestValidateCredentials:@pytest.mark.parametrize("status_code,schema_name,expected_valid",@@ -375,6 +386,72 @@ class TestSubstreamGenerators:assert mock_session.get.call_count == 1+class TestCompaniesScrollExists:+ @pytest.mark.parametrize(+ "body,status_code,expected",+ [+ (SCROLL_EXISTS_BODY, 400, True),+ # A different 400 (e.g. a genuinely malformed request) is not the transient lock.+ ({"type": "error.list", "errors": [{"code": "parameter_invalid"}]}, 400, False),+ # Right code, wrong status — not the scroll lock.+ (SCROLL_EXISTS_BODY, 404, False),+ # No errors array at all.+ ({"type": "error.list"}, 400, False),+ ],+ )+ def test_is_scroll_exists(self, body: Any, status_code: int, expected: bool):+ assert _is_scroll_exists(_http_error(body, status_code=status_code)) is expected++ def test_is_scroll_exists_handles_non_json_body(self):+ assert _is_scroll_exists(_http_error(None, status_code=400, text="<html>bad</html>")) is False++ def test_iter_companies_retries_open_past_stale_scroll(self):+ # A scroll left open by an interrupted/concurrent sync blocks the open with+ # `400 scroll_exists` until it expires. Wait it out and retry the open+ # rather than failing the whole sync.+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response(SCROLL_EXISTS_BODY, status_code=400),+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),+ _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"]+ sleep.assert_called_once_with(intercom_module._SCROLL_EXISTS_BACKOFF_SECONDS)+ # The retried open carries no scroll_param — a scroll can only restart from+ # the beginning, never resume.+ assert mock_session.get.call_args_list[1].kwargs["params"] is None++ def test_iter_companies_reraises_scroll_exists_after_max_retries(self):+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response(SCROLL_EXISTS_BODY, status_code=400)+ for _ in range(intercom_module._SCROLL_EXISTS_MAX_RETRIES + 1)+ ]++ with mock.patch.object(intercom_module.time, "sleep"):+ with pytest.raises(HTTPError):+ list(_iter_companies(mock_session))++ assert mock_session.get.call_count == intercom_module._SCROLL_EXISTS_MAX_RETRIES + 1++ def test_iter_companies_does_not_retry_other_400(self):+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response({"type": "error.list", "errors": [{"code": "parameter_invalid"}]}, status_code=400),+ ]++ with mock.patch.object(intercom_module.time, "sleep") as sleep:+ with pytest.raises(HTTPError):+ list(_iter_companies(mock_session))++ sleep.assert_not_called()+ assert mock_session.get.call_count == 1++class TestSubstreamSessionRetries:def test_idempotent_search_posts_are_retryable(self):# The substream walk reaches `/conversations/search` and `/companies/list`