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.

chore(warehouse-sources): split decagon get_rows into walk helpers (#100573)

posthog[bot]4065fa07577a
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.py
index e82100b39a83..86fb955b4a37 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
@@ -79,6 +79,35 @@ class DecagonResumeConfig:
timestamp_filter: Optional[str] = None
[email protected](frozen=True)
+class _IncrementalWindow:
+ """The server-side bound a walk sends on every request."""
+
+ value: Optional[int | str] = None
+ timestamp_filter: Optional[str] = None
+ # True when a real watermark bounds the request, rather than the fallback bound an
+ # endpoint with a mandatory filter needs. A windowed walk can legitimately keep no
+ # rows, so the contract guard at the end of the walk must not fire for it.
+ from_watermark: bool = False
+
+ def request_params(self, config: DecagonEndpointConfig) -> dict[str, str]:
+ if self.value is None or not config.incremental_param:
+ return {}
+ params = {config.incremental_param: str(self.value)}
+ if self.timestamp_filter and config.timestamp_filter_param:
+ params[config.timestamp_filter_param] = self.timestamp_filter
+ return params
+
+
[email protected](frozen=True)
+class _Batch:
+ """One page of a walk: the response envelope, the rows it carried, and the rows to emit."""
+
+ data: dict[str, Any]
+ items: list[Any]
+ fresh: list[dict[str, Any]]
+
+
class RequestThrottle:
"""Spaces consecutive requests at least `min_interval` seconds apart."""
@@ -176,40 +205,23 @@ def validate_credentials(api_key: str) -> bool:
return False
-def get_rows(
- api_key: str,
- endpoint: str,
+def _resolve_window(
+ config: DecagonEndpointConfig,
+ resume_config: Optional[DecagonResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str],
logger: FilteringBoundLogger,
- resumable_source_manager: ResumableSourceManager[DecagonResumeConfig],
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Optional[Any] = None,
- incremental_field: Optional[str] = None,
-) -> Iterator[list[dict[str, Any]]]:
- config = DECAGON_ENDPOINTS[endpoint]
- headers = _get_headers(api_key)
- url = f"{DECAGON_BASE_URL}{config.path}"
- session = make_tracked_session(redact_values=(api_key,))
- throttle = RequestThrottle()
-
- resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
-
- cursor: Optional[str] = None
- page = 1
- offset = 0
- rows_walked = 0
- window_value: Optional[int | str] = None
+) -> _IncrementalWindow:
+ """Decide the server-side bound the walk sends on every request."""
+ value: Optional[int | str] = None
timestamp_filter: Optional[str] = None
if resume_config:
- cursor = resume_config.cursor
- page = resume_config.page if resume_config.page is not None else 1
- offset = resume_config.offset if resume_config.offset is not None else 0
- rows_walked = resume_config.rows_walked if resume_config.rows_walked is not None else 0
# Resume the walk exactly where it stopped: same window, same position. See the
# DecagonResumeConfig field comments for why the window is not recomputed here.
- window_value = resume_config.min_timestamp
+ value = resume_config.min_timestamp
timestamp_filter = resume_config.timestamp_filter
- logger.debug(f"Decagon: resuming {endpoint} from saved state")
elif (
should_use_incremental_field
and db_incremental_field_last_value is not None
@@ -219,7 +231,7 @@ def get_rows(
if config.timestamp_filter_param:
filter_name = TIMESTAMP_FILTER_BY_FIELD.get(incremental_field)
if filter_name:
- window_value = _incremental_window_value(config, db_incremental_field_last_value)
+ value = _incremental_window_value(config, db_incremental_field_last_value)
timestamp_filter = filter_name
else:
logger.warning(
@@ -227,26 +239,43 @@ def get_rows(
f"filter; walking the full export instead"
)
else:
- window_value = _incremental_window_value(config, db_incremental_field_last_value)
- if config.primary_keys is None and isinstance(window_value, int):
+ value = _incremental_window_value(config, db_incremental_field_last_value)
+ if config.primary_keys is None and isinstance(value, int):
# Keyless streams append without a merge to dedupe re-fetched rows, so an
# inclusive bound would re-import the watermark second on every sync and
# inflate counts indefinitely. Advance past it instead: an event landing in
# that same second after the walk read it is the rarer failure, and a full
# refresh trues the table up.
- window_value += 1
+ value += 1
- # True when a real watermark bounds the request. A windowed walk can legitimately keep no
- # rows, so the contract guard at the end of the walk must not fire for it. Read before the
- # mandatory-bound fallback below, because an epoch bound includes every row: a walk under it
- # that keeps nothing carries the same mismatch signal as a walk with no bound at all.
- windowed_by_watermark = window_value is not None
+ # Read before the mandatory-bound fallback below, because an epoch bound includes every
+ # row: a walk under it that keeps nothing carries the same mismatch signal as a walk
+ # with no bound at all.
+ from_watermark = value is not None
- if window_value is None and config.incremental_param and config.incremental_param_required:
+ if value is None and config.incremental_param and config.incremental_param_required:
# No prior state and no watermark left the window unset, but this endpoint 400s
# on a request that omits the bound entirely. The epoch keeps a full walk honest
# (every row is included) while still satisfying the requirement.
- window_value = _incremental_window_value(config, _EPOCH)
+ value = _incremental_window_value(config, _EPOCH)
+
+ return _IncrementalWindow(value=value, timestamp_filter=timestamp_filter, from_watermark=from_watermark)
+
+
+class _PageFetcher:
+ """Reads one page: spaces requests, retries transient failures, and drops add-on params."""
+
+ def __init__(
+ self, api_key: str, config: DecagonEndpointConfig, endpoint: str, logger: FilteringBoundLogger
+ ) -> None:
+ self._session = make_tracked_session(redact_values=(api_key,))
+ self._url = f"{DECAGON_BASE_URL}{config.path}"
+ self._headers = _get_headers(api_key)
+ self._config = config
+ self._endpoint = endpoint
+ self._logger = logger
+ self._throttle = RequestThrottle()
+ self._optional_params_dropped = not config.optional_params
@retry(
retry=retry_if_exception_type((DecagonRetryableError, requests.ReadTimeout, requests.ConnectionError)),
@@ -255,191 +284,303 @@ def get_rows(
wait=wait_exponential_jitter(initial=2, max=60),
reraise=True,
)
- def fetch_page(params: dict[str, str]) -> dict[str, Any]:
- throttle.wait()
- response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+ def _request(self, params: dict[str, str]) -> dict[str, Any]:
+ self._throttle.wait()
+ response = self._session.get(self._url, params=params, headers=self._headers, timeout=REQUEST_TIMEOUT_SECONDS)
if response.status_code == 429 or response.status_code >= 500:
- raise DecagonRetryableError(f"Decagon API error (retryable): status={response.status_code}, url={url}")
+ raise DecagonRetryableError(
+ f"Decagon API error (retryable): status={response.status_code}, url={self._url}"
+ )
if not response.ok:
- logger.error(f"Decagon API error: status={response.status_code}, body={response.text}, url={url}")
+ self._logger.error(
+ f"Decagon API error: status={response.status_code}, body={response.text}, url={self._url}"
+ )
response.raise_for_status()
return response.json()
- # Decagon refuses the whole request when an optional add-on param names an entitlement
- # the team does not hold, so a table whose base response would sync fine never loads.
- # Drop the add-on params and retry; a 403 about the endpoint itself fails again and
- # still surfaces. The drop persists for the rest of the walk so each page costs one
- # request, which matters against the 1 rps limit.
- optional_params_dropped = not config.optional_params
-
- def fetch_page_with_optional(params: dict[str, str]) -> dict[str, Any]:
- nonlocal optional_params_dropped
- if not optional_params_dropped:
+ def fetch(self, params: dict[str, str]) -> dict[str, Any]:
+ # Decagon refuses the whole request when an optional add-on param names an entitlement
+ # the team does not hold, so a table whose base response would sync fine never loads.
+ # Drop the add-on params and retry; a 403 about the endpoint itself fails again and
+ # still surfaces. The drop persists for the rest of the walk so each page costs one
+ # request, which matters against the 1 rps limit.
+ if not self._optional_params_dropped:
try:
- return fetch_page({**params, **config.optional_params})
+ return self._request({**params, **self._config.optional_params})
except requests.HTTPError as err:
if err.response is None or err.response.status_code != 403:
raise
- optional_params_dropped = True
- logger.warning(
- f"Decagon: {endpoint} refused {sorted(config.optional_params)}; retrying without the add-on params"
+ self._optional_params_dropped = True
+ self._logger.warning(
+ f"Decagon: {self._endpoint} refused {sorted(self._config.optional_params)}; "
+ f"retrying without the add-on params"
)
- return fetch_page(params)
-
- def save_position(**position: Any) -> None:
- # Persisted only after a yield, so a crash re-yields the last batch rather than
- # skipping it (the duplicate rows a resumed re-yield can produce are bounded to
- # one page, and are cleaned up by the next full refresh or merged away on the
- # primary key).
- resumable_source_manager.save_state(
- DecagonResumeConfig(min_timestamp=window_value, timestamp_filter=timestamp_filter, **position)
- )
+ return self._request(params)
- # A row can re-enter the stream on a later page of one walk (a conversation that
- # receives new messages re-enters the export). Full-refresh writes are plain appends
- # (no primary-key merge), so re-emissions are skipped client-side; the next sync picks
- # up the newer version. Incremental writes merge on the primary key and the writer
- # keeps the last occurrence per key within a batch, so there the re-emission must flow
- # through (dropping it would keep the stale version) and the set, which grows
- # unboundedly across a large export, is not needed. Keyless streams have nothing to
- # dedupe on and always flow through.
- seen_keys: Optional[set[tuple[Any, ...]]] = (
- set() if config.primary_keys is not None and not should_use_incremental_field else None
- )
- saw_rows = False
- reported_total: Any = None
+class _RowDeduplicator:
+ """Skips rows this walk already emitted.
- while True:
- params: dict[str, str] = dict(config.extra_params)
- if config.pagination == "cursor":
- # An omitted cursor starts the stream at the oldest rows.
- if cursor:
- params["cursor"] = cursor
- elif config.pagination == "page":
- params["page"] = str(page)
- if config.page_size is not None:
- params["page_size"] = str(config.page_size)
- elif config.pagination == "offset":
- params["offset"] = str(offset)
- if config.page_size is not None:
- params["limit"] = str(config.page_size)
- if window_value is not None and config.incremental_param:
- params[config.incremental_param] = str(window_value)
- if timestamp_filter and config.timestamp_filter_param:
- params[config.timestamp_filter_param] = timestamp_filter
+ A row can re-enter the stream on a later page of one walk (a conversation that
+ receives new messages re-enters the export). Full-refresh writes are plain appends
+ (no primary-key merge), so re-emissions are skipped client-side; the next sync picks
+ up the newer version. Incremental writes merge on the primary key and the writer
+ keeps the last occurrence per key within a batch, so there the re-emission must flow
+ through (dropping it would keep the stale version) and the set, which grows
+ unboundedly across a large export, is not needed. Keyless streams have nothing to
+ dedupe on and always flow through.
+ """
- data = fetch_page_with_optional(params)
- items = _resolve_items(data, config, endpoint, logger)
+ def __init__(self, config: DecagonEndpointConfig, should_use_incremental_field: bool) -> None:
+ self._primary_keys = config.primary_keys
+ self._seen_keys: Optional[set[tuple[Any, ...]]] = (
+ set() if config.primary_keys is not None and not should_use_incremental_field else None
+ )
+ def fresh(self, items: list[Any]) -> list[dict[str, Any]]:
fresh: list[dict[str, Any]] = []
for item in items:
- if config.primary_keys is not None:
+ if self._primary_keys is not None:
# Direct access on purpose: these fields are the primary key, so a row
# missing one should fail the sync loudly rather than land in the
# warehouse unkeyed and undeduplicatable.
- key = tuple(item[k] for k in config.primary_keys)
- if seen_keys is not None:
- if key in seen_keys:
+ key = tuple(item[k] for k in self._primary_keys)
+ if self._seen_keys is not None:
+ if key in self._seen_keys:
continue
- seen_keys.add(key)
+ self._seen_keys.add(key)
fresh.append(item)
+ return fresh
+
+
+class _RowWalk:
+ """Walks one endpoint's pages, one method per pagination mode.
+
+ Tracks what the walk observed, so it can check the response against the endpoint's
+ contract once the walk ends.
+ """
+
+ def __init__(
+ self,
+ config: DecagonEndpointConfig,
+ endpoint: str,
+ fetcher: _PageFetcher,
+ window: _IncrementalWindow,
+ resume_config: Optional[DecagonResumeConfig],
+ resumable_source_manager: ResumableSourceManager[DecagonResumeConfig],
+ deduplicator: _RowDeduplicator,
+ logger: FilteringBoundLogger,
+ ) -> None:
+ self._config = config
+ self._endpoint = endpoint
+ self._fetcher = fetcher
+ self._window = window
+ self._window_params = window.request_params(config)
+ self._resumed = resume_config is not None
+ self._resume = resume_config or DecagonResumeConfig()
+ self._manager = resumable_source_manager
+ self._deduplicator = deduplicator
+ self._logger = logger
+ self._saw_rows = False
+ self._reported_total: Any = None
+
+ def run(self) -> Iterator[list[dict[str, Any]]]:
+ yield from self._walk()
+ self._check_contract()
+
+ def _walk(self) -> Iterator[list[dict[str, Any]]]:
+ if self._config.pagination == "single":
+ return self._walk_single()
+ if self._config.pagination == "cursor":
+ return self._walk_cursor()
+ if self._config.pagination == "page":
+ return self._walk_page()
+ return self._walk_offset()
+
+ def _read(self, position_params: dict[str, str]) -> _Batch:
+ params: dict[str, str] = {**self._config.extra_params, **position_params, **self._window_params}
+ data = self._fetcher.fetch(params)
+ items = _resolve_items(data, self._config, self._endpoint, self._logger)
+ fresh = self._deduplicator.fresh(items)
+ self._saw_rows = self._saw_rows or bool(fresh)
+ return _Batch(data=data, items=items, fresh=fresh)
+
+ def _record_total(self, batch: _Batch) -> Any:
+ self._reported_total = batch.data.get(self._config.total_key) if self._config.total_key else None
+ return self._reported_total
+
+ def _short_page(self, batch: _Batch) -> bool:
+ """Termination signal left when the response carries no usable total."""
+ page_size = self._config.page_size
+ return not batch.items or (page_size is not None and len(batch.items) < page_size)
+
+ def _check_contract(self) -> None:
+ # A walk that read every row of the endpoint and kept none, while the endpoint itself
+ # reports rows, means the response no longer matches this config. Fail the sync: the
+ # alternative is the table reporting success forever and never holding a row.
+ if (
+ not self._saw_rows
+ and not self._resumed
+ and not self._window.from_watermark
+ and isinstance(self._reported_total, int | float)
+ and self._reported_total > 0
+ ):
+ raise DecagonContractError(
+ f"{CONTRACT_MISMATCH_ERROR}: {self._endpoint} reports {self._reported_total} rows and the walk "
+ f"kept none. Check the response envelope against the endpoint config."
+ )
+
+ def _save_position(self, **position: Any) -> None:
+ # Persisted only after a yield, so a crash re-yields the last batch rather than
+ # skipping it (the duplicate rows a resumed re-yield can produce are bounded to
+ # one page, and are cleaned up by the next full refresh or merged away on the
+ # primary key).
+ self._manager.save_state(
+ DecagonResumeConfig(
+ min_timestamp=self._window.value, timestamp_filter=self._window.timestamp_filter, **position
+ )
+ )
- saw_rows = saw_rows or bool(fresh)
+ def _walk_single(self) -> Iterator[list[dict[str, Any]]]:
+ batch = self._read({})
+ if batch.fresh:
+ yield batch.fresh
- if config.pagination == "single":
- if fresh:
- yield fresh
- break
+ def _walk_cursor(self) -> Iterator[list[dict[str, Any]]]:
+ config = self._config
+ cursor = self._resume.cursor
- if config.pagination == "cursor":
- next_cursor = _next_cursor(data, config.next_cursor_keys or ())
- more = data.get(config.has_more_key) if config.has_more_key else None
+ while True:
+ # An omitted cursor starts the stream at the oldest rows.
+ batch = self._read({"cursor": cursor} if cursor else {})
+ next_cursor = _next_cursor(batch.data, config.next_cursor_keys or ())
+ more = batch.data.get(config.has_more_key) if config.has_more_key else None
- if fresh:
- yield fresh
+ if batch.fresh:
+ yield batch.fresh
if next_cursor and more is not False:
- save_position(cursor=next_cursor)
+ self._save_position(cursor=next_cursor)
if config.has_more_key is not None and not more:
- break
+ return
# The next-page cursor is null once the stream is exhausted. Also stop if the
# server ever returns the cursor we just used, to guard against spinning on
# one page forever.
if not next_cursor or next_cursor == cursor:
- if config.has_more_key is None and not next_cursor and len(items) >= DECAGON_PAGE_SIZE:
+ if config.has_more_key is None and not next_cursor and len(batch.items) >= DECAGON_PAGE_SIZE:
# A full page that ends the walk is legitimate only when the total row
# count happens to be a multiple of the page size; far more often it means
# Decagon renamed the pagination field again and rows were truncated.
- logger.warning(
- f"Decagon: {endpoint} stream ended on a full page of {len(items)} items without a "
- f"next-page cursor (response keys: {sorted(data.keys())}). If the synced row count "
- f"looks truncated, check the export pagination contract."
+ self._logger.warning(
+ f"Decagon: {self._endpoint} stream ended on a full page of {len(batch.items)} items "
+ f"without a next-page cursor (response keys: {sorted(batch.data.keys())}). If the "
+ f"synced row count looks truncated, check the export pagination contract."
)
- break
+ return
cursor = next_cursor
- continue
-
- total = data.get(config.total_key) if config.total_key else None
- reported_total = total
-
- if config.pagination == "page":
- # Terminate against the reported total using rows actually kept: a row that
- # shifted pages mid-walk arrives twice but counts once toward the server's
- # unique total, so counting raw items could reach the total a page early and
- # drop the final page. Counting kept rows also stays exact if the server caps
- # the requested page size. 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.
- rows_walked += len(fresh)
+
+ def _walk_page(self) -> Iterator[list[dict[str, Any]]]:
+ config = self._config
+ page = self._resume.page or 1
+ # Rows actually kept, not page * page_size: a row that shifted pages mid-walk arrives
+ # twice but counts once toward the server's unique total, so counting raw items could
+ # 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
+
+ while True:
+ params = {"page": str(page)}
+ if config.page_size is not None:
+ params["page_size"] = str(config.page_size)
+
+ 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 fresh or rows_walked >= total
+ exhausted = not batch.fresh or rows_walked >= total
else:
- exhausted = not items or (config.page_size is not None and len(items) < config.page_size)
- if fresh:
- yield fresh
+ exhausted = self._short_page(batch)
+
+ if batch.fresh:
+ yield batch.fresh
if not exhausted:
- save_position(page=page + 1, rows_walked=rows_walked)
+ self._save_position(page=page + 1, rows_walked=rows_walked)
if exhausted:
- break
+ return
+
page += 1
- continue
-
- # Offset mode: advance by the rows actually received rather than by page_size, so
- # a server that caps `limit` below what we asked still walks every row. The offset
- # itself is the cumulative row count, so the total check needs no separate counter.
- next_offset = offset + len(items)
- if isinstance(total, int | float):
- exhausted = not items or next_offset >= total
- else:
- exhausted = not items or (config.page_size is not None and len(items) < config.page_size)
- if fresh:
- yield fresh
- if not exhausted:
- save_position(offset=next_offset)
- if exhausted:
- break
- offset = next_offset
-
- # A walk that read every row of the endpoint and kept none, while the endpoint itself
- # reports rows, means the response no longer matches this config. Fail the sync: the
- # alternative is the table reporting success forever and never holding a row.
- if (
- not saw_rows
- and resume_config is None
- and not windowed_by_watermark
- and isinstance(reported_total, int | float)
- and reported_total > 0
- ):
- raise DecagonContractError(
- f"{CONTRACT_MISMATCH_ERROR}: {endpoint} reports {reported_total} rows and the walk kept none. "
- f"Check the response envelope against the endpoint config."
- )
+
+ def _walk_offset(self) -> Iterator[list[dict[str, Any]]]:
+ config = self._config
+ offset = self._resume.offset or 0
+
+ while True:
+ params = {"offset": str(offset)}
+ if config.page_size is not None:
+ params["limit"] = str(config.page_size)
+
+ batch = self._read(params)
+ total = self._record_total(batch)
+
+ # Advance by the rows actually received rather than by page_size, so a server that
+ # caps `limit` below what we asked still walks every row. The offset itself is the
+ # cumulative row count, so the total check needs no separate counter.
+ next_offset = offset + len(batch.items)
+ if isinstance(total, int | float):
+ exhausted = not batch.items or next_offset >= total
+ else:
+ exhausted = self._short_page(batch)
+
+ if batch.fresh:
+ yield batch.fresh
+ if not exhausted:
+ self._save_position(offset=next_offset)
+ if exhausted:
+ return
+
+ offset = next_offset
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DecagonResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = DECAGON_ENDPOINTS[endpoint]
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config:
+ logger.debug(f"Decagon: resuming {endpoint} from saved state")
+
+ window = _resolve_window(
+ config, resume_config, should_use_incremental_field, db_incremental_field_last_value, incremental_field, logger
+ )
+
+ walk = _RowWalk(
+ config=config,
+ endpoint=endpoint,
+ fetcher=_PageFetcher(api_key=api_key, config=config, endpoint=endpoint, logger=logger),
+ window=window,
+ resume_config=resume_config,
+ resumable_source_manager=resumable_source_manager,
+ deduplicator=_RowDeduplicator(config, should_use_incremental_field),
+ logger=logger,
+ )
+
+ yield from walk.run()
# Walked to completion, so drop any checkpoint: a retried attempt of this job would
# otherwise resume at the final page and append its rows again.
diff --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.py
index ee6a6a754a8a..8c7264e4fdc6 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,6 +1,6 @@
import json
from datetime import UTC, date, datetime
-from typing import Any
+from typing import Any, Optional
import pytest
from unittest.mock import MagicMock, patch
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.decagon.decagon import (
DECAGON_BASE_URL,
+ DECAGON_PAGE_SIZE,
DecagonContractError,
DecagonResumeConfig,
_to_epoch_seconds,
@@ -42,7 +43,11 @@ def _conversation(conversation_id: str) -> dict[str, Any]:
def _drive_rows(
- manager: MagicMock, responses: list[Response], endpoint: str = "conversations", **incremental_kwargs: Any
+ manager: MagicMock,
+ responses: list[Response],
+ 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]] = []
response_iter = iter(responses)
@@ -60,7 +65,7 @@ def _drive_rows(
get_rows(
api_key="key",
endpoint=endpoint,
- logger=MagicMock(),
+ logger=logger or MagicMock(),
resumable_source_manager=manager,
**incremental_kwargs,
)
@@ -199,6 +204,17 @@ class TestGetRows:
assert sent_params == [{}, {"cursor": "cur-1"}]
assert yielded_ids == [["c1"]]
+ def test_full_page_without_a_cursor_warns_that_the_walk_may_be_truncated(self) -> None:
+ # Reading only a renamed cursor field already truncated this export once. A full
+ # page that ends the walk is the one symptom left, so it has to reach the log.
+ manager = self._fresh_manager()
+ logger = MagicMock()
+ page = [_conversation(f"c{i}") for i in range(DECAGON_PAGE_SIZE)]
+ _drive_rows(manager, [_make_response({"conversations": page})], logger=logger)
+
+ assert logger.warning.call_count == 1
+ assert "ended on a full page" in logger.warning.call_args.args[0]
+
def test_incremental_walk_sends_window_on_every_page_and_saves_it(self) -> None:
manager = self._fresh_manager()
watermark = datetime(2026, 1, 15, 12, 0, 5, tzinfo=UTC)
@@ -723,6 +739,16 @@ class TestAdminLogs:
]
assert [len(b) for b in batches] == [2, 1]
+ def test_offset_walk_without_a_total_stops_on_a_short_page(self) -> None:
+ # Without `total` the only end signal is a page shorter than the requested limit.
+ # Missing it would re-request the same short page until the server complained.
+ manager = _fresh_manager()
+ responses = [_make_response({"admin_logs": [{"id": "a1"}]})]
+ sent_params, batches = _drive_rows(manager, responses, endpoint="admin_logs")
+
+ assert len(sent_params) == 1
+ assert [[r["id"] for r in b] for b in batches] == [["a1"]]
+
@parameterized.expand(
[
("full_refresh", {}),