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-warehouse): use intercom scroll api for companies sync (#67063)

estefania2b81d70ba058
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py
index 30eb9f0c8574..fd82af71e76b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py
@@ -84,12 +84,12 @@ def _auth_headers(access_token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {access_token}", **_default_headers()}
-# The substream walk reaches `/conversations/search` and `/companies/list` via
-# POST. The shared `DEFAULT_RETRY` excludes POST from `allowed_methods`, so a
-# transient read timeout on those calls is *not* retried — unlike the GET calls
-# in the same walk, which retry transparently. These POSTs are read-only,
-# idempotent queries (the body just carries the query + cursor), so it's safe to
-# retry them on transient read timeouts and 429/5xx like everything else.
+# The substream walk reaches `/conversations/search` via POST (the companies
+# scroll walk is all GET). The shared `DEFAULT_RETRY` excludes POST from
+# `allowed_methods`, so a transient read timeout on that call is *not* retried —
+# unlike the GET calls in the same walk, which retry transparently. This POST is
+# a read-only, idempotent query (the body just carries the query + cursor), so
+# it's safe to retry it on transient read timeouts and 429/5xx like everything else.
# Derived from DEFAULT_RETRY so the shared policy stays the single source of
# truth — the only intentional difference is adding POST to allowed_methods.
_INTERCOM_RETRY = Retry(
@@ -205,11 +205,6 @@ def get_resource(
# `value: 0` matches every record. Default to "updated_at" (the only
# cursor Intercom search endpoints support) when no field is passed.
endpoint["json"] = _build_search_body(cfg, incremental_field or "updated_at", db_incremental_field_last_value)
- elif cfg.method == "POST" and cfg.paginator_kind in ("cursor", "next_url"):
- # POST list endpoints (`/companies/list`) take `per_page` in the body.
- # The next-URL paginator preserves the POST method and body when it
- # follows `pages.next`, so the body just needs to be set once.
- endpoint["json"] = {"per_page": cfg.page_size}
elif cfg.paginator_kind in ("cursor", "next_url"):
params: dict[str, Any] = {"per_page": cfg.page_size, **cfg.extra_params}
if cfg.incremental_query_param:
@@ -487,6 +482,12 @@ def intercom_source(
# of re-handshaking per request.
session = _make_intercom_session(access_token)
items = lambda: _substream_items(session, endpoint, incremental_field, db_incremental_field_last_value)
+ elif cfg.paginator_kind == "scroll":
+ # The Scroll API doesn't fit the framework paginators (the cursor is a
+ # `scroll_param`, not a request mutation), so `companies` walks it with a
+ # custom iterator. One session is reused across the whole scroll walk.
+ session = _make_intercom_session(access_token)
+ items = lambda: _iter_companies(session)
else:
config: RESTAPIConfig = {
"client": {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py
index 44a379bbea95..e605e2ab2e21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/settings.py
@@ -4,7 +4,7 @@ from typing import Literal
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-PaginatorKind = Literal["single", "cursor", "next_url", "search", "substream"]
+PaginatorKind = Literal["single", "cursor", "next_url", "search", "substream", "scroll"]
PartitionMode = Literal["md5", "datetime"]
HttpMethod = Literal["GET", "POST"]
SortMode = Literal["asc", "desc"]
@@ -77,22 +77,20 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {
paginator_kind="single",
),
"companies": IntercomEndpointConfig(
- # `POST /companies/list` is the only paginated company-listing
- # endpoint that's stable in 2.13. `GET /companies` requires a filter
- # param (it's the "Retrieve Companies" lookup, returns 400 without
- # one), and `/companies/scroll` only allows one open cursor per
- # workspace at a time so concurrent or quickly-retried syncs collide.
- # The next-URL pagination shape matches the other list endpoints
- # (`pages.next` is a full URL); the framework follows it by mutating
- # `request.url` while preserving the POST method and body.
- # per_page max is 60 here, not 150 — Intercom rejects larger values
- # with `parameter_invalid: Per Page is too big`.
+ # `GET /companies/scroll` (the Scroll API), not `POST /companies/list`.
+ # The list endpoint is hard-capped at 10,000 companies — paging past it
+ # returns `400 bad_request: page limit reached, please use scroll API`
+ # (60 per page × 167 pages ≈ the 10k ceiling). The Scroll API has no such
+ # ceiling. It's walked by `_iter_companies` (see intercom.py), routed via
+ # the `scroll` paginator_kind rather than the `RESTAPIConfig` path because
+ # the cursor lives in a `scroll_param` the framework paginators don't model.
+ # Intercom allows only one open scroll per workspace; a stale scroll left
+ # by an interrupted or concurrent sync is handled by `_open_companies_scroll`'s
+ # `scroll_exists` backoff.
name="companies",
- path="/companies/list",
+ path="/companies/scroll",
data_selector="data",
- paginator_kind="next_url",
- method="POST",
- page_size=60,
+ paginator_kind="scroll",
),
"contacts": IntercomEndpointConfig(
name="contacts",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py
index 9d99891f5be3..9d4667770ab3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py
@@ -1,4 +1,5 @@
import json
+from collections.abc import Iterable
from typing import Any, cast
import pytest
@@ -222,19 +223,6 @@ class TestGetResource:
assert _endpoint(resource)["params"]["created_at_after"] == expected_cursor
assert resource["write_disposition"] == expected_disposition
- def test_post_list_endpoint_sets_per_page_body(self):
- resource = get_resource(
- "companies",
- should_use_incremental_field=False,
- incremental_field=None,
- db_incremental_field_last_value=None,
- )
-
- endpoint = _endpoint(resource)
- assert endpoint["method"] == "POST"
- assert endpoint["json"] == {"per_page": INTERCOM_ENDPOINTS["companies"].page_size}
- assert resource["write_disposition"] == "replace"
-
@pytest.mark.parametrize(
"endpoint_name,expected_model",
[("company_attributes", "company"), ("contact_attributes", "contact")],
@@ -588,3 +576,24 @@ class TestIntercomSource:
assert response.primary_keys == cfg.primary_keys
assert response.partition_keys == [cfg.partition_key]
assert response.sort_mode == cfg.sort_mode
+
+ def test_companies_routes_through_scroll_api(self):
+ # `companies` must walk the un-capped Scroll API, never `POST /companies/list`
+ # (capped at 10,000 — paging past it returns `400 page limit reached`). This
+ # guards the dispatch: if the endpoint config reverts to a list/next_url
+ # paginator it would 400 on large workspaces. The walk itself is covered by
+ # `test_iter_companies_walks_scroll`.
+ mock_session = mock.MagicMock()
+ mock_session.get.side_effect = [
+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),
+ _make_response({"data": [], "scroll_param": "s2"}),
+ ]
+
+ with mock.patch.object(intercom_module, "make_tracked_session", return_value=mock_session):
+ response = intercom_source(access_token="token", endpoint="companies", team_id=1, job_id="job-1")
+ # `items()` is typed `Iterable | AsyncIterable`; the scroll path yields a sync iterator.
+ companies = list(cast(Iterable[dict[str, Any]], response.items()))
+
+ assert [c["id"] for c in companies] == ["co1"]
+ urls = [call.args[0] for call in mock_session.get.call_args_list]
+ assert urls and all(url.endswith("/companies/scroll") for url in urls)