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.

feat(warehouse-sources): read Stripe's balance-transaction parent from the warehouse (#88745)

Daniel RC9ae4c22716d9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py
index c1ba5157f383..a90b927db51a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py
@@ -99,6 +99,12 @@ class ParentPage:
fragment_index: int
row_offset: int
+ def position_at(
+ self, row_index: int, table: "ParentTableRef", filter_fingerprint: str | None = None
+ ) -> ScanPosition:
+ """The position of this page's row `row_index` itself, for resuming back into that row."""
+ return self.position_after(row_index - 1, table=table, filter_fingerprint=filter_fingerprint)
+
def position_after(
self, row_index: int, table: "ParentTableRef", filter_fingerprint: str | None = None
) -> ScanPosition:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
index 2072e1e1da9c..7d49d46f23b0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py
@@ -72,7 +72,14 @@ class ResumableSourceManager(Generic[ResumableData]):
except Exception as e:
raise ValueError(f"Failed to load resumable data: {data}") from e
- return self._data_class(**parsed_data)
+ # Fields the running code does not know come from state a newer deploy wrote. Dropping
+ # them makes a rollback a cache miss; passing them through raises TypeError and fails
+ # every resume until the key expires.
+ known = {field.name for field in dataclasses.fields(self._data_class)}
+ unknown = sorted(set(parsed_data) - known)
+ if unknown:
+ self._logger.debug(f"Dropping unknown resumable state fields. key={self._key}, fields={unknown}")
+ return self._data_class(**{name: value for name, value in parsed_data.items() if name in known})
def save_state(self, data: ResumableData) -> None:
with self._get_redis() as redis:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
new file mode 100644
index 000000000000..23bf0c59fcb4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py
@@ -0,0 +1,23 @@
+from unittest.mock import MagicMock, patch
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+@frozen
+class _SweepPosition:
+ cursor: str | None = None
+
+
+class TestResumableSourceManager:
+ def test_state_written_by_a_newer_deploy_still_loads(self):
+ manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)
+ redis = MagicMock()
+ redis.get.return_value = '{"cursor": "cus_1", "nested_starting_after": "txn_9"}'
+
+ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:
+ get_redis.return_value.__enter__.return_value = redis
+ state = manager.load_state()
+
+ assert state == _SweepPosition(cursor="cus_1")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/settings.py
index 6b2aa770535f..9c32634ed502 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/settings.py
@@ -4,6 +4,8 @@
# Full list of the Stripe API endpoints you can find here: https://stripe.com/docs/api.
# These endpoints are converted into ExternalDataSchema objects when a source is linked.
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (
ACCOUNT_RESOURCE_NAME,
APPLICATION_FEE_RESOURCE_NAME,
@@ -167,6 +169,32 @@ PRIMARY_KEYS: dict[str, list[str]] = {
}
DEFAULT_PRIMARY_KEYS = ["id"]
+
+@frozen
+class WarehouseParent:
+ """The parent schema a converted child reads, and the parent fields its sweep needs beyond the id."""
+
+ schema: str
+ extra_columns: list[str]
+
+
+# Nested resources that read their parent from the parent schema's synced Delta table instead of
+# re-paging the parent endpoint, mapped to the parent schema and the parent fields the sweep needs
+# beyond the id. Single source of truth: the source's `get_required_parent_schemas`, the eager
+# table resolve, and the sweep all read it, so a resource cannot be half-converted.
+#
+# Only CustomerBalanceTransaction qualifies. Its `parent_has_nested` predicate answers from the
+# parent row itself, so almost every customer is skipped without a child call and the run is
+# dominated by paging the customer listing — the shape where dropping that listing pays. Every
+# other nested resource spends one child call per parent, which makes the listing a small
+# fraction of its requests; see the verdicts recorded beside each one in `_build_resources`.
+WAREHOUSE_PARENT_FANOUT: dict[str, WarehouseParent] = {
+ CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: WarehouseParent(
+ schema=CUSTOMER_RESOURCE_NAME, extra_columns=["balance"]
+ ),
+}
+
+
APPEND_ONLY_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
ACCOUNT_RESOURCE_NAME: [
{
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
index 2fc7dc5e2b98..9c3bf7fe7eb2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
@@ -54,6 +54,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
APPEND_ONLY_INCREMENTAL_FIELDS as STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS,
DEFAULT_OFF_ENDPOINTS as STRIPE_DEFAULT_OFF_ENDPOINTS,
ENDPOINTS as STRIPE_ENDPOINTS,
+ WAREHOUSE_PARENT_FANOUT,
WEBHOOK_ONLY_ENDPOINTS as STRIPE_WEBHOOK_ONLY_ENDPOINTS,
WEBHOOK_SYNC_ONLY_ENDPOINTS as STRIPE_WEBHOOK_SYNC_ONLY_ENDPOINTS,
)
@@ -543,4 +544,16 @@ If automatic creation failed with a permissions error, the fix depends on how yo
resumable_source_manager=resumable_source_manager,
webhook_source_manager=webhook_source_manager,
api_version=self.resolve_api_version(inputs.api_version),
+ team_id=inputs.team_id,
+ source_id=inputs.source_id,
+ # Both are required for the warehouse parent path, and both default to off, so a
+ # conversion that declares a parent without threading these silently keeps polling
+ # the parent API while the fan-out telemetry reports otherwise.
+ use_warehouse_parent=inputs.fanout_warehouse_reuse,
)
+
+ def get_required_parent_schemas(self, schema_name: str) -> list[str]:
+ # These sweeps run from the SDK rather than a DependentEndpointConfig, so the dependency
+ # is read off the same declaration the resolve and the sweep read rather than derived.
+ converted = WAREHOUSE_PARENT_FANOUT.get(schema_name)
+ return [converted.schema] if converted else []
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 cb389329e0bc..4fb833ec8b5f 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
@@ -3,8 +3,8 @@ import re
import time
import inspect
import dataclasses
-from collections.abc import Callable, Mapping
-from typing import Any, Literal, Optional, Union, cast, get_args, get_type_hints
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast, get_args, get_type_hints
import orjson
import stripe as stripe_lib
@@ -16,6 +16,7 @@ from stripe._base_address import BaseAddresses
from stripe._webhook_endpoint_service import WebhookEndpointService
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
from posthog.temporal.common.logger import get_logger
from products.warehouse_sources.backend.models.external_table_definitions import (
@@ -91,9 +92,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
DEFAULT_PRIMARY_KEYS,
NON_PARTITIONED_ENDPOINTS,
PRIMARY_KEYS,
+ WAREHOUSE_PARENT_FANOUT,
WEBHOOK_ONLY_ENDPOINTS,
)
+if TYPE_CHECKING:
+ # Type-only: importing the reader eagerly would pull deltalake/pyarrow into every Stripe
+ # import, and it is only needed when a warehouse-parent sweep actually runs.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (
+ ParentTableRef,
+ ScanPosition,
+ )
+
LOGGER = get_logger(__name__)
DEFAULT_LIMIT = 100
# Subscriptions are fetched with two levels of `expand` (subscription discounts and per-line-item
@@ -456,9 +466,23 @@ def _payment_method_history_snapshot_row(row: dict[str, Any]) -> dict[str, Any]:
}
+@frozen
class StripeResumeConfig:
- starting_after: str
+ """Where a sweep stopped, in whichever coordinate system it was walking.
+
+ `starting_after` is a Stripe list cursor and only means anything against Stripe's own
+ ordering, so it cannot carry over to a warehouse parent scan (and vice versa). The
+ warehouse fields are the `ScanPosition` triple; a run that finds the wrong kind of state,
+ or state from another table, version or filter, discards it and starts the sweep over.
+ """
+
+ starting_after: str | None = None
+ nested_parent_id: str | None = None
+ nested_starting_after: str | None = None
+ warehouse_fragment_index: int | None = None
+ warehouse_row_offset: int | None = None
+ warehouse_table_uri: str | None = None
+ warehouse_version: int | None = None
def _scrub_client_secrets(obj: Any) -> Any:
@@ -483,6 +507,146 @@ def _scrub_client_secrets(obj: Any) -> Any:
return obj
+class _WarehouseParentRows:
+ """Parent rows streamed from the parent schema's Delta table, tracking where it is.
+
+ Iterating yields the same plain dicts the Stripe listing yields, so the sweep body is
+ identical on both paths. `position_after_current` is the coordinate to resume from once
+ the row just yielded is finished with — the warehouse analogue of `starting_after`.
+ `position_at_current` points at that row instead, for re-entering a parent whose own
+ pages were only half read.
+ """
+
+ def __init__(
+ self,
+ table: "ParentTableRef",
+ columns: list[str],
+ page_size: int,
+ schema_name: str,
+ parent_name: str,
+ start_position: Optional["ScanPosition"],
+ ) -> None:
+ self._table = table
+ self._columns = columns
+ self._parent_name = parent_name
+ self._page_size = page_size
+ self._schema_name = schema_name
+ self._start_position = start_position
+ self.position_at_current: Optional[ScanPosition] = None
+ self.position_after_current: Optional[ScanPosition] = None
+
+ def __iter__(self) -> Iterator[dict[str, Any]]:
+ # noqa reason: keeps deltalake/pyarrow off the import path of the Stripe module — the
+ # reader stack loads only when a warehouse-parent sweep actually runs.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import ( # noqa: PLC0415
+ iter_parent_pages_with_positions,
+ )
+
+ for page in iter_parent_pages_with_positions(
+ table=self._table,
+ parent_name=self._parent_name,
+ columns=self._columns,
+ page_size=self._page_size,
+ schema_name=self._schema_name,
+ start_position=self._start_position,
+ ):
+ for index, row in enumerate(page.rows):
+ self.position_at_current = page.position_at(index, table=self._table)
+ self.position_after_current = page.position_after(index, table=self._table)
+ yield row
+
+
+def _resume_state(position: Optional["ScanPosition"], parent_id: Optional[str]) -> StripeResumeConfig:
+ """Resume state in whichever coordinate system this sweep is walking."""
+ if position is not None:
+ return StripeResumeConfig(
+ warehouse_fragment_index=position.fragment_index,
+ warehouse_row_offset=position.row_offset,
+ warehouse_table_uri=position.table_uri,
+ warehouse_version=position.version,
+ )
+ return StripeResumeConfig(starting_after=parent_id)
+
+
+def _nested_checkpoint(
+ py_table: pa.Table,
+ parent_param: str,
+ in_flight_parent: str,
+ parent_pages: Optional["_WarehouseParentRows"],
+ last_finished_parent: Optional[str],
+) -> Optional[StripeResumeConfig]:
+ """Where to restart after yielding `py_table`, or None when this chunk cannot name a position.
+
+ A chunk that ends inside the parent still being paginated has to re-enter that parent. Skipping
+ an unfinished parent drops the rest of its rows for good, while re-entering one that turns out
+ to be exhausted costs a single empty call.
+ """
+ chunk_parent = py_table.column(parent_param)[-1].as_py()
+ if chunk_parent != in_flight_parent:
+ # Only a split batch ends a chunk on an earlier parent, whose position is no longer to
+ # hand. Leave the previous checkpoint alone rather than claim progress past rows this
+ # drain has not yielded yet.
+ return None
+ if "id" not in py_table.column_names:
+ # Without an id there is no cursor into the parent's own pages, so the sweep can only move
+ # past it. The one resource in this shape returns a single row per parent, which is
+ # therefore finished by the time that row is written.
+ return _resume_state(parent_pages.position_after_current if parent_pages else None, chunk_parent)
+ return dataclasses.replace(
+ _resume_state(parent_pages.position_at_current if parent_pages else None, last_finished_parent),
+ nested_parent_id=chunk_parent,
+ nested_starting_after=py_table.column("id")[-1].as_py(),
+ )
+
+
+def _trusted_nested_resume(
+ resume_config: Optional[StripeResumeConfig],
+ warehouse_start: Optional["ScanPosition"],
+ from_warehouse: bool,
+) -> Optional[StripeResumeConfig]:
+ """`resume_config` when its nested cursor can still be trusted, else None.
+
+ A nested cursor only means anything beside the parent cursor it was saved with. Whenever that
+ parent cursor is discarded — state from the other coordinate system, or from another table or
+ version — the sweep restarts from the first parent, and a cursor into some parent's pages
+ would then skip rows this run has not written.
+ """
+ if resume_config is None or resume_config.nested_parent_id is None:
+ return None
+ if from_warehouse:
+ return resume_config if warehouse_start is not None else None
+ return resume_config if resume_config.warehouse_fragment_index is None else None
+
+
+def _warehouse_start_position(
+ resume_config: Optional[StripeResumeConfig], table: "ParentTableRef"
+) -> Optional["ScanPosition"]:
+ """A stored warehouse position, if it is still safe to resume from.
+
+ Discards state saved against another table, version or coordinate system — including
+ `starting_after` cursors from a run that took the API path, which name a place in Stripe's
+ ordering and mean nothing here. A discarded position restarts the sweep rather than
+ resuming somewhere arbitrary.
+ """
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import ( # noqa: PLC0415
+ ScanPosition,
+ )
+
+ if resume_config is None or resume_config.warehouse_fragment_index is None:
+ return None
+ if resume_config.warehouse_row_offset is None or resume_config.warehouse_table_uri is None:
+ return None
+ if resume_config.warehouse_version is None:
+ return None
+ position = ScanPosition(
+ fragment_index=resume_config.warehouse_fragment_index,
+ row_offset=resume_config.warehouse_row_offset,
+ table_uri=resume_config.warehouse_table_uri,
+ version=resume_config.warehouse_version,
+ )
+ return position if position.matches(table, None) else None
+
+
def _batch_and_yield(
objects: Any,
batcher: Batcher,
@@ -551,6 +715,9 @@ def _build_resources(
),
CREDIT_NOTE_RESOURCE_NAME: StripeResource(method=client.credit_notes.list),
COUPON_RESOURCE_NAME: StripeResource(method=client.coupons.list),
+ # The one nested resource that reads its parent from the warehouse. Its skip predicate
+ # answers from the parent row itself, so a run is dominated by paging the customer
+ # listing rather than by child calls — the shape where dropping the listing pays.
CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: StripeNestedResource(
method=client.customers.balance_transactions.list,
nested_parent_param="customer",
@@ -559,6 +726,9 @@ def _build_resources(
parent_name=CUSTOMER_RESOURCE_NAME,
parent_has_nested=_customer_might_have_balance_transactions,
),
+ # Stays on the parent API: one child call per customer with no skip signal, so the
+ # listing is a small fraction of the run and reusing the parent table saves ~nothing.
+ # Its cost needs a skip signal or webhook-driven sync, not parent reuse.
CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: StripeNestedResource(
method=client.customers.payment_methods.list,
nested_parent_param="customer",
@@ -593,6 +763,8 @@ def _build_resources(
EVENT_RESOURCE_NAME: StripeResource(method=client.events.list),
BILLING_METER_RESOURCE_NAME: StripeResource(method=client.billing.meters.list),
BILLING_CREDIT_GRANT_RESOURCE_NAME: StripeResource(method=client.billing.credit_grants.list),
+ # Stays on the parent API: the credit-grant listing fits in one page, so there is
+ # no listing cost to remove.
BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: StripeNestedResource(
method=_credit_balance_transaction_lister(client),
nested_parent_param="credit_grant",
@@ -614,6 +786,7 @@ def _build_resources(
SHIPPING_RATE_RESOURCE_NAME: StripeResource(method=client.shipping_rates.list),
# `/v1/subscription_items` requires a `subscription`, so it fans out over subscriptions. The
# parent list skips the discount expansions the Subscription table uses — we only need ids.
+ # Stays on the parent API: one call per subscription, no skip signal, so the listing is a small fraction of the run.
SUBSCRIPTION_ITEM_RESOURCE_NAME: StripeNestedResource(
method=client.subscription_items.list,
nested_parent_param="subscription",
@@ -622,6 +795,7 @@ def _build_resources(
parent_name=SUBSCRIPTION_RESOURCE_NAME,
),
# `/v1/entitlements/active_entitlements` requires a `customer`.
+ # Stays on the parent API: one call per customer, no skip signal, so the listing is a small fraction of the run.
ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME: StripeNestedResource(
method=client.entitlements.active_entitlements.list,
nested_parent_param="customer",
@@ -629,6 +803,8 @@ def _build_resources(
parent=StripeResource(method=client.customers.list),
parent_name=CUSTOMER_RESOURCE_NAME,
),
+ # Stays on the parent API: the credit-grant listing fits in one page, so there is
+ # no listing cost to remove.
BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME: StripeNestedResource(
method=_credit_balance_summary_lister(client),
nested_parent_param="credit_grant",
@@ -639,6 +815,7 @@ def _build_resources(
nested_params_from_parent=_credit_grant_customer_params,
),
# `/v1/setup_attempts` requires a `setup_intent`.
+ # Stays on the parent API: one call per setup intent, no skip signal, so the listing is a small fraction of the run.
SETUP_ATTEMPT_RESOURCE_NAME: StripeNestedResource(
method=client.setup_attempts.list,
nested_parent_param="setup_intent",
@@ -659,6 +836,7 @@ def get_rows(
resumable_source_manager: ResumableSourceManager[StripeResumeConfig],
api_version: str,
should_use_incremental_field: bool = False,
+ warehouse_parent: Optional["ParentTableRef"] = None,
):
client = StripeClient(
api_key,
@@ -699,16 +877,39 @@ def get_rows(
or isinstance(resource, StripeNestedResource)
):
logger.debug(f"Stripe: iterating all objects from resource")
+ # Set only on the nested warehouse path; the final flush below is shared with flat
+ # resources, which have no parent sweep to checkpoint.
+ parent_pages: Optional[_WarehouseParentRows] = None
resume_params = {}
- if resume_config is not None:
+ if resume_config is not None and resume_config.starting_after is not None:
resume_params = {"starting_after": resume_config.starting_after}
logger.debug(f"Stripe: resuming from object id: {resume_config.starting_after}")
if isinstance(resource, StripeNestedResource):
- stripe_parent_objects = _call_stripe(
- resource.parent.method,
- params={**default_params, **resource.parent.params, **resume_params},
+ # Reading the parent from its synced table replaces the whole paged listing with
+ # one filtered scan. Everything downstream — the skip predicate, the child call,
+ # the 404 skip, the row stamping — is untouched: only where parent rows come from
+ # changes, and an unresolved table leaves this on the API path exactly as before.
+ parent_rows: Iterable[dict[str, Any]]
+ warehouse_start = (
+ _warehouse_start_position(resume_config, warehouse_parent) if warehouse_parent is not None else None
)
+ if warehouse_parent is not None:
+ converted = WAREHOUSE_PARENT_FANOUT[endpoint]
+ parent_pages = _WarehouseParentRows(
+ table=warehouse_parent,
+ columns=[resource.parent_id, *converted.extra_columns],
+ page_size=DEFAULT_LIMIT,
+ schema_name=endpoint,
+ parent_name=converted.schema,
+ start_position=warehouse_start,
+ )
+ parent_rows = parent_pages
+ else:
+ parent_rows = _call_stripe(
+ resource.parent.method,
+ params={**default_params, **resource.parent.params, **resume_params},
+ ).auto_paging_iter()
# Path-scoped services (e.g. customers.payment_methods.list) take the parent id as a
# method keyword, while flat services with a required filter (e.g.
# entitlements.active_entitlements.list) accept it only inside `params`. Route by the
@@ -716,8 +917,14 @@ def get_rows(
parent_param_is_kwarg = resource.nested_parent_param in inspect.signature(resource.method).parameters
skipped_parents = 0
parents_since_checkpoint = 0
- last_finished_parent: Optional[str] = None
- for obj in stripe_parent_objects.auto_paging_iter():
+ # Seeded from where this run started, so an interruption before any parent finishes
+ # checkpoints there rather than back at the first parent.
+ last_finished_parent: Optional[str] = resume_config.starting_after if resume_config else None
+ last_finished_position: Optional[ScanPosition] = warehouse_start
+ nested_resume = _trusted_nested_resume(
+ resume_config, warehouse_start, from_warehouse=warehouse_parent is not None
+ )
+ for obj in parent_rows:
# Checkpoint the sweep's position through the parent list every so often. The only
# other checkpoint fires when a chunk fills, which for a sparse nested resource
# (most customers have no payment methods) can take the entire customer base — so a
@@ -728,19 +935,24 @@ def get_rows(
if parents_since_checkpoint >= NESTED_SWEEP_CHECKPOINT_PARENTS and last_finished_parent is not None:
while batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
- resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_finished_parent))
+ resumable_source_manager.save_state(_resume_state(last_finished_position, last_finished_parent))
parents_since_checkpoint = 0
parent_obj_id = obj[resource.parent_id]
parents_since_checkpoint += 1
+ nested_resume_params: dict[str, Any] = {}
+ if nested_resume is not None and parent_obj_id == nested_resume.nested_parent_id:
+ nested_resume_params = {"starting_after": nested_resume.nested_starting_after}
+ nested_resume = None
# Skip parents that a cheap signal on the parent object rules out — avoids one empty
# nested call per parent (the bulk of Stripe API volume for these resources).
if resource.parent_has_nested is not None and not resource.parent_has_nested(obj):
skipped_parents += 1
last_finished_parent = parent_obj_id
+ last_finished_position = parent_pages.position_after_current if parent_pages else None
continue
parent_params = resource.nested_params_from_parent(obj) if resource.nested_params_from_parent else {}
- nested_params = {**default_params, **resource.params, **parent_params}
+ nested_params = {**default_params, **resource.params, **parent_params, **nested_resume_params}
nested_kwargs: dict[str, Any] = {}
if parent_param_is_kwarg:
nested_kwargs[resource.nested_parent_param] = parent_obj_id
@@ -768,8 +980,15 @@ def get_rows(
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))
+ checkpoint = _nested_checkpoint(
+ py_table,
+ resource.nested_parent_param,
+ parent_obj_id,
+ parent_pages,
+ last_finished_parent,
+ )
+ if checkpoint is not None:
+ resumable_source_manager.save_state(checkpoint)
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
@@ -780,6 +999,7 @@ def get_rows(
# Reached whether the nested call succeeded or the parent had vanished: either way
# this parent contributes nothing further, so the sweep may resume after it.
last_finished_parent = parent_obj_id
+ last_finished_position = parent_pages.position_after_current if parent_pages else None
if skipped_parents:
logger.debug(
f"Stripe: skipped {skipped_parents} {resource.nested_parent_param}(s) with no nested data, saving that many API calls"
@@ -807,7 +1027,9 @@ def get_rows(
else:
last_cur = py_table.column("id")[-1].as_py()
- resumable_source_manager.save_state(StripeResumeConfig(starting_after=last_cur))
+ resumable_source_manager.save_state(
+ _resume_state(parent_pages.position_after_current if parent_pages else None, last_cur)
+ )
return
@@ -918,6 +1140,37 @@ def _webhook_history_table_transformer(table: pa.Table) -> pa.Table:
return table_from_py_list(list(rows.values()))
+def _resolve_warehouse_parent(
+ endpoint: str,
+ team_id: Optional[int],
+ source_id: Optional[str],
+ use_warehouse_parent: bool,
+) -> Optional["ParentTableRef"]:
+ """The parent's Delta table for this sweep, or None to page the parent endpoint instead.
+
+ Resolved here rather than inside the sweep because this runs in sync source-build context:
+ it reads the ORM, and the pipeline's iterator threads are the wrong place for ad-hoc DB
+ connections. Resolving eagerly also pins the parent's version for the whole fan-out and
+ validates the projected columns while falling back to the API is still possible.
+ """
+ if not use_warehouse_parent or endpoint not in WAREHOUSE_PARENT_FANOUT or team_id is None or not source_id:
+ return None
+
+ # noqa reason: keeps deltalake/pyarrow off the import path of every Stripe import.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import ( # noqa: PLC0415
+ try_resolve_parent_table,
+ )
+
+ converted = WAREHOUSE_PARENT_FANOUT[endpoint]
+ return try_resolve_parent_table(
+ team_id=team_id,
+ source_id=source_id,
+ parent_name=converted.schema,
+ required_columns=["id", *converted.extra_columns],
+ schema_name=endpoint,
+ )
+
+
def stripe_source(
api_key: str,
account_id: Optional[str],
@@ -929,6 +1182,9 @@ def stripe_source(
webhook_source_manager: WebhookSourceManager,
api_version: str,
should_use_incremental_field: bool = False,
+ team_id: Optional[int] = None,
+ source_id: Optional[str] = None,
+ use_warehouse_parent: bool = False,
):
# Only the endpoints with a PostHog-managed canonical schema have column hints; the rest let the
# pipeline infer their columns from the rows Stripe returns.
@@ -945,6 +1201,7 @@ def stripe_source(
# re-enable — a poll could never rebuild the table.
webhook_only = endpoint in WEBHOOK_ONLY_ENDPOINTS
webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=webhook_only)
+ warehouse_parent = _resolve_warehouse_parent(endpoint, team_id, source_id, use_warehouse_parent)
def items():
if webhook_enabled:
@@ -967,6 +1224,7 @@ def stripe_source(
should_use_incremental_field=should_use_incremental_field,
resumable_source_manager=resumable_source_manager,
api_version=api_version,
+ warehouse_parent=warehouse_parent,
)
# A few Stripe objects carry no timestamp at all, so there is nothing to partition on — the
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 9b7fb8aeb12e..83f8811b50bb 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
@@ -11,11 +11,16 @@ from django.conf import settings
import orjson
import stripe as stripe_lib
+import pyarrow as pa
+import deltalake
from parameterized import parameterized
from stripe import ListObject
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (
+ ParentTableRef,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stripe import (
StripeAuthMethodConfig,
@@ -416,10 +421,51 @@ class TestStripeSource:
assert client._last_request_method == "get"
-def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=None, resumable_source_manager=None):
+def _recording_nested_method(missing=()):
+ """A nested list method that records the parents it was called for.
+
+ A real function rather than a mock: the sweep routes the parent id by inspecting the
+ method's signature, so a signature-less mock would receive it inside `params` instead and
+ the test would not exercise the path production takes.
+ """
+ probed: list[str] = []
+
+ def _nested(customer, params):
+ probed.append(customer)
+ if customer in missing:
+ raise stripe_lib.InvalidRequestError("No such customer", param="customer", code="resource_missing")
+ return _list_object([{"id": f"cbt_{customer}"}])
+
+ return _nested, probed
+
+
+def _write_customer_parent_table(tmp_path, customers) -> str:
+ """The parent schema's synced Delta table, as the warehouse path would find it."""
+ uri = str(tmp_path / "stripe_customer")
+ deltalake.write_deltalake(
+ uri,
+ pa.table(
+ {
+ "id": [customer["id"] for customer in customers],
+ "balance": [customer.get("balance") for customer in customers],
+ }
+ ),
+ )
+ return uri
+
+
+def _run_nested_get_rows(
+ nested_method,
+ parent_objects=None,
+ parent_has_nested=None,
+ resumable_source_manager=None,
+ warehouse_parent=None,
+ parent_method=None,
+ can_resume=False,
+):
if parent_objects is None:
parent_objects = [{"id": "cus_ok1"}, {"id": "cus_gone"}, {"id": "cus_ok2"}]
- parent = StripeResource(method=lambda **kwargs: _list_object(parent_objects))
+ parent = StripeResource(method=parent_method or (lambda **kwargs: _list_object(parent_objects)))
resource = StripeNestedResource(
method=nested_method,
nested_parent_param="customer",
@@ -431,7 +477,7 @@ def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=N
if resumable_source_manager is None:
resumable_source_manager = MagicMock()
- resumable_source_manager.can_resume.return_value = False
+ resumable_source_manager.can_resume.return_value = can_resume
with (
patch.object(stripe_module, "StripeClient"),
@@ -451,6 +497,7 @@ def _run_nested_get_rows(nested_method, parent_objects=None, parent_has_nested=N
logger=MagicMock(),
resumable_source_manager=resumable_source_manager,
api_version=STRIPE_API_VERSION_ACACIA,
+ warehouse_parent=warehouse_parent,
):
rows.extend(table.to_pylist())
return rows
@@ -1460,3 +1507,323 @@ class TestStripeAppManifestCoversSourcePermissions:
assert required, "PERMISSIONS is empty, so this assertion would pass vacuously"
assert required - granted == set()
+
+
+class TestStripeWarehouseParentFanout:
+ """The `CustomerBalanceTransaction` sweep reading its parent from the warehouse."""
+
+ @parameterized.expand(
+ [
+ (CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME, [CUSTOMER_RESOURCE_NAME]),
+ (CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME, []),
+ (CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME, []),
+ (ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME, []),
+ (BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME, []),
+ (CUSTOMER_RESOURCE_NAME, []),
+ ]
+ )
+ def test_only_the_converted_child_declares_a_warehouse_parent(self, schema_name, expected):
+ # The checked statement of which children opted in — the blast radius a reviewer reads.
+ assert StripeSource().get_required_parent_schemas(schema_name) == expected
+
+ def test_the_sweep_never_pages_the_customer_listing(self, tmp_path):
+ # The silent-no-op guard. Declaring a parent without threading the flag and source id
+ # leaves the sweep on the API path while the fan-out telemetry reports "warehouse", so
+ # the test asserts the listing method is not merely unnecessary but never called.
+ uri = _write_customer_parent_table(tmp_path, [{"id": "cus_1", "balance": -500}])
+ parent_method = MagicMock(side_effect=AssertionError("the parent listing must not be paged"))
+ nested_method = MagicMock(return_value=_list_object([{"id": "cbt_1"}]))
+
+ rows = _run_nested_get_rows(
+ nested_method,
+ parent_method=parent_method,
+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),
+ )
+
+ parent_method.assert_not_called()
+ assert [row["id"] for row in rows] == ["cbt_1"]
+
+ def test_both_parent_paths_emit_identical_rows(self, tmp_path):
+ # Parity is the property that matters: the child's output must not depend on where its
+ # parent rows came from, including the parent id stamped onto every row.
+ customers = [{"id": "cus_1", "balance": -500}, {"id": "cus_2", "balance": 250}]
+ uri = _write_customer_parent_table(tmp_path, customers)
+
+ api_method, _ = _recording_nested_method()
+ warehouse_method, _ = _recording_nested_method()
+
+ api_rows = _run_nested_get_rows(api_method, parent_objects=customers)
+ warehouse_rows = _run_nested_get_rows(
+ warehouse_method,
+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),
+ )
+
+ assert warehouse_rows == api_rows
+ assert [row["customer"] for row in warehouse_rows] == ["cus_1", "cus_2"]
+
+ def test_the_skip_predicate_reads_the_balance_off_the_warehouse_row(self, tmp_path):
+ # The projected `balance` column is what makes this conversion worth doing: without it
+ # every customer would be probed, turning a listing-dominated run into one call each.
+ customers = [
+ {"id": "cus_zero", "balance": 0},
+ {"id": "cus_credit", "balance": -500},
+ {"id": "cus_unknown", "balance": None},
+ ]
+ uri = _write_customer_parent_table(tmp_path, customers)
+ nested_method, probed = _recording_nested_method()
+
+ _run_nested_get_rows(
+ nested_method,
+ parent_has_nested=stripe_module._customer_might_have_balance_transactions,
+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),
+ )
+
+ assert probed == ["cus_credit", "cus_unknown"]
+
+ def test_a_parent_deleted_since_the_snapshot_is_skipped(self, tmp_path):
+ # The snapshot can name customers deleted upstream since the parent last synced. Their
+ # child call 404s, and the sweep must carry on rather than failing the whole import.
+ customers = [{"id": "cus_ok", "balance": -1}, {"id": "cus_gone", "balance": -1}]
+ uri = _write_customer_parent_table(tmp_path, customers)
+
+ nested_method, probed = _recording_nested_method(missing={"cus_gone"})
+
+ rows = _run_nested_get_rows(
+ nested_method,
+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),
+ )
+
+ assert [row["id"] for row in rows] == ["cbt_cus_ok"]
+ assert probed == ["cus_ok", "cus_gone"]
+
+ def test_resume_state_records_the_scan_position_not_a_stripe_cursor(self, tmp_path):
+ # A Stripe cursor names a place in Stripe's list ordering, which a parquet scan does not
+ # have. Saving one here would resume the next run somewhere arbitrary.
+ uri = _write_customer_parent_table(tmp_path, [{"id": "cus_1", "balance": -500}])
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ _run_nested_get_rows(
+ MagicMock(return_value=_list_object([{"id": "cbt_1"}])),
+ resumable_source_manager=manager,
+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),
+ )
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved, "the sweep must checkpoint at least once"
+ assert all(state.starting_after is None for state in saved)
+ assert all(state.warehouse_table_uri == uri for state in saved)
+ assert all(state.warehouse_fragment_index is not None for state in saved)
+
+ @parameterized.expand(
+ [
+ ("api_cursor", {"starting_after": "cus_1"}),
+ (
+ "another_table",
+ {
+ "warehouse_fragment_index": 0,
+ "warehouse_row_offset": 1,
+ "warehouse_table_uri": "s3://elsewhere",
+ "warehouse_version": 0,
+ },
+ ),
+ ("another_version", {"warehouse_fragment_index": 0, "warehouse_row_offset": 1, "warehouse_version": 99}),
+ ]
+ )
+ def test_unusable_resume_state_restarts_the_sweep(self, _name, state_kwargs, tmp_path=None):
+ # Delta versions restart at 0 when a table is rebuilt, so a position from another table
+ # or version would skip rows the scan has never read. Restarting is the safe answer.
+ import tempfile
+
+ directory = Path(tempfile.mkdtemp())
+ customers = [{"id": "cus_1", "balance": -1}, {"id": "cus_2", "balance": -1}]
+ uri = _write_customer_parent_table(directory, customers)
+ if "warehouse_table_uri" in state_kwargs and state_kwargs["warehouse_table_uri"] != "s3://elsewhere":
+ state_kwargs["warehouse_table_uri"] = uri
+ elif "warehouse_version" in state_kwargs and "warehouse_table_uri" not in state_kwargs:
+ state_kwargs["warehouse_table_uri"] = uri
+
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = stripe_module.StripeResumeConfig(**state_kwargs)
+
+ nested_method, _ = _recording_nested_method()
+ rows = _run_nested_get_rows(
+ nested_method,
+ resumable_source_manager=manager,
+ warehouse_parent=ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()),
+ can_resume=True,
+ )
+
+ assert [row["id"] for row in rows] == ["cbt_cus_1", "cbt_cus_2"]
+
+ def test_a_matching_position_resumes_after_the_parent_it_names(self, tmp_path):
+ customers = [{"id": "cus_1", "balance": -1}, {"id": "cus_2", "balance": -1}, {"id": "cus_3", "balance": -1}]
+ uri = _write_customer_parent_table(tmp_path, customers)
+ version = deltalake.DeltaTable(uri).version()
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = stripe_module.StripeResumeConfig(
+ warehouse_fragment_index=0,
+ warehouse_row_offset=1,
+ warehouse_table_uri=uri,
+ warehouse_version=version,
+ )
+
+ nested_method, _ = _recording_nested_method()
+ rows = _run_nested_get_rows(
+ nested_method,
+ resumable_source_manager=manager,
+ warehouse_parent=ParentTableRef(uri=uri, version=version),
+ can_resume=True,
+ )
+
+ assert [row["id"] for row in rows] == ["cbt_cus_2", "cbt_cus_3"]
+
+ @parameterized.expand(
+ [
+ ("flag_off", False, CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME),
+ ("unconverted_endpoint", True, CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME),
+ ]
+ )
+ def test_resolve_returns_nothing_when_the_warehouse_path_does_not_apply(self, _name, flag, endpoint):
+ assert stripe_module._resolve_warehouse_parent(endpoint, 1, "source-1", flag) is None
+
+ def test_an_unusable_parent_table_falls_back_to_the_api_path(self):
+ # A soft dependency: a parent that cannot be read costs this run the optimization, never
+ # the sync itself.
+ with patch.object(stripe_module, "try_resolve_parent_table", return_value=None, create=True):
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.try_resolve_parent_table",
+ return_value=None,
+ ):
+ assert (
+ stripe_module._resolve_warehouse_parent(
+ CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME, 1, "source-1", True
+ )
+ is None
+ )
+
+
+class TestStripeNestedSweepResume:
+ @pytest.mark.parametrize("from_warehouse", [False, True], ids=["api", "warehouse"])
+ @pytest.mark.parametrize(
+ "first_parent_rows,expected",
+ [
+ (["txn_1", "txn_2", "txn_3"], ["txn_1", "txn_2", "txn_3", "txn_4"]),
+ (["txn_1", "txn_2"], ["txn_1", "txn_2", "txn_4"]),
+ ],
+ ids=["chunk_splits_a_parent", "chunk_ends_on_a_boundary"],
+ )
+ def test_interrupted_sweep_resumes_without_losing_or_repeating_rows(
+ self, from_warehouse, first_parent_rows, expected, tmp_path
+ ):
+ customers = [{"id": "cus_1", "balance": -500}, {"id": "cus_2", "balance": -500}]
+ nested_rows = {
+ "cus_1": [{"id": row_id} for row_id in first_parent_rows],
+ "cus_2": [{"id": "txn_4"}],
+ }
+
+ def _after(rows, cursor):
+ if cursor is None:
+ return rows
+ return rows[[row["id"] for row in rows].index(cursor) + 1 :]
+
+ def parent_method(params=None, **kwargs):
+ return _list_object(_after(customers, (params or {}).get("starting_after")))
+
+ def nested_method(customer=None, params=None):
+ return _list_object(_after(nested_rows[customer], (params or {}).get("starting_after")))
+
+ warehouse_parent = None
+ if from_warehouse:
+ uri = _write_customer_parent_table(tmp_path, customers)
+ warehouse_parent = ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version())
+
+ resource = StripeNestedResource(
+ method=nested_method,
+ nested_parent_param="customer",
+ parent_id="id",
+ parent=StripeResource(method=parent_method),
+ parent_name=CUSTOMER_RESOURCE_NAME,
+ )
+
+ def run(manager):
+ collected: list[dict] = []
+ checkpoints: list[tuple[int, Any]] = []
+ manager.save_state.side_effect = lambda state: checkpoints.append((len(collected), state))
+ with (
+ patch.object(stripe_module, "StripeClient"),
+ patch.object(stripe_module, "STRIPE_CHUNK_SIZE", 2),
+ patch.object(
+ stripe_module,
+ "_build_resources",
+ return_value={CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: resource},
+ ),
+ ):
+ 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=manager,
+ api_version=STRIPE_API_VERSION_ACACIA,
+ warehouse_parent=warehouse_parent,
+ ):
+ collected.extend(table.to_pylist())
+ return collected, checkpoints
+
+ killed = MagicMock()
+ killed.can_resume.return_value = False
+ all_rows, checkpoints = run(killed)
+ rows_written, crash_state = checkpoints[0]
+
+ restarted = MagicMock()
+ restarted.can_resume.return_value = True
+ restarted.load_state.return_value = crash_state
+ resumed_rows, _ = run(restarted)
+
+ assert [row["id"] for row in all_rows[:rows_written] + resumed_rows] == expected
+
+ @pytest.mark.parametrize("from_warehouse", [False, True], ids=["api_run", "warehouse_run"])
+ def test_a_nested_cursor_saved_by_the_other_path_is_discarded(self, from_warehouse, tmp_path):
+ customers = [{"id": "cus_1", "balance": -500}]
+ uri = _write_customer_parent_table(tmp_path, customers)
+ nested_params: list[dict] = []
+
+ def nested_method(customer=None, params=None):
+ nested_params.append(params or {})
+ return _list_object([{"id": "txn_1"}])
+
+ stale = (
+ stripe_module.StripeResumeConfig(
+ starting_after="cus_0", nested_parent_id="cus_1", nested_starting_after="txn_9"
+ )
+ if from_warehouse
+ else stripe_module.StripeResumeConfig(
+ nested_parent_id="cus_1",
+ nested_starting_after="txn_9",
+ warehouse_fragment_index=0,
+ warehouse_row_offset=0,
+ warehouse_table_uri="s3://somewhere-else",
+ warehouse_version=0,
+ )
+ )
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = stale
+
+ rows = _run_nested_get_rows(
+ nested_method,
+ parent_objects=customers,
+ warehouse_parent=(
+ ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version()) if from_warehouse else None
+ ),
+ resumable_source_manager=manager,
+ can_resume=True,
+ )
+
+ assert "starting_after" not in nested_params[0]
+ assert [row["id"] for row in rows] == ["txn_1"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
index 4fb2b581edc5..2743f8b112b7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/conftest.py
@@ -29,6 +29,10 @@ from posthog.hogql.query import execute_hogql_query
from posthog.temporal.tests.conftest import activity_environment, setup_postgres_test_db # noqa: F401
from posthog.temporal.utils import ExternalDataWorkflowInputs
+from products.managed_warehouse.backend.facade.temporal import (
+ DuckLakeCopyDataImportsWorkflow,
+ DuckLakeRegisterDataImportsWorkflow,
+)
from products.warehouse_sources.backend.facade.models import ExternalDataJob, get_latest_run_if_exists
from products.warehouse_sources.backend.models.external_table_definitions import external_tables
from products.warehouse_sources.backend.temporal.data_imports.external_data_job import ExternalDataJobWorkflow
@@ -187,7 +191,16 @@ async def run_external_data_job_workflow(
async with Worker(
activity_environment.client,
task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
- workflows=[ExternalDataJobWorkflow, PostImportWorkflow],
+ # DuckLake's registration/copy children are fire-and-forget (ABANDON policy) and
+ # normally run on their own task queue. Test settings collapse every queue to one
+ # name, so this worker receives them and would otherwise fail the parent on a
+ # workflow it does not know, turning an unrelated feature into an import failure.
+ workflows=[
+ ExternalDataJobWorkflow,
+ PostImportWorkflow,
+ DuckLakeRegisterDataImportsWorkflow,
+ DuckLakeCopyDataImportsWorkflow,
+ ],
activities=ACTIVITIES, # type: ignore
workflow_runner=UnsandboxedWorkflowRunner(),
activity_executor=ThreadPoolExecutor(max_workers=50),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/conftest.py
index 72643d8a0dce..d173c64c002e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/conftest.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/conftest.py
@@ -4,7 +4,12 @@ from urllib.parse import parse_qs, urlparse
import pytest
-from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.stripe.data import BALANCE_TRANSACTIONS
+from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.stripe.data import (
+ BALANCE_TRANSACTIONS,
+ CUSTOMER_BALANCE_TRANSACTIONS,
+ CUSTOMERS,
+ DELETED_CUSTOMER_IDS,
+)
class StripeData(TypedDict):
@@ -36,14 +41,35 @@ class MockStripeAPI:
self.max_created = None
def get_resources(self, request: Any, context: Any) -> dict:
- # Get the path without query string, then get the last segment
- resource = urlparse(request.url).path.split("/")[-1]
+ path = urlparse(request.url).path
+ # `/v1/customers/{id}/balance_transactions` and `/v1/balance_transactions` share a last
+ # segment, so the nested resource has to be matched on the whole path or the fan-out's
+ # child calls would be served the account-level ledger.
+ nested = re.match(r"^/v1/customers/(?P<customer>[^/]+)/balance_transactions$", path)
+ resource = path.split("/")[-1]
data: list[StripeData] = []
- match resource:
- case "balance_transactions":
- data = BALANCE_TRANSACTIONS # type: ignore
- case _:
- raise ValueError(f"Mock Stripe API: Unknown resource: {resource}")
+ if nested:
+ customer_id = nested.group("customer")
+ if customer_id in DELETED_CUSTOMER_IDS:
+ # Deleted between the parent listing and this call — Stripe 404s, and the sweep
+ # is expected to skip the parent rather than fail the import.
+ context.status_code = 404
+ return {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "resource_missing",
+ "message": f"No such customer: '{customer_id}'",
+ }
+ }
+ data = CUSTOMER_BALANCE_TRANSACTIONS.get(customer_id, []) # type: ignore
+ else:
+ match resource:
+ case "balance_transactions":
+ data = BALANCE_TRANSACTIONS # type: ignore
+ case "customers":
+ data = CUSTOMERS # type: ignore
+ case _:
+ raise ValueError(f"Mock Stripe API: Unknown resource: {resource}")
# Stripe returns data in reverse chronological order
filtered_data = sorted(data, key=lambda x: x["created"], reverse=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/data.py
index bde9748f48d9..cab6d03a65e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/data.py
@@ -125,3 +125,58 @@ BALANCE_TRANSACTIONS = [
"type": "charge",
},
]
+
+
+# Customers for the fan-out tests. The balance column is what the sweep's skip predicate reads,
+# so the set deliberately covers every branch of it: a zero balance (skipped without a child
+# call), a credit (probed), and a null (probed, because an unexpected payload shape must never
+# silently drop data).
+CUSTOMERS: list[dict] = [
+ {"id": "cus_zero_1", "object": "customer", "balance": 0, "created": 1700000001},
+ {"id": "cus_credit_1", "object": "customer", "balance": -2500, "created": 1700000002},
+ {"id": "cus_zero_2", "object": "customer", "balance": 0, "created": 1700000003},
+ {"id": "cus_null_balance", "object": "customer", "balance": None, "created": 1700000004},
+ {"id": "cus_credit_2", "object": "customer", "balance": -100, "created": 1700000005},
+ {"id": "cus_gone", "object": "customer", "balance": -50, "created": 1700000006},
+]
+
+# Keyed by customer. `cus_gone` has none: it is in the snapshot but deleted upstream, so its
+# child call 404s the way a stale warehouse row does in production.
+CUSTOMER_BALANCE_TRANSACTIONS: dict[str, list[dict]] = {
+ "cus_credit_1": [
+ {
+ "id": "cbtxn_1",
+ "object": "customer_balance_transaction",
+ "customer": "cus_credit_1",
+ "amount": -2500,
+ "created": 1700000010,
+ },
+ {
+ "id": "cbtxn_2",
+ "object": "customer_balance_transaction",
+ "customer": "cus_credit_1",
+ "amount": 500,
+ "created": 1700000011,
+ },
+ ],
+ "cus_credit_2": [
+ {
+ "id": "cbtxn_3",
+ "object": "customer_balance_transaction",
+ "customer": "cus_credit_2",
+ "amount": -100,
+ "created": 1700000012,
+ },
+ ],
+ "cus_null_balance": [
+ {
+ "id": "cbtxn_4",
+ "object": "customer_balance_transaction",
+ "customer": "cus_null_balance",
+ "amount": -1,
+ "created": 1700000013,
+ },
+ ],
+}
+
+DELETED_CUSTOMER_IDS = {"cus_gone"}
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.py
index 3f81c528dbca..f40f91fbbc8f 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
@@ -1,3 +1,4 @@
+import re
import uuid
from collections.abc import Mapping
from urllib.parse import parse_qs, urlparse
@@ -5,8 +6,11 @@ from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
+from django.test import override_settings
+
import stripe as stripe_lib
import requests
+from asgiref.sync import sync_to_async
from parameterized import parameterized
from stripe._http_client import HTTPClient
@@ -41,7 +45,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.str
)
from products.warehouse_sources.backend.temporal.data_imports.tests.e2e.conftest import run_external_data_job_workflow
-from .data import BALANCE_TRANSACTIONS
+from .data import BALANCE_TRANSACTIONS, CUSTOMER_BALANCE_TRANSACTIONS, CUSTOMERS
pytestmark = pytest.mark.usefixtures("minio_client")
@@ -1168,3 +1172,188 @@ class TestCreateWebhook:
assert "account" in result.error.lower()
assert "Failed to create webhook automatically" not in result.error
assert "permission to create webhooks" not in result.error
+
+
+# --- fan-out parent reuse -----------------------------------------------------------------
+#
+# The child under test is `CustomerBalanceTransaction`, whose sweep pages the whole customer
+# listing before it can call anything. These run the real workflow, so they assert on what the
+# sync actually did: which Stripe endpoints it hit, and what landed in the table.
+
+# Every customer the skip predicate lets through: the two credits, the null balance (probed
+# because an unexpected shape must not silently drop data), and the one deleted upstream. The
+# zero-balance customers are absent, which is the saving the projection buys. Compared sorted
+# throughout: the API path walks Stripe's reverse-chronological listing while the warehouse
+# path walks parquet file order, and neither promises the other's ordering.
+PROBED_CUSTOMERS = ["cus_credit_1", "cus_credit_2", "cus_gone", "cus_null_balance"]
+
+FANOUT_GATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.workflow_activities."
+ "import_data_sync.is_fanout_warehouse_reuse_enabled"
+)
+
+
+@sync_to_async
+def _customer_schema(source, team, sync_type: str):
+ return ExternalDataSchema.objects.create(
+ name="Customer",
+ team_id=team.pk,
+ source_id=source.pk,
+ sync_type=sync_type,
+ sync_type_config={},
+ should_sync=True,
+ )
+
+
+@sync_to_async
+def _balance_transaction_child(source, team):
+ return ExternalDataSchema.objects.create(
+ name="CustomerBalanceTransaction",
+ team_id=team.pk,
+ source_id=source.pk,
+ sync_type="full_refresh",
+ sync_type_config={},
+ should_sync=True,
+ )
+
+
+def _listing_calls(mock_stripe_api) -> list[str]:
+ return [c.url for c in mock_stripe_api.get_all_api_calls() if urlparse(c.url).path == "/v1/customers"]
+
+
+def _child_calls(mock_stripe_api) -> list[str]:
+ return [
+ urlparse(c.url).path.split("/")[3]
+ for c in mock_stripe_api.get_all_api_calls()
+ if re.match(r"^/v1/customers/[^/]+/balance_transactions$", urlparse(c.url).path)
+ ]
+
+
+async def _sync_parent_then_child(team, source, parent, child, mock_stripe_api, *, reuse_enabled: bool):
+ """Sync the parent so its table exists, then the child, and report what the child did."""
+ # The parent sync hands DuckLake a prepared folder and starts a registration child. Under
+ # test settings every task queue collapses to one name, so this worker picks that child up
+ # and fails on a workflow it does not register. Point it at a queue nobody polls: the child
+ # is ABANDON-policy fire-and-forget, so leaving it pending is what production does anyway.
+ with override_settings(DUCKLAKE_TASK_QUEUE="ducklake-task-queue-not-polled-in-tests"):
+ await run_external_data_job_workflow(
+ team=team,
+ external_data_source=source,
+ external_data_schema=parent,
+ table_name="stripe_customer",
+ expected_rows_synced=len(CUSTOMERS),
+ expected_total_rows=len(CUSTOMERS),
+ )
+ calls_before = len(mock_stripe_api.get_all_api_calls())
+
+ expected_rows = sum(len(rows) for rows in CUSTOMER_BALANCE_TRANSACTIONS.values())
+ with mock.patch(FANOUT_GATE, return_value=reuse_enabled):
+ response = await run_external_data_job_workflow(
+ team=team,
+ external_data_source=source,
+ external_data_schema=child,
+ table_name="stripe_customerbalancetransaction",
+ expected_rows_synced=expected_rows,
+ expected_total_rows=expected_rows,
+ )
+
+ child_phase = mock_stripe_api.get_all_api_calls()[calls_before:]
+ listing = [c.url for c in child_phase if urlparse(c.url).path == "/v1/customers"]
+ probed = [
+ urlparse(c.url).path.split("/")[3]
+ for c in child_phase
+ if re.match(r"^/v1/customers/[^/]+/balance_transactions$", urlparse(c.url).path)
+ ]
+ return response, listing, probed
+
+
[email protected]_db(transaction=True)
+async def test_fanout_pages_the_customer_listing_with_reuse_disabled(team, mock_stripe_api, external_data_source):
+ """Baseline: the sweep re-pages the parent listing every run, which is the cost being removed."""
+ parent = await _customer_schema(external_data_source, team, "full_refresh")
+ child = await _balance_transaction_child(external_data_source, team)
+
+ _, listing, probed = await _sync_parent_then_child(
+ team, external_data_source, parent, child, mock_stripe_api, reuse_enabled=False
+ )
+
+ assert listing, "with reuse off the child must page the customer listing itself"
+ assert sorted(probed) == PROBED_CUSTOMERS
+
+
[email protected]("parent_sync_type", ["full_refresh", "webhook"])
[email protected]_db(transaction=True)
+async def test_fanout_reads_the_parent_from_the_warehouse(
+ team, mock_stripe_api, external_data_source, parent_sync_type
+):
+ """The conversion: same child rows, without a single request for the parent listing."""
+ parent = await _customer_schema(external_data_source, team, parent_sync_type)
+ child = await _balance_transaction_child(external_data_source, team)
+
+ _, listing, probed = await _sync_parent_then_child(
+ team, external_data_source, parent, child, mock_stripe_api, reuse_enabled=True
+ )
+
+ assert listing == [], f"the parent listing must not be requested, got {listing}"
+ # Zero-balance customers are skipped by the predicate reading the warehouse row's balance;
+ # the null balance is probed, because an unexpected shape must not silently drop data.
+ assert sorted(probed) == PROBED_CUSTOMERS
+
+
[email protected]_db(transaction=True)
+async def test_both_paths_write_the_same_child_rows(team, mock_stripe_api, external_data_source):
+ """Parity: where the parent rows came from must not change what the child produces."""
+ api_parent = await _customer_schema(external_data_source, team, "full_refresh")
+ api_child = await _balance_transaction_child(external_data_source, team)
+ api_response, _, _ = await _sync_parent_then_child(
+ team, external_data_source, api_parent, api_child, mock_stripe_api, reuse_enabled=False
+ )
+
+ warehouse_response, _, _ = await _sync_parent_then_child(
+ team, external_data_source, api_parent, api_child, mock_stripe_api, reuse_enabled=True
+ )
+
+ assert warehouse_response.results is not None and api_response.results is not None
+ assert sorted(map(str, warehouse_response.results)) == sorted(map(str, api_response.results))
+
+
[email protected]_db(transaction=True)
+async def test_a_parent_the_gate_refuses_keeps_the_api_path(team, mock_stripe_api, external_data_source):
+ """Only sync types that hold one row per key are readable; the rest fall back, never fail.
+
+ `append` accumulates a row per sync, so reading it would fan the child out once per copy.
+ """
+ parent = await _customer_schema(external_data_source, team, "append")
+ child = await _balance_transaction_child(external_data_source, team)
+
+ _, listing, probed = await _sync_parent_then_child(
+ team, external_data_source, parent, child, mock_stripe_api, reuse_enabled=True
+ )
+
+ assert listing, "an append parent must not be read from the warehouse"
+ assert sorted(probed) == PROBED_CUSTOMERS
+
+
[email protected]_db(transaction=True)
+async def test_a_missing_parent_schema_keeps_the_api_path(team, mock_stripe_api, external_data_source):
+ """The child can be enabled without its parent, and that must cost the run nothing."""
+ child = await _balance_transaction_child(external_data_source, team)
+
+ expected_rows = sum(len(rows) for rows in CUSTOMER_BALANCE_TRANSACTIONS.values())
+ with mock.patch(FANOUT_GATE, return_value=True):
+ await run_external_data_job_workflow(
+ team=team,
+ external_data_source=external_data_source,
+ external_data_schema=child,
+ table_name="stripe_customerbalancetransaction",
+ expected_rows_synced=expected_rows,
+ expected_total_rows=expected_rows,
+ )
+
+ assert _listing_calls(mock_stripe_api), "with no parent table there is nothing to read but the API"
+ assert sorted(_child_calls(mock_stripe_api)) == PROBED_CUSTOMERS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 352531151814..0df096a9a084 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -125,17 +125,26 @@ def _get_external_data_schema(schema_id: uuid.UUID, team_id: int) -> ExternalDat
)
+# An allow-list, not a deny-list: every sync type here leaves one row per key, and the reader
+# streams the table with no dedupe state. Append keeps a row per sync and CDC keeps change
+# history, so either would fan the child out once per duplicate. Webhook qualifies because its
+# drains merge on the primary key — the pipeline maps it to `sync_type = "incremental"`.
+WAREHOUSE_READABLE_PARENT_SYNC_TYPES = frozenset(
+ {
+ ExternalDataSchema.SyncType.FULL_REFRESH,
+ ExternalDataSchema.SyncType.INCREMENTAL,
+ ExternalDataSchema.SyncType.WEBHOOK,
+ }
+)
+
+
def _parent_unusable_reason(parent: ExternalDataSchema | None) -> str | None:
"""Why a fan-out child can't read this parent from the warehouse, or None when it can."""
if parent is None:
return "missing"
if not parent.should_sync:
return "disabled"
- if not (parent.is_incremental or parent.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH):
- # An allow-list, not a deny-list: only merge and full-refresh parents hold one row per
- # key. Append accumulates a row per sync, and CDC keeps change history, so the reader —
- # which streams the table as-is, with no dedupe state — would fan the child out once
- # per duplicate. New sync types have to opt in here deliberately.
+ if parent.sync_type not in WAREHOUSE_READABLE_PARENT_SYNC_TYPES:
return "unsupported_sync_type"
if not parent.initial_sync_complete:
return "no_initial_sync"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index 19030925092e..74dd471267e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -803,10 +803,15 @@ async def test_unusable_parent_falls_back_to_the_api_path(parent):
@pytest.mark.asyncio
@pytest.mark.parametrize(
"sync_type",
- [ExternalDataSchema.SyncType.INCREMENTAL, ExternalDataSchema.SyncType.FULL_REFRESH],
+ [
+ ExternalDataSchema.SyncType.INCREMENTAL,
+ ExternalDataSchema.SyncType.FULL_REFRESH,
+ ExternalDataSchema.SyncType.WEBHOOK,
+ ],
)
async def test_synced_parent_uses_the_warehouse_path(sync_type):
- # Merge and full-refresh parents both hold one row per key, so both drive the reader.
+ # Every sync type here leaves one row per key, so each drives the reader. Webhook qualifies
+ # because its drains merge on the primary key rather than appending.
with (
mock.patch.object(module, "database_sync_to_async_pool", new=_passthrough),
mock.patch.object(module, "is_fanout_warehouse_reuse_enabled", return_value=True),