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.

feat(data-warehouse): implement intercom import source (#61585)

Tom Owersebfd17c78fc3
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index da43ade57c4e..7b8b6d73bd2e 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -72,6 +72,7 @@ the row lists both.
| granola | HTTP | requests | ✅ |
| gorgias | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
+| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| klaviyo | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
| lever | HTTP | requests | ✅ |
@@ -185,7 +186,6 @@ doesn't conflict with concurrent PRs.
- greenhouse
- helpscout
- instagram
-- intercom
- iterable
- jira
- kafka
diff --git a/posthog/temporal/data_imports/sources/intercom/source.py b/posthog/temporal/data_imports/sources/intercom/source.py
index 8be19f995d62..b8ac6a13df91 100644
--- a/posthog/temporal/data_imports/sources/intercom/source.py
+++ b/posthog/temporal/data_imports/sources/intercom/source.py
@@ -52,6 +52,7 @@ class IntercomSource(SimpleSource[IntercomSourceConfig], OAuthMixin):
),
],
),
+ unreleasedSource=True,
featureFlag="dwh_intercom",
releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py
new file mode 100644
index 000000000000..82b45b279a89
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom.py
@@ -0,0 +1,322 @@
+import json
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+from requests import Request, Response
+
+from posthog.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+ JSONResponsePaginator,
+ SinglePagePaginator,
+)
+from posthog.temporal.data_imports.sources.intercom import intercom as intercom_module
+from posthog.temporal.data_imports.sources.intercom.intercom import (
+ INTERCOM_API_BASE,
+ IntercomSearchPaginator,
+ _build_paginator,
+ _build_search_body,
+ _company_segments_generator,
+ _conversation_parts_generator,
+ _iter_companies,
+ get_resource,
+ intercom_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.intercom.settings import INTERCOM_ENDPOINTS
+
+
+def _make_response(json_body: Any, status_code: int = 200, text: str = "") -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(json_body).encode() if json_body is not None else text.encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _endpoint(resource: Any) -> dict[str, Any]:
+ # `EndpointResource["endpoint"]` is typed `str | Endpoint | None`; tests build dict endpoints.
+ return cast(dict[str, Any], resource["endpoint"])
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code,schema_name,expected_valid",
+ [
+ (200, None, True),
+ (200, "contacts", True),
+ (401, None, False),
+ (401, "contacts", False),
+ # 403 at source-create is accepted (token genuine, scope may be granted per-endpoint later)
+ (403, None, True),
+ # 403 for a specific schema means the scope is genuinely missing
+ (403, "contacts", False),
+ (500, None, False),
+ ],
+ )
+ def test_status_mapping(self, status_code: int, schema_name: str | None, expected_valid: bool):
+ mock_session = mock.MagicMock()
+ mock_session.get.return_value = _make_response({"type": "admin"}, status_code=status_code, text="boom")
+
+ with mock.patch.object(intercom_module, "make_tracked_session", return_value=mock_session):
+ is_valid, error = validate_credentials("token", schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ if expected_valid:
+ assert error is None
+ else:
+ assert error is not None
+
+ def test_missing_token(self):
+ is_valid, error = validate_credentials("")
+ assert is_valid is False
+ assert error is not None and "Missing" in error
+
+ def test_request_exception_returns_invalid(self):
+ mock_session = mock.MagicMock()
+ mock_session.get.side_effect = Exception("connection reset")
+
+ with mock.patch.object(intercom_module, "make_tracked_session", return_value=mock_session):
+ is_valid, error = validate_credentials("token")
+
+ assert is_valid is False
+ assert error is not None and "connection reset" in error
+
+
+class TestSearchPaginator:
+ def test_update_state_sets_next_cursor(self):
+ paginator = IntercomSearchPaginator()
+ response = _make_response({"pages": {"next": {"starting_after": "cursor-123"}}})
+
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is True
+ assert paginator._next_cursor == "cursor-123"
+
+ def test_update_state_terminal_when_no_next(self):
+ paginator = IntercomSearchPaginator()
+ response = _make_response({"pages": {"next": None}})
+
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+ assert paginator._next_cursor is None
+
+ def test_update_state_handles_bad_json(self):
+ paginator = IntercomSearchPaginator()
+ response = _make_response(None, text="not json")
+
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is False
+
+ def test_update_request_writes_cursor_into_body(self):
+ paginator = IntercomSearchPaginator()
+ paginator.update_state(_make_response({"pages": {"next": {"starting_after": "cursor-xyz"}}}))
+
+ request = Request(method="POST", url=f"{INTERCOM_API_BASE}/contacts/search", json={"pagination": {}})
+ paginator.update_request(request)
+
+ assert request.json["pagination"]["starting_after"] == "cursor-xyz"
+
+ def test_update_request_noop_without_cursor(self):
+ paginator = IntercomSearchPaginator()
+ request = Request(method="POST", url="http://x", json={"pagination": {}})
+
+ paginator.update_request(request)
+
+ assert "starting_after" not in request.json["pagination"]
+
+
+class TestBuildSearchBody:
+ def test_full_refresh_matches_all_records(self):
+ body = _build_search_body(INTERCOM_ENDPOINTS["contacts"], "updated_at", None)
+
+ assert body["query"] == {"field": "updated_at", "operator": ">", "value": 0}
+ assert body["sort"] == {"field": "updated_at", "order": "ascending"}
+ assert body["pagination"]["per_page"] == INTERCOM_ENDPOINTS["contacts"].page_size
+
+ def test_incremental_uses_last_value(self):
+ body = _build_search_body(INTERCOM_ENDPOINTS["conversations"], "updated_at", "1700000000")
+
+ assert body["query"]["value"] == 1700000000
+
+
+class TestBuildPaginator:
+ @pytest.mark.parametrize(
+ "kind,expected_type",
+ [
+ ("search", IntercomSearchPaginator),
+ ("cursor", JSONResponseCursorPaginator),
+ ("next_url", JSONResponsePaginator),
+ ("single", SinglePagePaginator),
+ ],
+ )
+ def test_paginator_per_kind(self, kind: str, expected_type: type):
+ cfg = mock.MagicMock()
+ cfg.paginator_kind = kind
+ assert isinstance(_build_paginator(cfg), expected_type)
+
+
+NON_SUBSTREAM_ENDPOINTS = [name for name, cfg in INTERCOM_ENDPOINTS.items() if cfg.paginator_kind != "substream"]
+
+
+class TestGetResource:
+ @pytest.mark.parametrize(
+ "should_use_incremental,last_value,expected_disposition,expected_query_value",
+ [
+ (True, "1700000000", {"disposition": "merge", "strategy": "upsert"}, 1700000000),
+ # Full refresh still needs a query body; value 0 matches everything.
+ (False, None, "replace", 0),
+ ],
+ )
+ def test_search_endpoint_body_and_disposition(
+ self, should_use_incremental: bool, last_value: str | None, expected_disposition: Any, expected_query_value: int
+ ):
+ resource = get_resource(
+ "contacts",
+ should_use_incremental_field=should_use_incremental,
+ incremental_field="updated_at" if should_use_incremental else None,
+ db_incremental_field_last_value=last_value,
+ )
+
+ assert resource["write_disposition"] == expected_disposition
+ endpoint = _endpoint(resource)
+ assert endpoint["method"] == "POST"
+ assert endpoint["json"]["query"]["value"] == expected_query_value
+
+ @pytest.mark.parametrize(
+ "should_use_incremental,last_value,expected_disposition,expected_cursor",
+ [
+ (True, "1700000000", {"disposition": "merge", "strategy": "upsert"}, 1700000000),
+ # Full refresh sets the cursor to the Unix epoch start (matches everything).
+ (False, None, "replace", 0),
+ ],
+ )
+ def test_query_param_endpoint_cursor_and_disposition(
+ self, should_use_incremental: bool, last_value: str | None, expected_disposition: Any, expected_cursor: int
+ ):
+ resource = get_resource(
+ "activity_logs",
+ should_use_incremental_field=should_use_incremental,
+ incremental_field="created_at" if should_use_incremental else None,
+ db_incremental_field_last_value=last_value,
+ )
+
+ 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")],
+ )
+ def test_single_endpoint_with_extra_params(self, endpoint_name: str, expected_model: str):
+ resource = get_resource(
+ endpoint_name,
+ should_use_incremental_field=False,
+ incremental_field=None,
+ db_incremental_field_last_value=None,
+ )
+
+ assert _endpoint(resource)["params"] == {"model": expected_model}
+
+ def test_single_endpoint_without_params(self):
+ resource = get_resource(
+ "admins", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ )
+
+ assert "params" not in _endpoint(resource)
+
+ @pytest.mark.parametrize("name", NON_SUBSTREAM_ENDPOINTS)
+ def test_table_format_and_name(self, name: str):
+ resource = get_resource(
+ name, should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None
+ )
+ assert resource["name"] == name
+ assert resource["table_name"] == name
+ assert resource["table_format"] == "delta"
+
+
+class TestSubstreamGenerators:
+ def test_conversation_parts_injects_conversation_id(self):
+ mock_session = mock.MagicMock()
+ mock_session.post.side_effect = [
+ _make_response({"conversations": [{"id": "c1"}, {"id": "c2"}], "pages": {}}),
+ ]
+ mock_session.get.side_effect = [
+ _make_response({"conversation_parts": {"conversation_parts": [{"id": "p1"}, {"id": "p2"}]}}),
+ _make_response({"conversation_parts": {"conversation_parts": [{"id": "p3"}]}}),
+ ]
+
+ parts = list(_conversation_parts_generator(mock_session, "updated_at", None))
+
+ assert [p["id"] for p in parts] == ["p1", "p2", "p3"]
+ assert {p["conversation_id"] for p in parts} == {"c1", "c2"}
+
+ def test_company_segments_injects_company_id(self):
+ mock_session = mock.MagicMock()
+ mock_session.post.side_effect = [
+ _make_response({"data": [{"id": "co1"}, {"id": "co2"}], "pages": {}}),
+ ]
+ mock_session.get.side_effect = [
+ _make_response({"data": [{"id": "s1"}]}),
+ _make_response({"data": [{"id": "s2"}, {"id": "s3"}]}),
+ ]
+
+ segments = list(_company_segments_generator(mock_session))
+
+ assert [s["id"] for s in segments] == ["s1", "s2", "s3"]
+ assert segments[0]["company_id"] == "co1"
+ assert segments[1]["company_id"] == "co2"
+
+ def test_iter_companies_follows_next_url(self):
+ next_url = f"{INTERCOM_API_BASE}/companies/list?cursor=2"
+ mock_session = mock.MagicMock()
+ mock_session.post.side_effect = [
+ _make_response({"data": [{"id": "co1"}], "pages": {"next": next_url}}),
+ ]
+ mock_session.get.side_effect = [
+ _make_response({"data": [{"id": "co2"}], "pages": {}}),
+ ]
+
+ companies = list(_iter_companies(mock_session))
+
+ assert [c["id"] for c in companies] == ["co1", "co2"]
+ assert mock_session.get.call_args_list[0].args[0] == next_url
+
+
+class TestIntercomSource:
+ @pytest.mark.parametrize("endpoint", list(INTERCOM_ENDPOINTS.keys()))
+ def test_source_response_metadata(self, endpoint: str):
+ cfg = INTERCOM_ENDPOINTS[endpoint]
+ sentinel = object()
+
+ with (
+ mock.patch.object(intercom_module, "rest_api_resource", return_value=sentinel),
+ mock.patch.object(intercom_module, "make_tracked_session", return_value=mock.MagicMock()),
+ ):
+ response = intercom_source(
+ access_token="token",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == cfg.primary_keys
+ assert response.partition_keys == [cfg.partition_key]
+ assert response.sort_mode == cfg.sort_mode
diff --git a/posthog/temporal/data_imports/sources/intercom/tests/test_intercom_source.py b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom_source.py
new file mode 100644
index 000000000000..0a4e7ef2568a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/intercom/tests/test_intercom_source.py
@@ -0,0 +1,150 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import SourceFieldOauthConfig
+
+from posthog.temporal.data_imports.sources.generated_configs import IntercomSourceConfig
+from posthog.temporal.data_imports.sources.intercom.settings import INTERCOM_ENDPOINTS
+from posthog.temporal.data_imports.sources.intercom.source import IntercomSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"contacts", "conversations", "tickets", "activity_logs", "conversation_parts"}
+
+
+class TestIntercomSource:
+ def setup_method(self):
+ self.source = IntercomSource()
+ self.team_id = 123
+ self.config = IntercomSourceConfig(intercom_integration_id=456)
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.INTERCOM
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Intercom"
+ assert config.releaseStatus == "alpha"
+ assert config.unreleasedSource is True
+
+ oauth_field = config.fields[0]
+ assert isinstance(oauth_field, SourceFieldOauthConfig)
+ assert oauth_field.name == "intercom_integration_id"
+ assert oauth_field.kind == "intercom"
+ assert oauth_field.required is True
+
+ def test_get_non_retryable_errors(self):
+ errors = self.source.get_non_retryable_errors()
+ assert "401 Client Error" in errors
+ assert "403 Client Error" in errors
+
+ def test_get_schemas_covers_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {s.name for s in schemas} == set(INTERCOM_ENDPOINTS.keys())
+
+ def test_get_schemas_incremental_flags(self):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ for name, schema in schemas.items():
+ expected = name in INCREMENTAL_ENDPOINTS
+ assert schema.supports_incremental is expected, name
+ assert schema.supports_append is expected, name
+
+ def test_get_schemas_names_filter(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts", "companies"])
+
+ assert {s.name for s in schemas} == {"contacts", "companies"}
+
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.validate_intercom_credentials")
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.IntercomSource.get_oauth_integration")
+ def test_validate_credentials_success(self, mock_get_integration, mock_validate):
+ mock_get_integration.return_value = mock.MagicMock(access_token="token")
+ mock_validate.return_value = (True, None)
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is True
+ assert error is None
+ mock_get_integration.assert_called_once_with(self.config.intercom_integration_id, self.team_id)
+ mock_validate.assert_called_once_with("token", schema_name=None)
+
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.IntercomSource.get_oauth_integration")
+ def test_validate_credentials_integration_value_error(self, mock_get_integration):
+ mock_get_integration.side_effect = ValueError("integration not found")
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error == "integration not found"
+
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.IntercomSource.get_oauth_integration")
+ def test_validate_credentials_no_access_token(self, mock_get_integration):
+ mock_get_integration.return_value = mock.MagicMock(access_token=None)
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error is not None and "no access token" in error
+
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.intercom_source")
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.IntercomSource.get_oauth_integration")
+ def test_source_for_pipeline_plumbing(self, mock_get_integration, mock_intercom_source):
+ mock_get_integration.return_value = mock.MagicMock(access_token="token")
+ sentinel = mock.MagicMock()
+ mock_intercom_source.return_value = sentinel
+
+ inputs = mock.MagicMock()
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.schema_name = "contacts"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updated_at"
+ inputs.db_incremental_field_last_value = "1700000000"
+
+ result = self.source.source_for_pipeline(self.config, inputs)
+
+ assert result is sentinel
+ mock_intercom_source.assert_called_once_with(
+ access_token="token",
+ endpoint="contacts",
+ team_id=self.team_id,
+ job_id="job-1",
+ should_use_incremental_field=True,
+ incremental_field="updated_at",
+ db_incremental_field_last_value="1700000000",
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.intercom_source")
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.IntercomSource.get_oauth_integration")
+ def test_source_for_pipeline_drops_incremental_args_when_not_incremental(
+ self, mock_get_integration, mock_intercom_source
+ ):
+ mock_get_integration.return_value = mock.MagicMock(access_token="token")
+
+ inputs = mock.MagicMock()
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.schema_name = "companies"
+ inputs.should_use_incremental_field = False
+ inputs.incremental_field = "updated_at"
+ inputs.db_incremental_field_last_value = "1700000000"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ _, kwargs = mock_intercom_source.call_args
+ assert kwargs["incremental_field"] is None
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ @mock.patch("posthog.temporal.data_imports.sources.intercom.source.IntercomSource.get_oauth_integration")
+ def test_source_for_pipeline_no_access_token_raises(self, mock_get_integration):
+ mock_get_integration.return_value = mock.MagicMock(access_token=None)
+
+ inputs = mock.MagicMock()
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.schema_name = "contacts"
+
+ with pytest.raises(ValueError, match="Intercom access token not found for job job-1"):
+ self.source.source_for_pipeline(self.config, inputs)