: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(warehouse): coerce Intercom owner_id and waiting_since to string (#74012)
Kyle Swanke062ee89c674
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/row_transforms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/row_transforms.pynew file mode 100644index 000000000000..a2762bab2713--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/row_transforms.py@@ -0,0 +1,21 @@+"""Shared per-item row transforms usable as REST-source `data_map` callables.++Sources supply their own `data_map` transforms, but some transforms recur across+sources. Centralize those here so a source doesn't re-implement the same loop.+"""++from collections.abc import Iterable+from typing import Any+++def coerce_fields_to_str(item: dict[str, Any], fields: Iterable[str]) -> dict[str, Any]:+ """Stringify the named fields in place, so a field whose JSON type varies across+ records (int in some, string in others) infers one stable type when the pipeline+ builds Arrow batches. `None` is left as-is to preserve nullability. Mutates and+ returns `item` so it can be used directly as a `data_map`.+ """+ for field in fields:+ value = item.get(field)+ if value is not None:+ item[field] = str(value)+ return itemdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_row_transforms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_row_transforms.pynew file mode 100644index 000000000000..b0715ab253c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_row_transforms.py@@ -0,0 +1,25 @@+from typing import Any++import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.common.row_transforms import coerce_fields_to_str+++class TestCoerceFieldsToStr:+ @pytest.mark.parametrize(+ "item,fields,expected",+ [+ # int -> str: the type flip that breaks Arrow batch merging.+ ({"owner_id": 42}, ["owner_id"], {"owner_id": "42"}),+ # An already-string value is unchanged.+ ({"owner_id": "42"}, ["owner_id"], {"owner_id": "42"}),+ # None is preserved so the column stays nullable.+ ({"owner_id": None}, ["owner_id"], {"owner_id": None}),+ # A missing field is a no-op.+ ({"name": "x"}, ["owner_id"], {"name": "x"}),+ # Only named fields are touched.+ ({"owner_id": 1, "count": 2}, ["owner_id"], {"owner_id": "1", "count": 2}),+ ],+ )+ def test_coerce_fields_to_str(self, item: dict[str, Any], fields: list[str], expected: dict[str, Any]):+ assert coerce_fields_to_str(item, fields) == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.pyindex e062488dbe1b..255c20d31d4a 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@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resEndpoint,EndpointResource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.row_transforms import coerce_fields_to_strfrom products.warehouse_sources.backend.temporal.data_imports.sources.intercom.settings import (INTERCOM_ENDPOINTS,IntercomEndpointConfig,@@ -239,7 +240,7 @@ def get_resource()write_disposition: Any = {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace"- return {+ resource: EndpointResource = {"name": cfg.name,"table_name": cfg.name,"write_disposition": write_disposition,@@ -247,6 +248,12 @@ def get_resource("table_format": "delta",}+ if cfg.coerce_string_fields:+ coerce_fields = cfg.coerce_string_fields+ resource["data_map"] = lambda item: coerce_fields_to_str(item, coerce_fields)++ return resource+def _resolve_intercom_url(path_or_url: str) -> str:"""Accept either an API path or a full URL (e.g. a `pages.next` link)."""@@ -527,10 +534,18 @@ def _substream_items(# walk every conversation. `updated_at` is the only declared# cursor, so default to it for the parent search filter.incremental_field = "updated_at"- return _conversation_parts_generator(session, incremental_field, db_incremental_field_last_value)- if endpoint == "company_segments":- return _company_segments_generator(session)- raise ValueError(f"Unknown Intercom substream endpoint: {endpoint}")+ base = _conversation_parts_generator(session, incremental_field, db_incremental_field_last_value)+ elif endpoint == "company_segments":+ base = _company_segments_generator(session)+ else:+ raise ValueError(f"Unknown Intercom substream endpoint: {endpoint}")++ # Substreams bypass the REST framework's `data_map`, so coerce type-flip+ # fields here to keep every Arrow batch's schema consistent (see get_resource).+ coerce_fields = INTERCOM_ENDPOINTS[endpoint].coerce_string_fields+ if not coerce_fields:+ return base+ return (coerce_fields_to_str(item, coerce_fields) for item in base)def validate_credentials(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.pyindex e605e2ab2e21..a0662907fe5b 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@@ -31,6 +31,9 @@ class IntercomEndpointConfig:incremental_query_param: str | None = None# Substream wiring — when set, this endpoint is fetched per-row of `parent_endpoint`.parent_endpoint: str | None = None+ # Fields whose Intercom JSON type is inconsistent across records (int vs string);+ # coerced to string at the source so every Arrow batch infers one stable type.+ coerce_string_fields: list[str] = field(default_factory=list)# Endpoint contracts validated against the live Intercom REST API (version 2.13).@@ -99,6 +102,7 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {paginator_kind="search",method="POST",partition_key="created_at",+ coerce_string_fields=["owner_id"],),"conversations": IntercomEndpointConfig(name="conversations",@@ -175,6 +179,7 @@ INTERCOM_ENDPOINTS: dict[str, IntercomEndpointConfig] = {paginator_kind="substream",parent_endpoint="conversations",partition_key="created_at",+ coerce_string_fields=["waiting_since"],),"company_segments": IntercomEndpointConfig(# Substream of `companies`. Intercom doesn't expose a server-sidediff --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.pyindex eb1879834ed4..2832d11e7558 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@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.intercom.i_iter_companies,_make_intercom_session,_rate_limit_backoff_seconds,+ _substream_items,get_resource,intercom_source,validate_credentials,@@ -259,6 +260,72 @@ class TestGetResource:assert resource["table_format"] == "delta"+class TestCoerceStringFields:+ def test_contacts_data_map_coerces_owner_id(self):+ # REST-path wiring: contacts declares owner_id in coerce_string_fields, so+ # get_resource must attach a data_map that stringifies it before rows hit Arrow.+ resource = get_resource(+ "contacts", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None+ )+ data_map = resource.get("data_map")+ assert data_map is not None+ assert data_map({"owner_id": 7, "id": "c1"}) == {"owner_id": "7", "id": "c1"}++ def test_endpoint_without_coerce_fields_has_no_data_map(self):+ # Only endpoints declaring coerce_string_fields get a data_map — others stay untouched.+ resource = get_resource(+ "admins", should_use_incremental_field=False, incremental_field=None, db_incremental_field_last_value=None+ )+ assert "data_map" not in resource++ def test_conversation_parts_substream_coerces_waiting_since(self):+ # Substream-path wiring: conversation_parts bypasses the framework's data_map,+ # so _substream_items must coerce waiting_since itself. Mixed int/str/None across+ # parts previously produced int64-vs-string Arrow batches that failed to merge.+ mock_session = mock.MagicMock()+ mock_session.post.side_effect = [+ _make_response({"conversations": [{"id": "c1"}], "pages": {}}),+ ]+ mock_session.get.side_effect = [+ _make_response(+ {+ "conversation_parts": {+ "conversation_parts": [+ {"id": "p1", "waiting_since": 1700000000},+ {"id": "p2", "waiting_since": "1700000001"},+ {"id": "p3", "waiting_since": None},+ ]+ }+ }+ ),+ ]++ parts = list(_substream_items(mock_session, "conversation_parts", "updated_at", None))++ assert [p["waiting_since"] for p in parts] == ["1700000000", "1700000001", None]++ def test_substream_without_coerce_fields_passes_rows_through_untouched(self):+ # company_segments declares no coerce_string_fields, so _substream_items must+ # return its rows unchanged — a numeric field stays an int, not stringified.+ # Guards the refactor against coercing endpoints that opted out.+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),+ _make_response({"data": []}),+ _make_response({"data": [{"id": "seg1", "count": 5}]}),+ ]++ segments = list(_substream_items(mock_session, "company_segments", None, None))++ assert segments == [{"id": "seg1", "count": 5, "company_id": "co1"}]++ def test_unknown_substream_endpoint_raises(self):+ # Adding a substream endpoint config without wiring it into _substream_items+ # must fail loud, not silently yield nothing.+ with pytest.raises(ValueError):+ list(_substream_items(mock.MagicMock(), "not_a_real_endpoint", None, None))++class TestSubstreamGenerators:def test_conversation_parts_injects_conversation_id(self):mock_session = mock.MagicMock()