: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): retry truncated list responses in-process (#64916)
Tom Owersaa0759db1aca
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.pyindex 4b41ea4561c0..530d1ba61c10 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@@ -57,6 +57,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.setLOGGER = get_logger(__name__)DEFAULT_LIMIT = 100+_JSON_WHITESPACE = frozenset(b" \t\n\r\f\v")+_OPEN_BRACE = ord("{")+_CLOSE_BRACE = ord("}")+def _is_retryable_connection_reset(error: stripe_lib.APIConnectionError) -> bool:"""A connection reset *mid-response* surfaces from ``requests`` as a ``ChunkedEncodingError``@@ -70,6 +74,41 @@ def _is_retryable_connection_reset(error: stripe_lib.APIConnectionError) -> boolreturn isinstance(error.__cause__, requests.exceptions.ChunkedEncodingError)+def _is_truncated_stripe_list_response(body: Any) -> bool:+ """True when ``body`` is a Stripe ``list`` response cut off before its closing brace.++ A complete Stripe JSON response always ends in ``}``. A list body that opens but never closes+ is a mid-stream truncation — a proxy or connection drop that still returned a 2xx with a+ short body. Stripe only notices while decoding it (in ``_interpret_response``, after the SDK's+ network-retry loop), where it raises ``APIError: Invalid response body from API`` straight out+ of ``get_rows``/``auto_paging_iter`` and fails the whole import.++ Scoped to list responses — every bulk read we make is an idempotent ``.list()`` call — so the+ retry never re-issues a non-idempotent webhook write, whose responses are single objects.+ """+ if isinstance(body, str):+ raw: bytes = body.encode("utf-8", "ignore")+ elif isinstance(body, bytes):+ raw = body+ else:+ return False+ # `_should_retry` runs on every successful list page during a sync, so we scan for the first+ # and last non-whitespace bytes in place rather than `raw.strip()`-ing a full-body copy.+ start = 0+ end = len(raw) - 1+ while start <= end and raw[start] in _JSON_WHITESPACE:+ start += 1+ while end >= start and raw[end] in _JSON_WHITESPACE:+ end -= 1+ if start > end or raw[start] != _OPEN_BRACE or raw[end] == _CLOSE_BRACE:+ return False+ head = raw[start : start + 64]+ # Match the specific `"object": "list"` field, not just the tokens "object" and "list"+ # appearing anywhere in the head — otherwise a truncated single-object response with "list"+ # in a URL or type (e.g. `"type": "list.updated"`) would be retried as if it were a list read.+ return b'"object": "list"' in head or b'"object":"list"' in head++class _RateLimitRetryingRequestsClient(RequestsClient):"""Stripe's SDK retries 409/5xx (and whatever ``Stripe-Should-Retry`` advises) but neverretries 429s on its own — ``_should_retry`` excludes them. A rate limit during a large sync,@@ -78,9 +117,11 @@ class _RateLimitRetryingRequestsClient(RequestsClient):Opt 429 into the SDK's existing ``Retry-After``-aware exponential backoff so transient ratelimits are absorbed in-process (bounded by ``max_network_retries``) instead of crashing the- run. We also retry a connection reset that drops the response mid-body — the SDK declines it- (see ``_is_retryable_connection_reset``). Our Stripe reads are list/GET calls, so retrying them- is idempotent."""+ run. We also retry a connection reset that drops the response mid-body (the SDK declines it,+ see ``_is_retryable_connection_reset``) and a 2xx whose list body was truncated mid-stream —+ Stripe surfaces the latter as a JSON decode failure (``Invalid response body from API``) only+ after the SDK's retry loop, too late for it to recover on its own. Our Stripe reads are+ list/GET calls, so retrying them is idempotent."""def _should_retry(self,@@ -91,21 +132,26 @@ class _RateLimitRetryingRequestsClient(RequestsClient):) -> bool:if super()._should_retry(response, api_connection_error, num_retries, max_network_retries):return True- # The base logic already enforced the retry budget and declined; the only retryable cases- # it leaves on the table are a 429 (the SDK omits it) and a connection reset mid-response- # body, both safe to retry on our idempotent list/GET calls.+ # The base logic already enforced the retry budget and declined; the cases it leaves on the+ # table are a 429 (the SDK omits it), a 2xx with a truncated list body (the SDK only fails+ # on it later, while parsing), and a connection reset that drops the response mid-body —+ # all safe to retry on our idempotent list/GET calls.if num_retries >= (max_network_retries or 0):return False- if response is not None:- return response[1] == 429- return api_connection_error is not None and _is_retryable_connection_reset(api_connection_error)+ if response is None:+ return api_connection_error is not None and _is_retryable_connection_reset(api_connection_error)+ body, status_code, _ = response+ if status_code == 429:+ return True+ return 200 <= status_code < 300 and _is_truncated_stripe_list_response(body)def _tracked_stripe_http_client() -> RequestsClient:"""Wrap a tracked `requests.Session` in Stripe's `RequestsClient` so everyStripe SDK call participates in our HTTP logging, metrics, and sample capture.- Uses a subclass that additionally retries 429 rate limits via the SDK's built-in backoff."""+ Uses a subclass that additionally retries 429 rate limits and truncated list responses via the+ SDK's built-in backoff."""return _RateLimitRetryingRequestsClient(session=make_tracked_session())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.pyindex dc7d7a3bcc19..e9fa4dba7ddd 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@@ -25,9 +25,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.strStripeResource,_all_known_webhook_events,_coerce_incremental_cursor,+ _is_truncated_stripe_list_response,+ _RateLimitRetryingRequestsClient,get_rows,)+_COMPLETE_LIST_BODY = b'{\n "object": "list",\n "data": [],\n "has_more": false\n}'+# A list page cut off mid-string — what Stripe later fails to decode as "Invalid response body".+_TRUNCATED_LIST_BODY = (+ b'{\n "object": "list",\n "data": [\n {\n "id": "in_1",\n "description": "a value that got cut'+)+# Webhook write responses are single objects, not lists — must never trigger the read-only retry.+_TRUNCATED_WEBHOOK_BODY = b'{\n "object": "webhook_endpoint",\n "id": "we_1",\n "url": "https://example.com/cut'+# A truncated single object whose head contains the tokens "object" and "list" without being a+# list response (here `"type": "list.updated"`) — must not be mistaken for a truncated list.+_TRUNCATED_NON_LIST_WITH_LIST_TOKEN = (+ b'{\n "object": "event",\n "type": "list.updated",\n "data": {\n "id": "evt_1'+)+def _list_object(items):obj = MagicMock()@@ -171,6 +186,44 @@ class TestStripeSource:assert pasted_secret not in messageassert message.startswith("Stripe rejected the API key.")+ @pytest.mark.parametrize(+ "body,expected",+ [+ (_TRUNCATED_LIST_BODY, True),+ (_TRUNCATED_LIST_BODY.decode(), True), # str bodies behave the same as bytes+ (_COMPLETE_LIST_BODY, False), # complete responses always close with "}"+ (_TRUNCATED_WEBHOOK_BODY, False), # truncated, but a single object — not a list read+ # truncated non-list whose head still contains the "object" and "list" tokens+ (_TRUNCATED_NON_LIST_WITH_LIST_TOKEN, False),+ (b'{\n "object": "webhook_endpoint",\n "id": "we_1"\n}', False),+ (b"", False),+ (None, False),+ ],+ )+ def test_is_truncated_stripe_list_response(self, body, expected):+ assert _is_truncated_stripe_list_response(body) is expected++ @pytest.mark.parametrize(+ "response,num_retries,expected",+ [+ # 2xx with a truncated list body is retried while budget remains...+ ((_TRUNCATED_LIST_BODY, 200, {}), 0, True),+ # ...but not once the network-retry budget is exhausted.+ ((_TRUNCATED_LIST_BODY, 200, {}), 2, False),+ # A complete 2xx list body is not retried.+ ((_COMPLETE_LIST_BODY, 200, {}), 0, False),+ # A truncated single-object (webhook write) body is not retried.+ ((_TRUNCATED_WEBHOOK_BODY, 200, {}), 0, False),+ # A truncated non-list body that merely mentions "list" is not retried.+ ((_TRUNCATED_NON_LIST_WITH_LIST_TOKEN, 200, {}), 0, False),+ # 429s stay retryable (regression guard for the existing rate-limit handling).+ ((b'{\n "error": {}\n}', 429, {}), 0, True),+ ],+ )+ def test_rate_limit_client_should_retry(self, response, num_retries, expected):+ client = _RateLimitRetryingRequestsClient()+ assert client._should_retry(response, None, num_retries=num_retries, max_network_retries=2) is expected+def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=None):if parent_objects is None: