: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
feat(data-warehouse): add stripe payment-method history (#80031)
jake sciottodeb9d91ec9b2
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex 4d6dc90780e5..73757fdb0d57 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -3432,7 +3432,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiFailure never breaks setup: the polling defaults stay in place and webhook-only tables remaindisabled, exactly as if the source didn't support webhooks."""- webhook_capable = {s.name for s in source_schemas if s.supports_webhooks}+ # Tables marked `should_sync_default=False` need explicit opt-in even when webhook-capable —+ # one-shot setup must not force-enable what the schema picker would leave off (the same+ # contract `build_default_schemas` honors).+ webhook_capable = {s.name for s in source_schemas if s.supports_webhooks and s.should_sync_default}if not webhook_capable or source.webhook_template is None:return Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.pyindex f99afa6aebea..7f423dfe08e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py@@ -29,8 +29,10 @@ class SourceSchema:incremental_fields: list[IncrementalField] = field(default_factory=list)row_count: int | None = Nonesupports_webhooks: bool = False- # True for resources with no API list endpoint that can only be populated via webhooks- # (e.g. Stripe `Discount`). The UI should hide non-webhook sync methods for these.+ # True for resources whose only valid sync method is webhooks: either no API list endpoint+ # exists at all (e.g. Stripe `Discount`), or a non-webhook sync would destroy captured data+ # (e.g. Stripe `CustomerPaymentMethodHistory`, which seeds once from an API sweep and then+ # appends webhook events). The UI should hide non-webhook sync methods for these.webhook_only: bool = Falsesupports_cdc: bool = False# Postgres-only: set by the Postgres source for heap tables / matviews (PG13+); alldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/canonical_descriptions.pyindex 3cee07744994..8a7cefe6242d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/canonical_descriptions.py@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conCOUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,@@ -297,6 +298,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {billing_details="Billing information (name, email, address) associated with the payment method.",),},+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME: {+ "description": "One row per observed state of a customer's payment method — seeded from the attached-payment-methods sweep, then appended from payment_method.* webhook events, so detached payment methods stay queryable as they existed historically.",+ "docs_url": "https://stripe.com/docs/api/payment_methods",+ "columns": _columns(+ customer="ID of the customer the payment method was attached to when observed; null on a detachment event (history_previous_attributes carries the previous customer).",+ type="Type of the payment method (e.g. card, sepa_debit, us_bank_account).",+ card="Details of the card if the payment method is a card (brand, last4, expiry).",+ billing_details="Billing information (name, email, address) associated with the payment method.",+ history_event_id="Unique id of this observation: the Stripe event id, or a synthetic snapshot key for rows seeded by the initial sweep. Primary key.",+ history_event_type="Stripe event type that produced the row (payment_method.attached, .updated, .detached, .automatically_updated), or 'snapshot' for rows seeded by the initial sweep.",+ history_captured_at="When the state was observed (event creation time, or sweep time for snapshot rows), as a Unix timestamp. The latest row per payment method id is its most recently observed state.",+ history_previous_attributes="JSON object of the fields the event changed, holding their previous values — for detachments this includes the customer the payment method was detached from. Null on snapshot rows.",+ ),+ },COUPON_RESOURCE_NAME: {"description": "A discount you can apply to customers, invoices, or subscriptions.","docs_url": "https://stripe.com/docs/api/coupons",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.pyindex bed13941b9e9..9a62ede541af 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/constants.py@@ -13,6 +13,7 @@ SUBSCRIPTION_RESOURCE_NAME = "Subscription"CREDIT_NOTE_RESOURCE_NAME = "CreditNote"CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME = "CustomerBalanceTransaction"CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME = "CustomerPaymentMethod"+CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME = "CustomerPaymentMethodHistory"COUPON_RESOURCE_NAME = "Coupon"DISCOUNT_RESOURCE_NAME = "Discount"PAYMENT_INTENT_RESOURCE_NAME = "PaymentIntent"@@ -46,6 +47,21 @@ SHIPPING_RATE_RESOURCE_NAME = "ShippingRate"# declaration (`StripeSource.supported_versions`) and the request layer share a single label.STRIPE_API_VERSION_ACACIA = "2024-09-30.acacia"+# CustomerPaymentMethodHistory metadata columns. Every row is one observation of a payment+# method: either a `payment_method.*` webhook event, or a row from the initial attached-payment-+# methods sweep (a "snapshot"). The event id doubles as the row's primary key, so webhook+# redeliveries merge into the same row instead of duplicating it.+HISTORY_EVENT_ID_COLUMN = "history_event_id"+HISTORY_EVENT_TYPE_COLUMN = "history_event_type"+HISTORY_CAPTURED_AT_COLUMN = "history_captured_at"+HISTORY_PREVIOUS_ATTRIBUTES_COLUMN = "history_previous_attributes"+HISTORY_SNAPSHOT_EVENT_TYPE = "snapshot"++# `schema_mapping` key the webhook HogFunction uses to route `payment_method` events to the+# history table *in addition to* the CustomerPaymentMethod upsert routed by the bare object+# type. Stripe object types never contain ":", so this can never collide with a real one.+PAYMENT_METHOD_HISTORY_MAPPING_KEY = "payment_method:history"+# Maps PostHog resource name -> Stripe API object type (as it appears in webhook data.object.object)## This is what the webhook HogFunction routes on: it reads `data.object.object` off the incoming@@ -54,6 +70,11 @@ STRIPE_API_VERSION_ACACIA = "2024-09-30.acacia"## A resource belongs here only when Stripe actually emits an event carrying that object type. The# ones that do not are listed at the bottom of RESOURCE_TO_STRIPE_WEBHOOK_EVENT below.+#+# CustomerPaymentMethodHistory is deliberately absent: one object type key can route to only one+# schema, and "payment_method" already routes to CustomerPaymentMethod. The history table receives+# the same events through the PAYMENT_METHOD_HISTORY_MAPPING_KEY fan-out in the webhook template+# (see `StripeSource.webhook_mapping_key`).RESOURCE_TO_STRIPE_OBJECT_TYPE: dict[str, str] = {ACCOUNT_RESOURCE_NAME: "account",BALANCE_TRANSACTION_RESOURCE_NAME: "balance_transaction",@@ -116,6 +137,12 @@ RESOURCE_TO_STRIPE_WEBHOOK_EVENT: dict[str, str] = {# `billing.credit_balance_transaction` object), none of which can populate this table. So it's# intentionally absent here and stays API-sweep-only.CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: "payment_method",+ # Same event family as CustomerPaymentMethod (the values here are collapsed to a set when+ # building the Stripe subscription, so this adds no new subscribed events). What differs is+ # the write: CustomerPaymentMethod upserts the latest state per payment method, while the+ # history table appends one row per event so `payment_method.detached` (Stripe's closest+ # analogue to deletion — no `payment_method.deleted` event exists) is preserved.+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME: "payment_method",COUPON_RESOURCE_NAME: "coupon",DISCOUNT_RESOURCE_NAME: "customer.discount",PAYMENT_INTENT_RESOURCE_NAME: "payment_intent",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.pyindex a2c7ae309188..6b2aa770535f 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@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conCOUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,@@ -25,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,ENTITLEMENTS_FEATURE_RESOURCE_NAME,EVENT_RESOURCE_NAME,+ HISTORY_EVENT_ID_COLUMN,INVOICE_ITEM_RESOURCE_NAME,INVOICE_PAYMENT_RESOURCE_NAME,INVOICE_RESOURCE_NAME,@@ -66,6 +68,7 @@ ENDPOINTS = (CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,COUPON_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,PAYMENT_INTENT_RESOURCE_NAME,@@ -132,6 +135,17 @@ INCREMENTAL_ENDPOINTS = (# Endpoints that have no API list path — populated only via webhooks.WEBHOOK_ONLY_ENDPOINTS = (DISCOUNT_RESOURCE_NAME,)+# Endpoints restricted to the webhook sync method in the UI, but which — unlike+# WEBHOOK_ONLY_ENDPOINTS — still seed from an API sweep on the initial sync. Used for history+# tables: any other sync method would truncate the table on each run and destroy the captured+# history (a detached payment method never comes back from `customers.payment_methods.list`).+WEBHOOK_SYNC_ONLY_ENDPOINTS = (CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,)++# Endpoints that stay disabled until the user explicitly enables them. The history table repeats+# the per-customer payment-methods sweep on its initial sync, so it must not be force-enabled by+# one-shot setup or auto-sync of newly discovered schemas.+DEFAULT_OFF_ENDPOINTS = (CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,)+# Stripe objects that carry no timestamp at all, so there is nothing stable to partition on.# `stripe_source` leaves partitioning off for these instead of falling back to `created`, which the# Delta partitioner would KeyError on.@@ -144,9 +158,12 @@ NON_PARTITIONED_ENDPOINTS = (# Endpoints keyed by something other than `id`. Stripe's credit balance summary is a per-customer# view rather than a stored object, so it has no id of its own — the credit grant it was fetched for-# is what makes each row unique.+# is what makes each row unique. The payment-method history table stores one row per observation+# (webhook event or seed-sweep snapshot), so its key is the observation id, not the payment method+# id — keying on `id` would collapse a payment method's history to a single row.PRIMARY_KEYS: dict[str, list[str]] = {BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME: ["credit_grant"],+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME: [HISTORY_EVENT_ID_COLUMN],}DEFAULT_PRIMARY_KEYS = ["id"]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.pyindex dd35a96f4fed..bc18f69d2f0c 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@@ -40,8 +40,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stripe import StripeSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (CHARGE_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,INVOICE_RESOURCE_NAME,+ PAYMENT_METHOD_HISTORY_MAPPING_KEY,PRODUCT_RESOURCE_NAME,RESOURCE_TO_STRIPE_OBJECT_TYPE,RESOURCE_TO_STRIPE_WEBHOOK_EVENT,@@ -50,8 +52,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.con)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (APPEND_ONLY_INCREMENTAL_FIELDS as STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS,+ DEFAULT_OFF_ENDPOINTS as STRIPE_DEFAULT_OFF_ENDPOINTS,ENDPOINTS as STRIPE_ENDPOINTS,WEBHOOK_ONLY_ENDPOINTS as STRIPE_WEBHOOK_ONLY_ENDPOINTS,+ WEBHOOK_SYNC_ONLY_ENDPOINTS as STRIPE_WEBHOOK_SYNC_ONLY_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (StripeAuthenticationError,@@ -129,6 +133,14 @@ class StripeSource(def webhook_resource_map(self) -> dict[str, str]:return RESOURCE_TO_STRIPE_OBJECT_TYPE+ def webhook_mapping_key(self, schema_name: str) -> str:+ # The history table consumes the same `payment_method` events as CustomerPaymentMethod,+ # but `schema_mapping` routes one schema per key — so it registers under a suffixed key+ # that the webhook template fans out to alongside the object-type routing.+ if schema_name == CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME:+ return PAYMENT_METHOD_HISTORY_MAPPING_KEY+ return super().webhook_mapping_key(schema_name)+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -348,10 +360,19 @@ If automatic creation failed due to a permissions error and you're using a restrsupports_webhooks=(endpoint in RESOURCE_TO_STRIPE_WEBHOOK_EVENT or endpoint in STRIPE_WEBHOOK_ONLY_ENDPOINTS),- webhook_only=endpoint in STRIPE_WEBHOOK_ONLY_ENDPOINTS,+ # Two flavors restrict the UI to the webhook sync method: resources with no list+ # API at all (WEBHOOK_ONLY_ENDPOINTS — their poll yields nothing), and history+ # tables (WEBHOOK_SYNC_ONLY_ENDPOINTS) whose non-webhook sync would truncate the+ # captured history on every run. Only the former sets `webhook_only` on the+ # SourceResponse (`stripe_source`): history tables still poll once, to seed from+ # the currently-attached sweep before webhook events take over.+ webhook_only=(+ endpoint in STRIPE_WEBHOOK_ONLY_ENDPOINTS or endpoint in STRIPE_WEBHOOK_SYNC_ONLY_ENDPOINTS+ ),# nested resources are only full refresh and are not in STRIPE_APPEND_ONLY_INCREMENTAL_FIELDSsupports_append=STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS.get(endpoint, None) is not None,incremental_fields=STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint not in STRIPE_DEFAULT_OFF_ENDPOINTS,)for endpoint in STRIPE_ENDPOINTS]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.pyindex ea6afa6f329d..5995f76738e2 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@@ -1,5 +1,6 @@import osimport re+import timeimport inspectimport dataclassesfrom collections.abc import Callable, Mapping@@ -46,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conCOUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISPUTE_RESOURCE_NAME,@@ -53,6 +55,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,ENTITLEMENTS_FEATURE_RESOURCE_NAME,EVENT_RESOURCE_NAME,+ HISTORY_CAPTURED_AT_COLUMN,+ HISTORY_EVENT_ID_COLUMN,+ HISTORY_EVENT_TYPE_COLUMN,+ HISTORY_PREVIOUS_ATTRIBUTES_COLUMN,+ HISTORY_SNAPSHOT_EVENT_TYPE,INVOICE_ITEM_RESOURCE_NAME,INVOICE_PAYMENT_RESOURCE_NAME,INVOICE_RESOURCE_NAME,@@ -348,6 +355,10 @@ class StripeNestedResource:# the default behaviour fans out one call per parent — most of which return nothing. A cheap# signal already present on the parent object lets us avoid the calls that can't yield data.parent_has_nested: Optional[Callable[[dict[str, Any]], bool]] = None+ # Optional per-row rewrite applied to each nested row (after the parent id is stamped, before+ # secret scrubbing). The history table uses it to stamp its observation-metadata columns onto+ # the seed sweep's rows.+ row_transform: Optional[Callable[[dict[str, Any]], dict[str, Any]]] = Noneclass _SingleObjectList:@@ -420,6 +431,23 @@ def _customer_might_have_balance_transactions(customer: dict[str, Any]) -> bool:return balance is None or balance != 0+def _payment_method_history_snapshot_row(row: dict[str, Any]) -> dict[str, Any]:+ """Stamp observation metadata onto one payment-method row from the history seed sweep.++ The sweep can only observe currently-attached payment methods, so each row is a "snapshot"+ observation keyed by payment method + customer: re-running the sweep (e.g. the poll fallback+ while the webhook handler is disabled) refreshes the same row instead of appending a+ duplicate, and a payment method later attached to a different customer gets a distinct+ snapshot row rather than overwriting the first customer's history.+ """+ return {+ **row,+ HISTORY_EVENT_ID_COLUMN: f"{HISTORY_SNAPSHOT_EVENT_TYPE}:{row.get('id')}:{row.get('customer')}",+ HISTORY_EVENT_TYPE_COLUMN: HISTORY_SNAPSHOT_EVENT_TYPE,+ HISTORY_CAPTURED_AT_COLUMN: int(time.time()),+ }++@dataclasses.dataclassclass StripeResumeConfig:starting_after: str@@ -530,6 +558,18 @@ def _build_resources(parent=StripeResource(method=client.customers.list),parent_name=CUSTOMER_RESOURCE_NAME,),+ # Same sweep as CustomerPaymentMethod, used only to seed the history table on its initial+ # sync; from then on `payment_method.*` webhook events land one row per event. The sweep+ # cannot see payment methods detached before it ran — Stripe exposes no endpoint listing+ # detached payment methods — so history from before the source connected is unrecoverable.+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME: StripeNestedResource(+ method=client.customers.payment_methods.list,+ nested_parent_param="customer",+ parent_id="id",+ parent=StripeResource(method=client.customers.list),+ parent_name=CUSTOMER_RESOURCE_NAME,+ row_transform=_payment_method_history_snapshot_row,+ ),PAYMENT_INTENT_RESOURCE_NAME: StripeResource(method=client.payment_intents.list),CHECKOUT_SESSION_RESOURCE_NAME: StripeResource(method=client.checkout.sessions.list),SUBSCRIPTION_SCHEDULE_RESOURCE_NAME: StripeResource(method=client.subscription_schedules.list),@@ -689,14 +729,13 @@ def get_rows(**nested_kwargs,)for nested_obj in stripe_nested_objects.auto_paging_iter():- batcher.batch(- _scrub_client_secrets(- {- **nested_obj,- **{resource.nested_parent_param: parent_obj_id},- }- )- )+ row = {+ **nested_obj,+ **{resource.nested_parent_param: parent_obj_id},+ }+ if resource.row_transform is not None:+ row = resource.row_transform(row)+ batcher.batch(_scrub_client_secrets(row))# A single batch can split into several ready chunks, so drain them all# before batching the next item — otherwise the next batch() trips the@@ -806,6 +845,52 @@ def _webhook_table_transformer(table: pa.Table) -> pa.Table:return table_from_py_list(rows)+def _webhook_history_table_transformer(table: pa.Table) -> pa.Table:+ """Turn a batch of webhook events into history rows: one immutable row per event.++ Unlike `_webhook_table_transformer` there is no latest-per-object collapse — several events+ for the same payment method in one batch (attached, updated, detached) must all survive, or+ the intermediate states the table exists to record are lost. Rows are keyed by the Stripe+ event id instead, so a redelivered event refreshes its own row rather than duplicating it.++ Reading columns through `_column` (None-filled when absent) keeps a malformed payload — only+ reachable with the signature check bypassed — from raising and wedging the batch forever:+ the S3 files are only deleted after a successful yield, so a raising transformer would replay+ the same poison batch on every sync.+ """++ def _column(name: str) -> list[Any]:+ if name in table.column_names:+ return table.column(name).to_pylist()+ return [None] * table.num_rows++ rows: dict[str, dict] = {}+ for event_id, event_type, data_str, event_created in zip(+ _column("id"), _column("type"), _column("data"), _column("created")+ ):+ if event_id is None or data_str is None:+ continue+ data = _scrub_client_secrets(orjson.loads(data_str))+ obj = data.get("object")+ if not isinstance(obj, dict) or obj.get("id") is None:+ continue+ # `previous_attributes` carries the pre-event values of the fields the event changed —+ # for `payment_method.detached` that's the customer the method was detached from, which+ # the object itself no longer shows (its `customer` is null after detachment).+ previous_attributes = data.get("previous_attributes")+ rows[event_id] = {+ **obj,+ HISTORY_EVENT_ID_COLUMN: event_id,+ HISTORY_EVENT_TYPE_COLUMN: event_type,+ HISTORY_CAPTURED_AT_COLUMN: event_created if isinstance(event_created, int) else None,+ HISTORY_PREVIOUS_ATTRIBUTES_COLUMN: (+ orjson.dumps(previous_attributes).decode() if previous_attributes else None+ ),+ }++ return table_from_py_list(list(rows.values()))++def stripe_source(api_key: str,account_id: Optional[str],@@ -836,7 +921,14 @@ def stripe_source(def items():if webhook_enabled:- return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)+ # History tables keep every event as its own row; everything else collapses each+ # batch to the latest state per object id and upserts it.+ table_transformer = (+ _webhook_history_table_transformer+ if endpoint == CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME+ else _webhook_table_transformer+ )+ return webhook_source_manager.get_items(table_transformer=table_transformer)return get_rows(api_key=api_key,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 39e4684657a2..97b8f0bb7ba6 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@@ -6,10 +6,12 @@ import pytestfrom unittest import mockfrom unittest.mock import MagicMock, patch+import orjsonimport stripe as stripe_libfrom parameterized import parameterizedfrom stripe import ListObject+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stripe import (@@ -26,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conCHARGE_RESOURCE_NAME,CHECKOUT_SESSION_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,+ CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,@@ -33,9 +36,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,ENTITLEMENTS_FEATURE_RESOURCE_NAME,EVENT_RESOURCE_NAME,+ HISTORY_CAPTURED_AT_COLUMN,+ HISTORY_EVENT_ID_COLUMN,+ HISTORY_EVENT_TYPE_COLUMN,+ HISTORY_PREVIOUS_ATTRIBUTES_COLUMN,+ HISTORY_SNAPSHOT_EVENT_TYPE,INVOICE_PAYMENT_RESOURCE_NAME,PAYMENT_INTENT_RESOURCE_NAME,PAYMENT_LINK_RESOURCE_NAME,+ PAYMENT_METHOD_HISTORY_MAPPING_KEY,PLAN_RESOURCE_NAME,PROMOTION_CODE_RESOURCE_NAME,QUOTE_RESOURCE_NAME,@@ -74,6 +83,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.str_is_truncated_stripe_list_response,_RateLimitRetryingRequestsClient,_scrub_client_secrets,+ _webhook_history_table_transformer,check_endpoint_permissions,create_webhook,get_rows,@@ -918,6 +928,233 @@ class TestWebhookOnlyResponseWiring:assert response.partition_keys == ["start"]+def _event_row(+ event_id: str, event_type: str, created: int, obj: dict, previous_attributes: dict | None = None+) -> dict[str, Any]:+ data: dict[str, Any] = {"object": obj}+ if previous_attributes is not None:+ data["previous_attributes"] = previous_attributes+ return {"id": event_id, "object": "event", "type": event_type, "created": created, "data": data}+++class TestCustomerPaymentMethodHistory:+ def _make_manager(self, enabled: bool) -> MagicMock:+ manager = MagicMock(spec=WebhookSourceManager)+ manager.webhook_enabled = mock.AsyncMock(return_value=enabled)+ return manager++ def _source(self, endpoint: str, manager: MagicMock) -> Any:+ return stripe_module.stripe_source(+ api_key="sk_test_123",+ account_id=None,+ endpoint=endpoint,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ logger=MagicMock(adebug=mock.AsyncMock()),+ resumable_source_manager=MagicMock(can_resume=MagicMock(return_value=False)),+ webhook_source_manager=manager,+ api_version=STRIPE_API_VERSION_ACACIA,+ )++ @parameterized.expand(+ [+ # History must stay opt-in (should_sync_default=False, or one-shot setup force-enables+ # a per-customer sweep) and webhook-sync-only (webhook_only=True, or the UI offers full+ # refresh, which truncates the captured history on every scheduled run).+ (CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME, True, False),+ # The existing upsert table must keep its behavior — the history flags must not leak.+ (CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME, False, True),+ ]+ )+ def test_schema_flags(self, endpoint: str, webhook_only: bool, should_sync_default: bool) -> None:+ source = StripeSource()+ config = StripeSourceConfig(+ auth_method=StripeAuthMethodConfig(selection="api_key", stripe_secret_key="sk_test_123")+ )+ schema = next(s for s in source.get_schemas(config, team_id=1) if s.name == endpoint)+ assert schema.webhook_only is webhook_only+ assert schema.should_sync_default is should_sync_default+ assert schema.supports_webhooks is True+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_history_mapping_key_cannot_collide_with_object_routing(self) -> None:+ # schema_mapping routes one schema per key. If the history table resolved to the bare+ # "payment_method" key, whichever schema registered last would silently steal the other's+ # events — so it must use the suffixed key, and that key must not equal any object type.+ source = StripeSource()+ assert (+ source.webhook_mapping_key(CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME)+ == PAYMENT_METHOD_HISTORY_MAPPING_KEY+ )+ assert source.webhook_mapping_key(CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME) == "payment_method"+ assert PAYMENT_METHOD_HISTORY_MAPPING_KEY not in RESOURCE_TO_STRIPE_OBJECT_TYPE.values()++ def test_history_response_keys_on_the_observation_and_still_polls(self) -> None:+ # primary_keys=["id"] would collapse a payment method's whole history to one row on merge;+ # webhook_only=True on the response would skip the seed sweep, leaving the table empty+ # until the first webhook event.+ manager = self._make_manager(enabled=False)+ response = self._source(CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME, manager)+ assert response.primary_keys == [HISTORY_EVENT_ID_COLUMN]+ assert response.webhook_only is False+ assert response.partition_keys == ["created"]+ manager.webhook_enabled.assert_awaited_once_with(webhook_only=False)++ @parameterized.expand(+ [+ # The history endpoint must keep both events; the upsert transformer would collapse+ # them to the latest state, silently dropping the intermediate observations the table+ # exists to record.+ (CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME, 2),+ (CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME, 1),+ ]+ )+ def test_webhook_transformer_choice_controls_event_collapsing(self, endpoint: str, expected_rows: int) -> None:+ events = table_from_py_list(+ [+ _event_row(+ "evt_1",+ "payment_method.attached",+ 1700000100,+ {"id": "pm_1", "object": "payment_method", "created": 1700000000, "customer": "cus_1"},+ ),+ _event_row(+ "evt_2",+ "payment_method.detached",+ 1700000200,+ {"id": "pm_1", "object": "payment_method", "created": 1700000000, "customer": None},+ previous_attributes={"customer": "cus_1"},+ ),+ ]+ )+ manager = self._make_manager(enabled=True)+ response = self._source(endpoint, manager)+ response.items()+ transformer = manager.get_items.call_args.kwargs["table_transformer"]+ assert transformer(events).num_rows == expected_rows++ def test_history_transformer_stamps_observation_columns(self) -> None:+ # The detached event's row must keep the event's identity and the detached-from customer+ # (via previous_attributes) — without them "which customer had this card on file, when?"+ # is unanswerable once the payment method is gone from the live list.+ events = table_from_py_list(+ [+ _event_row(+ "evt_1",+ "payment_method.attached",+ 1700000100,+ {"id": "pm_1", "object": "payment_method", "created": 1700000000, "customer": "cus_1"},+ ),+ _event_row(+ "evt_2",+ "payment_method.detached",+ 1700000200,+ {"id": "pm_1", "object": "payment_method", "created": 1700000000, "customer": None},+ previous_attributes={"customer": "cus_1"},+ ),+ ]+ )+ rows = {row[HISTORY_EVENT_ID_COLUMN]: row for row in _webhook_history_table_transformer(events).to_pylist()}++ attached = rows["evt_1"]+ assert attached["customer"] == "cus_1"+ assert attached[HISTORY_EVENT_TYPE_COLUMN] == "payment_method.attached"+ assert attached[HISTORY_CAPTURED_AT_COLUMN] == 1700000100+ assert attached[HISTORY_PREVIOUS_ATTRIBUTES_COLUMN] is None++ detached = rows["evt_2"]+ assert detached["customer"] is None+ assert detached[HISTORY_EVENT_TYPE_COLUMN] == "payment_method.detached"+ assert detached[HISTORY_CAPTURED_AT_COLUMN] == 1700000200+ assert orjson.loads(detached[HISTORY_PREVIOUS_ATTRIBUTES_COLUMN]) == {"customer": "cus_1"}++ def test_history_transformer_dedupes_redelivered_events(self) -> None:+ # Stripe redelivers events on retry. Two copies of the same event in one drained batch+ # must land as one row — duplicates on the merge key make every later merge multi-match.+ obj = {"id": "pm_1", "object": "payment_method", "created": 1700000000, "customer": "cus_1"}+ events = table_from_py_list(+ [+ _event_row("evt_1", "payment_method.attached", 1700000100, obj),+ _event_row("evt_1", "payment_method.attached", 1700000100, obj),+ ]+ )+ assert _webhook_history_table_transformer(events).num_rows == 1++ def test_history_transformer_skips_malformed_rows_without_raising(self) -> None:+ # The S3 batch files are only deleted after a successful yield, so a transformer that+ # raises on one malformed payload (only reachable with the signature check bypassed)+ # would replay the same poison batch on every sync, wedging the schema forever.+ events = table_from_py_list(+ [+ # No event id — cannot be keyed.+ {+ "object": "event",+ "created": 1700000100,+ "data": {"object": {"id": "pm_1", "object": "payment_method"}},+ },+ # No object id — cannot be attributed to a payment method.+ _event_row("evt_2", "payment_method.updated", 1700000200, {"object": "payment_method"}),+ _event_row(+ "evt_3",+ "payment_method.updated",+ 1700000300,+ {"id": "pm_1", "object": "payment_method", "created": 1700000000, "customer": "cus_1"},+ ),+ ]+ )+ # The `type` column is present here; drop it to also cover a batch missing a column outright.+ events = events.drop_columns(["type"])+ rows = _webhook_history_table_transformer(events).to_pylist()+ assert [row[HISTORY_EVENT_ID_COLUMN] for row in rows] == ["evt_3"]+ assert rows[0][HISTORY_EVENT_TYPE_COLUMN] is None++ @parameterized.expand(+ [+ (CUSTOMER_PAYMENT_METHOD_HISTORY_RESOURCE_NAME, True),+ (CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME, False),+ ]+ )+ def test_seed_sweep_stamps_snapshot_rows_only_for_history(self, endpoint: str, expect_stamped: bool) -> None:+ # The sweep rows need a stable snapshot key: without it they have no merge key (the+ # table's primary key column would be missing), and a fallback re-sweep would duplicate+ # instead of refresh them. The same sweep feeding CustomerPaymentMethod must stay unstamped.+ def payment_methods_list(customer=None, params=None):+ return _list_object(+ [{"id": f"pm_{customer}", "object": "payment_method", "created": 1700000000, "customer": customer}]+ )++ resumable_source_manager = MagicMock()+ resumable_source_manager.can_resume.return_value = False++ with patch.object(stripe_module, "StripeClient") as client_cls:+ client = client_cls.return_value+ client.customers.list = lambda params: _list_object([{"id": "cus_1"}])+ client.customers.payment_methods.list = payment_methods_list+ rows: list[dict] = []+ for table in get_rows(+ api_key="sk_test_123",+ endpoint=endpoint,+ account_id=None,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ logger=MagicMock(),+ resumable_source_manager=resumable_source_manager,+ api_version=STRIPE_API_VERSION_ACACIA,+ ):+ rows.extend(table.to_pylist())++ assert [row["id"] for row in rows] == ["pm_cus_1"]+ row = rows[0]+ assert row["customer"] == "cus_1"+ if expect_stamped:+ assert row[HISTORY_EVENT_ID_COLUMN] == f"{HISTORY_SNAPSHOT_EVENT_TYPE}:pm_cus_1:cus_1"+ assert row[HISTORY_EVENT_TYPE_COLUMN] == HISTORY_SNAPSHOT_EVENT_TYPE+ assert isinstance(row[HISTORY_CAPTURED_AT_COLUMN], int)+ else:+ assert HISTORY_EVENT_ID_COLUMN not in row++class TestEndpointCatalogWiring:def setup_method(self):self.resources = stripe_module._build_resources(MagicMock(), logger=None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_webhook_template.pyindex a54e62df25bf..9058dabb68c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_webhook_template.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_webhook_template.py@@ -98,6 +98,42 @@ class TestStripeWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):)self.mock_produce_to_warehouse_webhooks.assert_called_once_with(body, "schema_456")+ @parameterized.expand(+ [+ # Both tables enabled: the event must reach both, or the history table silently stops+ # recording (its rows only ever arrive via this fan-out).+ (+ "both_mapped",+ {"payment_method": "schema_pm", "payment_method:history": "schema_hist"},+ ["schema_pm", "schema_hist"],+ ),+ # Existing sources without the history table keep the current single delivery.+ ("primary_only", {"payment_method": "schema_pm"}, ["schema_pm"]),+ # History enabled while the upsert table is not — the suffixed key must route alone.+ ("history_only", {"payment_method:history": "schema_hist"}, ["schema_hist"]),+ # No mapping for the object type at all — the event is skipped, not delivered.+ ("unmapped", {"charge": "schema_ch"}, []),+ ]+ )+ def test_payment_method_event_fanout(self, _name, schema_mapping, expected_schema_ids):+ secret = "whsec_test"+ body = {+ "id": "evt_1",+ "type": "payment_method.detached",+ "created": 1700000200,+ "data": {+ "object": {"id": "pm_1", "object": "payment_method", "customer": None},+ "previous_attributes": {"customer": "cus_1"},+ },+ }+ globals = self._make_signed_request(secret, body=body)+ self.run_function(+ {"signing_secret": secret, "bypass_signature_check": False, "schema_mapping": schema_mapping},+ globals=globals,+ )+ delivered = [call.args for call in self.mock_produce_to_warehouse_webhooks.call_args_list]+ assert delivered == [(globals["request"]["body"], schema_id) for schema_id in expected_schema_ids]+@parameterized.expand([("null", None),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/webhook_template.pyindex d73e84810047..16ff30a0e373 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/webhook_template.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/webhook_template.py@@ -97,7 +97,11 @@ if (empty(objectType)) {let schemaId := inputs.schema_mapping?.[objectType]-if (empty(schemaId)) {+// History tables receive the same events as the object type's primary table, under a+// ':history'-suffixed mapping key (see PAYMENT_METHOD_HISTORY_MAPPING_KEY in constants.py).+let historySchemaId := inputs.schema_mapping?.[concat(objectType, ':history')]++if (empty(schemaId) and empty(historySchemaId)) {return {'httpResponse': {'status': 200,@@ -106,7 +110,13 @@ if (empty(schemaId)) {}}-produceToWarehouseWebhooks(request.body, schemaId)""",+if (not empty(schemaId)) {+ produceToWarehouseWebhooks(request.body, schemaId)+}++if (not empty(historySchemaId)) {+ produceToWarehouseWebhooks(request.body, historySchemaId)+}""",inputs_schema=[{"type": "string",