: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(warehouse-sources): parallelize stripe invoice line fetches (#97803)
Daniel RC3ccc11221193
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex f685e2f3fc71..5a5a492078ba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -119,7 +119,7 @@ LOGGER = get_logger(__name__)# Cap retries at 3 in local dev so failing syncs don't loop for tens of minutes while developers# iterate; prod cadence is unchanged. Defined at module level so tests can patch them to keep the# expensive retry-exhaustion paths fast.-MAX_RESUMABLE_SOURCE_RETRIES = 3 if settings.DEBUG else 15+MAX_RESUMABLE_SOURCE_RETRIES = 3 if settings.DEBUG else 20MAX_INCREMENTAL_SOURCE_RETRIES = 3 if settings.DEBUG else 9MISSING_INTEGRATION_MESSAGE = (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 47313cfe4707..e64e7017dfb7 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,55 +1,186 @@-# custom functions for stripe sources+import time+import threading+import contextvars+from collections.abc import Callable, Iterator+from concurrent.futures import Future, ThreadPoolExecutor+from typing import Optional, ParamSpec, TypeVar+import stripe as stripe_lib-from stripe import InvoiceService, StripeClient+from stripe import Invoice, InvoiceLineItem, InvoiceService, ListObject, StripeClientfrom structlog.types import FilteringBoundLogger+# Stripe's test-mode read limit is 25 requests/s and the live-mode limit is 100. Five workers stay+# under both, and the page fetch is the longer leg of an iteration, so more would not shorten a sweep.+LINE_FETCH_CONCURRENCY = 5+# Fast responses could still let five workers exceed the test-mode limit, so request starts are paced+# independently of the worker count. The limit is per account, shared with every other caller.+LINE_REQUESTS_PER_SECOND = 20.0+# How long a 429 keeps the pool at a reduced rate when Stripe sends no Retry-After.+RATE_LIMIT_HOLD_SECONDS = 30.0++_P = ParamSpec("_P")+_T = TypeVar("_T")++# Receives the Retry-After seconds from a 429, or None when Stripe sent none.+RateLimitCallback = Callable[[Optional[float]], None]+ClientFactory = Callable[[RateLimitCallback], StripeClient]+++class _RequestPacer:+ """Spaces request starts across threads and slows the whole pool after a rate limit.++ Every worker calls wait_turn() before a request, so the pool never starts more than+ `per_second` requests in any second. A 429 halves the rate for the hold window and, when+ Stripe sends Retry-After, holds every worker until it passes, including workers already+ waiting for a slot. Each quiet window after that doubles the rate back until the base rate+ is restored.+ """++ def __init__(+ self,+ per_second: float,+ clock: Callable[[], float] = time.monotonic,+ sleep: Callable[[float], None] = time.sleep,+ ) -> None:+ self._base_interval = 1.0 / per_second+ self._interval = self._base_interval+ self._clock = clock+ self._sleep = sleep+ self._lock = threading.Lock()+ self._next_start = 0.0+ self._hold_until = 0.0+ self._recover_at: Optional[float] = None++ def wait_turn(self) -> None:+ start = self._reserve_slot()+ while True:+ delay = start - self._clock()+ if delay > 0:+ self._sleep(delay)+ with self._lock:+ if self._hold_until <= start:+ return+ # A throttle arrived during the sleep and its hold covers this slot: take a later one.+ start = self._reserve_slot()++ def _reserve_slot(self) -> float:+ with self._lock:+ now = self._clock()+ if self._recover_at is not None and now >= self._recover_at:+ self._interval = max(self._interval / 2, self._base_interval)+ self._recover_at = None if self._interval == self._base_interval else now + RATE_LIMIT_HOLD_SECONDS+ start = max(now, self._next_start)+ self._next_start = start + self._interval+ return start++ def throttled(self, retry_after: Optional[float]) -> None:+ with self._lock:+ now = self._clock()+ if now < self._hold_until:+ # Requests already in flight when the first 429 landed report the same throttle.+ return+ hold = retry_after if retry_after is not None and retry_after > 0 else RATE_LIMIT_HOLD_SECONDS+ self._interval = min(self._interval * 2, self._base_interval * 16)+ if retry_after is not None and retry_after > 0:+ self._hold_until = now + retry_after+ self._next_start = max(self._next_start, self._hold_until)+ self._recover_at = now + hold+++def _submit(pool: ThreadPoolExecutor, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]:+ """Run `fn` on the pool inside a copy of the caller's context.++ Pool threads start with an empty context, which would strip the team and job labels that the+ HTTP observer and structlog read from contextvars.+ """+ ctx = contextvars.copy_context()+ return pool.submit(lambda: ctx.run(fn, *args, **kwargs))+class InvoiceListWithAllLines:- # Invoices have a line field that is a paginated list. This list needs to be expanded for all lines to be included+ """Invoice listing that expands each invoice's line items.- def __init__(self, client: StripeClient, params: InvoiceService.ListParams, logger: FilteringBoundLogger):- self.client = client+ The list endpoint embeds at most 10 lines per invoice, so an invoice above that needs one extra+ `/lines` call. Those calls run on a small thread pool while the next page downloads. Each worker+ thread builds its own client from the factory: Stripe's RequestsClient hands a caller-supplied+ session to every thread, `requests.Session` is not documented as thread-safe, and the retrying+ client keeps per-request state. The page client comes from the same factory, so a 429 on+ either leg slows the whole pool. Invoices are yielded in list order because the+ `starting_after` resume cursor is the last yielded id.+ """++ def __init__(+ self,+ params: InvoiceService.ListParams,+ logger: FilteringBoundLogger,+ client_factory: ClientFactory,+ concurrency: int = LINE_FETCH_CONCURRENCY,+ requests_per_second: float = LINE_REQUESTS_PER_SECOND,+ ) -> None:self.params = paramsself.logger = logger+ self._client_factory = client_factory+ self._concurrency = concurrency+ self._pacer = _RequestPacer(requests_per_second)+ self._thread_clients = threading.local()- def auto_paging_iter(self):- invoices = self.client.invoices.list(params=self.params)+ def auto_paging_iter(self) -> Iterator[Invoice]:+ page_client = self._client_factory(self._pacer.throttled)+ page: ListObject[Invoice] = page_client.invoices.list(params=self.params)total_line_calls = 0invoice_count = 0- for invoice in invoices.auto_paging_iter():- # if there are more lines, custom iterate over the lines- if invoice.lines.has_more:- if not invoice.id:- self.logger.warning(f"Invoice {invoice.id} has no id")- continue-- all_lines = []- 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:- # 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-- yield invoice-- # status update every 10000 invoices- invoice_count += 1- if invoice_count % 10000 == 0:- self.logger.info(f"Stripe: processed {invoice_count} invoices")+ # The next-page fetch is submitted first, so the extra worker picks it up at once and the+ # line calls fill the others.+ pool = ThreadPoolExecutor(max_workers=self._concurrency + 1, thread_name_prefix="stripe-invoice-lines")+ try:+ while not page.is_empty:+ next_page = _submit(pool, page.next_page)+ line_futures = [+ _submit(pool, self._fetch_lines, invoice.id) if invoice.lines.has_more and invoice.id else None+ for invoice in page.data+ ]++ for invoice, future in zip(page.data, line_futures):+ if invoice.lines.has_more and future is None:+ self.logger.warning(f"Invoice {invoice.id} has no id")+ continue++ if future is not None:+ all_lines = future.result()+ if all_lines is not None:+ total_line_calls += len(all_lines) // 100 + 1+ invoice.lines.data = all_lines+ invoice.lines.has_more = False+ invoice.lines.url = None # type: ignore++ yield invoice++ invoice_count += 1+ if invoice_count % 10000 == 0:+ self.logger.info(f"Stripe: processed {invoice_count} invoices")++ page = next_page.result()+ finally:+ # The consumer may close the generator early; never block on requests still in flight.+ pool.shutdown(wait=False, cancel_futures=True)self.logger.debug(f"Stripe: made {total_line_calls} calls for invoice line items")++ def _fetch_lines(self, invoice_id: str) -> Optional[list[InvoiceLineItem]]:+ self._pacer.wait_turn()+ try:+ line_items = self._thread_client().invoices.line_items.list(invoice=invoice_id, params={"limit": 100})+ return list(line_items.auto_paging_iter())+ except stripe_lib.InvalidRequestError as e:+ if getattr(e, "code", None) != "resource_missing":+ raise+ self.logger.debug(f"Stripe: invoice {invoice_id} no longer exists, yielding with partial lines")+ return None++ def _thread_client(self) -> StripeClient:+ client: Optional[StripeClient] = getattr(self._thread_clients, "client", None)+ if client is None:+ client = self._client_factory(self._pacer.throttled)+ self._thread_clients.client = client+ return clientdiff --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 7e862f683a84..9e76dc471be1 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@@ -89,7 +89,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conTOPUP_RESOURCE_NAME,TRANSFER_RESOURCE_NAME,)-from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLines+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import (+ ClientFactory,+ InvoiceListWithAllLines,+ RateLimitCallback,+)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (APPEND_ONLY_INCREMENTAL_FIELDS,DEFAULT_PRIMARY_KEYS,@@ -224,6 +228,17 @@ def _is_non_list_stripe_response(body: Any) -> bool:return not _head_mentions_list_object(raw, start)+# Tries a 429 gets before it fails the request; the other retryable errors keep `max_network_retries`.+RATE_LIMIT_RETRIES = 5+++def _retry_after_seconds(headers: Mapping[str, str]) -> Optional[float]:+ try:+ return float(headers["retry-after"])+ except (KeyError, ValueError):+ return None++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,@@ -231,7 +246,7 @@ class _RateLimitRetryingRequestsClient(RequestsClient):straight out of ``get_rows`` and fails the whole import activity.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+ limits are absorbed in-process (bounded by ``RATE_LIMIT_RETRIES``) instead of crashing therun. We also retry a connection reset that drops the response mid-body (the SDK declines it,see ``_is_retryable_connection_reset``), a 2xx whose list body was truncated mid-stream (Stripesurfaces the latter as a JSON decode failure only after the SDK's retry loop), and a 2xx GET@@ -243,6 +258,10 @@ class _RateLimitRetryingRequestsClient(RequestsClient):# scope the non-list-body retry to reads, never a single-object write response._last_request_method: str = ""+ def __init__(self, *args: Any, on_rate_limited: Optional[RateLimitCallback] = None, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._on_rate_limited = on_rate_limited+def request( # type: ignore[override] # mirrors RequestsClient.request, which already narrows HTTPClient's (str→bytes)self,method: str,@@ -260,20 +279,27 @@ class _RateLimitRetryingRequestsClient(RequestsClient):num_retries: int,max_network_retries: Optional[int],) -> bool:+ if response is not None and response[1] == 429:+ # A throttle gets its own, larger budget so it is absorbed here, with the SDK's+ # Retry-After-aware backoff, before it costs a Temporal attempt. The pool that owns this+ # client hears about it first so every worker slows down, not only the one that was hit.+ headers = response[2] or {}+ if self._on_rate_limited is not None:+ self._on_rate_limited(_retry_after_seconds(headers))+ if str(headers.get("stripe-should-retry", "")).lower() == "false":+ return False+ return num_retries < RATE_LIMIT_RETRIESif 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 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.+ # table are 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 Falseif 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 Trueif not (200 <= status_code < 300):return Falseif _is_truncated_stripe_list_response(body):@@ -283,13 +309,13 @@ class _RateLimitRetryingRequestsClient(RequestsClient):return self._last_request_method == "get" and _is_non_list_stripe_response(body)-def _tracked_stripe_http_client() -> RequestsClient:+def _tracked_stripe_http_client(on_rate_limited: Optional[RateLimitCallback] = None) -> 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 and truncated list responses via the- SDK's built-in backoff."""- return _RateLimitRetryingRequestsClient(session=make_tracked_session())+ SDK's built-in backoff, and reports each 429 to `on_rate_limited`."""+ return _RateLimitRetryingRequestsClient(session=make_tracked_session(), on_rate_limited=on_rate_limited)def _clean_stripe_error_message(msg: str) -> str:@@ -672,7 +698,9 @@ def _batch_and_yield(def _build_resources(- client: StripeClient, logger: Optional[FilteringBoundLogger] = None+ client: StripeClient,+ logger: Optional[FilteringBoundLogger] = None,+ client_factory: Optional[ClientFactory] = None,) -> dict[str, Union[StripeResource, StripeNestedResource]]:"""Single source of truth for the resources we sync from Stripe and how they relate.@@ -680,8 +708,9 @@ def _build_resources(checks). Nested resources carry their parent on `.parent`, so callers can derive thenested→parent linkage without restating it elsewhere.- `logger` is only consumed by InvoiceListWithAllLines; pass None when the caller doesn't- need the wrapped invoice expansion (e.g. validation, which just probes the list endpoint).+ `logger` and `client_factory` are only consumed by InvoiceListWithAllLines; pass None when the+ caller doesn't need the wrapped invoice expansion (e.g. validation, which just probes the list+ endpoint). The factory gives each of its worker threads a client of its own."""return {ACCOUNT_RESOURCE_NAME: StripeResource(method=client.accounts.list),@@ -692,8 +721,8 @@ def _build_resources(INVOICE_ITEM_RESOURCE_NAME: StripeResource(method=client.invoice_items.list),INVOICE_RESOURCE_NAME: StripeResource(method=(- (lambda params: InvoiceListWithAllLines(client, params, logger)) # type: ignore- if logger is not None+ (lambda params: InvoiceListWithAllLines(params, logger, client_factory=client_factory)) # type: ignore+ if logger is not None and client_factory is not Noneelse client.invoices.list)),@@ -841,16 +870,19 @@ def get_rows(should_use_incremental_field: bool = False,warehouse_parent: Optional["ParentTableRef"] = None,):- client = StripeClient(- api_key,- stripe_account=account_id,- stripe_version=api_version,- max_network_retries=2,- base_addresses=_stripe_base_addresses(),- http_client=_tracked_stripe_http_client(),- )+ def new_client(on_rate_limited: Optional[RateLimitCallback] = None) -> StripeClient:+ return StripeClient(+ api_key,+ stripe_account=account_id,+ stripe_version=api_version,+ max_network_retries=2,+ base_addresses=_stripe_base_addresses(),+ http_client=_tracked_stripe_http_client(on_rate_limited=on_rate_limited),+ )++ client = new_client()default_params = {"limit": DEFAULT_LIMIT}- resources = _build_resources(client, logger=logger)+ resources = _build_resources(client, logger=logger, client_factory=new_client)batcher = Batcher(logger=logger, chunk_size=STRIPE_CHUNK_SIZE)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 791d40113e48..83f7acd978b8 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,7 +1,9 @@import functools+import threading+import contextvarsfrom pathlib import Pathfrom types import SimpleNamespace-from typing import Any, cast+from typing import Any, Optional, castimport pytestfrom unittest import mock@@ -75,7 +77,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conTOPUP_RESOURCE_NAME,TRANSFER_RESOURCE_NAME,)-from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLines+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import (+ InvoiceListWithAllLines,+ RateLimitCallback,+ _RequestPacer,+)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (ENDPOINTS,NON_PARTITIONED_ENDPOINTS,@@ -401,12 +407,27 @@ class TestStripeSource:((_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),+ # A 429 outlives the network-retry budget on its own, larger one...+ ((b'{\n "error": {}\n}', 429, {}), 2, True),+ ((b'{\n "error": {}\n}', 429, {}), stripe_module.RATE_LIMIT_RETRIES, False),+ # ...unless Stripe says a retry is pointless.+ ((b'{\n "error": {}\n}', 429, {"stripe-should-retry": "false"}), 0, False),],)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 test_rate_limit_client_reports_retry_after_to_the_throttle_callback(self):+ seen: list[Optional[float]] = []+ client = _RateLimitRetryingRequestsClient(on_rate_limited=seen.append)++ client._should_retry((b"{}", 429, {"retry-after": "7"}), None, num_retries=0, max_network_retries=2)+ client._should_retry((b"{}", 429, {}), None, num_retries=0, max_network_retries=2)+ client._should_retry((b"{}", 500, {}), None, num_retries=0, max_network_retries=2)++ assert seen == [7, None]+@pytest.mark.parametrize("body,expected",[@@ -646,13 +667,165 @@ class TestStripeNestedResourceGetRows:assert {row["customer"] for row in rows} == {"cus_a", "cus_b"}+def _invoice(invoice_id: Optional[str], has_more: bool = True) -> SimpleNamespace:+ return SimpleNamespace(+ id=invoice_id, lines=SimpleNamespace(has_more=has_more, data=[{"id": "embedded"}], url="orig")+ )+++class _FakeInvoicePage:+ def __init__(self, data: list[SimpleNamespace], next_page: "Optional[_FakeInvoicePage]" = None) -> None:+ self.data = data+ self._next = next_page++ @property+ def is_empty(self) -> bool:+ return not self.data++ def next_page(self) -> "_FakeInvoicePage":+ return self._next if self._next is not None else _FakeInvoicePage([])+++class TestRequestPacer:+ def _pacer(self, per_second: float = 10.0) -> tuple[_RequestPacer, dict[str, float], list[float]]:+ clock = {"now": 0.0}+ sleeps: list[float] = []+ return _RequestPacer(per_second, clock=lambda: clock["now"], sleep=sleeps.append), clock, sleeps++ def test_spaces_request_starts_at_the_base_rate(self):+ pacer, _clock, sleeps = self._pacer()++ for _ in range(3):+ pacer.wait_turn()++ assert sleeps == pytest.approx([0.1, 0.2])++ def test_a_rate_limit_holds_for_retry_after_and_halves_the_rate(self):+ pacer, _clock, sleeps = self._pacer()+ pacer.wait_turn()++ pacer.throttled(retry_after=5)+ pacer.wait_turn()+ pacer.wait_turn()++ assert sleeps == pytest.approx([5.0, 5.2])++ def test_a_rate_limit_holds_a_worker_that_already_reserved_its_slot(self):+ clock = {"now": 0.0}+ sleeps: list[float] = []++ def sleep(seconds: float) -> None:+ sleeps.append(seconds)+ clock["now"] += seconds+ if len(sleeps) == 1:+ pacer.throttled(retry_after=5)++ pacer = _RequestPacer(10.0, clock=lambda: clock["now"], sleep=sleep)+ pacer.wait_turn()+ pacer.wait_turn()++ assert sleeps == pytest.approx([0.1, 5.0])++ def test_rate_limits_reported_during_a_hold_do_not_compound(self):+ pacer, clock, sleeps = self._pacer()+ pacer.throttled(retry_after=5)+ pacer.throttled(retry_after=5)++ clock["now"] = 4.9+ pacer.wait_turn()+ pacer.wait_turn()++ assert sleeps == pytest.approx([0.1, 0.3])++ def test_the_rate_recovers_after_a_quiet_window(self):+ pacer, clock, sleeps = self._pacer()+ pacer.throttled(retry_after=None)++ clock["now"] = 31.0+ pacer.wait_turn()+ pacer.wait_turn()++ assert sleeps == pytest.approx([0.1])++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 test_expands_lines_across_pages_in_list_order(self):+ pages = _FakeInvoicePage(+ [_invoice("in_1"), _invoice("in_2", has_more=False), _invoice(None)],+ next_page=_FakeInvoicePage([_invoice("in_3")]),+ )+ client = MagicMock()+ client.invoices.list.return_value = pages+ client.invoices.line_items.list.side_effect = lambda invoice=None, params=None: _list_object(+ [{"id": f"il_{invoice}_a"}, {"id": f"il_{invoice}_b"}]+ )++ result = list(+ InvoiceListWithAllLines(+ params={}, logger=MagicMock(), client_factory=lambda _throttled: client+ ).auto_paging_iter()+ )++ assert [inv.id for inv in result] == ["in_1", "in_2", "in_3"]+ assert result[0].lines.data == [{"id": "il_in_1_a"}, {"id": "il_in_1_b"}]+ assert result[0].lines.has_more is False+ assert result[1].lines.data == [{"id": "embedded"}]+ assert result[2].lines.data == [{"id": "il_in_3_a"}, {"id": "il_in_3_b"}]++ def test_line_fetches_run_with_the_callers_context(self):+ label: contextvars.ContextVar[str] = contextvars.ContextVar("label")+ label.set("job-42")+ seen = []+ def line_items_list(invoice=None, params=None):+ seen.append(label.get(None))+ return _list_object([{"id": "il_1"}])++ client = MagicMock()+ client.invoices.list.return_value = _FakeInvoicePage([_invoice("in_1"), _invoice("in_2")])+ client.invoices.line_items.list.side_effect = line_items_list++ list(+ InvoiceListWithAllLines(+ params={}, logger=MagicMock(), client_factory=lambda _throttled: client+ ).auto_paging_iter()+ )++ assert seen == ["job-42", "job-42"]++ def test_line_fetches_overlap_across_workers_on_their_own_clients(self):+ first_started = threading.Event()+ second_finished = threading.Event()+ threads_by_client: dict[int, set[int]] = {}++ def make_client(_throttled: RateLimitCallback) -> MagicMock:+ client = MagicMock()++ def line_items_list(invoice=None, params=None):+ threads_by_client.setdefault(id(client), set()).add(threading.get_ident())+ if invoice == "in_1":+ first_started.set()+ assert second_finished.wait(2), "the second fetch never ran while the first was in flight"+ else:+ first_started.wait(2)+ second_finished.set()+ return _list_object([{"id": f"il_{invoice}"}])++ client.invoices.list.return_value = _FakeInvoicePage([_invoice("in_1"), _invoice("in_2")])+ client.invoices.line_items.list.side_effect = line_items_list+ return client++ result = list(+ InvoiceListWithAllLines(+ params={}, logger=MagicMock(), client_factory=make_client, concurrency=2+ ).auto_paging_iter()+ )++ assert [inv.lines.data for inv in result] == [[{"id": "il_in_1"}], [{"id": "il_in_2"}]]+ assert len(threads_by_client) == 2+ assert all(len(threads) == 1 for threads in threads_by_client.values())++ def test_skips_lines_for_invoice_deleted_mid_sync(self):def line_items_list(invoice=None, params=None):if invoice == "in_gone":raise stripe_lib.InvalidRequestError(@@ -661,10 +834,14 @@ class TestInvoiceListWithAllLines:return _list_object([{"id": "il_1"}])client = MagicMock()- client.invoices.list.return_value = _list_object(invoices)+ client.invoices.list.return_value = _FakeInvoicePage([_invoice("in_gone"), _invoice("in_ok")])client.invoices.line_items.list.side_effect = line_items_list- result = list(InvoiceListWithAllLines(client, params={}, logger=MagicMock()).auto_paging_iter())+ result = list(+ InvoiceListWithAllLines(+ params={}, logger=MagicMock(), client_factory=lambda _throttled: client+ ).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.@@ -674,17 +851,19 @@ class TestInvoiceListWithAllLines: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.list.return_value = _FakeInvoicePage([_invoice("in_1")])client.invoices.line_items.list.side_effect = line_items_listwith pytest.raises(stripe_lib.InvalidRequestError):- list(InvoiceListWithAllLines(client, params={}, logger=MagicMock()).auto_paging_iter())+ list(+ InvoiceListWithAllLines(+ params={}, logger=MagicMock(), client_factory=lambda _throttled: client+ ).auto_paging_iter()+ )class TestScrubClientSecrets:diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.pyindex 130c434ed4aa..e585151c9859 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_stripe_source.py@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.confrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import WEBHOOK_ONLY_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (+ RATE_LIMIT_RETRIES,StripeAuthenticationError,StripeNestedResource,StripePermissionError,@@ -706,8 +707,8 @@ def test_call_stripe_passes_through_successful_result():# (status_code, num_retries, max_network_retries, expected)# 429 is now retried while budget remains — the SDK omits this on its own.("rate_limit_retried", 429, 0, 2, True),- # ...but stops once the retry budget is exhausted, so we don't loop forever.- ("rate_limit_budget_exhausted", 429, 2, 2, False),+ # ...on its own budget, and stops once that is exhausted, so we don't loop forever.+ ("rate_limit_budget_exhausted", 429, RATE_LIMIT_RETRIES, 2, False),# 5xx keeps the SDK's built-in retry behavior.("server_error_still_retried", 503, 0, 2, True),# Non-retryable 4xx (e.g. a bad request) must NOT be retried.diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.pyindex 97c0d65c26a0..253a2f566bcb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py@@ -3986,7 +3986,7 @@ async def test_non_retryable_error_short_circuiting(team, stripe_customer, mock_# cost. Each attempt re-executes the whole import activity, so we also shrink the retry budgets# to keep the test fast: cap resumable retries at 3 and make the non-retryable path give up after# 2 attempts. The contrast (3 retryable attempts vs 2 non-retryable attempts) is what proves the- # short-circuit; the prod caps (15 / 3) are just larger values of the same mechanism.+ # short-circuit; the prod caps (20 / 3) are just larger values of the same mechanism.resumable_retry_cap = 3non_retryable_attempts = 2