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): bound Close search field list to one custom selector (#91695)

posthog[bot]b5936466ef2c
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 17dc72c9615c..a97ebc2b8740 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
@@ -39,8 +39,10 @@ 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).
+ explicit field list per object type. A single `custom` selector is added at request time to
+ return every custom field as a flat `custom.cf_*` key. Naming each custom field instead grows
+ `_fields` one entry per field, which Close rejects with 400 "List is too long." once an org has
+ enough of them.
- 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.
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 3ee5322c6c6e..aaecac5bdcdb 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
@@ -9,8 +9,7 @@ from requests import Response, Session
from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.sources.close.search import (
- CloseSearchError,
- fetch_custom_field_selectors,
+ ALL_CUSTOM_FIELDS_SELECTOR,
iter_search_rows,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.close.settings import (
@@ -222,38 +221,19 @@ def close_search_source(
def items() -> Iterator[list[dict[str, Any]]]:
session = _make_search_session(api_key)
- custom_fields = fetch_custom_field_selectors(session, CLOSE_BASE_URL, object_type, logger)
- fields = [*config.search_fields, *custom_fields]
-
- try:
- 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,
- )
- except CloseSearchError as exc:
- if "list is too long" not in str(exc).lower() or not custom_fields:
- raise
- # Some orgs have enough custom fields that the combined _fields list exceeds Close's
- # undocumented limit. Fall back to standard fields so the sync can complete.
- logger.warning(
- f"Close: _fields list too long ({len(fields)} fields), retrying with standard fields. object_type={object_type}"
- )
- yield from iter_search_rows(
- session=session,
- base_url=CLOSE_BASE_URL,
- object_type=object_type,
- fields=config.search_fields,
- cursor_field=cursor_field,
- start_anchor=start_anchor,
- logger=logger,
- on_checkpoint=save_checkpoint,
- )
+ # One `custom` selector pulls every custom field, so the field list stays bounded no
+ # matter how many an org has. See ALL_CUSTOM_FIELDS_SELECTOR.
+ fields = [*config.search_fields, ALL_CUSTOM_FIELDS_SELECTOR]
+ 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,
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
index 383ce5cb0941..e322041cd379 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/close/search.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/close/search.py
@@ -20,14 +20,15 @@ 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
+# One `_fields` selector that returns every custom field as a flat `custom.cf_*` key. Naming each
+# custom field instead makes `_fields` grow one entry per field, which Close rejects with 400
+# "List is too long." once an org has enough of them. See advanced-filtering docs:
+# https://developer.close.com/resources/advanced-filtering/
+ALL_CUSTOM_FIELDS_SELECTOR = "custom"
# 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.
@@ -95,8 +96,9 @@ def _post_search(session: Session, base_url: str, body: dict[str, Any]) -> Searc
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.
+ # Any other 400 is Close rejecting the query itself, for example an unknown field, a
+ # malformed condition, or a field list it considers too long. Surface its message rather
+ # than a bare status code so the cause is visible in the error.
raise CloseSearchError(f"Close rejected the search query: {detail}")
response.raise_for_status()
@@ -113,39 +115,6 @@ def _post_search(session: Session, base_url: str, body: dict[str, Any]) -> Searc
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,
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 9e013391bc35..8833db57d832 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
@@ -16,7 +16,8 @@ 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>/`.
+# the offset-paginated ones. A single `custom` selector for every custom field is added at
+# runtime (see ALL_CUSTOM_FIELDS_SELECTOR).
LEAD_SEARCH_FIELDS = [
"addresses",
"contact_ids",
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 de8b1b6a45c6..113f25e7b9dc 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
@@ -43,6 +43,10 @@ class CloseSource(ResumableSource[CloseSourceConfig, CloseResumeConfig]):
return {
"401 Client Error: Unauthorized for url": "Close authentication failed. Please check your API key.",
"403 Client Error: Forbidden for url": "Your Close API key does not have access to this resource. Please check the key's permissions.",
+ # Close rejects an over-long `_fields` list this way. The search now asks for custom
+ # fields with a single selector, so this should not recur, but a stuck sync must stop
+ # rather than let Temporal retry a request that can never succeed.
+ "List is too long.": "Close rejected the request because the field list was too long. This can happen on an account with a very large number of custom fields. Contact PostHog support so we can adjust how the Close source requests them.",
}
def get_retryable_errors(self) -> set[str]:
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
index f44331f63189..d1c939e10485 100644
--- 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
@@ -4,7 +4,7 @@ from typing import Any, Optional, cast
import pytest
from unittest.mock import MagicMock
-from requests import RequestException, Response
+from requests import 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 (
@@ -15,7 +15,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.close.sear
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
@@ -38,11 +37,9 @@ def _row(row_id: str, date_created: str) -> dict[str, Any]:
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:
+ def __init__(self, pages: list[Response]) -> 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)
@@ -50,13 +47,6 @@ class FakeSession:
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"]:
@@ -276,32 +266,6 @@ class TestIterSearchRows:
_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:
@@ -309,7 +273,7 @@ class TestSearchSourceWiring:
# 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": []})])
+ session = FakeSession([_response({"data": []})])
monkeypatch.setattr(
"products.warehouse_sources.backend.temporal.data_imports.sources.close.close._make_search_session",
lambda _api_key: session,
@@ -328,38 +292,28 @@ class TestSearchSourceWiring:
assert session.bodies[0]["query"]["queries"][0]["object_type"] == endpoint.rstrip("s").lower()
- def test_fields_list_too_long_retries_without_custom_fields(self, monkeypatch: Any) -> None:
- # Orgs with many custom fields can push the combined _fields list past Close's limit.
- # The source must fall back to standard fields so the sync can complete rather than
- # permanently failing on every Temporal retry.
+ def test_custom_fields_are_requested_with_a_single_selector(self, monkeypatch: Any) -> None:
+ # Enumerating one selector per custom field grew `_fields` until Close rejected it with
+ # 400 "List is too long."; the `custom` selector returns them all in one bounded entry.
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
- too_long = _response(
- {"errors": [], "field-errors": {"_fields": {"errors": {"lead": "List is too long."}}}},
- status_code=400,
- )
- ok = _response({"data": []})
- custom_field_page = _response({"data": [{"id": "cf_x"}], "has_more": False})
- session = FakeSession(pages=[too_long, ok], get_pages=[custom_field_page])
+ session = FakeSession([_response({"data": []})])
monkeypatch.setattr(
"products.warehouse_sources.backend.temporal.data_imports.sources.close.close._make_search_session",
lambda _api_key: session,
)
- response = close_source(
+ response = close_search_source(
api_key="test-key",
endpoint="Leads",
- team_id=1,
- job_id="job",
resumable_source_manager=manager,
- db_incremental_field_last_value=None,
logger=MagicMock(),
)
list(cast(Any, response.items()))
- assert len(session.bodies) == 2
- assert "custom.cf_x" in session.bodies[0]["_fields"]["lead"]
- assert "custom.cf_x" not in session.bodies[1]["_fields"]["lead"]
+ requested = session.bodies[0]["_fields"]["lead"]
+ assert "custom" in requested
+ assert not any(f.startswith("custom.") for f in requested)
@pytest.mark.parametrize(
("incremental", "field", "last_value", "expected_cursor_field", "expected_anchor"),
@@ -382,7 +336,7 @@ class TestSearchSourceWiring:
) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
- session = FakeSession([_response({"data": []})], get_pages=[_response({"data": []})])
+ session = FakeSession([_response({"data": []})])
monkeypatch.setattr(
"products.warehouse_sources.backend.temporal.data_imports.sources.close.close._make_search_session",
lambda _api_key: session,
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 00d61d70847c..f457ad05c65a 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
@@ -69,6 +69,14 @@ class TestCloseSource:
assert is_valid is False
assert error_message == "Close API key is required"
+ def test_field_list_too_long_is_non_retryable(self) -> None:
+ # Close rejects an over-long `_fields` list with this message. It can never succeed on
+ # retry, so it must be classified non-retryable rather than looping in Temporal.
+ error_msg = 'Close rejected the search query: {"field-errors": {"_fields": "List is too long."}}'
+ matched = [msg for pattern, msg in self.source.get_non_retryable_errors().items() if pattern in error_msg]
+ assert len(matched) == 1
+ assert matched[0] is not None
+
def test_retryable_errors_match_exhausted_connection_retries(self) -> None:
error_msg = (
"HTTPSConnectionPool(host='api.close.com', port=443): Max retries exceeded with "