: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): key checkout.com financial actions on the action (#82099)
jake sciottobacb111da847
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.pyindex 2a741911a5e1..fd4eba6ddf70 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@@ -55,9 +55,34 @@ MAX_DISCOVERY_PAGES = 10REPORTS_METADATA_ENDPOINT = "reports"REPORT_TABLE_SUFFIX = "_report"+# Checkout.com regenerates the FinancialActions report over an overlapping date range every+# day, and every generated file carries its own `file_id`. Keyed on file position, an action+# that appears in ten daily files is retained ten times over. These report types carry a+# business key in their own columns, so they are keyed on that instead. Report types that do+# not overlap (settlement, balance breakdowns) keep the file-position key: their column sets+# are account-configurable and carry no key we can rely on.+BUSINESS_KEYED_REPORT_TABLES: dict[str, tuple[str, ...]] = {+ "financial_actions_report": ("action_id", "breakdown_type"),+ "financial_actions_by_payout_report": ("action_id", "breakdown_type"),+}+# The column a business key is meaningless without. `breakdown_type` only refines it, for the+# accounts whose template breaks an action into several rows, and the writer already drops key+# columns the data doesn't carry — so a missing `breakdown_type` degrades to keying on the+# action alone, which is correct for a template that emits one row per action.+BUSINESS_KEY_IDENTITY_COLUMN = "action_id"+logger: FilteringBoundLogger = structlog.get_logger(__name__)+class CheckoutComReportKeyError(Exception):+ """A report file lacks the columns its table is keyed on.++ Raised rather than falling back to another key: writing rows the merge cannot match+ would silently accumulate a duplicate per re-generated file, which is the failure this+ key exists to prevent.+ """++class CheckoutComReportsListingError(Exception):"""The reports listing could not be walked to completion.@@ -253,6 +278,7 @@ def _parse_report_file_rows(lines: Iterable[str],metadata: dict[str, Any],logger: FilteringBoundLogger,+ required_column: str = "",) -> Iterator[dict[str, Any]]:# `lines` is any iterator of physical CSV lines (a live response stream or a# StringIO), so a large report is parsed row-by-row without buffering the file.@@ -262,6 +288,11 @@ def _parse_report_file_rows(for row in reader:if headers is None:headers = [_normalize_header(header) for header in row]+ if required_column and required_column not in headers:+ raise CheckoutComReportKeyError(+ f"Checkout.com report file {metadata.get('file_id')} has no "+ f"{required_column!r} column, so its rows cannot be deduplicated"+ )continueif not any(cell.strip() for cell in row):continue@@ -301,6 +332,7 @@ def _report_file_rows(logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],completed_report_id: Optional[str],+ required_column: str = "",) -> Iterator[list[dict[str, Any]]]:for report in reports:report_id = str(report.get("id") or "")@@ -310,9 +342,14 @@ def _report_file_rows(raw_account = report.get("account")account: dict[str, Any] = raw_account if isinstance(raw_account, dict) else {}chunk: list[dict[str, Any]] = []- for file in report.get("files") or []:- if not isinstance(file, dict):- continue+ # Read order decides which copy of a restated row survives: the writer keeps the last+ # occurrence of a key per batch, and reports arrive oldest-first, so the newest report+ # wins. Sorting files by id makes the tie-break within one report deterministic too.+ files = sorted(+ (file for file in (report.get("files") or []) if isinstance(file, dict)),+ key=lambda file: str(file.get("id") or ""),+ )+ for file in files:file_id = str(file.get("id") or "")file_format = str(file.get("format") or "")if not file_id:@@ -339,7 +376,7 @@ def _report_file_rows(# the terminators csv needs).download.raw.decode_content = Truelines = codecs.getreader("utf-8")(download.raw)- for parsed in _parse_report_file_rows(lines, metadata, logger):+ for parsed in _parse_report_file_rows(lines, metadata, logger, required_column):chunk.append(parsed)if len(chunk) >= REPORT_CHUNK_SIZE:yield chunk@@ -412,6 +449,7 @@ def _get_rows(logger,resumable_source_manager,completed_report_id,+ BUSINESS_KEY_IDENTITY_COLUMN if schema_name in BUSINESS_KEYED_REPORT_TABLES else "",)@@ -428,9 +466,17 @@ def checkout_com_reports_source(if schema_name != REPORTS_METADATA_ENDPOINT and not schema_name.endswith(REPORT_TABLE_SUFFIX):raise ValueError(f"Unknown Checkout.com schema: {schema_name}")+ partition_keys: Optional[list[str]]if schema_name == REPORTS_METADATA_ENDPOINT:primary_keys = ["id"]partition_keys = ["created_on"]+ elif schema_name in BUSINESS_KEYED_REPORT_TABLES:+ primary_keys = list(BUSINESS_KEYED_REPORT_TABLES[schema_name])+ # The merge matches on primary key *and* partition, so partitioning these tables on+ # report creation time would put a restatement in a different partition from the row+ # it restates and insert a second copy instead of updating it. They stay unpartitioned+ # so a key matches wherever it was first written.+ partition_keys = Noneelse:# Report templates are account-configurable, so CSV columns carry no reliable# natural key; a file's contents are immutable once generated, so the position@@ -451,10 +497,10 @@ def checkout_com_reports_source(db_incremental_field_last_value=db_incremental_field_last_value,),primary_keys=primary_keys,- partition_count=1,- partition_size=1,- partition_mode="datetime",- partition_format="month",+ partition_count=1 if partition_keys else None,+ 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_keys=partition_keys,# Reports are sorted oldest-first before yielding, so the watermark only moves forward.sort_mode="asc",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.pyindex 15cf2cf405d6..a0128bf4e0f8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.py@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c)from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (MAX_DISCOVERY_PAGES,+ CheckoutComReportKeyError,CheckoutComReportsListingError,_parse_report_file_rows,checkout_com_reports_source,@@ -203,6 +204,14 @@ class TestParseReportFileRows:def test_empty_file_yields_nothing(self):assert list(_parse_report_file_rows(io.StringIO(""), {}, mock.MagicMock())) == []+ def test_missing_key_column_raises_rather_than_loading_undedupable_rows(self):+ # Without the key column the merge cannot match a restated row, so every+ # regenerated file would add another copy instead of updating one.+ text = "Payment ID,Amount\npay_1,10\n"++ with pytest.raises(CheckoutComReportKeyError):+ list(_parse_report_file_rows(io.StringIO(text), {"file_id": "file_1"}, mock.MagicMock(), "action_id"))+class TestReportsMetadataTable:@mock.patch(SESSION_PATCH)@@ -355,6 +364,38 @@ class TestReportFileSync:# No redirect means no separate download session is ever built.assert mock_make_session.call_count == 1+ @mock.patch(SESSION_PATCH)+ def test_restatements_are_read_oldest_first_so_the_newest_copy_wins(self, mock_make_session):+ # The writer keeps the last occurrence of a key in a batch, so read order decides+ # which copy of a restated action survives. Reports must be walked oldest-first and+ # files within a report in id order, whatever order the listing returned them in.+ api_session = _FakeSession(+ [+ _listing(+ [+ _report(+ "rpt_new",+ "2024-02-01T00:00:00Z",+ files=[_csv_file("file_z"), _csv_file("file_a")],+ ),+ _report("rpt_old", "2024-01-01T00:00:00Z", files=[_csv_file("file_m")]),+ ]+ ),+ _FakeResponse(text="Action ID,Amount\nact_1,10\n"),+ _FakeResponse(text="Action ID,Amount\nact_1,20\n"),+ _FakeResponse(text="Action ID,Amount\nact_1,30\n"),+ ]+ )+ mock_make_session.side_effect = [api_session]++ rows = _rows(_source("financial_actions_report"))++ assert [(row["file_id"], row["amount"]) for row in rows] == [+ ("file_m", "10"),+ ("file_a", "20"),+ ("file_z", "30"),+ ]+@pytest.mark.parametrize("location", [None, "http://files.example.com/signed"])@mock.patch(SESSION_PATCH)def test_non_https_redirect_location_raises(self, mock_make_session, location):@@ -471,7 +512,13 @@ class TestCheckoutComReportsSourceResponse:"schema_name, primary_keys, partition_keys",[("reports", ["id"], ["created_on"]),- ("financial_actions_report", ["file_id", "file_row_index"], ["report_created_on"]),+ ("balances_report", ["file_id", "file_row_index"], ["report_created_on"]),+ # Report types Checkout.com regenerates over an overlapping range key on the+ # action instead, and stay unpartitioned: the merge matches on primary key and+ # partition together, so partitioning on report creation time would put a+ # restatement in a different partition and insert a copy instead of updating.+ ("financial_actions_report", ["action_id", "breakdown_type"], None),+ ("financial_actions_by_payout_report", ["action_id", "breakdown_type"], None),],)def test_response_metadata(self, schema_name, primary_keys, partition_keys):@@ -480,7 +527,7 @@ class TestCheckoutComReportsSourceResponse:assert response.name == schema_nameassert response.primary_keys == primary_keysassert response.partition_keys == partition_keys- assert response.partition_mode == "datetime"+ assert response.partition_mode == ("datetime" if partition_keys else None)# Reports are re-sorted oldest-first before yielding, so ascending watermark# commits are safe.assert response.sort_mode == "asc"