: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(leadfeeder): stop syncing an account past the vendor's page depth limit (#101451)
Tom Owersfb9684b0abaf
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 a64c02a022f5..b796f6953fd5 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@@ -23,6 +23,8 @@ from datetime import UTC, date, datetime, timedeltafrom functools import partialfrom typing import Any, Optional+from requests.exceptions import HTTPError+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,@@ -243,6 +245,24 @@ def _unified_accounts_endpoint() -> Endpoint:}+def _is_offset_exceeded(error: HTTPError) -> bool:+ """True when Leadfeeder rejects a page as beyond its max explorable search window.++ The unified API's `meta.page_count` can report more pages than it will actually serve — an+ account 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.+ """+ response = error.response+ if response is None or response.status_code != 416:+ return False+ try:+ body = response.json()+ except ValueError:+ return False+ return isinstance(body, dict) and body.get("code") == "offset_exceeded"++def _unified_account_ids(client: ClientConfig, team_id: int, job_id: str) -> Iterator[str]:resource = _unified_single_resource(client,@@ -321,9 +341,16 @@ def _unified_leadfeeder_source(else:child_params["start_date"] = startchild_params["end_date"] = end- yield from _unified_single_resource(- client, endpoint, child_endpoint, team_id, job_id, partial(_flatten_item, account_id=account_id)- )+ 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# 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 64736b96e814..48696bb0b569 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@@ -8,6 +8,7 @@ from unittest import mockfrom parameterized import parameterizedfrom requests import Response+from requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (PageNumberPaginator,@@ -17,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeederLeadfeederResumeConfig,_default_start_date,_flatten_item,+ _is_offset_exceeded,_to_date_str,_unified_client_config,_unified_headers,@@ -369,6 +371,29 @@ class TestUnifiedClientConfig:assert _unified_headers("key123")["X-Api-Key"] == "key123"+def _http_error(status_code: int, body: dict[str, Any] | None) -> HTTPError:+ resp = Response()+ resp.status_code = status_code+ if body is not None:+ resp._content = json.dumps(body).encode()+ return HTTPError(response=resp)+++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(+ [+ ("different_code_on_416", 416, {"code": "unauthorized"}),+ ("offset_exceeded_code_on_other_status", 404, {"code": "offset_exceeded"}),+ ("no_body", 416, None),+ ]+ )+ def test_does_not_match(self, _name: str, status_code: int, body: dict[str, Any] | None) -> None:+ assert _is_offset_exceeded(_http_error(status_code, body)) is False++class TestUnifiedRequests:@mock.patch(CLIENT_SESSION_PATCH)def test_accounts_hits_v1_path_with_page_params(self, MockSession) -> None:@@ -441,6 +466,36 @@ class TestUnifiedRequests:assert visit_reqs[0]["json"] == {"start_date": "2024-01-01", "end_date": "2026-07-02"}assert visit_reqs[0]["params"]["account_id"] == "1"+ @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.+ session = MockSession.return_value+ offset_exceeded = Response()+ offset_exceeded.status_code = 416+ offset_exceeded._content = json.dumps({"code": "offset_exceeded"}).encode()+ _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("200", "company_location")]),+ ],+ )++ rows = _rows(+ _source("leads", _make_manager(), start_date_config="2024-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"},+ ]+@mock.patch(CLIENT_SESSION_PATCH)def test_legacy_pin_still_uses_token_api_paths(self, MockSession) -> None:# The legacy request path must be unchanged for sources still pinned to it.