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): Checkout.com payments retains duplicate ids despite a primary key (#82959)

jake sciotto566aba320634
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 f0be386cb363..8cb5cb98edd0 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
@@ -42,7 +42,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
+ PartitionFormat,
+ PartitionMode,
+ SourceResponse,
+)
PAYMENTS_ENDPOINTS = ("payments", "payment_actions", "customers", "instruments")
@@ -75,6 +79,10 @@ MAX_SEARCH_WINDOW = timedelta(days=90)
MAX_SEARCH_REQUESTS_PER_SYNC = 2_000
MAX_FANOUT_LOOKUPS_PER_SYNC = 10_000
FANOUT_CHUNK_SIZE = 500
+# Bucket count for the md5(id) partitioning of `payments` (see
+# checkout_com_payments_source): enough buckets to keep each per-partition merge small
+# on multi-million-row accounts, matching the count other id-hashed sources use.
+PAYMENTS_PARTITION_COUNT = 200
# 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"
@@ -395,17 +403,33 @@ def checkout_com_payments_source(
if schema_name == "payments":
primary_keys = ["id"]
- partition_keys: Optional[list[str]] = ["requested_on"]
+ # The merge matches on primary key *and* partition, and every sync re-reads
+ # `requested_on` from the search index, which does not promise the same value
+ # (or any value at all) for a payment across fetches. A timestamp-keyed
+ # partition can therefore shift between two runs that cover the same payment,
+ # and the merge inserts a second copy it can never match instead of updating
+ # the first, so duplicate ids accumulate. Hashing the immutable id gives every
+ # payment one partition for good while keeping merges partition-bounded.
+ partition_keys: Optional[list[str]] = ["id"]
+ partition_mode: Optional[PartitionMode] = "md5"
+ partition_format: Optional[PartitionFormat] = None
+ partition_count: Optional[int] = PAYMENTS_PARTITION_COUNT
elif schema_name == "payment_actions":
# Action ids look globally unique, but the API doesn't document that scope,
# so the parent payment id is part of the key.
primary_keys = ["payment_id", "id"]
partition_keys = ["payment_requested_on"]
+ partition_mode = "datetime"
+ partition_format = "month"
+ partition_count = 1
else:
# Customers and instruments are point lookups keyed by their own id; they
# carry no stable creation timestamp to partition on.
primary_keys = ["id"]
partition_keys = None
+ partition_mode = None
+ partition_format = None
+ partition_count = None
return SourceResponse(
name=schema_name,
@@ -421,10 +445,10 @@ def checkout_com_payments_source(
db_incremental_field_last_value=db_incremental_field_last_value,
),
primary_keys=primary_keys,
- partition_count=1 if partition_keys else None,
+ partition_count=partition_count,
partition_size=1 if partition_keys else None,
- partition_mode="datetime" if partition_keys else None,
- partition_format="month" if partition_keys else None,
+ partition_mode=partition_mode,
+ partition_format=partition_format,
partition_keys=partition_keys,
# Windows walk oldest-first and each window is sorted before yielding, so the
# watermark only moves forward.
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 dfd73f13e584..813653e3a152 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
@@ -4,6 +4,12 @@ import pytest
from freezegun import freeze_time
from unittest import mock
+import pyarrow as pa
+
+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 (
+ append_partition_key_to_table,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
CheckoutComResumeConfig,
)
@@ -422,11 +428,60 @@ class TestReferencedRecordFanout:
assert [state.search_window_to for state in manager.saved_states] == [NOW]
+def _yielded_payment(payment_id: str, requested_on: Optional[str]) -> dict[str, Any]:
+ # The row shape the source yields: a search result with `_links` stripped; the
+ # search index doesn't guarantee `requested_on`, so None models an absent field.
+ payment = _payment(payment_id, requested_on or "")
+ if requested_on is None:
+ del payment["requested_on"]
+ return {key: value for key, value in payment.items() if key != "_links"}
+
+
+def _derived_partition_value(response, payment: dict[str, Any]) -> Optional[str]:
+ # Derive the partition exactly as setup_partitioning does for a fresh schema
+ # (partition keys fall back to the primary keys). None means the batch is written
+ # unpartitioned, where the merge matches on primary key alone.
+ result = append_partition_key_to_table(
+ table=pa.Table.from_pylist([payment]),
+ partition_count=response.partition_count,
+ partition_size=response.partition_size,
+ partition_keys=response.partition_keys or response.primary_keys,
+ partition_mode=response.partition_mode,
+ partition_format=response.partition_format,
+ logger=mock.MagicMock(),
+ )
+ if result is None:
+ return None
+ return result.table.column(PARTITION_KEY).to_pylist()[0]
+
+
+class TestPaymentsPartitionStability:
+ # The delta merge matches rows on primary key AND partition, so a payment whose
+ # derived partition differs between two runs is re-inserted instead of updated and
+ # its id duplicates. Overlapping windows are re-covered by design (budget retries,
+ # incremental re-reads), and every fetch re-reads the payment from the search index,
+ # so the partition must be a pure function of an immutable attribute of the payment.
+ @pytest.mark.parametrize(
+ "first_requested_on, second_requested_on",
+ [
+ pytest.param(None, "2024-02-29T18:00:00Z", id="requested_on-missing-then-present"),
+ pytest.param("2024-02-29T23:59:30Z", "2024-03-01T00:00:15Z", id="requested_on-drifts-across-month"),
+ ],
+ )
+ def test_same_payment_id_gets_same_partition_across_runs(self, first_requested_on, second_requested_on):
+ response = _source("payments")
+
+ first = _derived_partition_value(response, _yielded_payment("pay_dup", first_requested_on))
+ second = _derived_partition_value(response, _yielded_payment("pay_dup", second_requested_on))
+
+ assert first == second
+
+
class TestCheckoutComPaymentsSourceResponse:
@pytest.mark.parametrize(
"schema_name, primary_keys, partition_keys",
[
- ("payments", ["id"], ["requested_on"]),
+ ("payments", ["id"], ["id"]),
("payment_actions", ["payment_id", "id"], ["payment_requested_on"]),
("customers", ["id"], None),
("instruments", ["id"], None),