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): let a budget-capped Checkout.com sync commit its progress (#91424)

jake sciottoa8e706dcfd8f
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 9c2443f3fd28..86bf4b355b32 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
@@ -10,10 +10,14 @@ 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.
+A sync bounds its own API usage with per-run call budgets. An incremental run that
+landed a row newer than its watermark before hitting one ends cleanly: the pipeline
+commits those rows, promotes the watermark, and the next scheduled sync continues
+from there, so a backlog converges run over run. A run that cannot advance the
+watermark (a full refresh, or no row newer than it) raises instead: returning would
+report the schema ``Completed`` while the table stayed where it was. Each fully-drained
+window is also checkpointed in Redis, so a retry within the same job 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 per
@@ -101,19 +105,30 @@ PAYMENTS_PARTITION_COUNT = 200
CUSTOMER_ID_PREFIX = "cus_"
INSTRUMENT_ID_PREFIX = "src_"
+# The incremental field each schema advances its watermark on. `source` declares these to
+# the pipeline; `_get_rows` reads the same field off a yielded row to tell whether the run
+# actually moved the watermark, so both sides share these names.
+PAYMENTS_INCREMENTAL_FIELD = "requested_on"
+FANOUT_INCREMENTAL_FIELD = "payment_requested_on"
+
# 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"
+# The text reaches the operator as `latest_error` when a job exhausts its retries, so it
+# describes the effect (the table fell behind) rather than the internal budget.
+SYNC_BUDGET_EXCEEDED_MARKER = "Checkout.com sync fell behind"
# Stable marker so the source can map an id-less run to a customer-facing error.
UNRESOLVED_REFERENCES_MARKER = "Checkout.com payments reference records without a usable identifier"
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.
+ """A sync stopped at its per-run API call budget without advancing the watermark.
+
+ Raised only when ending cleanly would hide the gap: a full refresh (a partial commit
+ would replace the whole table with a slice), or a run holding no row newer than the
+ watermark (there is nothing to promote it to, so `last_synced_at` would move while the
+ table did not). An incremental run that carries the watermark forward returns cleanly
+ instead, which commits the rows, so the next scheduled sync resumes from what was covered.
+ Every window completed before the budget ran out is also checkpointed in Redis, so a
+ retry within the same job resumes there instead of redoing the run.
"""
@@ -599,6 +614,28 @@ def _instrument_row(
return _instrument_record_row(session, auth, api_base, record_id, payment, logger)
+def _latest_incremental_value(
+ schema_name: str, rows: list[dict[str, Any]], current: Optional[datetime]
+) -> Optional[datetime]:
+ """The newest incremental value across `rows`, or `current` when none parse."""
+ field = PAYMENTS_INCREMENTAL_FIELD if schema_name == "payments" else FANOUT_INCREMENTAL_FIELD
+ for row in rows:
+ value = _to_datetime(row.get(field))
+ if value is not None and (current is None or value > current):
+ current = value
+ return current
+
+
+def _describe_lag(lag: timedelta) -> str:
+ """A human-readable duration for the falling-behind messages, never below one minute."""
+ total_minutes = max(int(lag.total_seconds() // 60), 1)
+ if total_minutes >= 2 * 24 * 60:
+ return f"{total_minutes // (24 * 60)} days"
+ if total_minutes >= 120:
+ return f"{total_minutes // 60} hours"
+ return "1 minute" if total_minutes == 1 else f"{total_minutes} minutes"
+
+
def _report_unresolved_references(schema_name: str, state: _FanoutRunState, logger: FilteringBoundLogger) -> None:
noun = "customer" if schema_name == "customers" else "payment instrument"
if state.rows_landed == 0:
@@ -640,6 +677,9 @@ def _get_rows(
now,
)
chunk: list[dict[str, Any]] = []
+ covered_to = start
+ watermark = _to_datetime(db_incremental_field_last_value) if should_use_incremental_field else None
+ latest_yielded: Optional[datetime] = None
for window, payments in _iter_bounded_payment_windows(session, auth, hosts["api"], start, now, logger, budget):
for payment in payments:
if schema_name == "payments":
@@ -667,6 +707,7 @@ def _get_rows(
state.rows_landed += 1
chunk.append(row)
if len(chunk) >= FANOUT_CHUNK_SIZE:
+ latest_yielded = _latest_incremental_value(schema_name, chunk, latest_yielded)
yield chunk
chunk = []
if budget.exhausted:
@@ -674,12 +715,31 @@ 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)))
+ covered_to = window.end
if chunk:
+ latest_yielded = _latest_incremental_value(schema_name, chunk, latest_yielded)
yield chunk
if budget.exhausted:
+ advanced = latest_yielded is not None and (watermark is None or latest_yielded > watermark)
+ if should_use_incremental_field and advanced:
+ # Ending cleanly commits the yielded rows and promotes the watermark, so the next
+ # scheduled sync continues from here instead of redoing the same ground. Raising
+ # would discard all of it: the pipeline only finalizes staged batches and the
+ # staged cursor when the generator completes. The watermark has to actually move
+ # first: a run whose rows all sit at or behind it would report success while
+ # covering the same range forever.
+ if state.unresolvable_references:
+ _report_unresolved_references(schema_name, state, logger)
+ logger.warning(
+ f"Checkout.com {schema_name} sync is {_describe_lag(now - covered_to)} behind; this run "
+ "commits what it covered and the next scheduled sync continues from there"
+ )
+ return
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"
+ f"{SYNC_BUDGET_EXCEEDED_MARKER}: {schema_name} is {_describe_lag(now - covered_to)} behind and "
+ "this run stopped before closing the gap. The sync retries and continues automatically. If the "
+ "gap keeps growing across runs, set a more recent start date on the source to narrow the range, "
+ "or contact PostHog support about a manual backfill."
)
if state.unresolvable_references:
_report_unresolved_references(schema_name, state, logger)
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 e52c9e27cdec..2c1a1e702a59 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
@@ -21,7 +21,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
validate_credentials as validate_checkout_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
+ FANOUT_INCREMENTAL_FIELD,
PAYMENTS_ENDPOINTS,
+ PAYMENTS_INCREMENTAL_FIELD,
SYNC_BUDGET_EXCEEDED_MARKER,
UNRESOLVED_REFERENCES_MARKER,
checkout_com_payments_source,
@@ -69,10 +71,10 @@ _REPORT_ROWS_INCREMENTAL_FIELDS: list[IncrementalField] = [incremental_field("re
# Payments search filters server-side on `from`/`to` over the payment request time;
# the fan-out tables inherit that cursor through the payment that references them.
_PAYMENTS_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- "payments": [incremental_field("requested_on")],
- "payment_actions": [incremental_field("payment_requested_on")],
- "customers": [incremental_field("payment_requested_on")],
- "instruments": [incremental_field("payment_requested_on")],
+ "payments": [incremental_field(PAYMENTS_INCREMENTAL_FIELD)],
+ "payment_actions": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
+ "customers": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
+ "instruments": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
}
_PAYMENTS_ENDPOINT_DESCRIPTIONS: dict[str, str] = {
@@ -151,11 +153,15 @@ 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.
+ # A run that stops at its per-run API budget without advancing the watermark is
+ # incomplete, not broken. Every window it finished is checkpointed, so the retry
+ # resumes there and covers more ground. Incremental runs that landed a row newer
+ # than the watermark end cleanly instead of raising (see payments._get_rows), so
+ # this only fires when the watermark could not move: a full refresh, or a run
+ # holding no row past it.
SYNC_BUDGET_EXCEEDED_MARKER,
+ # Jobs in flight across a deploy can still raise the pre-rename message text.
+ "Checkout.com sync hit its per-run API budget",
}
@property
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 f4a63a2c4418..c8de803ea875 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
@@ -6,6 +6,7 @@ from unittest import mock
import pyarrow as pa
import requests
+from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
@@ -35,6 +36,9 @@ SESSION_PATCH = (
)
NOW = "2024-03-01T00:00:00Z"
+# Stored watermark for the budget tests. A payment stamped with exactly this value is the
+# boundary row the search re-reads every run, because the range starts at the watermark.
+BUDGET_WATERMARK = "2024-02-28T00:00:00Z"
class _FakeResponse:
@@ -382,14 +386,90 @@ class TestPaymentActionsFanout:
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.
+ # A full-refresh run cannot commit a partial slice, so it raises: returning would
+ # report the schema Completed over a range holding no rows and the gap would be
+ # invisible. The interrupted window is not checkpointed.
assert [row["id"] for row in collected] == ["act_1"]
assert len(session.lookups) == 1
assert manager.saved_states == []
- # The source classifies this as retryable by matching the marker in the message.
+ # The source classifies this as retryable by matching the marker in the message,
+ # and the message states the lag rather than the internal budget.
assert SYNC_BUDGET_EXCEEDED_MARKER in str(excinfo.value)
+ assert "behind" in str(excinfo.value)
+ assert "budget" not in str(excinfo.value)
+
+ @mock.patch(LOOKUP_BUDGET_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_budget_run_commits_its_prefix_instead_of_raising(self, mock_make_session):
+ # The regression this guards: raising here discards every staged batch and the staged
+ # watermark, so a backlogged incremental table burned its whole budget each run and
+ # committed nothing, falling further behind every day.
+ session = _FakeSession(
+ search_responses=[
+ _search_page(
+ [
+ _payment("pay_1", "2024-02-29T06:00:00Z"),
+ _payment("pay_2", "2024-02-29T18:00:00Z"),
+ ]
+ )
+ ],
+ lookup_responses=[_FakeResponse(json_data={"items": [{"id": "act_1"}]})],
+ )
+ mock_make_session.side_effect = [session]
+ logger = mock.MagicMock()
+
+ rows = _rows(
+ _source(
+ "payment_actions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=BUDGET_WATERMARK,
+ logger=logger,
+ )
+ )
+
+ # The prefix lands (no raise), so the pipeline finalizes it and promotes the watermark.
+ assert [row["id"] for row in rows] == ["act_1"]
+ assert len(session.lookups) == 1
+ warning = logger.warning.call_args[0][0]
+ assert "behind" in warning
+
+ @parameterized.expand(
+ [
+ # Nothing landed, so there is no value to promote the watermark to.
+ ("no rows landed", "2024-02-29T06:00:00Z", {"items": []}),
+ # The only row is the boundary payment the watermark already covers. Counting it
+ # as progress would promote the watermark to where it already sat, so every
+ # scheduled run would re-cover this range forever while reporting success.
+ ("only rows at the watermark", BUDGET_WATERMARK, {"items": [{"id": "act_1"}]}),
+ ]
+ )
+ @mock.patch(LOOKUP_BUDGET_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_budget_run_that_cannot_advance_the_watermark_raises(
+ self, _name, first_requested_on, lookup_payload, mock_make_session
+ ):
+ # Ending cleanly here would report Completed while the table stayed where it was,
+ # so the run must stay a failure and retry.
+ session = _FakeSession(
+ search_responses=[
+ _search_page(
+ [
+ _payment("pay_1", first_requested_on),
+ _payment("pay_2", "2024-02-29T18:00:00Z"),
+ ]
+ )
+ ],
+ lookup_responses=[_FakeResponse(json_data=lookup_payload)],
+ )
+ mock_make_session.side_effect = [session]
+
+ response = _source(
+ "payment_actions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=BUDGET_WATERMARK,
+ )
+ with pytest.raises(CheckoutComSyncBudgetExceeded):
+ _rows(response)
class TestCustomersFanout:
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 dbd9232bf055..5d89588073e3 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
@@ -77,10 +77,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",
+ # A run stopped at its per-run API budget without landing rows 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.
+ f"{SYNC_BUDGET_EXCEEDED_MARKER}: payment_actions is 3 days behind and this run stopped "
+ "before closing the gap.",
+ # Jobs in flight across the marker rename keep their old message text.
+ "Checkout.com sync hit its per-run API budget for payment_actions before reaching 2024-03-01T00:00:00Z",
],
)
def test_retryable_errors_match_transient_and_partial_run_failures(self, observed_error):