: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 parent objects deleted mid-sync in nested resources (#65065)
Tom Owers96c11ad5021c
diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.pyindex b06a6bffb59b..99b7e3278553 100644--- a/posthog/temporal/data_imports/sources/stripe/stripe.py+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py@@ -117,6 +117,13 @@ def _call_stripe(method: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:raise+def _is_stripe_resource_missing_error(error: stripe_lib.StripeError) -> bool:+ """True for Stripe's ``resource_missing`` 404 — e.g. a customer deleted between when we+ listed it and when we fetched its nested resources. The object is genuinely gone, so the+ caller can skip it instead of failing the whole sync."""+ return getattr(error, "code", None) == "resource_missing"++def _stripe_base_addresses() -> BaseAddresses:# Redirect Stripe API calls to a local mock (e.g. STRIPE_API_BASE=http://localhost:12111)# when running the stripe-mock dev service. No-op in production where the var is unset.@@ -267,25 +274,34 @@ def get_rows(params={**default_params, **resource.parent.params, **resume_params},)for obj in stripe_parent_objects.auto_paging_iter():- stripe_nested_objects = _call_stripe(- resource.method,- **{resource.nested_parent_param: obj[resource.parent_id]},- params={**default_params, **resource.params},- )- for nested_obj in stripe_nested_objects.auto_paging_iter(): # noqa: UP028- batcher.batch(- {- **nested_obj,- **{resource.nested_parent_param: obj[resource.parent_id]},- }+ parent_obj_id = obj[resource.parent_id]+ try:+ stripe_nested_objects = _call_stripe(+ resource.method,+ **{resource.nested_parent_param: parent_obj_id},+ params={**default_params, **resource.params},)-- if batcher.should_yield():- py_table = batcher.get_table()- yield py_table-- last_cur = py_table.column(resource.nested_parent_param)[-1].as_py()- resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))+ for nested_obj in stripe_nested_objects.auto_paging_iter():+ batcher.batch(+ {+ **nested_obj,+ **{resource.nested_parent_param: parent_obj_id},+ }+ )++ if batcher.should_yield():+ py_table = batcher.get_table()+ yield py_table++ last_cur = py_table.column(resource.nested_parent_param)[-1].as_py()+ resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))+ except stripe_lib.InvalidRequestError as e:+ # The parent was deleted between listing it and fetching its nested resources,+ # so Stripe 404s the nested call. Skip the now-gone parent and keep syncing the+ # rest rather than failing the whole import.+ if not _is_stripe_resource_missing_error(e):+ raise+ logger.debug(f"Stripe: skipping {resource.nested_parent_param}={parent_obj_id}, no longer exists")else:stripe_objects = _call_stripe(resource.method, params={**default_params, **resource.params, **resume_params}diff --git a/posthog/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/posthog/temporal/data_imports/sources/stripe/tests/test_stripe_source.pyindex 686bcea90178..5388009cc35b 100644--- a/posthog/temporal/data_imports/sources/stripe/tests/test_stripe_source.py+++ b/posthog/temporal/data_imports/sources/stripe/tests/test_stripe_source.py@@ -1,9 +1,28 @@import pytestfrom unittest import mock+from unittest.mock import MagicMock, patch++import stripe as stripe_libfrom posthog.temporal.data_imports.sources.generated_configs import StripeAuthMethodConfig, StripeSourceConfig+from posthog.temporal.data_imports.sources.stripe import stripe as stripe_module+from posthog.temporal.data_imports.sources.stripe.constants import (+ CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,+ CUSTOMER_RESOURCE_NAME,+)from posthog.temporal.data_imports.sources.stripe.source import StripeSource-from posthog.temporal.data_imports.sources.stripe.stripe import StripeAuthenticationError+from posthog.temporal.data_imports.sources.stripe.stripe import (+ StripeAuthenticationError,+ StripeNestedResource,+ StripeResource,+ get_rows,+)+++def _list_object(items):+ obj = MagicMock()+ obj.auto_paging_iter.return_value = iter(items)+ return objclass TestStripeSource:@@ -85,3 +104,61 @@ class TestStripeSource:assert message is not Noneassert pasted_secret not in messageassert message.startswith("Stripe rejected the API key.")+++def _run_nested_get_rows(nested_method):+ parent = StripeResource(+ method=lambda **kwargs: _list_object([{"id": "cus_ok1"}, {"id": "cus_gone"}, {"id": "cus_ok2"}])+ )+ resource = StripeNestedResource(+ method=nested_method,+ nested_parent_param="customer",+ parent_id="id",+ parent=parent,+ parent_name=CUSTOMER_RESOURCE_NAME,+ )++ resumable_source_manager = MagicMock()+ resumable_source_manager.can_resume.return_value = False++ with (+ patch.object(stripe_module, "StripeClient"),+ patch.object(+ stripe_module,+ "_build_resources",+ return_value={CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: resource},+ ),+ ):+ rows: list[dict] = []+ for table in get_rows(+ api_key="sk_test_123",+ endpoint=CUSTOMER_BALANCE_TRANSACTION_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,+ ):+ rows.extend(table.to_pylist())+ return rows+++class TestStripeNestedResourceGetRows:+ def test_skips_parent_deleted_mid_sync(self):+ def nested_method(customer=None, params=None):+ if customer == "cus_gone":+ raise stripe_lib.InvalidRequestError(+ f"No such customer: '{customer}'", "customer", code="resource_missing", http_status=404+ )+ return _list_object([{"id": f"cbt_{customer}", "amount": 100}])++ rows = _run_nested_get_rows(nested_method)++ assert {row["customer"] for row in rows} == {"cus_ok1", "cus_ok2"}++ def test_other_invalid_request_errors_still_raise(self):+ def nested_method(customer=None, params=None):+ raise stripe_lib.InvalidRequestError("Invalid string", "expand", code="parameter_unknown", http_status=400)++ with pytest.raises(stripe_lib.InvalidRequestError):+ _run_nested_get_rows(nested_method)