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(warehouse): read Close leads and contacts via Advanced Filtering (#74146)

Luke Belton6d74e9c9ca3e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/close/api_inventory.md
index 591b908025d3..17dc72c9615c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/api_inventory.md
@@ -15,11 +15,37 @@ Spec: <https://api.close.com/api/openapi.json> (version 1.0.0).
- Some small dimension endpoints (`/status/lead/`, `/status/opportunity/`, `/pipeline/`) return all
rows in one response with no pagination params; they may omit `has_more`. The paginator treats a
missing/false `has_more` as the last page.
-- Close caps `_skip` per resource — very large full-refresh tables (leads/contacts on big orgs) can
- hit this cap. This matches the documented offset behavior and the dlt/Airbyte connectors; the
- Advanced Filtering / Export APIs are the long-term answer for huge tables. Noted as a known limit.
+- Close caps `_skip` per resource. Every endpoint except Leads and Contacts exposes a server-side
+ date filter (or is a single-page dimension table), so an incremental sync never accumulates a
+ deep enough offset to reach the cap.
+- Leads and Contacts have no date filter on their list endpoints, so offset was the only option and
+ a big org's table stopped syncing at the cap. Both now read through Advanced Filtering instead —
+ see below.
- All paths require a trailing slash to avoid a redirect.
+## Advanced Filtering (`POST /data/search/`) — Leads and Contacts
+
+Advanced Filtering is the only read path that exposes `date_created`/`date_updated` filters for
+leads and contacts. It is cursor-paginated, but the cursor has limits of its own: it expires after
+30s, and one cursor walk returns at most 10,000 objects.
+
+We therefore page by **keyset**, not by cursor: sort ascending on the cursor field and re-query
+`<field> on_or_after <last value emitted>` for each page. Every request is a fresh, shallow query,
+so neither the `_skip` cap, the 10k cursor cap, nor the 30s TTL applies. The cursor is used only to
+step over a run of rows sharing one exact timestamp, where the keyset filter cannot advance.
+
+Notes:
+
+- Only `lead` and `contact` are documented as searchable object types, and they are also the only
+ two that need this — everything else already filters server-side.
+- Search returns bare IDs unless each field is named in `_fields`, so `settings.py` carries an
+ explicit field list per object type. Custom fields are appended at runtime from
+ `/custom_field/<object_type>/` (best-effort — a key without access still syncs standard columns).
+- The `moment_range` condition (`on_or_after` / `before` with `{"type": "fixed_utc"}` moments) is
+ what the Close app itself emits; the public docs describe date-range filtering without naming
+ the condition type.
+- Resuming re-reads rows tied to the checkpointed anchor timestamp; they dedupe on `id`.
+
## Incremental support (verified against the OpenAPI spec query params)
Only endpoints with a genuine server-side timestamp filter get `supports_incremental=True`:
@@ -29,8 +55,8 @@ Only endpoints with a genuine server-side timestamp filter get `supports_increme
| Activities | `/activity/` | yes | `date_created__gte/lte/gt/lt` | yes | date_created |
| Opportunities | `/opportunity/` | yes | `date_created__*`, `date_updated__*`, `date_won__*` | yes | date_created (+ date_updated) |
| Tasks | `/task/` | yes | `date_created__*`, `date_updated__*`, `date__*` | yes | date_created (+ date_updated) |
-| Leads | `/lead/` | yes | **none** (only the search/query API) | no | full refresh |
-| Contacts | `/contact/` | yes | **none** | no | full refresh |
+| Leads | `/data/search/` | keyset | `date_created`, `date_updated` (Advanced Filtering) | sort | date_created (+ date_updated) |
+| Contacts | `/data/search/` | keyset | `date_created`, `date_updated` (Advanced Filtering) | sort | date_created (+ date_updated) |
| Users | `/user/` | yes | none | yes | full refresh |
| Lead statuses | `/status/lead/` | no | none | no | full refresh |
| Opp. statuses | `/status/opportunity/` | no | none | no | full refresh |
@@ -39,9 +65,9 @@ Only endpoints with a genuine server-side timestamp filter get `supports_increme
Notes:
-- The plain `GET /lead/` list endpoint exposes **no** `date_*` filter param (only `_skip`/`_limit`),
- so despite Airbyte using a `date_updated` cursor for leads (it goes through Close's separate
- search/query API), we ship Leads as full refresh rather than fake incremental. Same for Contacts.
+- The plain `GET /lead/` and `GET /contact/` list endpoints expose **no** `date_*` filter param
+ (only `_skip`/`_limit`/`_fields`, plus `lead_id` on contacts). Both resources go through
+ Advanced Filtering instead, which is also how Airbyte reaches a `date_updated` cursor for leads.
- The Event Log (`/event/`) does support `date_updated__gte` but is capped to ~30 days of history and
has consolidation/ordering caveats, so it is intentionally left out of v1; it can be added later as
an append-only stream.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/close.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/close.py
index e2399d9a61a4..3a969bd99b56 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/close.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/close.py
@@ -1,16 +1,25 @@
import base64
import dataclasses
+from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
from dateutil import parser
-from requests import Response
+from requests import Response, Session
+from structlog.types import FilteringBoundLogger
+from products.warehouse_sources.backend.temporal.data_imports.sources.close.search import (
+ fetch_custom_field_selectors,
+ iter_search_rows,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.close.settings import (
CLOSE_ENDPOINTS,
CloseEndpointConfig,
)
-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.http import (
+ DEFAULT_RETRY,
+ make_tracked_session,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
@@ -33,9 +42,19 @@ PAGE_LIMIT = 100
INITIAL_INCREMENTAL_VALUE = "1970-01-01T00:00:00+00:00"
+# The shared DEFAULT_RETRY only allows GET/HEAD/OPTIONS, so a transient failure on the
+# Advanced Filtering POST would not be retried. The search call is a read-only query, so it is
+# safe to retry alongside everything else. Derived via `.new()` so the policy stays a
+# BoundedRetry (Retry-After clamping) and every other knob tracks DEFAULT_RETRY.
+CLOSE_RETRY = DEFAULT_RETRY.new(allowed_methods=frozenset(DEFAULT_RETRY.allowed_methods or ()) | {"POST"})
+
+
@dataclasses.dataclass
class CloseResumeConfig:
- next_skip: int
+ next_skip: int = 0
+ # Advanced Filtering walk (Leads/Contacts): the last cursor-field value already emitted.
+ search_anchor: Optional[str] = None
+ search_cursor_field: Optional[str] = None
def _format_close_datetime(value: Any) -> str:
@@ -148,6 +167,85 @@ def get_resource(
}
+def _make_search_session(api_key: str) -> Session:
+ basic_token = base64.b64encode(f"{api_key}:".encode("ascii")).decode("ascii")
+ return make_tracked_session(
+ retry=CLOSE_RETRY,
+ headers={"Authorization": f"Basic {basic_token}"},
+ redact_values=(api_key, basic_token),
+ )
+
+
+def _search_cursor_field(config: CloseEndpointConfig, is_incremental: bool, incremental_field: Optional[str]) -> str:
+ if not is_incremental:
+ # Full refresh walks creation order, which never reorders under us.
+ return "date_created"
+ advertised = {f["field"] for f in config.incremental_fields}
+ return incremental_field if incremental_field in advertised else config.incremental_fields[0]["field"]
+
+
+def close_search_source(
+ api_key: str,
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[CloseResumeConfig],
+ logger: FilteringBoundLogger,
+ db_incremental_field_last_value: Optional[Any] = None,
+ should_use_incremental_field: bool = False,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ """Read Leads or Contacts through Close's Advanced Filtering API.
+
+ Their list endpoints take no date filter, so offset pagination is the only option there and
+ Close's `_skip` cap silently truncates large tables. See search.py for the paging strategy.
+ """
+ config = CLOSE_ENDPOINTS[endpoint]
+ object_type = config.search_object_type
+ if object_type is None:
+ raise ValueError(f"Close endpoint {endpoint} is not backed by the search API")
+
+ is_incremental = should_use_incremental_field and bool(config.incremental_fields)
+ cursor_field = _search_cursor_field(config, is_incremental, incremental_field)
+
+ start_anchor: Optional[str] = None
+ if is_incremental and db_incremental_field_last_value is not None:
+ start_anchor = _format_close_datetime(db_incremental_field_last_value)
+
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ # Only resume a walk that used the same cursor field; otherwise the anchor is meaningless.
+ if resume_config is not None and resume_config.search_cursor_field == cursor_field:
+ start_anchor = resume_config.search_anchor or start_anchor
+
+ def save_checkpoint(anchor: str) -> None:
+ resumable_source_manager.save_state(CloseResumeConfig(search_anchor=anchor, search_cursor_field=cursor_field))
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ session = _make_search_session(api_key)
+ fields = [*config.search_fields, *fetch_custom_field_selectors(session, CLOSE_BASE_URL, object_type, logger)]
+ yield from iter_search_rows(
+ session=session,
+ base_url=CLOSE_BASE_URL,
+ object_type=object_type,
+ fields=fields,
+ cursor_field=cursor_field,
+ start_anchor=start_anchor,
+ logger=logger,
+ on_checkpoint=save_checkpoint,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
+
+
def close_source(
api_key: str,
endpoint: str,
@@ -155,9 +253,21 @@ def close_source(
job_id: str,
resumable_source_manager: ResumableSourceManager[CloseResumeConfig],
db_incremental_field_last_value: Optional[Any],
+ logger: FilteringBoundLogger,
should_use_incremental_field: bool = False,
incremental_field: Optional[str] = None,
) -> SourceResponse:
+ if CLOSE_ENDPOINTS[endpoint].search_object_type is not None:
+ return close_search_source(
+ api_key=api_key,
+ endpoint=endpoint,
+ resumable_source_manager=resumable_source_manager,
+ logger=logger,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ )
+
config: RESTAPIConfig = {
"client": {
"base_url": CLOSE_BASE_URL,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/search.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/search.py
new file mode 100644
index 000000000000..383ce5cb0941
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/search.py
@@ -0,0 +1,225 @@
+"""Close Advanced Filtering (`POST /data/search/`) walker for Leads and Contacts.
+
+`GET /lead/` and `GET /contact/` accept no filter beyond `_skip`/`_limit`/`_fields`, and Close
+caps `_skip` per resource, so on a large org those two tables stop syncing partway through with
+no way to window around the cap. Advanced Filtering is the only read path that exposes a
+`date_created`/`date_updated` filter for them, which lets us page by keyset — re-querying from
+the last timestamp we emitted — instead of by ever-growing offset.
+
+Keyset paging also sidesteps the two limits Advanced Filtering has of its own: cursors expire
+after 30s, and a single cursor walk returns at most 10k objects. Every keyset request is a fresh
+query for the next page-worth of rows, so neither applies. The cursor is used only to step over a
+run of rows sharing one exact timestamp, where moving the filter forward cannot make progress.
+"""
+
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any, Optional
+
+from requests import Session
+from structlog.types import FilteringBoundLogger
+
+CLOSE_SEARCH_PATH = "/data/search/"
+CUSTOM_FIELD_PATH = "/custom_field/{object_type}/"
+REQUEST_TIMEOUT_SECONDS = 60
+# Close caps `_limit` per resource and doesn't publish the ceiling for search, so stay at the
+# value the list endpoints already accept rather than probing for a higher one.
+SEARCH_PAGE_LIMIT = 100
+CUSTOM_FIELD_PAGE_LIMIT = 100
+# Cap on how many custom-field pages we walk. Orgs have tens of custom fields, not thousands.
+MAX_CUSTOM_FIELD_PAGES = 20
+# How many consecutive cursor pages we'll follow across a single-timestamp run before giving up.
+# At SEARCH_PAGE_LIMIT rows a page this covers 50k rows sharing one exact timestamp; past that
+# something is wrong with the data and failing loudly beats looping.
+MAX_PLATEAU_PAGES = 500
+
+
+class CloseSearchError(Exception):
+ pass
+
+
+class CloseCursorExpiredError(CloseSearchError):
+ pass
+
+
[email protected](frozen=True)
+class SearchPage:
+ rows: list[dict[str, Any]]
+ cursor: Optional[str]
+
+
+def _moment(value: str) -> dict[str, str]:
+ return {"type": "fixed_utc", "value": value}
+
+
+def _regular_field(object_type: str, field_name: str) -> dict[str, str]:
+ return {"type": "regular_field", "object_type": object_type, "field_name": field_name}
+
+
+def build_search_body(
+ object_type: str,
+ fields: list[str],
+ cursor_field: str,
+ anchor: Optional[str],
+ page_cursor: Optional[str] = None,
+ limit: int = SEARCH_PAGE_LIMIT,
+) -> dict[str, Any]:
+ queries: list[dict[str, Any]] = [{"type": "object_type", "object_type": object_type}]
+ if anchor is not None:
+ queries.append(
+ {
+ "type": "field_condition",
+ "field": _regular_field(object_type, cursor_field),
+ # Inclusive so a row sharing the anchor timestamp is never skipped; the walker
+ # filters the ones it already emitted.
+ "condition": {"type": "moment_range", "on_or_after": _moment(anchor)},
+ }
+ )
+
+ body: dict[str, Any] = {
+ "query": {"type": "and", "queries": queries},
+ # Advanced Filtering returns bare IDs unless every wanted field is named explicitly.
+ "_fields": {object_type: fields},
+ "sort": [{"direction": "asc", "field": _regular_field(object_type, cursor_field)}],
+ "_limit": limit,
+ }
+ if page_cursor:
+ body["cursor"] = page_cursor
+ return body
+
+
+def _post_search(session: Session, base_url: str, body: dict[str, Any]) -> SearchPage:
+ response = session.post(f"{base_url}{CLOSE_SEARCH_PATH}", json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 400:
+ detail = response.text[:500]
+ if "cursor" in detail.lower() and "expire" in detail.lower():
+ raise CloseCursorExpiredError(detail)
+ # The query shape and field selectors are built from a static list, so a 400 means
+ # Close's field set drifted. Surface its message rather than a bare status code.
+ raise CloseSearchError(f"Close rejected the search query: {detail}")
+
+ response.raise_for_status()
+ payload = response.json()
+ if not isinstance(payload, dict):
+ raise CloseSearchError(f"Unexpected Close search response: {str(payload)[:200]}")
+
+ raw_rows = payload.get("data")
+ rows = [row for row in raw_rows if isinstance(row, dict)] if isinstance(raw_rows, list) else []
+ # `id` is the primary key the whole walk dedupes and merges on. A row without one can't be
+ # tracked across the inclusive anchor re-reads, so it would silently duplicate — fail instead.
+ if any(not row.get("id") for row in rows):
+ raise CloseSearchError("Close returned a search row without an id")
+ return SearchPage(rows=rows, cursor=payload.get("cursor") or None)
+
+
+def fetch_custom_field_selectors(
+ session: Session, base_url: str, object_type: str, logger: FilteringBoundLogger
+) -> list[str]:
+ """Name each custom field explicitly so its value comes back as a flat `custom.cf_*` key.
+
+ Best-effort: a key without custom-field read access should still sync the standard columns
+ rather than fail the whole table.
+ """
+ selectors: list[str] = []
+ url = f"{base_url}{CUSTOM_FIELD_PATH.format(object_type=object_type)}"
+
+ try:
+ for page in range(MAX_CUSTOM_FIELD_PAGES):
+ response = session.get(
+ url,
+ params={"_limit": CUSTOM_FIELD_PAGE_LIMIT, "_skip": page * CUSTOM_FIELD_PAGE_LIMIT},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ rows = payload.get("data") or []
+ selectors.extend(f"custom.{row['id']}" for row in rows if isinstance(row, dict) and row.get("id"))
+ if not payload.get("has_more"):
+ break
+ except Exception as exc:
+ logger.warning(
+ f"Close: could not list custom fields, syncing standard fields only. object_type={object_type} error={exc}"
+ )
+ return []
+
+ return selectors
+
+
+def iter_search_rows(
+ session: Session,
+ base_url: str,
+ object_type: str,
+ fields: list[str],
+ cursor_field: str,
+ start_anchor: Optional[str],
+ logger: FilteringBoundLogger,
+ on_checkpoint: Optional[Callable[[str], None]] = None,
+ limit: int = SEARCH_PAGE_LIMIT,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk every object of `object_type` in ascending `cursor_field` order, a page at a time.
+
+ `on_checkpoint(anchor)` is called after each page is yielded, so a crash re-reads the last
+ anchor rather than skipping past it. Rows tied to the anchor timestamp are re-read on resume
+ and deduped downstream by primary key.
+ """
+ anchor = start_anchor
+ emitted_at_anchor: set[str] = set()
+ page_cursor: Optional[str] = None
+ plateau_pages = 0
+
+ while True:
+ used_cursor = page_cursor is not None
+ body = build_search_body(object_type, fields, cursor_field, anchor, page_cursor, limit)
+
+ try:
+ page = _post_search(session, base_url, body)
+ except CloseCursorExpiredError:
+ if not used_cursor:
+ raise
+ # Downstream Delta writes can stall the walk past the 30s cursor TTL. Re-issue the
+ # same query without the cursor; emitted_at_anchor keeps the replay from duplicating.
+ logger.warning(f"Close: search cursor expired, re-anchoring. object_type={object_type} anchor={anchor}")
+ page_cursor = None
+ continue
+
+ if not page.rows:
+ return
+
+ fresh = [row for row in page.rows if row["id"] not in emitted_at_anchor]
+ if fresh:
+ yield fresh
+
+ last_value = page.rows[-1].get(cursor_field)
+ if last_value is None:
+ raise CloseSearchError(f"Close returned {object_type} rows without a {cursor_field} value")
+
+ if last_value == anchor:
+ # Every row on this page shares the anchor timestamp, so advancing the keyset filter
+ # would just re-read them. Step over the run with Close's cursor instead.
+ plateau_pages += 1
+ if plateau_pages > MAX_PLATEAU_PAGES:
+ raise CloseSearchError(
+ f"Close returned more than {MAX_PLATEAU_PAGES * limit} {object_type} rows "
+ f"sharing {cursor_field}={anchor}, which cannot be paged past"
+ )
+ emitted_at_anchor.update(row["id"] for row in page.rows)
+ if page.cursor is None:
+ return
+ page_cursor = page.cursor
+ continue
+
+ plateau_pages = 0
+ anchor = last_value
+ emitted_at_anchor = {row["id"] for row in page.rows if row.get(cursor_field) == last_value}
+ page_cursor = None
+ if on_checkpoint is not None:
+ on_checkpoint(anchor)
+
+ # A short keyset page means we've drained the table. In cursor mode the terminal signal
+ # is Close handing back a null cursor instead.
+ if used_cursor:
+ if page.cursor is None:
+ return
+ elif len(page.rows) < limit:
+ return
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/settings.py
index f7762c6eb09d..9e013391bc35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/settings.py
@@ -14,6 +14,51 @@ def _date_incremental_field(name: str) -> IncrementalField:
}
+# Standard fields returned by the plain list endpoints. Advanced Filtering only returns the
+# fields you name, so these lists are what keeps the search-backed tables column-compatible with
+# the offset-paginated ones. Custom fields are appended at runtime from `/custom_field/<type>/`.
+LEAD_SEARCH_FIELDS = [
+ "addresses",
+ "contact_ids",
+ "contacts",
+ "created_by",
+ "created_by_name",
+ "date_created",
+ "date_updated",
+ "description",
+ "display_name",
+ "html_url",
+ "id",
+ "integration_links",
+ "name",
+ "opportunities",
+ "organization_id",
+ "status_id",
+ "status_label",
+ "tasks",
+ "updated_by",
+ "updated_by_name",
+ "url",
+]
+
+CONTACT_SEARCH_FIELDS = [
+ "created_by",
+ "date_created",
+ "date_updated",
+ "display_name",
+ "emails",
+ "id",
+ "integration_links",
+ "lead_id",
+ "name",
+ "organization_id",
+ "phones",
+ "title",
+ "updated_by",
+ "urls",
+]
+
+
@dataclass
class CloseEndpointConfig:
name: str
@@ -32,22 +77,35 @@ class CloseEndpointConfig:
# endpoints (lead/opportunity statuses, pipelines) return every row in one response and
# take no pagination params, so they use a single-page paginator instead (see api_inventory.md).
paginated: bool = True
+ # Advanced Filtering object type. Set only for the two resources whose list endpoints expose
+ # no date filter at all, so offset pagination is the only option and Close's `_skip` cap
+ # eventually truncates the table (see api_inventory.md).
+ search_object_type: Optional[str] = None
+ # Fields to request from Advanced Filtering. Required when `search_object_type` is set.
+ search_fields: list[str] = field(default_factory=list)
-# Canonical CRM endpoint set. Incremental support is only enabled where the OpenAPI spec
-# exposes a genuine server-side `<field>__gte` filter (see api_inventory.md).
+# Canonical CRM endpoint set. Incremental support is only enabled where a genuine server-side
+# date filter exists — a `<field>__gte` query param on the list endpoint, or a `moment_range`
+# condition on Advanced Filtering for the two resources routed there (see api_inventory.md).
CLOSE_ENDPOINTS: dict[str, CloseEndpointConfig] = {
"Leads": CloseEndpointConfig(
name="Leads",
path="/lead/",
table_name="leads",
+ incremental_fields=[_date_incremental_field("date_created"), _date_incremental_field("date_updated")],
partition_key="date_created",
+ search_object_type="lead",
+ search_fields=LEAD_SEARCH_FIELDS,
),
"Contacts": CloseEndpointConfig(
name="Contacts",
path="/contact/",
table_name="contacts",
+ incremental_fields=[_date_incremental_field("date_created"), _date_incremental_field("date_updated")],
partition_key="date_created",
+ search_object_type="contact",
+ search_fields=CONTACT_SEARCH_FIELDS,
),
"Opportunities": CloseEndpointConfig(
name="Opportunities",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/source.py
index fad94304c120..05a107053f69 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/source.py
@@ -103,6 +103,7 @@ class CloseSource(ResumableSource[CloseSourceConfig, CloseResumeConfig]):
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ logger=inputs.logger,
should_use_incremental_field=inputs.should_use_incremental_field,
incremental_field=inputs.incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close.py
index 0990f40a915a..0daa4589b0b4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close.py
@@ -41,16 +41,16 @@ class TestCloseOffsetPaginator:
def test_update_state_has_more_advances_offset(self) -> None:
paginator = CloseOffsetPaginator()
response = MagicMock()
- response.json.return_value = {"data": [{"id": "lead_1"}], "has_more": True}
- paginator.update_state(response, [{"id": "lead_1"}])
+ response.json.return_value = {"data": [{"id": "user_1"}], "has_more": True}
+ paginator.update_state(response, [{"id": "user_1"}])
assert paginator.offset == 100
assert paginator.has_next_page is True
def test_update_state_no_more_stops(self) -> None:
paginator = CloseOffsetPaginator()
response = MagicMock()
- response.json.return_value = {"data": [{"id": "lead_1"}], "has_more": False}
- paginator.update_state(response, [{"id": "lead_1"}])
+ response.json.return_value = {"data": [{"id": "user_1"}], "has_more": False}
+ paginator.update_state(response, [{"id": "user_1"}])
assert paginator.has_next_page is False
def test_update_state_missing_has_more_stops(self) -> None:
@@ -71,15 +71,15 @@ class TestCloseOffsetPaginator:
def test_get_resume_state_when_next_page(self) -> None:
paginator = CloseOffsetPaginator()
response = MagicMock()
- response.json.return_value = {"data": [{"id": "lead_1"}], "has_more": True}
- paginator.update_state(response, [{"id": "lead_1"}])
+ response.json.return_value = {"data": [{"id": "user_1"}], "has_more": True}
+ paginator.update_state(response, [{"id": "user_1"}])
assert paginator.get_resume_state() == {"skip": 100}
def test_get_resume_state_none_on_terminal_page(self) -> None:
paginator = CloseOffsetPaginator()
response = MagicMock()
- response.json.return_value = {"data": [{"id": "lead_1"}], "has_more": False}
- paginator.update_state(response, [{"id": "lead_1"}])
+ response.json.return_value = {"data": [{"id": "user_1"}], "has_more": False}
+ paginator.update_state(response, [{"id": "user_1"}])
assert paginator.get_resume_state() is None
def test_set_resume_state_round_trip(self) -> None:
@@ -148,7 +148,7 @@ class TestGetResource:
assert resource["primary_key"] == ["id"]
assert _endpoint(resource)["data_selector"] == "data"
- @pytest.mark.parametrize("endpoint", ["Leads", "Contacts", "Users", "Pipelines"])
+ @pytest.mark.parametrize("endpoint", ["Users", "Pipelines", "EmailTemplates"])
def test_full_refresh_endpoints_never_incremental(self, endpoint: str) -> None:
# Even when the user enables incremental, endpoints with no server-side date filter
# stay on full replace and emit no `__gte` param.
@@ -184,7 +184,7 @@ class TestGetResource:
resource = get_resource(endpoint, should_use_incremental_field=False, incremental_field=None)
assert isinstance(_endpoint(resource)["paginator"], SinglePagePaginator)
- @pytest.mark.parametrize("endpoint", ["Leads", "Contacts", "Opportunities", "Activities", "Tasks", "Users"])
+ @pytest.mark.parametrize("endpoint", ["Opportunities", "Activities", "Tasks", "Users", "EmailTemplates"])
def test_paginated_endpoints_inherit_client_paginator(self, endpoint: str) -> None:
# Offset-paginated endpoints don't set an endpoint-level paginator, so they fall back to
# the client-level CloseOffsetPaginator.
@@ -216,6 +216,7 @@ class TestCloseSourcePartitioning:
team_id=1,
job_id="job",
resumable_source_manager=manager,
+ logger=MagicMock(),
db_incremental_field_last_value=None,
should_use_incremental_field=False,
)
@@ -272,6 +273,7 @@ class TestCloseSourceResumeBehavior:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ logger=MagicMock(),
db_incremental_field_last_value=db_incremental_field_last_value,
should_use_incremental_field=should_use_incremental_field,
incremental_field=incremental_field,
@@ -284,11 +286,11 @@ class TestCloseSourceResumeBehavior:
manager.can_resume.return_value = False
responses = [
- _make_http_response({"data": [{"id": "lead_1"}], "has_more": True}),
- _make_http_response({"data": [{"id": "lead_2"}], "has_more": True}),
- _make_http_response({"data": [{"id": "lead_3"}], "has_more": False}),
+ _make_http_response({"data": [{"id": "user_1"}], "has_more": True}),
+ _make_http_response({"data": [{"id": "user_2"}], "has_more": True}),
+ _make_http_response({"data": [{"id": "user_3"}], "has_more": False}),
]
- sent_params = self._drive("Leads", manager, responses)
+ sent_params = self._drive("Users", manager, responses)
assert [p.get("_skip") for p in sent_params] == [0, 100, 200]
@@ -300,8 +302,8 @@ class TestCloseSourceResumeBehavior:
manager.can_resume.return_value = True
manager.load_state.return_value = CloseResumeConfig(next_skip=200)
- responses = [_make_http_response({"data": [{"id": "lead_9"}], "has_more": False})]
- sent_params = self._drive("Leads", manager, responses)
+ responses = [_make_http_response({"data": [{"id": "user_9"}], "has_more": False})]
+ sent_params = self._drive("Users", manager, responses)
assert [p.get("_skip") for p in sent_params] == [200]
manager.load_state.assert_called_once()
@@ -311,7 +313,7 @@ class TestCloseSourceResumeBehavior:
manager.can_resume.return_value = False
responses = [_make_http_response({"data": [{"id": "only"}], "has_more": False})]
- self._drive("Leads", manager, responses)
+ self._drive("Users", manager, responses)
manager.save_state.assert_not_called()
@@ -320,7 +322,7 @@ class TestCloseSourceResumeBehavior:
manager.can_resume.return_value = False
responses = [_make_http_response({"data": [{"id": "a"}], "has_more": False})]
- self._drive("Leads", manager, responses)
+ self._drive("Users", manager, responses)
manager.load_state.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_search.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_search.py
new file mode 100644
index 000000000000..2a48f5068a69
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_search.py
@@ -0,0 +1,370 @@
+import json
+from typing import Any, Optional, cast
+
+import pytest
+from unittest.mock import MagicMock
+
+from requests import RequestException, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.close import search as close_search
+from products.warehouse_sources.backend.temporal.data_imports.sources.close.close import (
+ close_search_source,
+ close_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.close.search import (
+ CloseCursorExpiredError,
+ CloseSearchError,
+ build_search_body,
+ fetch_custom_field_selectors,
+ iter_search_rows,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BASE_URL = "https://api.close.com/api/v1"
+
+
+def _response(body: dict[str, Any], status_code: int = 200) -> Response:
+ response = Response()
+ response.status_code = status_code
+ response._content = json.dumps(body).encode()
+ response.headers["Content-Type"] = "application/json"
+ return response
+
+
+def _row(row_id: str, date_created: str) -> dict[str, Any]:
+ return {"id": row_id, "date_created": date_created}
+
+
+class FakeSession:
+ """Stands in for the tracked HTTP session, recording the search bodies it was sent."""
+
+ def __init__(self, pages: list[Response], get_pages: Optional[list[Any]] = None) -> None:
+ self._pages = list(pages)
+ self._get_pages = list(get_pages or [])
+ self.bodies: list[dict[str, Any]] = []
+ self.get_params: list[dict[str, Any]] = []
+
+ def post(self, url: str, json: dict[str, Any], timeout: int) -> Response: # noqa: A002
+ self.bodies.append(json)
+ if not self._pages:
+ raise AssertionError(f"unexpected extra search request: {json}")
+ return self._pages.pop(0)
+
+ def get(self, url: str, params: dict[str, Any], timeout: int) -> Response:
+ self.get_params.append(params)
+ page = self._get_pages.pop(0)
+ if isinstance(page, Exception):
+ raise page
+ return page
+
+
+def _anchor_of(body: dict[str, Any]) -> Optional[str]:
+ for query in body["query"]["queries"]:
+ if query["type"] == "field_condition":
+ return cast(str, query["condition"]["on_or_after"]["value"])
+ return None
+
+
+class FakeClose:
+ """Answers `/data/search/` out of a fixed, ascending dataset the way Close does.
+
+ Cursor-less requests re-run the `on_or_after` filter from the top; a cursor resumes where
+ the page that handed it out left off. Faithful enough that the walker's paging decisions —
+ not the test's assumptions about them — are what's under test.
+ """
+
+ def __init__(self, rows: list[dict[str, Any]], expire_next_cursor: bool = False) -> None:
+ self.rows = rows
+ self.bodies: list[dict[str, Any]] = []
+ self._cursors: dict[str, int] = {}
+ self._issued = 0
+ self._expire_next_cursor = expire_next_cursor
+
+ def post(self, url: str, json: dict[str, Any], timeout: int) -> Response: # noqa: A002
+ self.bodies.append(json)
+ cursor = json.get("cursor")
+
+ if cursor is not None:
+ if self._expire_next_cursor:
+ self._expire_next_cursor = False
+ return _response({"error": "Expired cursor"}, status_code=400)
+ start = self._cursors[cursor]
+ else:
+ anchor = _anchor_of(json)
+ start = (
+ 0
+ if anchor is None
+ else next((i for i, row in enumerate(self.rows) if row["date_created"] >= anchor), len(self.rows))
+ )
+
+ page = self.rows[start : start + json["_limit"]]
+ end = start + len(page)
+ body: dict[str, Any] = {"data": page, "cursor": None}
+ if end < len(self.rows):
+ token = f"cur{self._issued}"
+ self._issued += 1
+ self._cursors[token] = end
+ body["cursor"] = token
+ return _response(body)
+
+
+def _walk(session: FakeSession | FakeClose, limit: int = 2, start_anchor: Optional[str] = None) -> list[dict[str, Any]]:
+ batches = iter_search_rows(
+ session=cast(Any, session),
+ base_url=BASE_URL,
+ object_type="contact",
+ fields=["id", "date_created"],
+ cursor_field="date_created",
+ start_anchor=start_anchor,
+ logger=MagicMock(),
+ limit=limit,
+ )
+ return [row for batch in batches for row in batch]
+
+
+class TestBuildSearchBody:
+ def test_anchored_body_filters_and_sorts_on_the_cursor_field(self) -> None:
+ body = build_search_body("contact", ["id"], "date_updated", "2024-01-02T03:04:05+00:00", limit=50)
+
+ condition = body["query"]["queries"][1]
+ assert condition["field"] == {
+ "type": "regular_field",
+ "object_type": "contact",
+ "field_name": "date_updated",
+ }
+ # `on_or_after` (not `after`) is what makes re-reading the anchor safe rather than lossy.
+ assert condition["condition"] == {
+ "type": "moment_range",
+ "on_or_after": {"type": "fixed_utc", "value": "2024-01-02T03:04:05+00:00"},
+ }
+ assert body["sort"][0]["direction"] == "asc"
+ assert body["sort"][0]["field"]["field_name"] == "date_updated"
+ assert body["_fields"] == {"contact": ["id"]}
+ assert body["_limit"] == 50
+ assert "cursor" not in body
+
+ def test_unanchored_body_has_no_date_filter(self) -> None:
+ body = build_search_body("lead", ["id"], "date_created", None)
+ assert [q["type"] for q in body["query"]["queries"]] == ["object_type"]
+
+ def test_cursor_is_sent_when_stepping_over_a_plateau(self) -> None:
+ body = build_search_body("lead", ["id"], "date_created", "2024-01-01T00:00:00+00:00", page_cursor="abc")
+ assert body["cursor"] == "abc"
+
+
+class TestIterSearchRows:
+ def test_walk_reads_every_row_exactly_once(self) -> None:
+ # Each keyset page re-reads the rows tied to the anchor because `on_or_after` is
+ # inclusive; they must not be emitted twice.
+ close = FakeClose([_row(f"c{i}", f"2024-01-{i:02d}T00:00:00+00:00") for i in range(1, 8)])
+
+ rows = _walk(close)
+
+ assert [row["id"] for row in rows] == [f"c{i}" for i in range(1, 8)]
+ # Every request after the first moves the anchor strictly forward, so no request ever
+ # reaches for a deep offset and none of them repeat.
+ anchors = [_anchor_of(body) for body in close.bodies]
+ assert anchors[0] is None
+ assert anchors[1:] == sorted(set(cast(list[str], anchors[1:])))
+
+ def test_short_page_ends_the_walk(self) -> None:
+ session = FakeSession([_response({"data": [_row("c1", "2024-01-01T00:00:00+00:00")]})])
+
+ assert [row["id"] for row in _walk(session)] == ["c1"]
+ assert len(session.bodies) == 1
+
+ def test_rows_sharing_one_timestamp_are_paged_with_the_cursor(self) -> None:
+ # The keyset filter cannot advance across a run of identical timestamps, so without the
+ # cursor fallback this walk would re-request the same page forever.
+ tied = "2024-01-01T00:00:00+00:00"
+ close = FakeClose(
+ [_row(f"c{i}", tied) for i in range(1, 6)] + [_row("c6", "2024-02-01T00:00:00+00:00")],
+ )
+
+ rows = _walk(close)
+
+ assert [row["id"] for row in rows] == ["c1", "c2", "c3", "c4", "c5", "c6"]
+ assert any(body.get("cursor") for body in close.bodies)
+
+ def test_expired_cursor_reanchors_instead_of_failing_the_sync(self) -> None:
+ # A slow Delta write can stall the walk past Close's 30s cursor TTL; the run should
+ # recover by re-issuing the query rather than dying.
+ tied = "2024-01-01T00:00:00+00:00"
+ close = FakeClose(
+ [_row(f"c{i}", tied) for i in range(1, 6)] + [_row("c6", "2024-02-01T00:00:00+00:00")],
+ expire_next_cursor=True,
+ )
+
+ rows = _walk(close)
+
+ assert [row["id"] for row in rows] == ["c1", "c2", "c3", "c4", "c5", "c6"]
+
+ def test_start_anchor_is_applied_to_the_first_request(self) -> None:
+ session = FakeSession([_response({"data": [_row("c1", "2024-06-01T00:00:00+00:00")]})])
+
+ _walk(session, start_anchor="2024-05-01T00:00:00+00:00")
+
+ assert _anchor_of(session.bodies[0]) == "2024-05-01T00:00:00+00:00"
+
+ def test_checkpoint_records_the_last_emitted_anchor(self) -> None:
+ session = FakeSession(
+ [
+ _response({"data": [_row("c1", "2024-01-01T00:00:00+00:00"), _row("c2", "2024-01-02T00:00:00+00:00")]}),
+ _response({"data": [_row("c2", "2024-01-02T00:00:00+00:00")]}),
+ ]
+ )
+ seen: list[str] = []
+
+ list(
+ iter_search_rows(
+ session=cast(Any, session),
+ base_url=BASE_URL,
+ object_type="contact",
+ fields=["id"],
+ cursor_field="date_created",
+ start_anchor=None,
+ logger=MagicMock(),
+ on_checkpoint=seen.append,
+ limit=2,
+ )
+ )
+
+ assert seen == ["2024-01-02T00:00:00+00:00"]
+
+ def test_rejected_query_surfaces_closes_message(self) -> None:
+ session = FakeSession([_response({"field-errors": {"_fields": "unknown field"}}, status_code=400)])
+
+ with pytest.raises(CloseSearchError, match="unknown field"):
+ _walk(session)
+
+ @pytest.mark.parametrize(
+ ("row", "match"),
+ [
+ ({"date_created": "2024-01-01T00:00:00+00:00"}, "without an id"),
+ ({"id": "c1"}, "without a date_created value"),
+ ],
+ ids=["missing_id", "missing_cursor_field"],
+ )
+ def test_malformed_rows_fail_loudly(self, row: dict[str, Any], match: str) -> None:
+ # A row the walker can't key or order would otherwise duplicate silently (no id to
+ # dedupe the inclusive anchor re-reads on) or re-request the same page forever (no
+ # cursor-field value to advance the anchor with).
+ session = FakeSession([_response({"data": [row]})])
+
+ with pytest.raises(CloseSearchError, match=match):
+ _walk(session)
+
+ def test_expired_cursor_on_a_cursorless_request_is_fatal(self) -> None:
+ # The re-anchor recovery only makes sense when a cursor was actually sent; replaying
+ # an identical cursor-less request can never succeed, so it must propagate instead of
+ # retrying forever.
+ session = FakeSession([_response({"error": "Expired cursor"}, status_code=400)])
+
+ with pytest.raises(CloseCursorExpiredError):
+ _walk(session)
+
+ assert len(session.bodies) == 1
+
+ def test_endless_single_timestamp_run_aborts_instead_of_looping(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # If Close's cursor never terminates a run of identical timestamps, the plateau guard
+ # is the only thing standing between the walk and an infinite loop.
+ monkeypatch.setattr(close_search, "MAX_PLATEAU_PAGES", 2)
+ tied = "2024-01-01T00:00:00+00:00"
+ close = FakeClose([_row(f"c{i}", tied) for i in range(1, 13)])
+
+ with pytest.raises(CloseSearchError, match="cannot be paged past"):
+ _walk(close)
+
+
+class TestFetchCustomFieldSelectors:
+ def test_selectors_are_built_from_every_page(self) -> None:
+ session = FakeSession(
+ [],
+ get_pages=[
+ _response({"data": [{"id": "cf_a"}], "has_more": True}),
+ _response({"data": [{"id": "cf_b"}], "has_more": False}),
+ ],
+ )
+
+ selectors = fetch_custom_field_selectors(cast(Any, session), BASE_URL, "contact", MagicMock())
+
+ assert selectors == ["custom.cf_a", "custom.cf_b"]
+
+ @pytest.mark.parametrize(
+ "failure",
+ [RequestException("403 Forbidden"), ValueError("not json")],
+ ids=["no_access", "bad_payload"],
+ )
+ def test_failure_falls_back_to_standard_fields(self, failure: Exception) -> None:
+ # A key without custom-field access should still sync the standard columns.
+ session = FakeSession([], get_pages=[failure])
+
+ assert fetch_custom_field_selectors(cast(Any, session), BASE_URL, "contact", MagicMock()) == []
+
+
+class TestSearchSourceWiring:
+ @pytest.mark.parametrize("endpoint", ["Leads", "Contacts"])
+ def test_capped_endpoints_read_through_advanced_filtering(self, endpoint: str, monkeypatch: Any) -> None:
+ # Guards the routing itself: if these fall back to /lead/ and /contact/, they silently
+ # truncate again at Close's `_skip` cap.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ session = FakeSession([_response({"data": []})], get_pages=[_response({"data": []})])
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.close.close._make_search_session",
+ lambda _api_key: session,
+ )
+
+ response = close_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ logger=MagicMock(),
+ )
+ list(cast(Any, response.items()))
+
+ assert session.bodies[0]["query"]["queries"][0]["object_type"] == endpoint.rstrip("s").lower()
+
+ @pytest.mark.parametrize(
+ ("incremental", "field", "last_value", "expected_cursor_field", "expected_anchor"),
+ [
+ (False, None, "2024-06-01T00:00:00+00:00", "date_created", None),
+ (True, "date_updated", "2024-06-01T00:00:00+00:00", "date_updated", "2024-06-01T00:00:00+00:00"),
+ (True, "bogus", "2024-06-01T00:00:00+00:00", "date_created", "2024-06-01T00:00:00+00:00"),
+ (True, "date_created", None, "date_created", None),
+ ],
+ ids=["full_refresh_ignores_watermark", "honors_chosen_cursor", "falls_back_to_first_cursor", "no_watermark"],
+ )
+ def test_starting_anchor_follows_the_incremental_settings(
+ self,
+ incremental: bool,
+ field: Optional[str],
+ last_value: Optional[str],
+ expected_cursor_field: str,
+ expected_anchor: Optional[str],
+ monkeypatch: Any,
+ ) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ session = FakeSession([_response({"data": []})], get_pages=[_response({"data": []})])
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.close.close._make_search_session",
+ lambda _api_key: session,
+ )
+
+ response = close_search_source(
+ api_key="test-key",
+ endpoint="Contacts",
+ resumable_source_manager=manager,
+ logger=MagicMock(),
+ db_incremental_field_last_value=last_value,
+ should_use_incremental_field=incremental,
+ incremental_field=field,
+ )
+ list(cast(Any, response.items()))
+
+ assert session.bodies[0]["sort"][0]["field"]["field_name"] == expected_cursor_field
+ assert _anchor_of(session.bodies[0]) == expected_anchor
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_source.py
index 98c2c6863df5..746a1419c2e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/tests/test_close_source.py
@@ -11,7 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.close import CloseSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
-INCREMENTAL_ENDPOINTS = {"Opportunities", "Activities", "Tasks"}
+INCREMENTAL_ENDPOINTS = {"Leads", "Contacts", "Opportunities", "Activities", "Tasks"}
class TestCloseSource:
@@ -130,6 +130,7 @@ class TestCloseSource:
team_id=7,
job_id="job-1",
resumable_source_manager=manager,
+ logger=inputs.logger,
should_use_incremental_field=True,
incremental_field="date_updated",
db_incremental_field_last_value="2024-01-01T00:00:00+00:00",