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(data-imports): add required query to checkout.com payments search (#79119)

jake sciottoda9d600729ba
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
index 8612d7d61b80..c14c4168e303 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
@@ -2,6 +2,8 @@ import dataclasses
from datetime import UTC, date, datetime
from typing import Any, Optional
+import requests
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
@@ -79,6 +81,16 @@ def _format_timestamp(value: Any) -> str:
return str(value)
+def _error_details(response: requests.Response) -> str:
+ """Bounded body excerpt for API error logs.
+
+ Checkout.com 4xx bodies carry the machine-readable failure reason (`error_type` and
+ `error_codes`) that the status line hides, e.g. a 422 naming the invalid request
+ field. Bounded so an unexpected HTML error page can't flood the log.
+ """
+ return (response.text or "").strip()[:500]
+
+
def validate_credentials(environment: str, client_id: str, client_secret: str) -> bool:
"""Confirm the API credentials are valid by minting a token and probing disputes."""
try:
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 3acf4e412ff4..1f6aafe13396 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
@@ -2,10 +2,12 @@
Bulk payment objects come from ``POST /payments/search`` (the one server-side
listing surface; ``GET /payments`` only looks up by reference). The search
-request supports ``query``, ``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.
+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.
``payment_actions``, ``customers`` and ``instruments`` have no listing
endpoints at all, so their syncs walk the same payment windows and fan out to
@@ -23,6 +25,7 @@ from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
CheckoutComResumeConfig,
+ _error_details,
_format_timestamp,
_hosts,
_make_auth,
@@ -39,9 +42,17 @@ PAYMENTS_ENDPOINTS = ("payments", "payment_actions", "customers", "instruments")
# The search endpoint caps `limit` at 1000.
SEARCH_PAGE_LIMIT = 1000
+# The search endpoint rejects a request without a non-empty `query` as unprocessable
+# (422), and Checkout.com documents no match-all expression, so the widest valid
+# filter is a predicate every payment satisfies. Comparisons use the colon-prefixed
+# 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.
+SEARCH_HORIZON = timedelta(days=90)
REQUEST_TIMEOUT_SECONDS = 120
-# How far back the first (non-incremental) sync reaches when no start date is configured.
-DEFAULT_BACKFILL_DAYS = 365
# A window that still fills a whole page at this span can't be split further; anything
# past it is yielded with an error log rather than silently truncated.
MIN_WINDOW = timedelta(seconds=1)
@@ -107,7 +118,7 @@ def _resolve_start(
configured = _to_datetime(start_date) if start_date else None
if configured is not None:
return configured
- return now - timedelta(days=DEFAULT_BACKFILL_DAYS)
+ return now - SEARCH_HORIZON
def _search_payments(
@@ -118,13 +129,17 @@ def _search_payments(
logger: FilteringBoundLogger,
) -> list[dict[str, Any]]:
body = {
+ "query": SEARCH_MATCH_ALL_QUERY,
"from": _format_timestamp(window.start),
"to": _format_timestamp(window.end),
"limit": SEARCH_PAGE_LIMIT,
}
response = session.post(f"{api_base}/payments/search", json=body, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)
if not response.ok:
- logger.error(f"Checkout.com API error: status={response.status_code}, url={api_base}/payments/search")
+ logger.error(
+ f"Checkout.com API error: status={response.status_code}, "
+ f"url={api_base}/payments/search, body={_error_details(response)}"
+ )
response.raise_for_status()
payload = response.json()
data = payload.get("data") if isinstance(payload, dict) else None
@@ -202,7 +217,9 @@ def _fanout_get(
if response.status_code == 404:
return None
if not response.ok:
- logger.error(f"Checkout.com API error: status={response.status_code}, url={url}")
+ logger.error(
+ f"Checkout.com API error: status={response.status_code}, url={url}, body={_error_details(response)}"
+ )
response.raise_for_status()
payload = response.json()
return payload if isinstance(payload, dict | list) else None
@@ -299,6 +316,14 @@ 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]] = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py
index 0d550d6b9046..2a741911a5e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py
@@ -26,6 +26,7 @@ from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
CheckoutComResumeConfig,
+ _error_details,
_format_timestamp,
_hosts,
_make_auth,
@@ -147,7 +148,10 @@ def _list_reports(
page_params["pagination_token"] = pagination_token
response = session.get(f"{api_base}/reports", params=page_params, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)
if not response.ok:
- logger.error(f"Checkout.com API error: status={response.status_code}, url={api_base}/reports")
+ logger.error(
+ f"Checkout.com API error: status={response.status_code}, "
+ f"url={api_base}/reports, body={_error_details(response)}"
+ )
response.raise_for_status()
payload = response.json()
data = payload.get("data") if isinstance(payload, dict) else None
@@ -353,8 +357,8 @@ def discover_report_types(environment: str, client_id: str, client_secret: str)
"""Map table name -> report type for the report types visible to these credentials.
Used by ``get_schemas``, which runs inline on API requests, so the listing is
- bounded to the most recent pages. Raises on any API failure; the caller degrades
- to the static schema catalog.
+ bounded to the most recent pages. Raises on any API failure; ``get_schemas``
+ decides which failures degrade to the static schema catalog.
"""
hosts = _hosts(environment)
auth = _make_auth(environment, client_id, client_secret)
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 124ba1c866cc..e6c8aa4eecdd 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
@@ -1,5 +1,6 @@
from typing import Optional, cast
+import requests
import structlog
from posthog.schema import (
@@ -152,7 +153,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. 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, 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.""",
iconPath="/static/services/checkout_com.png",
docsUrl="https://posthog.com/docs/cdp/sources/checkout-com",
releaseStatus=ReleaseStatus.ALPHA,
@@ -233,14 +234,26 @@ Payments, payment actions, customers and instruments sync from the payments sear
)
# One table per report type the account generates. Discovery needs the API, so
- # the credential-free path (public docs, placeholder configs) stays static, and
- # any discovery failure degrades to the static catalog instead of breaking the
- # schema listing.
+ # the credential-free path (public docs, placeholder configs) stays static.
if config.client_id and config.client_secret:
try:
discovered = discover_report_types(config.environment, config.client_id, config.client_secret)
- except Exception:
- logger.exception("Checkout.com report type discovery failed", team_id=team_id)
+ except requests.HTTPError as e:
+ # 401/403 from the reports endpoint means the access key lacks the
+ # reports scope, which is a valid permanent configuration whose correct
+ # listing is the static catalog. Every other failure must propagate:
+ # degrading to the static catalog on a transient error would make
+ # scheduled discovery prune the report-type schemas it discovered on
+ # earlier runs (sync_old_schemas_with_new_schemas soft-deletes or
+ # disables stored names the listing no longer returns).
+ status = e.response.status_code if e.response is not None else None
+ if status not in (401, 403):
+ raise
+ logger.warning(
+ "Checkout.com report type discovery denied; listing the static catalog only",
+ team_id=team_id,
+ status=status,
+ )
discovered = {}
for table_name in sorted(discovered):
schemas.append(
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 32908b2f6b4b..149691962c5b 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
@@ -1,4 +1,3 @@
-from datetime import datetime
from typing import Any, Optional
import pytest
@@ -9,7 +8,6 @@ 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 (
- MAX_SEARCH_WINDOW,
checkout_com_payments_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -28,9 +26,10 @@ NOW = "2024-03-01T00:00:00Z"
class _FakeResponse:
- def __init__(self, status_code: int = 200, json_data: Any = None) -> None:
+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = "") -> None:
self.status_code = status_code
self._json_data = json_data
+ self.text = text
@property
def ok(self) -> bool:
@@ -169,6 +168,8 @@ class TestPaymentsWindowWalking:
("2024-02-29T12:00:00Z", "2024-03-01T00:00:00Z"),
]
assert all(s["json"]["limit"] == 2 and s["auth"] is not None for s in session.searches)
+ # The search endpoint rejects a request without a non-empty `query` as unprocessable.
+ assert all(s["json"]["query"] for s in session.searches)
# Each completed window checkpoints its end, ascending.
assert [state.search_window_to for state in manager.saved_states] == [
"2024-02-29T12:00:00Z",
@@ -178,10 +179,12 @@ class TestPaymentsWindowWalking:
@pytest.mark.parametrize(
"start_date, should_use_incremental_field, last_value, expected_from, expected_search_count",
[
- # A year-long default backfill exceeds MAX_SEARCH_WINDOW, so it's chunked
- # into 5 requests (4 full 90-day chunks plus a 5-day remainder).
- (None, False, None, "2023-03-02T00:00:00Z", 5),
+ # No configured start: the default backfill reaches the ~90-day search horizon,
+ # 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),
("2024-01-01", True, "2024-02-01T00:00:00Z", "2024-02-01T00:00:00Z", 1),
],
)
@@ -212,28 +215,6 @@ class TestPaymentsWindowWalking:
assert session.searches[0]["json"]["from"] == expected_from
assert session.searches[-1]["json"]["to"] == NOW
- @mock.patch(SESSION_PATCH)
- def test_default_backfill_is_chunked_to_max_search_window(self, mock_make_session):
- # The search API 422s on a full one-year range sent as a single request, so the
- # overall sync range is walked in MAX_SEARCH_WINDOW-sized chunks.
- session = _FakeSession(search_responses=[_search_page([]) for _ in range(5)])
- mock_make_session.side_effect = [session]
-
- _rows(_source("payments"))
-
- spans = [
- (
- datetime.fromisoformat(s["json"]["from"].replace("Z", "+00:00")),
- datetime.fromisoformat(s["json"]["to"].replace("Z", "+00:00")),
- )
- for s in session.searches
- ]
- assert all(end - start <= MAX_SEARCH_WINDOW for start, end in spans)
- # Chunks are contiguous and ascending, covering the full backfill range.
- assert all(spans[i][1] == spans[i + 1][0] for i in range(len(spans) - 1))
- assert spans[0][0] == datetime.fromisoformat("2023-03-02T00:00:00+00:00")
- assert spans[-1][1] == datetime.fromisoformat(NOW.replace("Z", "+00:00"))
-
@mock.patch(SESSION_PATCH)
def test_resume_checkpoint_wins_over_watermark(self, mock_make_session):
session = _FakeSession(search_responses=[_search_page([])])
@@ -275,6 +256,34 @@ class TestPaymentsWindowWalking:
assert len(session.searches) == 1
logger.error.assert_called_once()
+ @mock.patch(SESSION_PATCH)
+ def test_search_error_raises_and_logs_response_body(self, mock_make_session):
+ # The 4xx body carries the machine-readable reason (`error_codes`); without it in
+ # the log a rejected request is undiagnosable server-side.
+ session = _FakeSession(
+ search_responses=[
+ _FakeResponse(
+ status_code=422,
+ text='{"error_type":"request_invalid","error_codes":["query_required"]}',
+ )
+ ]
+ )
+ mock_make_session.side_effect = [session]
+ logger = mock.MagicMock()
+
+ response = checkout_com_payments_source(
+ environment="production",
+ client_id="ack_id",
+ client_secret="secret",
+ schema_name="payments",
+ logger=logger,
+ resumable_source_manager=_FakeManager(),
+ )
+ with pytest.raises(Exception, match="422"):
+ _rows(response)
+
+ assert "query_required" in logger.error.call_args[0][0]
+
@freeze_time(NOW)
class TestPaymentActionsFanout:
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 1979382a75d1..6b7d18d2b92d 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
@@ -1,6 +1,8 @@
import pytest
from unittest import mock
+import requests
+
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
@@ -22,6 +24,12 @@ DISCOVER_PATCH = (
_STATIC_SCHEMAS = ["disputes", "reports", "payments", "payment_actions", "customers", "instruments"]
+def _http_error(status: int) -> requests.HTTPError:
+ response = requests.Response()
+ response.status_code = status
+ return requests.HTTPError(f"{status} Client Error", response=response)
+
+
class TestCheckoutComSource:
def setup_method(self):
self.source = CheckoutComSource()
@@ -163,14 +171,30 @@ class TestCheckoutComSource:
mock_discover.assert_not_called()
assert [s.name for s in schemas] == _STATIC_SCHEMAS
+ @pytest.mark.parametrize("status", [401, 403])
@mock.patch(DISCOVER_PATCH)
- def test_get_schemas_discovery_failure_degrades_to_static(self, mock_discover):
- mock_discover.side_effect = Exception("boom")
+ def test_get_schemas_scope_denied_discovery_degrades_to_static(self, mock_discover, status):
+ # A key without the reports scope is a valid configuration; its correct listing
+ # is the static catalog.
+ mock_discover.side_effect = _http_error(status)
schemas = self.source.get_schemas(self.config, self.team_id)
assert [s.name for s in schemas] == _STATIC_SCHEMAS
+ @pytest.mark.parametrize(
+ "error",
+ [_http_error(429), _http_error(500), requests.ConnectionError("connection reset")],
+ )
+ @mock.patch(DISCOVER_PATCH)
+ def test_get_schemas_transient_discovery_failure_propagates(self, mock_discover, error):
+ # Degrading to the static catalog on a transient failure would make scheduled
+ # discovery prune the report-type schemas it discovered on earlier runs.
+ mock_discover.side_effect = error
+
+ with pytest.raises(type(error)):
+ self.source.get_schemas(self.config, self.team_id)
+
@pytest.mark.parametrize(
"names, expected",
[