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(warehouse-sources): add copper lookup and relationship tables (#103710)

Tom Owersacbbce2a2c20
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.md
index 1f33875bd791..6bac60ff00db 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
@@ -2034,11 +2034,11 @@ Diffed against: <https://developer.copper.com/index.html>
- [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)
+- [x] `GET /v1/custom_field_definitions` — resolves custom_field_definition_id, which appears on companies, people, leads, opportunities and projects (high)
+- [x] `GET /v1/tags` — tag lookup for segmenting every record type (medium)
+- [x] `GET /v1/related_items (view all records related to an entity)` — cross-object relationship junction linking companies, people, opportunities and projects (medium)
- [ ] `GET /v1/{entity}/{id}/activities (see a company's / person's / lead's activities)` — per-record activity fan-out when the global activity search is too coarse (low)
-- [ ] `GET /v1/field_layouts/{entity_type}` — field layout metadata for interpreting per-pipeline custom field sets (low)
+- [x] `GET /v1/field_layouts/{entity_type}` — field layout metadata for interpreting per-pipeline custom field sets (low)
Note: MkDocs site; its nav enumerates every operation one page per endpoint, which is what I diffed against. Copper already exposes most lookup tables (contact_types, customer_sources, loss_reasons, pipelines) - the notable omissions are the remaining lookups plus the activity log.
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.py
index 53c2785d954c..70b1c75bb010 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
@@ -220,4 +220,56 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"is_default_task_type": "Whether this type is the default for newly created tasks.",
},
},
+ "custom_field_definitions": {
+ "description": "A custom field configured for the account, describing what the matching entry in a record's custom_fields holds.",
+ "docs_url": "https://developer.copper.com/custom-fields/general/list-custom-field-definitions.html",
+ "columns": {
+ "id": "Unique identifier for the custom field definition, matching custom_field_definition_id on a record.",
+ "name": "Label of the custom field.",
+ "data_type": "Type of data the field stores: String, Text, Dropdown, Date, Checkbox, Float, URL, Percentage, Currency, Connect or MultiSelect.",
+ "available_on": "Record types the field applies to: lead, person, opportunity, company, project or task.",
+ "is_filterable": "Whether the field can be used in filters.",
+ "currency": "Currency of the field. Set only when the data type is Currency.",
+ "options": "Dropdown options for the field. Set only when the data type is Dropdown.",
+ },
+ },
+ "tags": {
+ "description": "A tag used in the account, with how many records of each type carry it. Tags have no id, so the name identifies the row.",
+ "docs_url": "https://developer.copper.com/tags/list-tags.html",
+ "columns": {
+ "name": "The tag text, and the identity of the tag.",
+ "count": "Total number of records carrying the tag.",
+ "count_people": "Number of people carrying the tag.",
+ "count_leads": "Number of leads carrying the tag.",
+ "count_companies": "Number of companies carrying the tag.",
+ "count_opportunities": "Number of opportunities carrying the tag.",
+ "count_projects": "Number of projects carrying the tag.",
+ "count_tasks": "Number of tasks carrying the tag.",
+ },
+ },
+ "field_layouts": {
+ "description": "One field of one record type's layout, saying which fields apply to that record type and in what order. Configured in Copper under Settings, Manage Fields On Records.",
+ "docs_url": "https://developer.copper.com/field-layouts/list-field-layout-by-entity-type.html",
+ "columns": {
+ "entity_type": "Record type the layout belongs to, in plural form: people, companies, leads, opportunities, projects or tasks.",
+ "pipeline_id": "Pipeline the layout applies to. Only opportunity layouts are pipeline-specific; every other row carries 0.",
+ "field_id": "Identifier of the field. Standard fields are sequential integers; custom and embedded-app fields carry the id of that entity.",
+ "field_label": "Label the app shows for the field.",
+ "field_key": "Internal name of the field. Custom fields are prefixed cf_ and embedded-app fields embedded_.",
+ "field_type": "Kind of field: static_field, custom_field or embedded_app_field.",
+ "enabled": "Whether the field is enabled for this record type in the app.",
+ "required": "Whether the field must be set when a record is created.",
+ "required_editable": "Whether the field must be set when a record is edited.",
+ },
+ },
+ "related_items": {
+ "description": "One link between two Copper records, as shown in the Related Items section of the app. Links are bidirectional, so each link appears twice, once from each end.",
+ "docs_url": "https://developer.copper.com/related-items/view-all-records-related-to-an-entity.html",
+ "columns": {
+ "parent_type": "Record type the link was read from: lead, person, company, opportunity, project or task.",
+ "parent_id": "Identifier of the record the link was read from, unique within parent_type.",
+ "type": "Record type at the other end of the link.",
+ "id": "Identifier of the record at the other end of the link, unique within type.",
+ },
+ },
}
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.py
index 7ed0697cc885..576bfb6d677b 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
@@ -1,8 +1,10 @@
-import dataclasses
+from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from requests import Request, Response
+from requests import Request, Response, Session
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
@@ -19,17 +21,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.copper.settings import (
COPPER_DEFAULT_PAGE_SIZE,
COPPER_ENDPOINTS,
+ DATE_CREATED,
+ FIELD_LAYOUT_ENTITIES,
+ FIELD_LAYOUT_NO_PIPELINE,
+ FIELD_LAYOUT_PIPELINED_ENTITY,
+ FIELD_LAYOUTS_ENDPOINT,
+ RELATED_ITEM_PARENTS,
CopperEndpointConfig,
)
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"
+COPPER_REQUEST_TIMEOUT = 60
+@frozen
class CopperResumeConfig:
page_number: int
+ # Which entry of RELATED_ITEM_PARENTS the related-items fan-out was walking. Unused by the
+ # single-endpoint searches, which only ever resume a page number.
+ parent_index: int = 0
class CopperPageNumberPaginator(BasePaginator):
@@ -152,6 +164,132 @@ def validate_credentials(api_key: str, user_email: str) -> tuple[bool, str | Non
return False, f"Copper credential check failed with status {status}"
+def _copper_session(api_key: str, user_email: str) -> Session:
+ return make_tracked_session(
+ headers={"X-PW-AccessToken": api_key, **_headers(user_email)},
+ redact_values=(api_key,),
+ )
+
+
+def _get_json(session: Session, path: str, params: dict[str, Any] | None = None) -> Any | None:
+ """GET a Copper path, answering None when the record or layout is gone."""
+ response = session.get(f"{COPPER_BASE_URL}{path}", params=params, timeout=COPPER_REQUEST_TIMEOUT)
+ if response.status_code == 404:
+ return None
+ response.raise_for_status()
+ return response.json()
+
+
+@frozen
+class CopperSearchPage:
+ number: int
+ has_next_page: bool
+ records: list[dict[str, Any]]
+
+
+def _iter_search_pages(session: Session, path: str, page_size: int, start_page: int) -> Iterator[CopperSearchPage]:
+ page = start_page
+ while True:
+ response = session.post(
+ f"{COPPER_BASE_URL}{path}",
+ json={
+ "page_size": page_size,
+ "page_number": page,
+ "sort_by": DATE_CREATED,
+ "sort_direction": "asc",
+ },
+ timeout=COPPER_REQUEST_TIMEOUT,
+ )
+ response.raise_for_status()
+ records = response.json()
+ if not isinstance(records, list):
+ # Reading a malformed page as empty would end the walk early and silently truncate.
+ raise ValueError(f"Copper returned a non-list search page for {path}")
+ has_next_page = len(records) >= page_size
+ yield CopperSearchPage(number=page, has_next_page=has_next_page, records=records)
+ if not has_next_page:
+ return
+ page += 1
+
+
+def _iter_field_layouts(session: Session, path_template: str) -> Iterator[list[dict[str, Any]]]:
+ pipeline_ids = [
+ pipeline["id"] for pipeline in (_get_json(session, "/pipelines") or []) if pipeline.get("id") is not None
+ ]
+
+ for entity in FIELD_LAYOUT_ENTITIES:
+ targets = pipeline_ids if entity == FIELD_LAYOUT_PIPELINED_ENTITY else [FIELD_LAYOUT_NO_PIPELINE]
+ for pipeline_id in targets:
+ params = {"pipeline_id": pipeline_id} if pipeline_id != FIELD_LAYOUT_NO_PIPELINE else None
+ layout = _get_json(session, path_template.format(entity=entity), params=params)
+ if not layout:
+ continue
+ yield [{"entity_type": entity, "pipeline_id": pipeline_id, **field} for field in layout]
+
+
+def _iter_related_items(
+ session: Session,
+ path_template: str,
+ resumable_source_manager: ResumableSourceManager[CopperResumeConfig],
+ page_size: int,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ first_parent = resume.parent_index if resume else 0
+ first_page = resume.page_number if resume else 1
+
+ for parent_index in range(first_parent, len(RELATED_ITEM_PARENTS)):
+ parent_type, parent_endpoint = RELATED_ITEM_PARENTS[parent_index]
+ start_page = first_page if parent_index == first_parent else 1
+ search_path = COPPER_ENDPOINTS[parent_endpoint].path
+
+ for page in _iter_search_pages(session, search_path, page_size, start_page):
+ rows: list[dict[str, Any]] = []
+ for record in page.records:
+ parent_id = record.get("id")
+ if parent_id is None:
+ continue
+ related = _get_json(session, path_template.format(entity=parent_endpoint, record_id=parent_id))
+ if related is None:
+ # Deleted between the parent page and this call.
+ continue
+ rows.extend({"parent_type": parent_type, "parent_id": parent_id, **item} for item in related)
+ if rows:
+ yield rows
+
+ next_parent, next_page = (parent_index, page.number + 1) if page.has_next_page else (parent_index + 1, 1)
+ if next_parent < len(RELATED_ITEM_PARENTS):
+ # Saved after the page is yielded, so a crash re-walks it rather than skipping it.
+ resumable_source_manager.save_state(CopperResumeConfig(page_number=next_page, parent_index=next_parent))
+
+ # The walk finished: leaving the last checkpoint would make a later attempt resume mid-stream.
+ resumable_source_manager.clear_state()
+
+
+def _custom_iterator_source(
+ config: CopperEndpointConfig,
+ api_key: str,
+ user_email: str,
+ resumable_source_manager: ResumableSourceManager[CopperResumeConfig],
+) -> SourceResponse:
+ """Endpoints Copper only exposes per entity, so one schema needs many differently-shaped requests."""
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ session = _copper_session(api_key, user_email)
+ if config.name == FIELD_LAYOUTS_ENDPOINT:
+ yield from _iter_field_layouts(session, config.path)
+ else:
+ yield from _iter_related_items(session, config.path, resumable_source_manager, COPPER_DEFAULT_PAGE_SIZE)
+
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ sort_mode=config.sort_mode,
+ )
+
+
def copper_source(
api_key: str,
user_email: str,
@@ -165,6 +303,9 @@ def copper_source(
) -> SourceResponse:
config = COPPER_ENDPOINTS[endpoint]
+ if config.custom_iterator:
+ return _custom_iterator_source(config, api_key, user_email, resumable_source_manager)
+
body: dict[str, Any] | None
paginator: BasePaginator
if config.paginated:
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.py
index 0b5ba0001c87..e9a0060e9e25 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
@@ -79,6 +79,9 @@ class CopperEndpointConfig:
sort_mode: SortMode = "asc"
# Set when the response wraps rows in an envelope instead of returning a bare array.
data_selector: str | None = None
+ # Rows come from a custom iterator in `copper.py`; `path` is then a template that iterator
+ # formats per request, not a complete request path.
+ custom_iterator: bool = False
def _searchable(name: str, path: str) -> CopperEndpointConfig:
@@ -106,6 +109,28 @@ def _reference(name: str, path: str) -> CopperEndpointConfig:
)
+FIELD_LAYOUTS_ENDPOINT = "field_layouts"
+RELATED_ITEMS_ENDPOINT = "related_items"
+
+# Entity types Copper lets users configure field layouts for, spelled as the path wants them.
+FIELD_LAYOUT_ENTITIES: tuple[str, ...] = ("people", "companies", "leads", "opportunities", "projects", "tasks")
+# Only opportunity layouts are pipeline-specific.
+FIELD_LAYOUT_PIPELINED_ENTITY = "opportunities"
+# Stands in for "this layout is not pipeline-specific". A null would leave the column all-null on an
+# account with no pipelines, and the next sync that found one would change the column's type.
+FIELD_LAYOUT_NO_PIPELINE = 0
+
+# Entity types Copper can relate to each other, as (the singular name it reports in a related row,
+# the endpoint whose records we walk to collect those rows).
+RELATED_ITEM_PARENTS: tuple[tuple[str, str], ...] = (
+ ("lead", "leads"),
+ ("person", "people"),
+ ("company", "companies"),
+ ("opportunity", "opportunities"),
+ ("project", "projects"),
+ ("task", "tasks"),
+)
+
COPPER_ENDPOINTS: dict[str, CopperEndpointConfig] = {
# Core CRM records: POST `/search`, page-based pagination, server-side timestamp filtering.
"people": _searchable("people", "/people/search"),
@@ -163,6 +188,39 @@ COPPER_ENDPOINTS: dict[str, CopperEndpointConfig] = {
full_refresh_sort=None,
data_selector="$.*[*]",
),
+ "custom_field_definitions": _reference("custom_field_definitions", "/custom_field_definitions"),
+ # Tags carry no id — the name is the identity, and Copper returns them sorted by name already.
+ "tags": CopperEndpointConfig(
+ name="tags",
+ path="/tags",
+ method="GET",
+ paginated=False,
+ primary_keys=["name"],
+ full_refresh_sort=None,
+ ),
+ # Field layouts: one GET per entity type, plus one per pipeline for opportunities, whose layout
+ # Copper varies by pipeline and refuses to return without a `pipeline_id`.
+ FIELD_LAYOUTS_ENDPOINT: CopperEndpointConfig(
+ name=FIELD_LAYOUTS_ENDPOINT,
+ path="/field_layouts/by_entity/{entity}",
+ method="GET",
+ paginated=False,
+ custom_iterator=True,
+ primary_keys=["entity_type", "pipeline_id", "field_id"],
+ full_refresh_sort=None,
+ ),
+ # Related items: the cross-object junction. Copper exposes it per record only, so this walks
+ # every relatable record and asks for its edges. Relationships are bidirectional, so each edge
+ # arrives twice, once from each end.
+ RELATED_ITEMS_ENDPOINT: CopperEndpointConfig(
+ name=RELATED_ITEMS_ENDPOINT,
+ path="/{entity}/{record_id}/related",
+ method="GET",
+ paginated=False,
+ custom_iterator=True,
+ primary_keys=["parent_type", "parent_id", "type", "id"],
+ full_refresh_sort=None,
+ ),
}
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.py
index 4a71422e53ca..ff657e592950 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
@@ -2,18 +2,25 @@ import json
from datetime import UTC, date, datetime
from typing import Any
+import pytest
from unittest import mock
from parameterized import parameterized
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.copper.copper import (
+ COPPER_BASE_URL,
COPPER_DEFAULT_PAGE_SIZE,
CopperResumeConfig,
+ _iter_related_items,
_to_unix_seconds,
copper_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.copper.settings import (
+ COPPER_ENDPOINTS,
+ RELATED_ITEM_PARENTS,
+)
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -413,3 +420,208 @@ class TestValidateCredentials:
validate_credentials("secret-key", "[email protected]")
assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)
+
+
+def _fake_api(
+ get_routes: dict[str, Any] | None = None,
+ search_pages: dict[str, list[list[dict[str, Any]]]] | None = None,
+) -> mock.MagicMock:
+ """A session answering Copper paths from a routing table; anything unrouted is a 404."""
+ routes = get_routes or {}
+ pages = search_pages or {}
+
+ def _get(url: str, params: Any = None, timeout: Any = None) -> Response:
+ path = url.removeprefix(COPPER_BASE_URL)
+ if path not in routes:
+ return _response(None, status_code=404)
+ return _response(routes[path])
+
+ def _post(url: str, json: Any = None, timeout: Any = None) -> Response:
+ path = url.removeprefix(COPPER_BASE_URL)
+ endpoint_pages = pages.get(path, [])
+ index = json["page_number"] - 1
+ return _response(endpoint_pages[index] if index < len(endpoint_pages) else [])
+
+ session = mock.MagicMock()
+ session.get.side_effect = _get
+ session.post.side_effect = _post
+ return session
+
+
+def _requested_paths(session: mock.MagicMock) -> list[str]:
+ return [call.args[0].removeprefix(COPPER_BASE_URL) for call in session.get.call_args_list]
+
+
+class TestFieldLayouts:
+ @mock.patch(COPPER_SESSION_PATCH)
+ def test_fans_out_per_entity_and_per_opportunity_pipeline(self, mock_session) -> None:
+ layout = [{"field_id": 0, "field_key": "full_name", "field_type": "static_field"}]
+ session = _fake_api(
+ {
+ "/pipelines": [{"id": 5}, {"id": 6}],
+ "/field_layouts/by_entity/people": layout,
+ "/field_layouts/by_entity/opportunities": layout,
+ }
+ )
+ mock_session.return_value = session
+
+ rows = _rows(_source("field_layouts", _make_manager()))
+
+ # Each row is stamped with the layout it came from — the response itself carries neither.
+ assert rows == [
+ {
+ "entity_type": "people",
+ "pipeline_id": 0,
+ "field_id": 0,
+ "field_key": "full_name",
+ "field_type": "static_field",
+ },
+ {
+ "entity_type": "opportunities",
+ "pipeline_id": 5,
+ "field_id": 0,
+ "field_key": "full_name",
+ "field_type": "static_field",
+ },
+ {
+ "entity_type": "opportunities",
+ "pipeline_id": 6,
+ "field_id": 0,
+ "field_key": "full_name",
+ "field_type": "static_field",
+ },
+ ]
+
+ @mock.patch(COPPER_SESSION_PATCH)
+ def test_only_opportunities_carry_a_pipeline_param(self, mock_session) -> None:
+ layout = [{"field_id": 0}]
+ session = _fake_api(
+ {
+ "/pipelines": [{"id": 5}],
+ "/field_layouts/by_entity/people": layout,
+ "/field_layouts/by_entity/opportunities": layout,
+ }
+ )
+ mock_session.return_value = session
+
+ _rows(_source("field_layouts", _make_manager()))
+
+ params_by_path = {
+ call.args[0].removeprefix(COPPER_BASE_URL): call.kwargs["params"] for call in session.get.call_args_list
+ }
+ # Copper rejects an opportunities layout request without a pipeline, and rejects the param
+ # on every other entity.
+ assert params_by_path["/field_layouts/by_entity/opportunities"] == {"pipeline_id": 5}
+ assert params_by_path["/field_layouts/by_entity/people"] is None
+
+ @mock.patch(COPPER_SESSION_PATCH)
+ def test_entity_copper_does_not_serve_is_skipped(self, mock_session) -> None:
+ session = _fake_api({"/pipelines": [], "/field_layouts/by_entity/tasks": [{"field_id": 3}]})
+ mock_session.return_value = session
+
+ rows = _rows(_source("field_layouts", _make_manager()))
+
+ # The other five entities 404 on this account; the walk keeps going instead of failing.
+ assert rows == [{"entity_type": "tasks", "pipeline_id": 0, "field_id": 3}]
+
+
+class TestRelatedItems:
+ @mock.patch(COPPER_SESSION_PATCH)
+ def test_stamps_each_edge_with_the_record_it_was_read_from(self, mock_session) -> None:
+ session = _fake_api(
+ {"/people/7/related": [{"id": 208105, "type": "project"}, {"id": 44, "type": "company"}]},
+ {"/people/search": [[{"id": 7}]]},
+ )
+ mock_session.return_value = session
+
+ rows = _rows(_source("related_items", _make_manager()))
+
+ assert rows == [
+ {"parent_type": "person", "parent_id": 7, "id": 208105, "type": "project"},
+ {"parent_type": "person", "parent_id": 7, "id": 44, "type": "company"},
+ ]
+
+ @mock.patch(COPPER_SESSION_PATCH)
+ def test_walks_every_relatable_entity_type(self, mock_session) -> None:
+ session = _fake_api({}, {config.path: [[]] for config in COPPER_ENDPOINTS.values()})
+ mock_session.return_value = session
+
+ _rows(_source("related_items", _make_manager()))
+
+ searched = [call.args[0].removeprefix(COPPER_BASE_URL) for call in session.post.call_args_list]
+ assert searched == [
+ "/leads/search",
+ "/people/search",
+ "/companies/search",
+ "/opportunities/search",
+ "/projects/search",
+ "/tasks/search",
+ ]
+
+ @mock.patch(COPPER_SESSION_PATCH)
+ def test_record_deleted_mid_walk_is_skipped(self, mock_session) -> None:
+ session = _fake_api(
+ {"/people/8/related": [{"id": 1, "type": "company"}]},
+ {"/people/search": [[{"id": 7}, {"id": 8}]]},
+ )
+ mock_session.return_value = session
+
+ rows = _rows(_source("related_items", _make_manager()))
+
+ # Person 7 was deleted between the search page and its related lookup, so it 404s.
+ assert "/people/7/related" in _requested_paths(session)
+ assert rows == [{"parent_type": "person", "parent_id": 8, "id": 1, "type": "company"}]
+
+ def test_checkpoints_the_next_position_after_each_page(self) -> None:
+ session = _fake_api(
+ {"/leads/1/related": [{"id": 1, "type": "task"}], "/leads/2/related": []},
+ {"/leads/search": [[{"id": 1}], [{"id": 2}]]},
+ )
+ manager = _make_manager()
+
+ list(_iter_related_items(session, COPPER_ENDPOINTS["related_items"].path, manager, page_size=1))
+
+ checkpoints = [(c.args[0].parent_index, c.args[0].page_number) for c in manager.save_state.call_args_list]
+ # Leads pages 1 and 2, then the walk moves on to people (index 1) at page 1. Every later
+ # parent contributes one more checkpoint as its single empty page ends it.
+ assert checkpoints[:3] == [(0, 2), (0, 3), (1, 1)]
+
+ def test_final_parent_leaves_no_checkpoint_behind(self) -> None:
+ session = _fake_api({}, {})
+ manager = _make_manager()
+
+ list(_iter_related_items(session, COPPER_ENDPOINTS["related_items"].path, manager, page_size=1))
+
+ saved = [c.args[0].parent_index for c in manager.save_state.call_args_list]
+ # A checkpoint past the last parent would make a retry resume onto nothing.
+ assert max(saved) == len(RELATED_ITEM_PARENTS) - 1
+ manager.clear_state.assert_called_once()
+
+ def test_malformed_search_page_fails_loudly(self) -> None:
+ null_page = Response()
+ null_page.status_code = 200
+ null_page._content = b"null"
+ session = _fake_api({}, {})
+ session.post.side_effect = lambda url, json=None, timeout=None: null_page
+ manager = _make_manager()
+
+ with pytest.raises(ValueError):
+ list(_iter_related_items(session, COPPER_ENDPOINTS["related_items"].path, manager, page_size=1))
+
+ def test_resumes_from_the_saved_parent_and_page(self) -> None:
+ session = _fake_api(
+ {"/projects/9/related": [{"id": 3, "type": "task"}]},
+ {"/projects/search": [[], [], [{"id": 9}]]},
+ )
+ manager = _make_manager(CopperResumeConfig(page_number=3, parent_index=4))
+
+ rows = [
+ row for page in _iter_related_items(session, "/{entity}/{record_id}/related", manager, 1) for row in page
+ ]
+
+ searched = [call.args[0].removeprefix(COPPER_BASE_URL) for call in session.post.call_args_list]
+ # Projects is index 4, so leads through opportunities are not re-walked, and projects
+ # restarts at page 3 rather than page 1.
+ assert searched == ["/projects/search", "/projects/search", "/tasks/search"]
+ assert session.post.call_args_list[0].kwargs["json"]["page_number"] == 3
+ assert rows == [{"parent_type": "project", "parent_id": 9, "id": 3, "type": "task"}]
diff --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.py
index 9589dc119065..9d3bfae7a452 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
@@ -34,6 +34,10 @@ class TestCopperSource:
("activity_types", False),
("custom_activity_types", False),
("loss_reasons", False),
+ ("custom_field_definitions", False),
+ ("tags", False),
+ ("field_layouts", False),
+ ("related_items", False),
],
)
def test_get_schemas_incremental_support(self, endpoint, expected_incremental):