:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): keep leadfeeder windows under the vendor row cap (#103668)
Tom Owersf6dbf0dad316
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.pyindex b796f6953fd5..1330d34eddf9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py@@ -17,14 +17,18 @@ dispatches between them on the resolved API-version pin:"work in progress") and warrant live verification before the source leaves alpha."""+import loggingimport dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetime, timedeltafrom functools import partial+from math import ceilfrom typing import Any, Optionalfrom requests.exceptions import HTTPError+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -52,9 +56,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeederLeadfeederEndpointConfig,)+logger = logging.getLogger(__name__)+LEADFEEDER_BASE_URL = "https://api.leadfeeder.com"PAGE_SIZE = 100 # JSON:API page[size] max is 100 (default 10)DEFAULT_LOOKBACK_DAYS = 365 # First-sync window when the user leaves start_date blank+# One search reads at most the first 10,000 results, whichever generation serves it: the legacy API+# documents "the total number of results is limited to the first 10000 leads", and the unified API+# refuses the page past that offset with a 416 `offset_exceeded` instead of an empty page. At+# PAGE_SIZE rows a page that is 100 pages, so a window holding more rows than this can only be read+# in full by asking for narrower date ranges.+MAX_PAGES_PER_WINDOW = 10_000 // PAGE_SIZE+++@frozen+class _DateWindow:+ start: str+ end: str+# Name the accounts fan-out parent uses; the framework injects the parent id into child rows under# `_accounts_id` (see make_parent_key_name), which the child data_map renames to `account_id`.@@ -250,17 +269,83 @@ def _is_offset_exceeded(error: HTTPError) -> bool:The unified API's `meta.page_count` can report more pages than it will actually serve — anaccount with enough web-visits/leads in the sync window pages past a fixed vendor-side depth- limit and gets a 416 `offset_exceeded` instead of an empty page. No page size or start_date- tweak avoids this for a busy account, so it isn't a transient failure to retry either.+ limit and gets a 416 `offset_exceeded` instead of an empty page. Retrying the same page can+ never turn it into data, so it isn't a transient failure either.++ The vendor names the condition in the error body; match it wherever the body carries it rather+ than assuming one error envelope, since a JSON:API error is as likely to arrive wrapped in+ `errors` as at the top level."""response = error.responseif response is None or response.status_code != 416:return False+ return "offset_exceeded" in response.text+++def _unified_child_endpoint(config: LeadfeederEndpointConfig, account_id: str, start: str, end: str) -> Endpoint:+ """One account's slice of a fan-out endpoint, bounded to the `start`..`end` date window."""+ params: dict[str, Any] = {**_unified_base_params(), "account_id": account_id}+ child_endpoint: Endpoint = {"path": config.unified_path, "params": params, "data_selector": "data"}+ if config.unified_method == "POST":+ # Web visits are a POST search whose date window lives in the body, not the query string.+ child_endpoint["method"] = "POST"+ child_endpoint["json"] = {"start_date": start, "end_date": end}+ else:+ params["start_date"] = start+ params["end_date"] = end+ return child_endpoint+++def _split_window(start: str, end: str, parts: int) -> list[_DateWindow]:+ """Cut a date window into at most `parts` day-aligned sub-windows, oldest first.++ Returns an empty list when there is nothing narrower left to ask the vendor for: a single-day+ window, or a bound that is not a plain yyyy-mm-dd date (a hand-typed start date, which the+ vendor rejects on its own terms).+ """try:- body = response.json()+ first = date.fromisoformat(start)+ last = date.fromisoformat(end)except ValueError:- return False- return isinstance(body, dict) and body.get("code") == "offset_exceeded"+ return []+ days = (last - first).days + 1+ if days < 2:+ return []+ window_days = ceil(days / max(2, min(parts, days)))+ windows: list[_DateWindow] = []+ cursor = first+ while cursor <= last:+ window_end = min(cursor + timedelta(days=window_days - 1), last)+ windows.append(_DateWindow(start=cursor.isoformat(), end=window_end.isoformat()))+ cursor = window_end + timedelta(days=1)+ return windows+++def _unified_window_page_count(+ client: ClientConfig,+ name: str,+ config: LeadfeederEndpointConfig,+ account_id: str,+ team_id: int,+ job_id: str,+ start: str,+ end: str,+) -> Optional[int]:+ """How many pages the vendor reports for one account's window, read from `meta` before syncing it.++ Asking first is what keeps a window the vendor cannot page through from being half read and then+ read again: the rows are only fetched once the window is known to fit under the offset ceiling.+ Returns None when the response carries no page count, which leaves the 416 handling as the only+ signal that a window is too deep.+ """+ probe = _unified_child_endpoint(config, account_id, start, end)+ probe["data_selector"] = "meta"+ probe["paginator"] = PageNumberPaginator(base_page=1, page_param="page[num]", maximum_page=1)+ for page in _unified_single_resource(client, name, probe, team_id, job_id, None):+ for meta in page:+ if isinstance(meta, dict) and isinstance(meta.get("page_count"), int):+ return meta["page_count"]+ return Nonedef _unified_account_ids(client: ClientConfig, team_id: int, job_id: str) -> Iterator[str]:@@ -326,31 +411,51 @@ def _unified_leadfeeder_source()end = datetime.now(UTC).date().isoformat()+ def _iter_account_window(account_id: str, window_start: str, window_end: str) -> Iterator[list[dict[str, Any]]]:+ """Yield one account's rows for a date window, narrowing the window until the vendor serves it.++ A window holding more rows than one search can read is split into shorter ones, each read in+ full, so a busy account keeps every row instead of losing whatever sits past the ceiling.+ """+ page_count = _unified_window_page_count(+ client, endpoint, config, account_id, team_id, job_id, window_start, window_end+ )+ if page_count is not None and page_count > MAX_PAGES_PER_WINDOW:+ narrower = _split_window(window_start, window_end, ceil(page_count / MAX_PAGES_PER_WINDOW))+ if narrower:+ for window in narrower:+ yield from _iter_account_window(account_id, window.start, window.end)+ return++ try:+ yield from _unified_single_resource(+ client,+ endpoint,+ _unified_child_endpoint(config, account_id, window_start, window_end),+ team_id,+ job_id,+ partial(_flatten_item, account_id=account_id),+ )+ except HTTPError as e:+ if not _is_offset_exceeded(e):+ raise+ # The window reported fewer pages than it holds, so the vendor refused one mid-sync.+ # Read it as halves rather than dropping the rest of it; the pages already yielded are+ # fetched again, which merge dedupes on the primary key.+ narrower = _split_window(window_start, window_end, 2)+ if not narrower:+ logger.warning(+ "leadfeeder: a single day holds more rows than the vendor will page through, "+ "so the rows past its limit are not synced",+ extra={"endpoint": endpoint, "day": window_start, "team_id": team_id},+ )+ return+ for window in narrower:+ yield from _iter_account_window(account_id, window.start, window.end)+def _fanned() -> Iterator[list[dict[str, Any]]]:for account_id in _unified_account_ids(client, team_id, job_id):- child_params: dict[str, Any] = {**_unified_base_params(), "account_id": account_id}- child_endpoint: Endpoint = {- "path": config.unified_path,- "params": child_params,- "data_selector": "data",- }- if config.unified_method == "POST":- # Web visits are a POST search whose date window lives in the body, not the query string.- child_endpoint["method"] = "POST"- child_endpoint["json"] = {"start_date": start, "end_date": end}- else:- child_params["start_date"] = start- child_params["end_date"] = end- try:- yield from _unified_single_resource(- client, endpoint, child_endpoint, team_id, job_id, partial(_flatten_item, account_id=account_id)- )- except HTTPError as e:- # The account has more rows in this window than the vendor's search depth allows- # to page through. Stop this account here rather than failing the whole sync — the- # rest of the accounts, and the rows already fetched, still land.- if not _is_offset_exceeded(e):- raise+ yield from _iter_account_window(account_id, start, end)# Partition only on a field confirmed present in the unified schema (visits' `started_at`). The# visitor-companies rows carry no confirmed top-level date, so leads sync unpartitioned here.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.pyindex 48696bb0b569..85840832484c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder_default_start_date,_flatten_item,_is_offset_exceeded,+ _split_window,_to_date_str,_unified_client_config,_unified_headers,@@ -371,6 +372,13 @@ class TestUnifiedClientConfig:assert _unified_headers("key123")["X-Api-Key"] == "key123"+def _offset_exceeded_response(body: dict[str, Any]) -> Response:+ resp = Response()+ resp.status_code = 416+ resp._content = json.dumps(body).encode()+ return resp++def _http_error(status_code: int, body: dict[str, Any] | None) -> HTTPError:resp = Response()resp.status_code = status_code@@ -380,8 +388,15 @@ def _http_error(status_code: int, body: dict[str, Any] | None) -> HTTPError:class TestIsOffsetExceeded:- def test_matches_416_with_offset_exceeded_code(self) -> None:- assert _is_offset_exceeded(_http_error(416, {"code": "offset_exceeded"})) is True+ @parameterized.expand(+ [+ ("top_level_code", {"code": "offset_exceeded"}),+ # A JSON:API error body wraps the code in an `errors` list.+ ("wrapped_in_errors", {"errors": [{"code": "offset_exceeded", "title": "Offset exceeded"}]}),+ ]+ )+ def test_matches_416_naming_the_code(self, _name: str, body: dict[str, Any]) -> None:+ assert _is_offset_exceeded(_http_error(416, body)) is True@parameterized.expand([@@ -394,6 +409,51 @@ class TestIsOffsetExceeded:assert _is_offset_exceeded(_http_error(status_code, body)) is False+class TestSplitWindow:+ @parameterized.expand(+ [+ (+ "two_days_in_halves",+ "2026-07-01",+ "2026-07-02",+ 2,+ [("2026-07-01", "2026-07-01"), ("2026-07-02", "2026-07-02")],+ ),+ (+ "five_days_in_three",+ "2026-07-01",+ "2026-07-05",+ 3,+ [("2026-07-01", "2026-07-02"), ("2026-07-03", "2026-07-04"), ("2026-07-05", "2026-07-05")],+ ),+ # Fewer than two parts would leave the window unchanged and recurse forever.+ (+ "one_part_still_splits",+ "2026-07-01",+ "2026-07-04",+ 1,+ [("2026-07-01", "2026-07-02"), ("2026-07-03", "2026-07-04")],+ ),+ ]+ )+ def test_covers_the_window_without_gaps(+ self, _name: str, start: str, end: str, parts: int, expected: list[tuple[str, str]]+ ) -> None:+ assert [(window.start, window.end) for window in _split_window(start, end, parts)] == expected++ @parameterized.expand(+ [+ ("single_day", "2026-07-02", "2026-07-02", 4),+ ("end_before_start", "2026-07-02", "2026-07-01", 4),+ ("unparseable_bound", "01/07/2026", "2026-07-02", 4),+ ]+ )+ def test_returns_nothing_when_there_is_no_narrower_window(+ self, _name: str, start: str, end: str, parts: int+ ) -> None:+ assert _split_window(start, end, parts) == []++class TestUnifiedRequests:@mock.patch(CLIENT_SESSION_PATCH)def test_accounts_hits_v1_path_with_page_params(self, MockSession) -> None:@@ -434,7 +494,9 @@ class TestUnifiedRequests:session,[_unified_response([_item("1", "account"), _item("2", "account")]),+ _unified_response([], page_count=1),_unified_response([_item("100", "company_location")]),+ _unified_response([], page_count=1),_unified_response([_item("200", "company_location")]),],)@@ -454,6 +516,7 @@ class TestUnifiedRequests:session,[_unified_response([_item("1", "account")]),+ _unified_response([], page_count=1),_unified_response([_item("100", "web_visit", started_at="2026-06-01T10:00:00Z")]),],)@@ -468,33 +531,98 @@ class TestUnifiedRequests:@mock.patch(CLIENT_SESSION_PATCH)@time_machine.travel("2026-07-02", tick=False)- def test_leads_fan_out_skips_account_past_offset_exceeded(self, MockSession) -> None:- # A busy account can have more rows in the sync window than the vendor's search depth- # limit allows paging through; the vendor 416s with `offset_exceeded` on the page past that- # limit instead of returning an empty page. That must end the account's pagination, not the- # whole sync — the next account's rows still need to land.+ def test_window_reporting_more_pages_than_the_vendor_serves_is_split(self, MockSession) -> None:+ # A busy account can hold more rows in the sync window than the vendor will page through:+ # past 100 pages of 100 it answers 416 `offset_exceeded` instead of the next page. The rows+ # past that point are only reachable through a narrower date window, so a window reporting+ # more pages than that must be split before any of it is read.session = MockSession.return_value- offset_exceeded = Response()- offset_exceeded.status_code = 416- offset_exceeded._content = json.dumps({"code": "offset_exceeded"}).encode()- _wire_full(+ requests = _wire_full(session,[- _unified_response([_item("1", "account"), _item("2", "account")]),- _unified_response([_item("100", "company_location")], page_count=2),- offset_exceeded,+ _unified_response([_item("1", "account")]),+ _unified_response([], page_count=200),+ _unified_response([], page_count=1),+ _unified_response([_item("100", "company_location")]),+ _unified_response([], page_count=1),_unified_response([_item("200", "company_location")]),],)rows = _rows(- _source("leads", _make_manager(), start_date_config="2024-01-01", api_version=LEADFEEDER_API_2026_08_07)+ _source("leads", _make_manager(), start_date_config="2026-01-01", api_version=LEADFEEDER_API_2026_08_07))assert rows == [{"id": "100", "type": "company_location", "account_id": "1"},- {"id": "200", "type": "company_location", "account_id": "2"},+ {"id": "200", "type": "company_location", "account_id": "1"},+ ]+ windows = [+ (r["params"]["start_date"], r["params"]["end_date"])+ for r in requests+ if "/v1/web-visits/companies" in r["url"]]+ # The whole window is covered by halves, each read end to end, with no gap or overlap.+ assert windows[0] == ("2026-01-01", "2026-07-02")+ assert set(windows[1:]) == {("2026-01-01", "2026-04-02"), ("2026-04-03", "2026-07-02")}++ @mock.patch(CLIENT_SESSION_PATCH)+ @time_machine.travel("2026-07-02", tick=False)+ def test_offset_exceeded_mid_window_re_reads_the_window_narrower(self, MockSession) -> None:+ # The page count the vendor reports can understate what it will serve, so a window can still+ # run into the 416 half way through. The rest of that window must be re-read as narrower+ # windows; stopping there would silently drop every row past the limit.+ session = MockSession.return_value+ requests = _wire_full(+ session,+ [+ _unified_response([_item("1", "account")]),+ _unified_response([], page_count=1),+ _unified_response([_item("100", "company_location")], page_count=2),+ _offset_exceeded_response({"code": "offset_exceeded"}),+ _unified_response([], page_count=1),+ _unified_response([_item("200", "company_location")]),+ _unified_response([], page_count=1),+ _unified_response([_item("300", "company_location")]),+ ],+ )++ rows = _rows(+ _source("leads", _make_manager(), start_date_config="2026-07-01", api_version=LEADFEEDER_API_2026_08_07)+ )++ assert [row["id"] for row in rows] == ["100", "200", "300"]+ windows = {+ (r["params"]["start_date"], r["params"]["end_date"])+ for r in requests+ if "/v1/web-visits/companies" in r["url"]+ }+ assert ("2026-07-01", "2026-07-01") in windows+ assert ("2026-07-02", "2026-07-02") in windows++ @mock.patch(CLIENT_SESSION_PATCH)+ @time_machine.travel("2026-07-02", tick=False)+ def test_single_day_over_the_limit_keeps_the_rows_it_can_read(self, MockSession) -> None:+ # A single day can hold more rows than the vendor will page through, and there is no+ # narrower window to ask for. Keep the rows that were read and finish the table instead of+ # splitting forever or failing the sync.+ session = MockSession.return_value+ requests = _wire_full(+ session,+ [+ _unified_response([_item("1", "account")]),+ _unified_response([], page_count=150),+ _unified_response([_item("100", "company_location")], page_count=150),+ _offset_exceeded_response({"code": "offset_exceeded"}),+ ],+ )++ rows = _rows(+ _source("leads", _make_manager(), start_date_config="2026-07-02", api_version=LEADFEEDER_API_2026_08_07)+ )++ assert rows == [{"id": "100", "type": "company_location", "account_id": "1"}]+ assert len(requests) == 4@mock.patch(CLIENT_SESSION_PATCH)def test_legacy_pin_still_uses_token_api_paths(self, MockSession) -> None: