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(hubspot): sub-divide search windows by id when a cursor tie exceeds the result cap (#76060)

Tom Owers8953860bd867
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
index 28f9a2860345..f2a49bac2192 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/hubspot.py
@@ -10,8 +10,9 @@ Two fetch paths:
- get_rows_via_search: POST to /crm/v3/objects/{entity}/search with server-side date
filtering, used for subsequent incremental syncs. Mirrors Airbyte's CRM-search
pattern: time-windowed queries sorted by the cursor property, with cursor-advance
- sub-slicing when the 10k result cap is hit within a window. Backfills associations
- per page via v4 batch-read.
+ sub-slicing when the 10k result cap is hit within a window, falling back to
+ hs_object_id-based sub-slicing when every record in the cap shares one cursor value.
+ Backfills associations per page via v4 batch-read.
"""
import dataclasses
@@ -60,11 +61,6 @@ SEARCH_PROPERTIES_LIMIT = 250
WINDOW_SIZE_MS = SEARCH_WINDOW_DAYS * 24 * 60 * 60 * 1000
-class HubspotPathologicalWindowError(Exception):
- """Raised when a single cursor-ms value has >SEARCH_RESULT_CAP records and the window
- cannot be sub-divided further. Extremely unlikely in practice for HubSpot CRM data."""
-
-
@dataclasses.dataclass
class HubspotResumeConfig:
# Full-refresh / seed incremental (GET) path
@@ -570,8 +566,10 @@ def get_rows_via_search(
- Within each window, sort by the cursor property ASC and paginate via `after`.
- When a sub-slice exceeds SEARCH_RESULT_CAP results, advance the lower bound to
`sub_slice_max_cursor` (the highest cursor seen in the slice) and continue with
- GTE so boundary-cursor records are re-fetched and deduplicated by primary key,
- rather than id-walking. This avoids skipping records that share the boundary cursor.
+ GTE so boundary-cursor records are re-fetched and deduplicated by primary key.
+ This avoids skipping records that share the boundary cursor. If every record in the
+ capped slice shares one cursor value, fall back to hs_object_id-based sub-slicing
+ (see `_drain_tied_cursor`).
- Backfill associations (if any) per page via the v4 batch-read endpoint.
- Checkpoint (sync_start_ms, sync_end_ms, last_cursor_ms) to Redis on each batch flush.
"""
@@ -614,6 +612,9 @@ def get_rows_via_search(
current_lower = sync_start_ms
last_cursor_ms = current_lower
+ # Placeholder; reassigned per-window below. Bound here so the nested `_process_results`
+ # closure (defined before the window loop) has a `nonlocal` target to resolve against.
+ sub_slice_max_cursor = current_lower - 1
@retry(
retry=retry_if_exception_type(
@@ -664,6 +665,98 @@ def get_rows_via_search(
)
)
+ def _process_results(results: list[dict[str, Any]]) -> Iterator[Any]:
+ """Flatten, batch, and yield `results`, tracking cursor progress as a side effect."""
+ nonlocal last_cursor_ms, sub_slice_max_cursor
+ for result in results:
+ row = _flatten_result(result)
+ if expected_properties:
+ _backfill_missing_properties(row, expected_properties)
+
+ row_cursor_ms = _iso_to_ms(row.get(cursor_prop))
+ if row_cursor_ms is not None:
+ if row_cursor_ms > last_cursor_ms:
+ last_cursor_ms = row_cursor_ms
+ if row_cursor_ms > sub_slice_max_cursor:
+ sub_slice_max_cursor = row_cursor_ms
+
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ save_progress()
+
+ def _drain_tied_cursor(cursor_ms: int) -> Iterator[Any]:
+ """SEARCH_RESULT_CAP+ records share `cursor_ms` (e.g. a bulk import stamping a whole
+ batch with the same lastmodifieddate), so the cursor value can't sub-divide the window
+ any further. Page through them by the unique hs_object_id instead: each query filters
+ on `hs_object_id > anchor_id`, so re-issuing a fresh query with an advanced anchor once
+ one query's own `after`-pagination ends shrinks the match count each time, sidestepping
+ HubSpot's per-query SEARCH_RESULT_CAP regardless of how many records are tied. This
+ re-walks records already seen for `cursor_ms` in the caller's cursor-sorted pass, but
+ writes dedup by primary key, so re-fetching is safe.
+ """
+ next_anchor_id = -1
+ while True:
+ anchor_id = next_anchor_id
+ after: Optional[str] = None
+ got_any = False
+
+ while True:
+ body: dict[str, Any] = {
+ "limit": SEARCH_PAGE_SIZE,
+ "sorts": [{"propertyName": "hs_object_id", "direction": "ASCENDING"}],
+ "filterGroups": [
+ {
+ "filters": [
+ {"propertyName": cursor_prop, "operator": "EQ", "value": str(cursor_ms)},
+ {"propertyName": "hs_object_id", "operator": "GT", "value": str(anchor_id)},
+ ]
+ }
+ ],
+ "properties": props_list,
+ }
+ if after is not None:
+ body["after"] = after
+
+ data = fetch_search(body)
+ results = data.get("results", [])
+ if not results:
+ break
+ got_any = True
+
+ if config.associations:
+ _backfill_associations_into_results(
+ results=results,
+ from_entity_plural=endpoint,
+ association_types=config.associations,
+ headers=headers,
+ refresh_token=refresh_token,
+ source_id=source_id,
+ logger=logger,
+ api_version=api_version,
+ )
+
+ for result in results:
+ try:
+ result_id = int(result["id"])
+ except (KeyError, ValueError):
+ continue
+ if result_id > next_anchor_id:
+ next_anchor_id = result_id
+
+ yield from _process_results(results)
+
+ next_cursor = data.get("paging", {}).get("next", {}).get("after")
+ if not next_cursor:
+ break
+ after = next_cursor
+
+ # An empty result for this anchor means every tied record has been seen; a
+ # non-empty query that just ran out of `after` pages (likely SEARCH_RESULT_CAP)
+ # restarts fresh with the advanced anchor to keep shrinking the match count.
+ if not got_any:
+ break
+
while current_lower <= sync_end_ms:
window_upper = min(current_lower + WINDOW_SIZE_MS, sync_end_ms)
window_lower = current_lower
@@ -713,23 +806,7 @@ def get_rows_via_search(
api_version=api_version,
)
- for result in results:
- row = _flatten_result(result)
- if expected_properties:
- _backfill_missing_properties(row, expected_properties)
-
- row_cursor_ms = _iso_to_ms(row.get(cursor_prop))
- if row_cursor_ms is not None:
- if row_cursor_ms > last_cursor_ms:
- last_cursor_ms = row_cursor_ms
- if row_cursor_ms > sub_slice_max_cursor:
- sub_slice_max_cursor = row_cursor_ms
-
- batcher.batch(row)
- if batcher.should_yield():
- py_table = batcher.get_table()
- yield py_table
- save_progress()
+ yield from _process_results(results)
window_result_count += len(results)
paging = data.get("paging", {})
@@ -738,18 +815,17 @@ def get_rows_via_search(
# Sub-slice the window if we hit the 10k cap.
if window_result_count >= SEARCH_RESULT_CAP:
# If every record in this sub-slice had cursor == window_lower we can't
- # safely advance (moving to window_lower + 1 would skip any unseen records
- # at the same timestamp). This requires 10k+ records at a single ms,
- # which is effectively impossible for real HubSpot CRM data.
+ # safely advance by cursor value alone (moving to window_lower + 1 would skip
+ # any unseen records at the same timestamp) — sub-divide by the unique
+ # hs_object_id instead.
if sub_slice_max_cursor <= window_lower:
- raise HubspotPathologicalWindowError(
- f"Hubspot search: {SEARCH_RESULT_CAP} records share cursor={window_lower}ms "
- f"for {endpoint}; cannot sub-divide further"
- )
- # Use GTE (not GT) so boundary records at sub_slice_max_cursor are re-fetched.
- # Primary-key dedup handles the duplicates without risk of skipping records
- # that share the boundary cursor.
- window_lower = sub_slice_max_cursor
+ yield from _drain_tied_cursor(window_lower)
+ window_lower = window_lower + 1
+ else:
+ # Use GTE (not GT) so boundary records at sub_slice_max_cursor are re-fetched.
+ # Primary-key dedup handles the duplicates without risk of skipping records
+ # that share the boundary cursor.
+ window_lower = sub_slice_max_cursor
sub_slice_max_cursor = window_lower - 1
after = None
window_result_count = 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
index 90490d637586..924d04ec9fe4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/test/test_hubspot_search.py
@@ -11,7 +11,6 @@ from requests.exceptions import (
)
from products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hubspot import (
- HubspotPathologicalWindowError,
HubspotResumeConfig,
_backfill_associations_into_results,
_batch_read_associations,
@@ -760,8 +759,10 @@ class TestGetRowsViaSearch:
assert subslice_lower > first_lower
assert subslice_lower == cursor_base + SEARCH_RESULT_CAP - 1
- def test_pathological_window_raises(self) -> None:
- # SEARCH_RESULT_CAP records all with the same cursor_ms → can't sub-divide.
+ def test_pathological_window_subdivides_by_hs_object_id(self) -> None:
+ # SEARCH_RESULT_CAP records all share one cursor_ms (e.g. a bulk import stamping a
+ # whole batch with the same lastmodifieddate) → can't sub-divide by cursor value, so
+ # this must fall back to hs_object_id-based sub-slicing instead of dropping the sync.
identical_cursor = 1_799_000_000_000
pages_in_cap = SEARCH_RESULT_CAP // SEARCH_PAGE_SIZE
pages = []
@@ -770,7 +771,17 @@ class TestGetRowsViaSearch:
is_last = i == pages_in_cap - 1
pages.append(_search_page(batch, after=None if is_last else f"c{i}"))
- side_effect, _ = _setup_search_post([_make_response(200, p) for p in pages])
+ # Only reachable once the id-anchored query subdivides past the cursor-sort cap.
+ tail_id = str(SEARCH_RESULT_CAP + 1)
+ tail = [_result(tail_id, identical_cursor)]
+
+ responses = (
+ [_make_response(200, p) for p in pages]
+ + [_make_response(200, _search_page(tail))] # id-drain page: the extra tied record
+ + [_make_response(200, _search_page([]))] # id-drain page: confirms exhaustion
+ + [_make_response(200, _search_page([]))] # window resumes past the tied cursor
+ )
+ side_effect, captured = _setup_search_post(responses)
manager = _make_manager()
logger = MagicMock()
@@ -778,21 +789,172 @@ class TestGetRowsViaSearch:
"products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hubspot.make_tracked_session",
new=lambda *_a, **_k: type("_S", (), {"post": staticmethod(side_effect)})(),
):
- with pytest.raises(HubspotPathologicalWindowError):
- # Force a narrow sync window so the identical cursors trigger the cap check.
- list(
- get_rows_via_search(
- api_key="k",
- refresh_token="r",
- endpoint="deals",
- logger=logger,
- resumable_source_manager=manager,
- db_incremental_field_last_value=str(identical_cursor - 1),
- include_custom_props=False,
- now_ms=identical_cursor + 1_000,
- api_version=HUBSPOT_API_VERSION_V3,
- )
+ # Force a narrow sync window so the identical cursors trigger the cap check.
+ tables = list(
+ get_rows_via_search(
+ api_key="k",
+ refresh_token="r",
+ endpoint="deals",
+ logger=logger,
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=str(identical_cursor - 1),
+ include_custom_props=False,
+ now_ms=identical_cursor + 1_000,
+ api_version=HUBSPOT_API_VERSION_V3,
)
+ )
+
+ # Every record is delivered, including the one only reachable past the cap.
+ assert sum(t.num_rows for t in tables) == SEARCH_RESULT_CAP + 1
+
+ drain_request = captured[pages_in_cap]["json"]
+ assert drain_request["sorts"] == [{"propertyName": "hs_object_id", "direction": "ASCENDING"}]
+ drain_filters = drain_request["filterGroups"][0]["filters"]
+ assert {
+ "propertyName": "hs_lastmodifieddate",
+ "operator": "EQ",
+ "value": str(identical_cursor),
+ } in drain_filters
+ assert {"propertyName": "hs_object_id", "operator": "GT", "value": "-1"} in drain_filters
+
+ # The next id-drain query is anchored past the tail record just seen.
+ second_drain_request = captured[pages_in_cap + 1]["json"]
+ assert {
+ "propertyName": "hs_object_id",
+ "operator": "GT",
+ "value": tail_id,
+ } in second_drain_request["filterGroups"][0]["filters"]
+
+ def test_pathological_window_drain_paginates_within_one_anchor_and_backfills_associations(
+ self,
+ ) -> None:
+ # Regression: continuing a drain query via its `after` token must keep the same
+ # hs_object_id GT anchor (HubSpot's `after` cursor is scoped to the filters it was
+ # issued with) — only a *new* query after `after` runs out may advance the anchor.
+ # Also covers contacts, the object type that actually hit this cap, to prove
+ # association backfill still runs for records only reachable via the drain.
+ identical_cursor = 1_799_000_000_000
+ pages_in_cap = SEARCH_RESULT_CAP // SEARCH_PAGE_SIZE
+ pages = []
+ for i in range(pages_in_cap):
+ batch = [
+ _result(str(i * SEARCH_PAGE_SIZE + j), identical_cursor, cursor_prop="lastmodifieddate")
+ for j in range(SEARCH_PAGE_SIZE)
+ ]
+ is_last = i == pages_in_cap - 1
+ pages.append(_search_page(batch, after=None if is_last else f"c{i}"))
+
+ drain_id_1 = str(SEARCH_RESULT_CAP + 1)
+ drain_id_2 = str(SEARCH_RESULT_CAP + 2)
+ drain_page_1 = [_result(drain_id_1, identical_cursor, cursor_prop="lastmodifieddate")]
+ drain_page_2 = [_result(drain_id_2, identical_cursor, cursor_prop="lastmodifieddate")]
+
+ responses = (
+ [_make_response(200, p) for p in pages]
+ + [_make_response(200, _search_page(drain_page_1, after="drain-1"))] # anchor -1, page 1
+ + [_make_response(200, _search_page(drain_page_2))] # anchor -1, page 2 via `after`
+ + [_make_response(200, _search_page([]))] # fresh query, advanced anchor: exhausted
+ + [_make_response(200, _search_page([]))] # window resumes past the tied cursor
+ )
+ side_effect, captured = _setup_search_post(responses)
+ manager = _make_manager()
+ logger = MagicMock()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hubspot.make_tracked_session",
+ new=lambda *_a, **_k: type("_S", (), {"post": staticmethod(side_effect)})(),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hubspot._batch_read_associations",
+ return_value={},
+ ) as mock_batch,
+ ):
+ tables = list(
+ get_rows_via_search(
+ api_key="k",
+ refresh_token="r",
+ endpoint="contacts",
+ logger=logger,
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=str(identical_cursor - 1),
+ include_custom_props=False,
+ now_ms=identical_cursor + 1_000,
+ api_version=HUBSPOT_API_VERSION_V3,
+ )
+ )
+
+ assert sum(t.num_rows for t in tables) == SEARCH_RESULT_CAP + 2
+
+ # Second page of the first drain query: continues via `after`, anchor unchanged.
+ continued_request = captured[pages_in_cap + 1]["json"]
+ assert continued_request.get("after") == "drain-1"
+ assert {"propertyName": "hs_object_id", "operator": "GT", "value": "-1"} in (
+ continued_request["filterGroups"][0]["filters"]
+ )
+
+ # Once that query's `after` pages run out, a fresh query advances the anchor.
+ restart_request = captured[pages_in_cap + 2]["json"]
+ assert "after" not in restart_request
+ assert {"propertyName": "hs_object_id", "operator": "GT", "value": drain_id_2} in (
+ restart_request["filterGroups"][0]["filters"]
+ )
+
+ # Records only reachable via the drain still get their associations backfilled.
+ assoc_ids_seen = {i for call in mock_batch.call_args_list for i in call.kwargs["ids"]}
+ assert {drain_id_1, drain_id_2} <= assoc_ids_seen
+
+ def test_drain_tied_cursor_skips_records_with_non_numeric_id(self) -> None:
+ # Defensive: a record with a missing/non-numeric id must not crash the drain — it's
+ # still batched, just excluded from the id-anchor advance for that record.
+ identical_cursor = 1_799_000_000_000
+ pages_in_cap = SEARCH_RESULT_CAP // SEARCH_PAGE_SIZE
+ pages = []
+ for i in range(pages_in_cap):
+ batch = [_result(str(i * SEARCH_PAGE_SIZE + j), identical_cursor) for j in range(SEARCH_PAGE_SIZE)]
+ is_last = i == pages_in_cap - 1
+ pages.append(_search_page(batch, after=None if is_last else f"c{i}"))
+
+ bad_id_record = _result("not-a-number", identical_cursor)
+ good_id_record = _result(str(SEARCH_RESULT_CAP + 1), identical_cursor)
+
+ responses = (
+ [_make_response(200, p) for p in pages]
+ + [_make_response(200, _search_page([bad_id_record, good_id_record]))]
+ + [_make_response(200, _search_page([]))] # restart anchored past the good id
+ + [_make_response(200, _search_page([]))] # window resumes past the tied cursor
+ )
+ side_effect, captured = _setup_search_post(responses)
+ manager = _make_manager()
+ logger = MagicMock()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hubspot.hubspot.make_tracked_session",
+ new=lambda *_a, **_k: type("_S", (), {"post": staticmethod(side_effect)})(),
+ ):
+ tables = list(
+ get_rows_via_search(
+ api_key="k",
+ refresh_token="r",
+ endpoint="deals",
+ logger=logger,
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=str(identical_cursor - 1),
+ include_custom_props=False,
+ now_ms=identical_cursor + 1_000,
+ api_version=HUBSPOT_API_VERSION_V3,
+ )
+ )
+
+ # The bad-id record is still delivered; it just doesn't drive the anchor forward.
+ assert sum(t.num_rows for t in tables) == SEARCH_RESULT_CAP + 2
+
+ restart_request = captured[pages_in_cap + 1]["json"]
+ assert {
+ "propertyName": "hs_object_id",
+ "operator": "GT",
+ "value": str(SEARCH_RESULT_CAP + 1),
+ } in restart_request["filterGroups"][0]["filters"]
def test_saves_progress_at_window_boundaries(self) -> None:
manager = _make_manager()