: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): Checkout.com report files with a legacy column set parse to zero rows silently (#82957)
jake sciotto1d8280113274
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 fd4eba6ddf70..679e49f01ea0 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@@ -43,6 +43,11 @@ REQUEST_TIMEOUT_SECONDS = 120REPORT_FILE_TIMEOUT_SECONDS = 600# Yield parsed CSV rows in chunks rather than one list per file.REPORT_CHUNK_SIZE = 5000+# Individual rows whose width the file's own header cannot explain (e.g. an unquoted+# embedded delimiter) are skipped with a warning, but only up to this share of a+# file's data rows. Past it the file's layout is not being parsed correctly, and+# silently under-loading financial data is worse than failing the sync.+MAX_SKIPPED_ROW_RATIO = 0.1# Guard against a pagination loop (a next link that never advances) and bound how much# a single listing walks. 1000 pages is ~100k reports, centuries of daily reports; a# sync that hits it fails loudly rather than syncing a partial listing (see@@ -92,6 +97,15 @@ class CheckoutComReportsListingError(Exception):"""+class CheckoutComReportParseError(Exception):+ """A listed report file's data rows could not be parsed.++ Raised rather than warning-and-continuing: a file that yields no rows (or drops+ more than MAX_SKIPPED_ROW_RATIO of them) under-loads the table while the sync+ still reports success, which silently loses recoverable financial history.+ """++def report_type_table_name(report_type: str) -> Optional[str]:"""Stable table name for an API report type, e.g. ``FinancialActions`` -> ``financial_actions_report``.@@ -285,9 +299,16 @@ def _parse_report_file_rows(reader = csv.reader(lines)headers: Optional[list[str]] = Nonerow_index = 0+ data_row_count = 0+ skipped_row_count = 0for row in reader:if headers is None:headers = [_normalize_header(header) for header in row]+ # A trailing delimiter on the header line reads as one unnamed final+ # column; drop unnamed trailing cells so the header width means "named+ # columns" when data-row widths are checked against it.+ while headers and not headers[-1]:+ headers.pop()if required_column and required_column not in headers:raise CheckoutComReportKeyError(f"Checkout.com report file {metadata.get('file_id')} has no "@@ -296,9 +317,22 @@ def _parse_report_file_rows(continueif not any(cell.strip() for cell in row):continue- # zip would silently truncate a short row and misalign columns, corrupting the- # data; skip the malformed line instead so the failure is visible.+ data_row_count += 1+ # The file's own header row describes its data rows, but some report+ # generators make the widths disagree without changing what a row means: a+ # trailing delimiter adds an empty overflow cell to every row, and ragged+ # writers omit trailing empty fields. Normalize both to the header's width;+ # treating these layout variants as malformed once dropped whole report files+ # to zero rows.+ if len(row) > len(headers) and not any(cell.strip() for cell in row[len(headers) :]):+ row = row[: len(headers)]+ elif len(row) < len(headers):+ row = [*row, *[""] * (len(headers) - len(row))]+ # Extra cells that carry values (e.g. an unquoted embedded delimiter) cannot+ # be assigned to columns without corrupting the data; skip the malformed line+ # visibly instead.if len(row) != len(headers):+ skipped_row_count += 1logger.warning("Checkout.com report row length mismatch; skipping row",expected=len(headers),@@ -314,6 +348,21 @@ def _parse_report_file_rows(parsed["file_row_index"] = row_indexrow_index += 1yield parsed+ if data_row_count == 0:+ # Header-only (or empty) files occur by design when a report covers a period+ # with no activity; raising on them would wedge the sync permanently.+ return+ if row_index == 0:+ raise CheckoutComReportParseError(+ f"Checkout.com report file {metadata.get('file_id')} has {data_row_count} "+ "data rows but none parsed; refusing to load a listed report file as empty"+ )+ if skipped_row_count / data_row_count > MAX_SKIPPED_ROW_RATIO:+ raise CheckoutComReportParseError(+ f"Checkout.com report file {metadata.get('file_id')} skipped {skipped_row_count} "+ f"of {data_row_count} data rows (threshold {MAX_SKIPPED_ROW_RATIO:.0%}); "+ "refusing to load a partially parsed report file"+ )def _report_metadata_rows(reports: list[dict[str, Any]]) -> Iterator[list[dict[str, Any]]]: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 a0128bf4e0f8..3917c4e1aacc 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@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_cfrom products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (MAX_DISCOVERY_PAGES,CheckoutComReportKeyError,+ CheckoutComReportParseError,CheckoutComReportsListingError,_parse_report_file_rows,checkout_com_reports_source,@@ -174,8 +175,8 @@ class TestReportTypeTableName:class TestParseReportFileRows:- def test_parses_rows_with_metadata_and_skips_malformed_lines(self):- text = "Action ID,Payment ID,Report ID\nact_1,pay_1,csv_value\n\nact_2,pay_2\nact_3,pay_3,csv_value\n"+ def test_parses_current_layout_with_metadata_and_skips_blank_lines(self):+ text = "Action ID,Payment ID,Report ID\nact_1,pay_1,csv_value\n\nact_2,pay_2,csv_value\n"logger = mock.MagicMock()metadata = {"report_id": "rpt_1", "file_id": "file_1"}@@ -192,17 +193,92 @@ class TestParseReportFileRows:"file_row_index": 0,},{- "action_id": "act_3",- "payment_id": "pay_3",+ "action_id": "act_2",+ "payment_id": "pay_2","report_id": "rpt_1","file_id": "file_1","file_row_index": 1,},]+ logger.warning.assert_not_called()++ # Legacy report generators make header and data-row widths disagree without+ # changing what a row means: a trailing delimiter on every data row adds an empty+ # overflow cell, a trailing delimiter on the header line adds an unnamed column,+ # and ragged writers omit trailing empty fields. Files like these used to parse to+ # zero rows while the sync reported success.+ @pytest.mark.parametrize(+ "text, expected",+ [+ pytest.param(+ "Action ID,Amount,Payout ID\nact_1,10,pout_1,\nact_2,20,pout_2,\n",+ [("act_1", "10", "pout_1"), ("act_2", "20", "pout_2")],+ id="trailing-delimiter-on-data-rows",+ ),+ pytest.param(+ "Action ID,Amount,Payout ID,\nact_1,10,pout_1\nact_2,20,pout_2\n",+ [("act_1", "10", "pout_1"), ("act_2", "20", "pout_2")],+ id="trailing-delimiter-on-header",+ ),+ pytest.param(+ "Action ID,Amount,Payout ID\nact_1,10,pout_1\nact_2,20\n",+ [("act_1", "10", "pout_1"), ("act_2", "20", "")],+ id="ragged-rows-omit-trailing-empty-fields",+ ),+ ],+ )+ def test_width_variant_layouts_parse_all_rows(self, text, expected):+ logger = mock.MagicMock()++ rows = list(_parse_report_file_rows(io.StringIO(text), {"file_id": "file_1"}, logger))++ assert [(row["action_id"], row["amount"], row["payout_id"]) for row in rows] == expected+ assert [row["file_row_index"] for row in rows] == [0, 1]+ # Layout variants are parsed, not treated as malformed, so a large legacy file+ # doesn't emit one warning per row.+ logger.warning.assert_not_called()++ def test_malformed_row_below_skip_threshold_warns_and_keeps_the_rest(self):+ # An unquoted embedded delimiter adds a cell that carries a value, which no+ # header assignment can make safe; that row is skipped, the rest survive.+ good_rows = "\n".join(f"act_{i},{i}" for i in range(19))+ text = f"Action ID,Amount\n{good_rows}\nact_bad,1,000\n"+ logger = mock.MagicMock()++ rows = list(_parse_report_file_rows(io.StringIO(text), {"file_id": "file_1"}, logger))++ assert len(rows) == 19+ assert all(row["action_id"] != "act_bad" for row in rows)logger.warning.assert_called_once()- def test_empty_file_yields_nothing(self):- assert list(_parse_report_file_rows(io.StringIO(""), {}, mock.MagicMock())) == []+ def test_skip_ratio_above_threshold_fails_the_file(self):+ good_rows = "\n".join(f"act_{i},10" for i in range(6))+ malformed_rows = "\n".join(f"act_bad_{i},1,000" for i in range(4))+ text = f"Action ID,Amount\n{good_rows}\n{malformed_rows}\n"++ with pytest.raises(CheckoutComReportParseError, match="skipped 4 of 10"):+ list(_parse_report_file_rows(io.StringIO(text), {"file_id": "file_1"}, mock.MagicMock()))++ def test_file_whose_data_rows_all_fail_to_parse_raises(self):+ text = "Action ID,Amount\nact_1,1,000\nact_2,2,000\n"++ with pytest.raises(CheckoutComReportParseError, match="none parsed"):+ list(_parse_report_file_rows(io.StringIO(text), {"file_id": "file_1"}, mock.MagicMock()))++ # A scheduled report over a period with no activity is header-only (or empty) by+ # design, so a file with no data lines at all yields nothing rather than raising —+ # raising would wedge the sync permanently on a legitimately quiet period. Only a+ # file whose data lines exist but all fail to parse is a defect (tested above).+ @pytest.mark.parametrize(+ "text",+ [+ pytest.param("", id="zero-byte-file"),+ pytest.param("Action ID,Amount\n", id="header-only"),+ pytest.param("Action ID,Amount\n\n \n", id="header-and-blank-lines"),+ ],+ )+ def test_file_with_no_data_lines_is_empty_not_a_defect(self, text):+ assert list(_parse_report_file_rows(io.StringIO(text), {}, 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@@ -364,6 +440,23 @@ 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_file_parsing_to_zero_rows_fails_the_sync_without_checkpointing(self, mock_make_session):+ api_session = _FakeSession(+ [+ _listing([_report("rpt_1", "2024-02-01T00:00:00Z", files=[_csv_file("file_1")])]),+ _FakeResponse(text="Action ID,Amount\nact_1,1,000\n"),+ ]+ )+ mock_make_session.side_effect = [api_session]+ manager = _FakeManager()++ with pytest.raises(CheckoutComReportParseError):+ _rows(_source("financial_actions_report", manager=manager))+ # The failed report is not checkpointed, so a retry re-reads it instead of+ # resuming past data that never loaded.+ assert manager.saved_states == []+@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