: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(warehouse-sources): bound the Decagon page walk by the server total (#101793)
jake sciotto7b62af04be6d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.pyindex 86fb955b4a37..48e06b0e5000 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/decagon.py@@ -1,3 +1,4 @@+import mathimport timeimport dataclassesfrom collections.abc import Iterator@@ -28,6 +29,11 @@ DECAGON_PAGE_SIZE = 100# than relying on 429 backoff alone.MIN_SECONDS_BETWEEN_REQUESTS = 1.0+# Hard bound on the pages a "page" walk requests when the response gives no total to+# derive one from. It stops a server that ignores the page param and returns a full page+# on every request; a real export of this size would still end on its short last page.+MAX_PAGES_WITHOUT_TOTAL = 10_000+# Maps a conversation row column to the `timestamp_filter` enum value that makes the# export's min_timestamp/max_timestamp params bound that column. The filter for the# `last_message_at` column is named `last_message_time`; both spellings are the@@ -356,6 +362,13 @@ class _RowDeduplicator:return fresh+def _usable_total(reported: Any) -> Optional[int | float]:+ """The reported total when it can bound a walk: a finite, non-negative number."""+ if isinstance(reported, bool) or not isinstance(reported, int | float) or not math.isfinite(reported):+ return None+ return reported if reported >= 0 else None++class _RowWalk:"""Walks one endpoint's pages, one method per pagination mode.@@ -491,6 +504,9 @@ class _RowWalk:# reach the total a page early and drop the final page. This also stays exact if the# server caps the requested page size.rows_walked = self._resume.rows_walked or 0+ # The largest raw page the server returned: its effective page size, which can be+ # smaller than the one requested.+ page_rows = 0while True:params = {"page": str(page)}@@ -500,15 +516,8 @@ class _RowWalk:batch = self._read(params)total = self._record_total(batch)rows_walked += len(batch.fresh)-- # A page that contributes nothing new cannot make progress against the total, so- # it ends the walk rather than spinning on a server that ignores the page param.- # A missing or malformed total falls back to short-page termination, the only end- # signal left besides an empty page.- if isinstance(total, int | float):- exhausted = not batch.fresh or rows_walked >= total- else:- exhausted = self._short_page(batch)+ page_rows = max(page_rows, len(batch.items))+ exhausted = self._page_walk_exhausted(page, rows_walked, page_rows, total, batch)if batch.fresh:yield batch.fresh@@ -519,6 +528,46 @@ class _RowWalk:page += 1+ def _page_walk_exhausted(self, page: int, rows_walked: int, page_rows: int, reported: Any, batch: _Batch) -> bool:+ # A page of only already-seen rows does not end the walk: the catalog can shift rows+ # between pages mid-walk, so a later page can still hold rows this walk has not kept.+ # The page bound is what stops a server that ignores the page param instead.+ if not batch.items:+ return True+ total = _usable_total(reported)+ if total is not None and rows_walked >= total:+ return True++ if total is None:+ # A missing or malformed total falls back to short-page termination and a+ # constant cap. With nothing to check the kept rows against, the cap can only+ # warn.+ if self._short_page(batch):+ return True+ if page < MAX_PAGES_WITHOUT_TOTAL:+ return False+ self._logger.warning(+ f"Decagon: {self._endpoint} walk stopped at the page cap of {MAX_PAGES_WITHOUT_TOTAL} with no "+ f"usable total (got {reported!r}). If the synced row count looks truncated, check that the "+ f"endpoint honors the page param."+ )+ return True++ # One page more than the total needs at the server's page size, so rows that shift+ # pages mid-walk (arriving twice, kept once) do not push the last unique rows past+ # the bound. Sized from the pages received, not the size requested, because the+ # server can cap the requested size and a bound from the larger size would truncate.+ max_pages = math.ceil(total / page_rows) + 1+ if page < max_pages:+ return False+ # Every page the total allows for is walked and rows are still missing: the server+ # ignores the page param or the total does not describe the export. Completing here+ # would report success on a partial table.+ raise DecagonContractError(+ f"Decagon: {self._endpoint} walked {max_pages} pages and kept {rows_walked} rows against a "+ f"reported total of {total}. Check that the endpoint honors the page param."+ )+def _walk_offset(self) -> Iterator[list[dict[str, Any]]]:config = self._configoffset = self._resume.offset or 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.pyindex e06b7467b5e6..2a1284c2ba27 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/settings.py@@ -43,7 +43,8 @@ class DecagonEndpointConfig:# ends the walk.has_more_key: Optional[str] = None# "page"/"offset" modes: rows requested per page. None sends no size param and leaves- # the server default, in which case only an empty page ends the walk.+ # the server default, in which case only an empty page or the reported total ends the+ # walk ("page" mode also stops at a constant page cap).page_size: Optional[int] = None# "page"/"offset" modes: response field carrying the total row count.total_key: Optional[str] = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.pyindex 8c7264e4fdc6..350c04447691 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/decagon/tests/test_decagon.py@@ -1,4 +1,7 @@import json+import math+import dataclasses+from collections.abc import Callablefrom datetime import UTC, date, datetimefrom typing import Any, Optional@@ -49,12 +52,27 @@ def _drive_rows(logger: Optional[MagicMock] = None,**incremental_kwargs: Any,) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:- sent_params: list[dict[str, Any]] = []response_iter = iter(responses)+ return _drive_server(+ manager, lambda _params: next(response_iter), len(responses), endpoint, logger, **incremental_kwargs+ )+++def _drive_server(+ manager: MagicMock,+ respond: Callable[[dict[str, Any]], Response],+ max_requests: int,+ endpoint: str = "conversations",+ logger: Optional[MagicMock] = None,+ **incremental_kwargs: Any,+) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:+ sent_params: list[dict[str, Any]] = []def fake_get(_url: str, *, params: dict[str, Any], **_kwargs: Any) -> Response:sent_params.append(dict(params or {}))- return next(response_iter)+ if len(sent_params) > max_requests:+ raise AssertionError(f"walk did not stop within {max_requests} requests")+ return respond(sent_params[-1])with (patch(f"{DECAGON_MODULE}.make_tracked_session") as mock_session,@@ -590,18 +608,82 @@ class TestArticleTables:assert len(sent_params) == 3assert [[r["id"] for r in b] for b in batches] == [[1, 2], [3], [4]]- def test_page_contributing_nothing_new_ends_the_walk(self) -> None:- # A server that ignores the page param would otherwise repeat the same page- # forever without the kept-row count ever reaching the total.- manager = _fresh_manager()- responses = [- _make_response({"articles": [{"id": 1}, {"id": 2}], "total": 10}),- _make_response({"articles": [{"id": 1}, {"id": 2}], "total": 10}),- ]- sent_params, batches = _drive_rows(manager, responses, endpoint="articles")+ def test_duplicate_only_page_does_not_end_the_walk_before_the_total(self) -> None:+ # A page of only already-seen rows used to end the walk, which silently dropped+ # every later page. The page bound derived from the total ends the walk instead.+ cfg = dataclasses.replace(DECAGON_ENDPOINTS["articles"], page_size=2)+ with patch.dict(DECAGON_ENDPOINTS, {"articles": cfg}):+ manager = _fresh_manager()+ responses = [+ _make_response({"articles": [{"id": 1}, {"id": 2}], "total": 4}),+ _make_response({"articles": [{"id": 1}, {"id": 2}], "total": 4}),+ _make_response({"articles": [{"id": 3}, {"id": 4}], "total": 4}),+ ]+ sent_params, batches = _drive_rows(manager, responses, endpoint="articles")++ assert [p["page"] for p in sent_params] == ["1", "2", "3"]+ assert [[r["id"] for r in b] for b in batches] == [[1, 2], [3, 4]]+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [DecagonResumeConfig(page=2, rows_walked=2)]++ def test_server_that_ignores_the_page_param_fails_at_the_page_bound(self) -> None:+ # The same two rows come back on every request in a flipping order, so neither an+ # empty page nor the total nor a "same page as before" check would end the walk.+ # Completing at the bound would report success on a partial table, so the walk fails.+ cfg = dataclasses.replace(DECAGON_ENDPOINTS["articles"], page_size=2)+ rows = [{"id": 1}, {"id": 2}]+ max_pages = math.ceil(10 / 2) + 1+ sent_params: list[dict[str, Any]] = []++ def respond(params: dict[str, Any]) -> Response:+ sent_params.append(params)+ rows.reverse()+ return _make_response({"articles": list(rows), "total": 10})++ with patch.dict(DECAGON_ENDPOINTS, {"articles": cfg}):+ manager = _fresh_manager()+ with pytest.raises(DecagonContractError, match="honors the page param"):+ _drive_server(manager, respond, max_pages, endpoint="articles")++ assert [p["page"] for p in sent_params] == [str(n) for n in range(1, max_pages + 1)]++ @parameterized.expand([("negative", -1), ("boolean", True), ("string", "3"), ("null", None)])+ def test_malformed_total_falls_back_to_short_page_termination(self, _name: str, total: Any) -> None:+ # A total that cannot bound the walk must not end it early: a negative or boolean+ # total is below the kept-row count at once. (NaN and Infinity never arrive here;+ # the JSON parser rejects them.)+ cfg = dataclasses.replace(DECAGON_ENDPOINTS["articles"], page_size=2)+ with patch.dict(DECAGON_ENDPOINTS, {"articles": cfg}):+ manager = _fresh_manager()+ responses = [+ _make_response({"articles": [{"id": 1}, {"id": 2}], "total": total}),+ _make_response({"articles": [{"id": 3}], "total": total}),+ ]+ sent_params, batches = _drive_rows(manager, responses, endpoint="articles")assert len(sent_params) == 2+ assert [[r["id"] for r in b] for b in batches] == [[1, 2], [3]]++ def test_page_walk_without_a_total_stops_at_the_constant_page_cap(self) -> None:+ # With no total there is no bound to derive, so a server that repeats a full page+ # forever is stopped by the constant cap instead.+ cfg = dataclasses.replace(DECAGON_ENDPOINTS["articles"], page_size=2)+ cap = 7++ def respond(_params: dict[str, Any]) -> Response:+ return _make_response({"articles": [{"id": 1}, {"id": 2}]})++ logger = MagicMock()+ with (+ patch.dict(DECAGON_ENDPOINTS, {"articles": cfg}),+ patch(f"{DECAGON_MODULE}.MAX_PAGES_WITHOUT_TOTAL", cap),+ ):+ manager = _fresh_manager()+ sent_params, batches = _drive_server(manager, respond, cap, endpoint="articles", logger=logger)++ assert len(sent_params) == capassert [[r["id"] for r in b] for b in batches] == [[1, 2]]+ logger.warning.assert_called_once()def test_rows_are_read_from_the_response_only_list_when_the_configured_key_is_absent(self) -> None:# A renamed envelope key otherwise reads as an empty page: the walk ends on the