: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
feat(copper): sync activities, stages, statuses and activity types (#103458)
Tom Owers27bae4f5ae36
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 1fcf99b20372..1828869231be 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2030,10 +2030,10 @@ Today (11): `companies`, `contact_types`, `customer_sources`, `leads`, `loss_reaDiffed against: <https://developer.copper.com/index.html>-- [ ] `POST /v1/activities/search` — the CRM interaction log (calls, emails, notes, status changes) - the main analytical event stream, entirely unsynced (high)-- [ ] `GET /v1/pipeline_stages (and /v1/pipelines/{id}/stages)` — stage lookup; opportunities carry pipeline_stage_id and pipelines is already synced, so funnel analysis is blocked on this one table (high)-- [ ] `GET /v1/lead_statuses` — status lookup; every lead row carries status_id with nothing to resolve it against (high)-- [ ] `GET /v1/activity_types (and /v1/custom_activity_types)` — lookup resolving activity_type on activity rows; also needed to separate user activity from system activity (high)+- [x] `POST /v1/activities/search` — the CRM interaction log (calls, emails, notes, status changes) - the main analytical event stream, entirely unsynced (high)+- [x] `GET /v1/pipeline_stages (and /v1/pipelines/{id}/stages)` — stage lookup; opportunities carry pipeline_stage_id and pipelines is already synced, so funnel analysis is blocked on this one table (high)+- [x] `GET /v1/lead_statuses` — status lookup; every lead row carries status_id with nothing to resolve it against (high)+- [x] `GET /v1/activity_types (and /v1/custom_activity_types)` — lookup resolving activity_type on activity rows; also needed to separate user activity from system activity (high)- [ ] `GET /v1/custom_field_definitions` — resolves custom_field_definition_id, which appears on companies, people, leads, opportunities and projects (high)- [ ] `GET /v1/tags` — tag lookup for segmenting every record type (medium)- [ ] `GET /v1/related_items (view all records related to an entity)` — cross-object relationship junction linking companies, people, opportunities and projects (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/canonical_descriptions.pyindex f38aa33496f7..53c2785d954c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/canonical_descriptions.py@@ -118,6 +118,22 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {activity_type="The activity type associated with the task.",),},+ "activities": {+ "description": "An entry in the Copper interaction log: a user-entered note, call or meeting, or a system-generated record of a property or pipeline stage change.",+ "docs_url": "https://developer.copper.com/activities/list-activities-search.html",+ "columns": {+ "id": "Unique identifier for the activity.",+ "type": "The activity type, as an object carrying the type id and its category (user or system).",+ "parent": "The record the activity belongs to, as an object carrying the record id and its type (lead, person, company, opportunity, project or task).",+ "details": "Text body of the activity, when it has one.",+ "user_id": "Unique identifier of the user who performed the activity.",+ "activity_date": "Unix timestamp (seconds) of when the activity took place.",+ "old_value": "Value of the changed property before the activity, for system activities.",+ "new_value": "Value of the changed property after the activity, for system activities.",+ "date_created": "Unix timestamp (seconds) of when the activity was created.",+ "date_modified": "Unix timestamp (seconds) of when the activity was last modified.",+ },+ },"users": {"description": "A user (team member) in the Copper CRM account.","docs_url": "https://developer.copper.com/users/list-users-search.html",@@ -160,4 +176,48 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"name": "Name of the contact type.",},},+ "pipeline_stages": {+ "description": "A stage within a sales pipeline, defining where an opportunity sits in that pipeline.",+ "docs_url": "https://developer.copper.com/opportunities/list-pipeline-stages.html",+ "columns": {+ "id": "Unique identifier for the pipeline stage.",+ "name": "Name of the pipeline stage.",+ "pipeline_id": "Unique identifier of the pipeline this stage belongs to.",+ "win_probability": "Expected probability (0-100) of winning an opportunity in this stage.",+ },+ },+ "lead_statuses": {+ "description": "A reference list of statuses marking where a lead sits in the qualification process.",+ "docs_url": "https://developer.copper.com/leads/list-lead-statuses.html",+ "columns": {+ "id": "Unique identifier for the lead status.",+ "name": "Name of the lead status.",+ "order": "Position of the status in the list as displayed in the app.",+ "is_default": "Whether this status is selected by default on a new lead.",+ },+ },+ "activity_types": {+ "description": "A reference list of the activity types in the account. Types in the user category are user-entered (notes, calls, meetings and any custom types); types in the system category are generated by Copper.",+ "docs_url": "https://developer.copper.com/activities/list-activity-types.html",+ "columns": {+ "id": "Identifier of the activity type. Unique within its category, not across both.",+ "category": "Category of the activity type: user or system.",+ "name": "Name of the activity type.",+ "is_disabled": "For custom activity types, whether the type is disabled.",+ "count_as_interaction": "For user activity types, whether activities of this type count toward interactions data.",+ },+ },+ "custom_activity_types": {+ "description": "An activity type created for the account, with the display settings the app uses for it.",+ "docs_url": "https://developer.copper.com/custom-fields/general/list-all-custom-activity-types.html",+ "columns": {+ "id": "Unique identifier for the custom activity type.",+ "company_id": "Unique identifier of the Copper account the type belongs to.",+ "icon_type": "Icon the app shows for activities of this type.",+ "is_disabled": "Whether the type is disabled.",+ "is_interaction": "Whether activities of this type count as an interaction.",+ "name": "Name of the custom activity type.",+ "is_default_task_type": "Whether this type is the default for newly created tasks.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/copper.py b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/copper.pyindex 660563598962..7ed0697cc885 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/copper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/copper.py@@ -26,14 +26,6 @@ COPPER_BASE_URL = "https://api.copper.com/developer_api/v1"# Copper requires this header on every request; "developer" is the documented value for API-key auth.COPPER_APPLICATION = "developer"-# Maps an advertised incremental field to its server-side filter param and sort column.-# Copper's search endpoints filter by `minimum_modified_date` / `minimum_created_date`-# (inclusive Unix-epoch-seconds bounds) and sort by `date_modified` / `date_created`.-INCREMENTAL_FIELD_TO_PARAMS: dict[str, tuple[str, str]] = {- "date_modified": ("minimum_modified_date", "date_modified"),- "date_created": ("minimum_created_date", "date_created"),-}-@dataclasses.dataclassclass CopperResumeConfig:@@ -124,15 +116,21 @@ def _build_search_body() -> dict[str, Any]:body: dict[str, Any] = {"page_size": page_size}- if should_use_incremental_field and incremental_field in INCREMENTAL_FIELD_TO_PARAMS:- min_param, sort_field = INCREMENTAL_FIELD_TO_PARAMS[incremental_field]- body["sort_by"] = sort_field- body["sort_direction"] = "asc"+ if config.incremental_ceiling_param is not None:+ # Applied on every sync, not just incremental ones, so a future-dated row can never enter+ # the table and become the watermark.+ body[config.incremental_ceiling_param] = int(datetime.now(UTC).timestamp())++ min_param = config.incremental_params.get(incremental_field or "") if should_use_incremental_field else None+ if min_param is not None:+ if config.sortable:+ body["sort_by"] = incremental_field+ body["sort_direction"] = "asc"last_value = _to_unix_seconds(db_incremental_field_last_value)if last_value is not None:# Inclusive bound: the boundary row is re-fetched and deduped by merge on primary key.body[min_param] = last_value- elif config.full_refresh_sort:+ elif config.sortable and config.full_refresh_sort:body["sort_by"] = config.full_refresh_sortbody["sort_direction"] = "asc"@@ -195,8 +193,9 @@ def copper_source("endpoint": {"path": config.path,"method": config.method,- # Copper responses are bare JSON arrays, so there's no data_selector.+ # Most Copper responses are bare JSON arrays, so data_selector is usually unset."json": body,+ "data_selector": config.data_selector,"paginator": paginator,},}@@ -227,11 +226,11 @@ def copper_source(return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=[config.primary_key],+ primary_keys=config.primary_keys,partition_count=1,partition_size=1,partition_mode=config.partition_mode,partition_format=config.partition_format,partition_keys=config.partition_keys,- sort_mode="asc",+ sort_mode=config.sort_mode,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/settings.pyindex 644f2f4f93a6..0b5ba0001c87 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/settings.py@@ -1,15 +1,19 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Literal+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (PartitionFormat,PartitionMode,+ SortMode,)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Copper records expose `date_created` and `date_modified` as Unix epoch seconds (integers).DATE_MODIFIED = "date_modified"DATE_CREATED = "date_created"+ACTIVITY_DATE = "activity_date"ID = "id"# Copper caps `page_size` at 200 for the search endpoints.@@ -31,8 +35,25 @@ INCREMENTAL_FIELDS_MODIFIED_CREATED: list[IncrementalField] = [},]+# `/activities/search` filters on the activity date only — it has no modified/created filter.+INCREMENTAL_FIELDS_ACTIVITY_DATE: list[IncrementalField] = [+ {+ "label": ACTIVITY_DATE,+ "type": IncrementalFieldType.Integer,+ "field": ACTIVITY_DATE,+ "field_type": IncrementalFieldType.Integer,+ },+]++# Inclusive minimum-date params the record search endpoints accept, per advertised incremental field.+SEARCH_INCREMENTAL_PARAMS = {+ DATE_MODIFIED: "minimum_modified_date",+ DATE_CREATED: "minimum_created_date",+}+ACTIVITY_INCREMENTAL_PARAMS = {ACTIVITY_DATE: "minimum_activity_date"}-@dataclass++@frozenclass CopperEndpointConfig:name: strpath: str@@ -41,13 +62,23 @@ class CopperEndpointConfig:# GET reference endpoints return the full collection in one unpaginated array.paginated: bool = Trueincremental_fields: list[IncrementalField] = field(default_factory=list)+ # Maps each advertised incremental field to the search body's inclusive minimum-date param.+ incremental_params: dict[str, str] = field(default_factory=dict)+ # Search param capping the window at the sync's start time, for endpoints whose incremental+ # field the customer can edit.+ incremental_ceiling_param: str | None = None# Stable creation timestamp used for partitioning (never `date_modified`).partition_keys: list[str] | None = Nonepartition_mode: PartitionMode | None = Nonepartition_format: PartitionFormat | None = None- primary_key: str = ID+ primary_keys: list[str] = field(default_factory=lambda: [ID])+ # Whether the search body accepts `sort_by` / `sort_direction`.+ sortable: bool = True# Sort field applied on full-refresh syncs to keep pagination stable.full_refresh_sort: str | None = DATE_CREATED+ sort_mode: SortMode = "asc"+ # Set when the response wraps rows in an envelope instead of returning a bare array.+ data_selector: str | None = Nonedef _searchable(name: str, path: str) -> CopperEndpointConfig:@@ -57,6 +88,7 @@ def _searchable(name: str, path: str) -> CopperEndpointConfig:method="POST",paginated=True,incremental_fields=INCREMENTAL_FIELDS_MODIFIED_CREATED,+ incremental_params=SEARCH_INCREMENTAL_PARAMS,partition_keys=[DATE_CREATED],partition_mode="datetime",partition_format="week",@@ -82,6 +114,26 @@ COPPER_ENDPOINTS: dict[str, CopperEndpointConfig] = {"opportunities": _searchable("opportunities", "/opportunities/search"),"projects": _searchable("projects", "/projects/search"),"tasks": _searchable("tasks", "/tasks/search"),+ # Activities: the CRM interaction log. Same page-based search, but it takes no sort params and+ # answers newest-first, and the only server-side filter is on `activity_date`. That date is+ # user-editable, so the window is capped at the sync's start time: one activity dated years+ # ahead would otherwise become the watermark and hide every later activity behind it. An+ # activity backdated below the watermark still needs a full refresh to appear.+ "activities": CopperEndpointConfig(+ name="activities",+ path="/activities/search",+ method="POST",+ paginated=True,+ incremental_fields=INCREMENTAL_FIELDS_ACTIVITY_DATE,+ incremental_params=ACTIVITY_INCREMENTAL_PARAMS,+ incremental_ceiling_param="maximum_activity_date",+ partition_keys=[DATE_CREATED],+ partition_mode="datetime",+ partition_format="week",+ sortable=False,+ full_refresh_sort=None,+ sort_mode="desc",+ ),# Users: paginated search but no reliable timestamp filter, so full refresh only."users": CopperEndpointConfig(name="users",@@ -93,9 +145,24 @@ COPPER_ENDPOINTS: dict[str, CopperEndpointConfig] = {),# Reference data: small unpaginated GET collections, useful for joins."pipelines": _reference("pipelines", "/pipelines"),+ "pipeline_stages": _reference("pipeline_stages", "/pipeline_stages"),"customer_sources": _reference("customer_sources", "/customer_sources"),"loss_reasons": _reference("loss_reasons", "/loss_reasons"),"contact_types": _reference("contact_types", "/contact_types"),+ "lead_statuses": _reference("lead_statuses", "/lead_statuses"),+ "custom_activity_types": _reference("custom_activity_types", "/custom_activity_types"),+ # Activity types come back grouped under "user" and "system" instead of as a bare array, and the+ # two categories share an id space (system "Property Changed" is id 1, and custom types are+ # numbered from 1 too), so the category has to be part of the key.+ "activity_types": CopperEndpointConfig(+ name="activity_types",+ path="/activity_types",+ method="GET",+ paginated=False,+ primary_keys=[ID, "category"],+ full_refresh_sort=None,+ data_selector="$.*[*]",+ ),}ENDPOINTS = tuple(COPPER_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper.py b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper.pyindex 53fca9ce3b21..4a71422e53ca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper.py@@ -23,7 +23,7 @@ COPPER_SESSION_PATCH = ()-def _response(items: list[dict[str, Any]] | None, status_code: int = 200) -> Response:+def _response(items: Any, status_code: int = 200) -> Response:resp = Response()resp.status_code = status_coderesp._content = json.dumps(items).encode() if items is not None else b""@@ -159,13 +159,14 @@ class TestPagination:class TestSearchBody:@parameterized.expand([- ("date_modified", "minimum_modified_date", "date_modified"),- ("date_created", "minimum_created_date", "date_created"),+ ("people", "date_modified", "minimum_modified_date"),+ ("people", "date_created", "minimum_created_date"),+ ("activities", "activity_date", "minimum_activity_date"),])@mock.patch(CLIENT_SESSION_PATCH)- def test_incremental_sets_filter_and_sort(- self, incremental_field: str, min_param: str, sort_field: str, MockSession+ def test_incremental_sets_endpoint_filter_param(+ self, endpoint: str, incremental_field: str, min_param: str, MockSession) -> None:session = MockSession.return_valuebodies = _wire(session, [_response([])])@@ -173,7 +174,7 @@ class TestSearchBody:_rows(_source(- "people",+ endpoint,manager,should_use_incremental_field=True,db_incremental_field_last_value=1700000000,@@ -183,10 +184,79 @@ class TestSearchBody:body = bodies[0]assert body[min_param] == 1700000000- assert body["sort_by"] == sort_field- assert body["sort_direction"] == "asc"assert body["page_size"] == COPPER_DEFAULT_PAGE_SIZE+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_sorts_on_the_chosen_field(self, MockSession) -> None:+ session = MockSession.return_value+ bodies = _wire(session, [_response([])])++ _rows(+ _source(+ "people",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="date_modified",+ )+ )++ assert bodies[0]["sort_by"] == "date_modified"+ assert bodies[0]["sort_direction"] == "asc"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_activities_search_sends_no_sort_params(self, MockSession) -> None:+ session = MockSession.return_value+ bodies = _wire(session, [_response([])])++ _rows(+ _source(+ "activities",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="activity_date",+ )+ )++ # `/activities/search` documents no sort params, so sending one risks a rejected request.+ assert "sort_by" not in bodies[0]+ assert "sort_direction" not in bodies[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_activities_full_refresh_omits_the_watermark(self, MockSession) -> None:+ session = MockSession.return_value+ bodies = _wire(session, [_response([])])++ _rows(_source("activities", _make_manager(), should_use_incremental_field=False))++ assert "minimum_activity_date" not in bodies[0]+ assert bodies[0]["page_size"] == COPPER_DEFAULT_PAGE_SIZE++ @parameterized.expand([("incremental", True), ("full_refresh", False)])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_activities_cap_the_window_at_the_sync_start(+ self, _name: str, should_use_incremental_field: bool, MockSession+ ) -> None:+ session = MockSession.return_value+ bodies = _wire(session, [_response([])])++ before = int(datetime.now(UTC).timestamp())+ _rows(+ _source(+ "activities",+ _make_manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=1700000000,+ incremental_field="activity_date",+ )+ )+ after = int(datetime.now(UTC).timestamp())++ # `activity_date` is customer-editable, so a row dated far ahead would otherwise become the+ # watermark and hide every later activity behind it.+ assert before <= bodies[0]["maximum_activity_date"] <= after+@mock.patch(CLIENT_SESSION_PATCH)def test_full_refresh_sorts_by_created_for_searchable(self, MockSession) -> None:session = MockSession.return_value@@ -217,6 +287,31 @@ class TestReferenceEndpoint:manager.can_resume.assert_not_called()+class TestActivityTypes:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_flattens_the_category_envelope(self, MockSession) -> None:+ session = MockSession.return_value+ envelope = {+ "user": [{"id": 0, "category": "user", "name": "Note"}],+ "system": [{"id": 1, "category": "system", "name": "Property Changed"}],+ }+ _wire(session, [_response(envelope)])++ response = _source("activity_types", _make_manager())+ rows = _rows(response)++ assert rows == [envelope["user"][0], envelope["system"][0]]+ # Ids repeat across the two categories, so the category has to be part of the key.+ assert response.primary_keys == ["id", "category"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_envelope_yields_nothing(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"user": [], "system": []})])++ assert _rows(_source("activity_types", _make_manager())) == []++class TestRetries:@parameterized.expand([("rate_limited", 429), ("server_error", 503)])@mock.patch("tenacity.nap.sleep", return_value=None)@@ -259,6 +354,17 @@ class TestSourceResponseMetadata:assert response.sort_mode == "asc"assert [r["id"] for r in rows] == [1]+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_activities_declare_descending_arrival_order(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response(_records([1]))])++ response = _source("activities", _make_manager())++ # `/activities/search` answers newest-first and takes no sort param to change that.+ assert response.sort_mode == "desc"+ assert response.partition_keys == ["date_created"]+@mock.patch(CLIENT_SESSION_PATCH)def test_metadata_for_reference(self, MockSession) -> None:session = MockSession.return_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper_source.pyindex 4a60d72b9cfc..9589dc119065 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/copper/tests/test_copper_source.py@@ -26,8 +26,13 @@ class TestCopperSource:("people", True),("companies", True),("opportunities", True),+ ("activities", True),("users", False),("pipelines", False),+ ("pipeline_stages", False),+ ("lead_statuses", False),+ ("activity_types", False),+ ("custom_activity_types", False),("loss_reasons", False),],)@@ -36,11 +41,21 @@ class TestCopperSource:schema = schemas[endpoint]assert schema.supports_incremental is expected_incrementalassert schema.supports_append is expected_incremental- if expected_incremental:- assert {f["field"] for f in schema.incremental_fields} == {"date_modified", "date_created"}- else:+ if not expected_incremental:assert schema.incremental_fields == []+ @pytest.mark.parametrize(+ "endpoint,expected_fields",+ [+ ("people", {"date_modified", "date_created"}),+ # Activities only filter on the activity date, so that is all we advertise.+ ("activities", {"activity_date"}),+ ],+ )+ def test_get_schemas_advertises_only_server_filterable_fields(self, endpoint, expected_fields):+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=1)}+ assert {f["field"] for f in schemas[endpoint].incremental_fields} == expected_fields+def test_get_schemas_filters_by_names(self):schemas = self.source.get_schemas(_config(), team_id=1, names=["people"])assert [s.name for s in schemas] == ["people"]