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-sources): re-anchor Aircall pagination before the 10k cap (#74634)

posthog[bot]ab591b4e5278
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/aircall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/aircall.py
index 4ddaca29ca83..6bf8b2df3da2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/aircall.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/aircall.py
@@ -1,7 +1,8 @@
+import logging
import dataclasses
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode
+from urllib.parse import parse_qs, urlencode, urlsplit
from requests import Request, Response
from requests.auth import HTTPBasicAuth
@@ -20,9 +21,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+logger = logging.getLogger(__name__)
+
AIRCALL_BASE_URL = "https://api.aircall.io/v1"
# Aircall caps list pages at 50 items.
PAGE_SIZE = 50
+# Aircall refuses to serve any record past the 10,000th of a single query and answers with a
+# 400. It keeps advertising a `meta.next_page_link` across that boundary, so the link cannot be
+# followed blindly: the offset it points at has to be range-checked first.
+MAX_RECORDS_PER_QUERY = 10_000
@dataclasses.dataclass
@@ -62,6 +69,24 @@ def _build_url(path: str, params: dict[str, Any]) -> str:
return f"{AIRCALL_BASE_URL}{path}?{urlencode(clean_params)}"
+def _reaches_record_cap(url: str) -> bool:
+ """Whether `url` asks Aircall for a record at or past the 10,000th of the current query.
+
+ Aircall's own next-page links carry `page` and `per_page`, so the offset a link starts at is
+ `(page - 1) * per_page`. Requesting a link whose offset lands on or past the cap returns a
+ 400 that kills the extraction, which is why the link is range-checked instead of followed.
+ """
+ query = parse_qs(urlsplit(url).query)
+ try:
+ page = int(query["page"][0])
+ per_page = int(query.get("per_page", [str(PAGE_SIZE)])[0])
+ except (KeyError, IndexError, ValueError):
+ # A link carrying no usable page number cannot be range-checked here. The paginator's
+ # record counter is the backstop for that case.
+ return False
+ return (page - 1) * per_page >= MAX_RECORDS_PER_QUERY
+
+
def _build_params(config: AircallEndpointConfig, from_value: Optional[int]) -> dict[str, Any]:
params: dict[str, Any] = {"per_page": PAGE_SIZE}
# Ascending creation order keeps already-fetched pages stable and lets the incremental
@@ -76,10 +101,14 @@ def _build_params(config: AircallEndpointConfig, from_value: Optional[int]) -> d
class AircallPaginator(BasePaginator):
"""Follows Aircall's `meta.next_page_link` chain, re-anchoring around the 10k cap.
- When a page chain ends on a capped endpoint (calls/contacts), the paginator re-anchors
- the `from` query param to the latest value of the cursor field seen so far and starts a
- fresh chain, to fetch records beyond Aircall's hard 10k-record-per-query cap. The
- strict-advance guard prevents an infinite loop when many records share the boundary
+ On a capped endpoint (calls/contacts) the paginator re-anchors the `from` query param to the
+ latest value of the cursor field seen so far and starts a fresh chain, so records beyond
+ Aircall's hard 10k-record-per-query cap are still fetched. Reaching the cap is itself a
+ re-anchor trigger, because Aircall goes on advertising a next page past the cap and then
+ rejects that page with a 400: waiting for the page chain to end would never re-anchor the
+ tables that actually need it. The end of a page chain re-anchors too, since a chain that ends
+ at the cap boundary is indistinguishable from one that ends because the window is exhausted.
+ The strict-advance guard prevents an infinite loop when many records share the boundary
timestamp.
"""
@@ -96,6 +125,9 @@ class AircallPaginator(BasePaginator):
# Latest value of the cursor field seen across the whole run.
self._max_cursor: Optional[int] = None
self._next_url: Optional[str] = None
+ # Records consumed since the current `from` window opened. Backs up the per-link range
+ # check for a next-page link that carries no page number.
+ self._window_records = 0
def init_request(self, request: Request) -> None:
# Apply a seeded resume URL to the first request so a resumed run starts at the
@@ -106,6 +138,7 @@ class AircallPaginator(BasePaginator):
def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
items = data or []
+ self._window_records += len(items)
if self._cursor_field is not None and items:
page_max = max(
(
@@ -124,23 +157,42 @@ class AircallPaginator(BasePaginator):
body = None
next_url = ((body or {}).get("meta") or {}).get("next_page_link") if isinstance(body, dict) else None
- if next_url:
+ capped = self._config.reanchor_field is not None and (
+ self._window_records >= MAX_RECORDS_PER_QUERY or (next_url is not None and _reaches_record_cap(next_url))
+ )
+
+ if next_url and not capped:
self._next_url = next_url
self._has_next_page = True
return
- # Page chain ended. For capped endpoints, re-anchor on the latest cursor value to
- # fetch records beyond the 10k window.
+ # Either the page chain ended or the next page Aircall offered would be rejected for
+ # crossing the cap. Both call for the same move on a capped endpoint: anchor `from` on
+ # the latest cursor value seen and open a fresh window.
if (
self._config.reanchor_field is not None
and self._max_cursor is not None
and (self._from_value is None or self._max_cursor > self._from_value)
):
self._from_value = self._max_cursor
+ self._window_records = 0
self._next_url = _build_url(self._config.path, _build_params(self._config, self._from_value))
self._has_next_page = True
return
+ if capped:
+ # A window that fills the cap without its cursor advancing cannot be moved forward,
+ # because the next window would open on the same timestamp and return the same
+ # records. Stop rather than loop, and make the truncation visible in the job logs.
+ logger.warning(
+ "Aircall: %s reached the %s-record query cap without %s advancing past %s, "
+ "so the rest of this window is unreachable and the table is truncated",
+ self._config.path,
+ MAX_RECORDS_PER_QUERY,
+ self._config.reanchor_field,
+ self._from_value,
+ )
+
self._has_next_page = False
def update_request(self, request: Request) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/source.py
index 6844e3149f54..3aede7dce467 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/source.py
@@ -49,6 +49,7 @@ class AircallSource(ResumableSource[AircallSourceConfig, AircallResumeConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
+ "400 Client Error: Bad Request for url: https://api.aircall.io": "Aircall rejected the request. Contact support if this keeps happening so we can look into it.",
"401 Client Error: Unauthorized for url: https://api.aircall.io": "Aircall authentication failed. Please check your API ID and API token.",
"403 Client Error: Forbidden for url: https://api.aircall.io": "Aircall denied access. Please check that your API key has the required permissions.",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
index f7139937648f..74bd3d72e8c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aircall.ai
AircallResumeConfig,
_build_params,
_build_url,
+ _reaches_record_cap,
_to_epoch,
aircall_source,
validate_credentials,
@@ -114,6 +115,24 @@ class TestBuildUrl:
assert url == "https://api.aircall.io/v1/calls?per_page=50&order=asc"
+class TestReachesRecordCap:
+ @pytest.mark.parametrize(
+ "url, expected",
+ [
+ # Page 201 starts at record 10,000, which is the first offset Aircall rejects.
+ ("https://api.aircall.io/v1/contacts?order=asc&per_page=50&page=201", True),
+ ("https://api.aircall.io/v1/contacts?order=asc&per_page=50&page=200", False),
+ ("https://api.aircall.io/v1/contacts?per_page=100&page=101", True),
+ ("https://api.aircall.io/v1/contacts?per_page=100&page=100", False),
+ # No page number to range-check, so the record counter has to catch it instead.
+ ("https://api.aircall.io/v1/contacts?per_page=50", False),
+ ("https://api.aircall.io/v1/contacts?per_page=50&page=abc", False),
+ ],
+ )
+ def test_cap_boundary(self, url, expected):
+ assert _reaches_record_cap(url) is expected
+
+
class TestValidateCredentials:
@pytest.mark.parametrize(
"status_code, expected",
@@ -201,7 +220,7 @@ class TestPagination:
assert requests_seen[0]["params"] == {}
@mock.patch(CLIENT_SESSION_PATCH)
- def test_reanchors_from_cursor_to_page_around_cap(self, MockSession):
+ def test_reanchors_from_cursor_when_page_chain_ends(self, MockSession):
# First window ends without a next link; the latest started_at is used to issue a
# fresh `from`-anchored request, then that window ends with no new advancement.
session = MockSession.return_value
@@ -225,6 +244,69 @@ class TestPagination:
# Boundary row re-emitted; merge on primary key dedupes downstream.
assert [row["id"] for row in rows] == [1, 2, 2]
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reanchors_instead_of_following_a_next_link_past_the_cap(self, MockSession):
+ # Aircall keeps advertising a next page past its 10k-record cap and answers that page
+ # with a 400, so the link must be dropped in favor of a fresh `from`-anchored window.
+ session = MockSession.return_value
+ over_cap_link = "https://api.aircall.io/v1/contacts?order=asc&order_by=created_at&per_page=50&page=201"
+ requests_seen = _wire(
+ session,
+ [
+ _response("contacts", [{"id": 1, "created_at": 100}, {"id": 2, "created_at": 200}], over_cap_link),
+ _response("contacts", [{"id": 2, "created_at": 200}], None),
+ ],
+ )
+
+ rows = _rows(_source("contacts", _make_manager()))
+
+ assert len(requests_seen) == 2
+ assert "page=201" not in requests_seen[1]["url"]
+ assert "from=200" in requests_seen[1]["url"]
+ assert [row["id"] for row in rows] == [1, 2, 2]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reanchors_after_cap_records_when_next_link_has_no_page(self, MockSession):
+ # A next link the range check can't read (no page number) falls back to counting the
+ # records consumed since the window opened.
+ session = MockSession.return_value
+ pages = [
+ _response(
+ "contacts",
+ [{"id": page * 50 + index, "created_at": page * 50 + index} for index in range(1, 51)],
+ "https://api.aircall.io/v1/contacts?cursor=opaque",
+ )
+ for page in range(200)
+ ]
+ requests_seen = _wire(session, [*pages, _response("contacts", [{"id": 10000, "created_at": 10000}], None)])
+
+ _rows(_source("contacts", _make_manager()))
+
+ assert len(requests_seen) == 201
+ assert "from=10000" in requests_seen[200]["url"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_when_a_capped_window_cursor_cannot_advance(self, MockSession):
+ # Every record in the capped window shares the boundary timestamp, so a re-anchored
+ # window would repeat the same query forever. Truncate instead of looping.
+ session = MockSession.return_value
+ over_cap_link = "https://api.aircall.io/v1/contacts?order=asc&per_page=50&page=201"
+ requests_seen = _wire(session, [_response("contacts", [{"id": 1, "created_at": 200}], over_cap_link)])
+
+ manager = _make_manager()
+ _rows(
+ _source(
+ "contacts",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=200,
+ incremental_field="created_at",
+ )
+ )
+
+ assert len(requests_seen) == 1
+ manager.save_state.assert_not_called()
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_no_reanchor_for_full_refresh_endpoint(self, MockSession):
session = MockSession.return_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall_source.py
index 1bf13a19e107..a590736e70b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall_source.py
@@ -49,9 +49,10 @@ class TestAircallSource:
[
"401 Client Error: Unauthorized for url: https://api.aircall.io/v1/calls?per_page=50",
"403 Client Error: Forbidden for url: https://api.aircall.io/v1/contacts",
+ "400 Client Error: Bad Request for url: https://api.aircall.io/v1/contacts?per_page=50&page=201",
],
)
- def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ def test_non_retryable_errors_match_aircall_client_errors(self, observed_error):
non_retryable_errors = self.source.get_non_retryable_errors()
assert any(key in observed_error for key in non_retryable_errors)