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): fail partial checkout.com payment syncs loudly (#82115)

jake sciotto42b25637bff0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
index 1f6aafe13396..f0be386cb363 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
@@ -6,8 +6,14 @@ request requires a non-empty ``query`` and supports ``from``/``to`` and
``limit`` (max 1000) but no documented page cursor, so listing walks the time
range and recursively splits any window that fills a whole page; a window
returning fewer than ``limit`` rows is provably complete. Documented search
-coverage is roughly the previous 90 days, so range starts are clamped to that
-horizon; older history is only available via the report tables.
+coverage is roughly the previous 90 days, which sets how far back a first sync
+reaches; the endpoint serves older payments too, so a configured ``start_date``
+reaching further back is honoured rather than clamped forward.
+
+A sync bounds its own API usage with per-run call budgets. Hitting one leaves the
+range incomplete, so it raises: returning would report the schema ``Completed``
+over months holding no rows. Each fully-drained window is checkpointed, so the
+retry resumes where the budget ran out.
``payment_actions``, ``customers`` and ``instruments`` have no listing
endpoints at all, so their syncs walk the same payment windows and fan out to
@@ -48,9 +54,10 @@ SEARCH_PAGE_LIMIT = 1000
# form (`field:>=value`) to match the documented `field:value` grammar; a bare
# `amount>=0` appears in no official example.
SEARCH_MATCH_ALL_QUERY = "amount:>=0"
-# Checkout.com documents payments search as covering roughly the previous 90 days, so
-# this is both the default backfill reach and the clamp for configured start dates and
-# stale watermarks; anything older can't come back from search.
+# Checkout.com documents payments search as covering roughly the previous 90 days, so this
+# is how far back a first sync reaches when nothing else says otherwise. It is a default,
+# not a limit: the endpoint serves well past its documented window, so a configured
+# `start_date` reaching further back is honoured rather than clamped forward.
SEARCH_HORIZON = timedelta(days=90)
REQUEST_TIMEOUT_SECONDS = 120
# A window that still fills a whole page at this span can't be split further; anything
@@ -69,6 +76,19 @@ MAX_SEARCH_REQUESTS_PER_SYNC = 2_000
MAX_FANOUT_LOOKUPS_PER_SYNC = 10_000
FANOUT_CHUNK_SIZE = 500
+# Stable marker so the source can classify a budget stop as retryable rather than a bug.
+SYNC_BUDGET_EXCEEDED_MARKER = "Checkout.com sync hit its per-run API budget"
+
+
+class CheckoutComSyncBudgetExceeded(Exception):
+ """A sync stopped at its per-run API call budget before covering its whole range.
+
+ Raised rather than returned. Returning cleanly reported the schema `Completed` with no
+ error while the range past the cut-off held no rows at all, so the gap was invisible:
+ `last_synced_at` moved, the table did not. Every window completed before the budget ran
+ out is checkpointed, so the retry resumes there instead of redoing the run.
+ """
+
class _SyncBudget:
"""Counts API calls for one sync and says when to stop cleanly."""
@@ -316,15 +336,6 @@ def _get_rows(
resume.search_window_to if resume is not None else None,
now,
)
- horizon_start = now - SEARCH_HORIZON
- if start < horizon_start:
- logger.warning(
- "Checkout.com payments search covers roughly the previous 90 days; clamping the range start",
- requested_start=_format_timestamp(start),
- clamped_start=_format_timestamp(horizon_start),
- )
- start = horizon_start
-
seen_ids: set[str] = set()
chunk: list[dict[str, Any]] = []
for window, payments in _iter_bounded_payment_windows(session, auth, hosts["api"], start, now, logger, budget):
@@ -359,13 +370,13 @@ def _get_rows(
# next scheduled sync re-covers it (merge dedupes overlapping rows).
break
resumable_source_manager.save_state(CheckoutComResumeConfig(search_window_to=_format_timestamp(window.end)))
- if budget.exhausted:
- logger.warning(
- "Checkout.com sync hit its per-run API budget; continuing from the last complete window next run",
- schema=schema_name,
- )
if chunk:
yield chunk
+ if budget.exhausted:
+ raise CheckoutComSyncBudgetExceeded(
+ f"{SYNC_BUDGET_EXCEEDED_MARKER} for {schema_name} before reaching "
+ f"{_format_timestamp(now)}; the range past the last complete window holds no rows yet"
+ )
def checkout_com_payments_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
index e6c8aa4eecdd..8a5bc879234e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
PAYMENTS_ENDPOINTS,
+ SYNC_BUDGET_EXCEEDED_MARKER,
checkout_com_payments_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (
@@ -141,6 +142,11 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
return {
"503 Server Error: Service Unavailable for url: https://api.checkout.com/payments/search",
"503 Server Error: Service Unavailable for url: https://api.sandbox.checkout.com/payments/search",
+ # A run that stops at its per-run API budget is incomplete, not broken. Every
+ # window it finished is checkpointed, so the retry resumes there and covers more
+ # ground; a long backfill converges over several attempts. It has to raise rather
+ # than return so the schema never reports Completed over an unfilled range.
+ SYNC_BUDGET_EXCEEDED_MARKER,
}
@property
@@ -153,7 +159,7 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.com/) under Settings > Access keys. Grant it the scopes for the tables you want to sync: `disputes`, `reports`, `payments` (search), `gateway` (payment actions), and `vault` (customers and instruments).
-Payments, payment actions, customers and instruments sync from the payments search API, which covers roughly the last 90 days of payments. Financial reporting data (financial actions, payouts, balances) syncs from your generated report files: each report type available for your account becomes a table. If no report tables show up, set up scheduled reports in your Checkout.com dashboard first.""",
+Payments, payment actions, customers and instruments sync from the payments search API. It reaches back 90 days by default. Set a start date to sync more history. Financial reporting data (financial actions, payouts, balances) syncs from your generated report files: each report type available for your account becomes a table. If no report tables show up, set up scheduled reports in your Checkout.com dashboard first.""",
iconPath="/static/services/checkout_com.png",
docsUrl="https://posthog.com/docs/cdp/sources/checkout-com",
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
index 149691962c5b..dfd73f13e584 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
@@ -8,6 +8,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
CheckoutComResumeConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
+ SYNC_BUDGET_EXCEEDED_MARKER,
+ CheckoutComSyncBudgetExceeded,
checkout_com_payments_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -116,6 +118,12 @@ def _rows(source_response) -> list[dict[str, Any]]:
return [row for chunk in source_response.items() for row in chunk]
+def _collect_rows(source_response, into: list[dict[str, Any]]) -> None:
+ """Drain into a caller-owned list, so rows yielded before a raise stay inspectable."""
+ for chunk in source_response.items():
+ into.extend(chunk)
+
+
def _source(
schema_name: str,
manager: Optional[_FakeManager] = None,
@@ -183,8 +191,10 @@ class TestPaymentsWindowWalking:
# which fits a single MAX_SEARCH_WINDOW request.
(None, False, None, "2023-12-02T00:00:00Z", 1),
("2024-01-01", False, None, "2024-01-01T00:00:00Z", 1),
- # A start older than the horizon clamps to it; search can't return older payments.
- ("2023-01-01", False, None, "2023-12-02T00:00:00Z", 1),
+ # A start older than the documented horizon is honoured rather than clamped
+ # forward: search serves well past 90 days, and clamping silently dropped every
+ # month before it. 425 days walks as five MAX_SEARCH_WINDOW chunks.
+ ("2023-01-01", False, None, "2023-01-01T00:00:00Z", 5),
("2024-01-01", True, "2024-02-01T00:00:00Z", "2024-02-01T00:00:00Z", 1),
],
)
@@ -324,7 +334,7 @@ class TestPaymentActionsFanout:
@mock.patch(LOOKUP_BUDGET_PATCH, 1)
@mock.patch(SESSION_PATCH)
- def test_lookup_budget_stops_cleanly_without_checkpointing(self, mock_make_session):
+ def test_lookup_budget_raises_instead_of_reporting_a_complete_sync(self, mock_make_session):
session = _FakeSession(
search_responses=[
_search_page(
@@ -349,14 +359,18 @@ class TestPaymentActionsFanout:
resumable_source_manager=manager,
start_date="2024-02-28",
)
- rows = _rows(response)
-
- # Only the budgeted lookup ran, the interrupted window is not checkpointed (the
- # next run re-covers it), and the stop is loud.
- assert [row["id"] for row in rows] == ["act_1"]
+ collected: list[dict[str, Any]] = []
+ with pytest.raises(CheckoutComSyncBudgetExceeded) as excinfo:
+ _collect_rows(response, collected)
+
+ # Returning here reported the schema Completed over a range holding no rows, so the
+ # gap was invisible. Rows found before the cut-off still land, the interrupted window
+ # is not checkpointed, and the run fails so the gap surfaces as latest_error.
+ assert [row["id"] for row in collected] == ["act_1"]
assert len(session.lookups) == 1
assert manager.saved_states == []
- logger.warning.assert_called_once()
+ # The source classifies this as retryable by matching the marker in the message.
+ assert SYNC_BUDGET_EXCEEDED_MARKER in str(excinfo.value)
@freeze_time(NOW)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
index 6b7d18d2b92d..e0ab0d63505c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
@@ -8,6 +8,9 @@ from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInp
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
CheckoutComResumeConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
+ SYNC_BUDGET_EXCEEDED_MARKER,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.source import CheckoutComSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
OAUTH2_PERMANENT_ERROR_MARKER,
@@ -107,9 +110,13 @@ class TestCheckoutComSource:
[
"503 Server Error: Service Unavailable for url: https://api.checkout.com/payments/search",
"503 Server Error: Service Unavailable for url: https://api.sandbox.checkout.com/payments/search",
+ # A run stopped at its per-run API budget is incomplete, not broken: it raises so
+ # the schema never reports Completed over an unfilled range, and the retry resumes
+ # from the last checkpointed window. Classified as a bug, it would page instead.
+ f"{SYNC_BUDGET_EXCEEDED_MARKER} for payment_actions before reaching 2024-03-01T00:00:00Z",
],
)
- def test_retryable_errors_match_payments_search_503(self, observed_error):
+ def test_retryable_errors_match_transient_and_partial_run_failures(self, observed_error):
retryable_errors = self.source.get_retryable_errors()
assert any(key in observed_error for key in retryable_errors)