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): retry a non-list list-read response instead of crashing pagination (#69217)

Tom Owers6b221b9ec417
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 c7887ae28448..13989e711f27 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
@@ -85,41 +85,84 @@ def _is_retryable_connection_reset(error: stripe_lib.APIConnectionError) -> bool
return 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.
+def _trimmed_body_bounds(body: Any) -> Optional[tuple[bytes, int, int]]:
+ """Return ``body`` as bytes plus the indices of its first and last non-whitespace byte, or
+ None when ``body`` isn't str/bytes or is empty/all-whitespace.
- 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.
- """
+ `_should_retry` runs on every successful list page during a sync, so the callers scan the head
+ and tail in place rather than `raw.strip()`-ing a full-body copy; this shares that decode-and-
+ trim step so each shape check differs only in the byte comparison that matters."""
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.
+ return None
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
+ if start > end:
+ return None
+ return raw, start, end
+
+
+def _head_mentions_list_object(raw: bytes, start: int) -> bool:
+ """Whether the object's head declares ``"object": "list"``. Matches the specific field, not
+ just the tokens "object" and "list" appearing anywhere — otherwise a single-object response
+ with "list" in a URL or type (e.g. `"type": "list.updated"`) would look like a list read."""
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
+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.
+ """
+ bounds = _trimmed_body_bounds(body)
+ if bounds is None:
+ return False
+ raw, start, end = bounds
+ if raw[start] != _OPEN_BRACE or raw[end] == _CLOSE_BRACE:
+ return False
+ return _head_mentions_list_object(raw, start)
+
+
+def _is_non_list_stripe_response(body: Any) -> bool:
+ """True when ``body`` is a *complete* JSON object that is not a Stripe ``list``.
+
+ Every bulk read we make is an idempotent ``.list()`` call, whose body is always
+ ``{"object": "list", ...}``. A 2xx whose body parses cleanly but omits that marker is a
+ corrupted/misrouted response (e.g. a proxy returning a different object). Stripe's SDK doesn't
+ validate the shape — it builds a plain ``StripeObject`` and ``auto_paging_iter`` then blows up
+ on the missing ``is_empty`` property (``KeyError: 'is_empty'``) straight out of ``get_rows``,
+ failing the whole import instead of surfacing a retryable error.
+
+ Distinct from ``_is_truncated_stripe_list_response`` (an unclosed list body): here the object
+ is closed, so we require a trailing ``}``. Callers must gate this on GET requests so a
+ single-object write response is never mistaken for a corrupt list read.
+ """
+ bounds = _trimmed_body_bounds(body)
+ if bounds is None:
+ return False
+ raw, start, end = bounds
+ # A complete JSON object opens with `{` and closes with `}`; anything else is a truncation
+ # (handled above) or a non-object body (which fails JSON decode in the SDK, not here).
+ if raw[start] != _OPEN_BRACE or raw[end] != _CLOSE_BRACE:
+ return False
+ return not _head_mentions_list_object(raw, start)
+
+
class _RateLimitRetryingRequestsClient(RequestsClient):
"""Stripe's SDK retries 409/5xx (and whatever ``Stripe-Should-Retry`` advises) but never
retries 429s on its own — ``_should_retry`` excludes them. A rate limit during a large sync,
@@ -129,11 +172,26 @@ class _RateLimitRetryingRequestsClient(RequestsClient):
Opt 429 into the SDK's existing ``Retry-After``-aware exponential backoff so transient rate
limits 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``) 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
+ see ``_is_retryable_connection_reset``), a 2xx whose list body was truncated mid-stream (Stripe
+ surfaces the latter as a JSON decode failure only after the SDK's retry loop), and a 2xx GET
+ whose body parses cleanly but isn't a Stripe list — the SDK builds a plain ``StripeObject`` and
+ ``auto_paging_iter`` then crashes on the missing ``is_empty`` property. Our Stripe reads are
list/GET calls, so retrying them is idempotent."""
+ # Records the method of the in-flight request so `_should_retry` (whose signature omits it) can
+ # scope the non-list-body retry to reads, never a single-object write response.
+ _last_request_method: str = ""
+
+ def request( # type: ignore[override] # mirrors RequestsClient.request, which already narrows HTTPClient's (str→bytes)
+ self,
+ method: str,
+ url: str,
+ headers: Optional[Mapping[str, str]],
+ post_data: Any = None,
+ ) -> tuple[bytes, int, Mapping[str, str]]:
+ self._last_request_method = (method or "").lower()
+ return super().request(method, url, headers, post_data)
+
def _should_retry(
self,
response: Optional[tuple[Any, int, Optional[Mapping[str, str]]]],
@@ -144,9 +202,10 @@ class _RateLimitRetryingRequestsClient(RequestsClient):
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 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.
+ # table are a 429 (the SDK omits it), a 2xx with a truncated or non-list body (the SDK only
+ # fails on either later — while parsing, or on `.is_empty` during pagination), 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 None:
@@ -154,7 +213,13 @@ class _RateLimitRetryingRequestsClient(RequestsClient):
body, status_code, _ = response
if status_code == 429:
return True
- return 200 <= status_code < 300 and _is_truncated_stripe_list_response(body)
+ if not (200 <= status_code < 300):
+ return False
+ if _is_truncated_stripe_list_response(body):
+ return True
+ # A complete but non-list body identifies a corrupt list read only for a GET — a write
+ # (webhook create/update/delete) legitimately returns a single object, so gate on method.
+ return self._last_request_method == "get" and _is_non_list_stripe_response(body)
def _tracked_stripe_http_client() -> RequestsClient:
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 383b934f39ed..0e2a95fa58d7 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
@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.str
StripeResource,
_all_known_webhook_events,
_coerce_incremental_cursor,
+ _is_non_list_stripe_response,
_is_truncated_stripe_list_response,
_RateLimitRetryingRequestsClient,
get_rows,
@@ -45,6 +46,9 @@ _TRUNCATED_WEBHOOK_BODY = b'{\n "object": "webhook_endpoint",\n "id": "we_1",\
_TRUNCATED_NON_LIST_WITH_LIST_TOKEN = (
b'{\n "object": "event",\n "type": "list.updated",\n "data": {\n "id": "evt_1'
)
+# A complete 2xx body returned where a list read expected `{"object": "list", ...}` — the SDK
+# builds a plain StripeObject and auto_paging_iter crashes on the missing `is_empty` property.
+_COMPLETE_NON_LIST_BODY = b'{\n "object": "customer",\n "id": "cus_1"\n}'
def _list_object(items):
@@ -259,6 +263,45 @@ class TestStripeSource:
client = _RateLimitRetryingRequestsClient()
assert client._should_retry(response, None, num_retries=num_retries, max_network_retries=2) is expected
+ @pytest.mark.parametrize(
+ "body,expected",
+ [
+ (_COMPLETE_NON_LIST_BODY, True),
+ (_COMPLETE_NON_LIST_BODY.decode(), True), # str bodies behave the same as bytes
+ (b"{}", True), # a bare object with no marker is still not a list
+ (_COMPLETE_LIST_BODY, False), # a genuine list carries "object": "list"
+ (_TRUNCATED_LIST_BODY, False), # unclosed — handled by the truncation check instead
+ (_TRUNCATED_WEBHOOK_BODY, False), # unclosed single object, not a complete body
+ (b"", False),
+ (None, False),
+ ],
+ )
+ def test_is_non_list_stripe_response(self, body, expected):
+ assert _is_non_list_stripe_response(body) is expected
+
+ @pytest.mark.parametrize(
+ "method,num_retries,expected",
+ [
+ # A GET (list read) that returns a complete non-list body is retried while budget remains.
+ ("get", 0, True),
+ # ...but not once the network-retry budget is exhausted.
+ ("get", 2, False),
+ # A write's single-object response must never be retried on shape alone.
+ ("post", 0, False),
+ ],
+ )
+ def test_rate_limit_client_retries_non_list_read_only_for_gets(self, method, num_retries, expected):
+ client = _RateLimitRetryingRequestsClient()
+ client._last_request_method = method
+ response: tuple[bytes, int, dict[str, str]] = (_COMPLETE_NON_LIST_BODY, 200, {})
+ assert client._should_retry(response, None, num_retries=num_retries, max_network_retries=2) is expected
+
+ def test_request_records_method_for_scoping(self):
+ client = _RateLimitRetryingRequestsClient()
+ with patch.object(stripe_lib.RequestsClient, "request", return_value=(b"{}", 200, {})):
+ client.request("GET", "https://api.stripe.com/v1/customers", {})
+ assert client._last_request_method == "get"
+
def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=None):
if parent_objects is None: