: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(stripe): skip line-item expansion for invoices deleted mid-sync (#72759)
Tom Owersd936d2ce7492
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.pyindex 49105359ffec..47313cfe4707 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py@@ -1,4 +1,5 @@# custom functions for stripe sources+import stripe as stripe_libfrom stripe import InvoiceService, StripeClientfrom structlog.types import FilteringBoundLogger@@ -19,22 +20,30 @@ class InvoiceListWithAllLines:for invoice in invoices.auto_paging_iter():# if there are more lines, custom iterate over the linesif invoice.lines.has_more:+ if not invoice.id:+ self.logger.warning(f"Invoice {invoice.id} has no id")+ continue+all_lines = []- if invoice.id:+ try:line_items = self.client.invoices.line_items.list(invoice=invoice.id, params={"limit": 100})for line in line_items.auto_paging_iter():all_lines.append(line)+ except stripe_lib.InvalidRequestError as e:+ # The invoice was deleted between listing it and fetching its lines (e.g. a+ # draft invoice removed mid-sync). Yield it with whatever lines it already had+ # from the initial listing rather than failing the whole import.+ if getattr(e, "code", None) != "resource_missing":+ raise+ self.logger.debug(f"Stripe: invoice {invoice.id} no longer exists, yielding with partial lines")else:- self.logger.warning(f"Invoice {invoice.id} has no id")- continue-- # number of api pages made. Each page is 100- total_line_calls += len(all_lines) // 100 + 1+ # number of api pages made. Each page is 100+ total_line_calls += len(all_lines) // 100 + 1- invoice.lines.data = all_lines- invoice.lines.has_more = False- # type is string but stripe api error message says None is the right way to set this- invoice.lines.url = None # type: ignore+ invoice.lines.data = all_lines+ invoice.lines.has_more = False+ # type is string but stripe api error message says None is the right way to set this+ invoice.lines.url = None # type: ignoreyield invoicediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.pyindex b5ff2c1555fb..6012554318c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py@@ -1,4 +1,5 @@import functools+from types import SimpleNamespacefrom typing import Any, castimport pytest@@ -23,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conSTRIPE_API_VERSION_ACACIA,SUBSCRIPTION_RESOURCE_NAME,)+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLinesfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (SUBSCRIPTION_PAGE_LIMIT,@@ -390,6 +392,47 @@ class TestStripeNestedResourceGetRows:assert {row["customer"] for row in rows} == {"cus_credit", "cus_owed"}+class TestInvoiceListWithAllLines:+ def test_skips_lines_for_invoice_deleted_mid_sync(self):+ invoices = [+ SimpleNamespace(id="in_gone", lines=SimpleNamespace(has_more=True, data=[], url="orig")),+ SimpleNamespace(id="in_ok", lines=SimpleNamespace(has_more=True, data=[], url="orig")),+ ]++ def line_items_list(invoice=None, params=None):+ if invoice == "in_gone":+ raise stripe_lib.InvalidRequestError(+ f"No such invoice: '{invoice}'", "invoice", code="resource_missing", http_status=404+ )+ return _list_object([{"id": "il_1"}])++ client = MagicMock()+ client.invoices.list.return_value = _list_object(invoices)+ client.invoices.line_items.list.side_effect = line_items_list++ result = list(InvoiceListWithAllLines(client, params={}, logger=MagicMock()).auto_paging_iter())++ assert [inv.id for inv in result] == ["in_gone", "in_ok"]+ # The deleted invoice keeps its original (incomplete) lines rather than crashing the sync.+ assert result[0].lines.has_more is True+ # The still-existing invoice gets its lines fully expanded.+ assert result[1].lines.has_more is False+ assert result[1].lines.data == [{"id": "il_1"}]++ def test_other_invalid_request_errors_still_raise(self):+ invoices = [SimpleNamespace(id="in_1", lines=SimpleNamespace(has_more=True, data=[], url="orig"))]++ def line_items_list(invoice=None, params=None):+ raise stripe_lib.InvalidRequestError("Invalid string", "expand", code="parameter_unknown", http_status=400)++ client = MagicMock()+ client.invoices.list.return_value = _list_object(invoices)+ client.invoices.line_items.list.side_effect = line_items_list++ with pytest.raises(stripe_lib.InvalidRequestError):+ list(InvoiceListWithAllLines(client, params={}, logger=MagicMock()).auto_paging_iter())++class TestSubscriptionPageSize:def test_build_resources_caps_subscription_page_size(self):# Subscriptions expand discounts at two levels, so a full DEFAULT_LIMIT page can grow past the