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(stripe): recover when a resumed listing cursor is gone (#115863)

Tom Owersd6f10d05c718
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
index 51afed0f549f..9c60a9aea039 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
@@ -1097,18 +1097,38 @@ def get_rows(
f"Stripe: skipped {skipped_parents} {resource.nested_parent_param}(s) with no nested data, saving that many API calls"
)
else:
- stripe_objects = _call_stripe(
- resource.method, params={**default_params, **resource.params, **resume_params}
- )
- for obj in stripe_objects.auto_paging_iter():
- batcher.batch(_scrub_client_secrets(obj))
-
- while batcher.should_yield():
- py_table = batcher.get_table()
- # Staged before the yield, so the commit that follows this table's write covers it.
- last_cur = py_table.column("id")[-1].as_py()
- resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))
- yield py_table
+
+ def _list_resource(params: dict[str, Any]) -> Any:
+ return _call_stripe(resource.method, params=params).auto_paging_iter()
+
+ list_params = {**default_params, **resource.params, **resume_params}
+ cursor_restarted = False
+ while True:
+ try:
+ for obj in _list_resource(list_params):
+ batcher.batch(_scrub_client_secrets(obj))
+
+ while batcher.should_yield():
+ py_table = batcher.get_table()
+ # Staged before the yield, so the commit that follows this table's write covers it.
+ last_cur = py_table.column("id")[-1].as_py()
+ resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))
+ yield py_table
+ break
+ except stripe_lib.InvalidRequestError as e:
+ # A cursor saved by a previous run (or the auto-paging cursor mid-run) can
+ # outlive the object it names, e.g. the invoice_payment it pointed at was
+ # voided between runs. Stripe can't resume pagination from a cursor it no
+ # longer has, so every retry of this job would 404 identically forever. Drop
+ # the cursor and restart the listing once instead of getting stuck.
+ if cursor_restarted or not (resume_params and _is_stripe_resource_missing_error(e)):
+ raise
+ logger.debug(
+ f"Stripe: resume cursor {resume_params['starting_after']} no longer exists, restarting {endpoint} from the beginning"
+ )
+ resume_params = {}
+ cursor_restarted = True
+ list_params = {**default_params, **resource.params}
def trailing_state(py_table: pa.Table) -> StripeResumeConfig:
if isinstance(resource, StripeNestedResource):
diff --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.py
index 2e1cbb2266db..dafbe939aeff 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
@@ -221,6 +221,80 @@ class TestStripeGetRowsIncrementalCursor:
assert len(tables) > 1
+class TestStripeFlatResourceResumeCursor:
+ def test_restarts_listing_when_resume_cursor_no_longer_exists(self):
+ # A cursor saved by a previous run can outlive the object it names (e.g. the
+ # invoice_payment it pointed at was voided between runs). Without recovery, every retry
+ # reloads the same stale cursor and 404s identically forever — this locks in restarting
+ # the listing instead of getting the job permanently stuck.
+ calls: list[dict] = []
+
+ def method(params=None):
+ calls.append(params or {})
+ if (params or {}).get("starting_after") == "inpay_gone":
+ raise stripe_lib.InvalidRequestError(
+ "No such invoice_payment: 'inpay_gone'",
+ "starting_after",
+ code="resource_missing",
+ http_status=404,
+ )
+ return cast(ListObject[Any], _FakeStripeList([{"id": "inpay_1"}, {"id": "inpay_2"}]))
+
+ resource = StripeResource(method=method)
+ resumable_source_manager = MagicMock()
+ resumable_source_manager.can_resume.return_value = True
+ resumable_source_manager.load_state.return_value = stripe_module.StripeResumeConfig(starting_after="inpay_gone")
+
+ with (
+ patch.object(stripe_module, "StripeClient"),
+ patch.object(stripe_module, "_build_resources", return_value={INVOICE_PAYMENT_RESOURCE_NAME: resource}),
+ ):
+ tables = list(
+ get_rows(
+ api_key="sk_test_123",
+ endpoint=INVOICE_PAYMENT_RESOURCE_NAME,
+ account_id=None,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ logger=MagicMock(),
+ resumable_source_manager=resumable_source_manager,
+ api_version=STRIPE_API_VERSION_ACACIA,
+ )
+ )
+
+ rows = [row for table in tables for row in table.to_pylist()]
+ assert [row["id"] for row in rows] == ["inpay_1", "inpay_2"]
+ # First call carries the stale cursor and 404s; the recovery call drops it entirely.
+ assert calls == [{"limit": DEFAULT_LIMIT, "starting_after": "inpay_gone"}, {"limit": DEFAULT_LIMIT}]
+
+ def test_other_invalid_request_errors_still_raise(self):
+ def method(params=None):
+ raise stripe_lib.InvalidRequestError("Invalid string", "expand", code="parameter_unknown", http_status=400)
+
+ resource = StripeResource(method=method)
+ resumable_source_manager = MagicMock()
+ resumable_source_manager.can_resume.return_value = True
+ resumable_source_manager.load_state.return_value = stripe_module.StripeResumeConfig(starting_after="inpay_1")
+
+ with (
+ patch.object(stripe_module, "StripeClient"),
+ patch.object(stripe_module, "_build_resources", return_value={INVOICE_PAYMENT_RESOURCE_NAME: resource}),
+ ):
+ with pytest.raises(stripe_lib.InvalidRequestError):
+ list(
+ get_rows(
+ api_key="sk_test_123",
+ endpoint=INVOICE_PAYMENT_RESOURCE_NAME,
+ account_id=None,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ logger=MagicMock(),
+ resumable_source_manager=resumable_source_manager,
+ api_version=STRIPE_API_VERSION_ACACIA,
+ )
+ )
+
+
class TestStripeSource:
def setup_method(self):
self.source = StripeSource()