: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 26 tables to the Stripe source (#73866)
Tom Owers95608b509719
diff --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 8ea5fbed2d3c..3cee07744994 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@@ -10,8 +10,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (+ APPLICATION_FEE_RESOURCE_NAME,BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_GRANT_RESOURCE_NAME,+ BILLING_METER_RESOURCE_NAME,CHARGE_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,@@ -19,13 +25,33 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conCUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,DISPUTE_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,+ ENTITLEMENTS_FEATURE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,INVOICE_ITEM_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,INVOICE_RESOURCE_NAME,+ PAYMENT_INTENT_RESOURCE_NAME,+ PAYMENT_LINK_RESOURCE_NAME,PAYOUT_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,PRICE_RESOURCE_NAME,PRODUCT_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ QUOTE_RESOURCE_NAME,REFUND_RESOURCE_NAME,+ REVIEW_RESOURCE_NAME,+ SETUP_ATTEMPT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,+ SUBSCRIPTION_ITEM_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ TAX_ID_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,)# Common Stripe fields shared by most objects; merged into each entry so we don't repeat them.@@ -38,6 +64,12 @@ _COMMON_COLUMNS = {}+# Not every Stripe object carries the full common set: some have no `metadata` (e.g. Event,+# ApplicationFee), and a few have no `created` at all (entitlement features, payment links).+_COMMON_COLUMNS_NO_METADATA = {k: v for k, v in _COMMON_COLUMNS.items() if k != "metadata"}+_COMMON_COLUMNS_NO_CREATED = {k: v for k, v in _COMMON_COLUMNS.items() if k != "created"}++def _columns(**overrides: str) -> dict[str, str]:return {**_COMMON_COLUMNS, **overrides}@@ -294,4 +326,439 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {end="Date the discount will end, as a Unix timestamp, if it is time-limited.",),},+ PAYMENT_INTENT_RESOURCE_NAME: {+ "description": "The full lifecycle of collecting one payment, including attempts that never became a charge.",+ "docs_url": "https://stripe.com/docs/api/payment_intents",+ "columns": _columns(+ amount="Amount intended to be collected, in the smallest currency unit (e.g. cents).",+ amount_capturable="Amount that can still be captured from this PaymentIntent.",+ amount_received="Amount this PaymentIntent has collected.",+ currency="Three-letter ISO currency code, in lowercase.",+ customer="ID of the customer this PaymentIntent belongs to, if one exists.",+ description="Arbitrary free-form description attached to the PaymentIntent.",+ status="Status of the PaymentIntent: requires_payment_method, requires_confirmation, requires_action, processing, requires_capture, canceled, or succeeded.",+ canceled_at="Time at which the PaymentIntent was canceled, as a Unix timestamp.",+ cancellation_reason="Why the PaymentIntent was canceled (e.g. duplicate, fraudulent, requested_by_customer, abandoned, failed_invoice).",+ capture_method="Controls when funds are captured from the customer's account.",+ confirmation_method="Whether the PaymentIntent can be confirmed automatically or needs customer action.",+ last_payment_error="The error from the previous confirmation attempt, cleared when the PaymentIntent is updated.",+ latest_charge="ID of the most recent charge created by this PaymentIntent.",+ payment_method="ID of the payment method used in this PaymentIntent.",+ payment_method_types="Payment method types this PaymentIntent is allowed to use.",+ application_fee_amount="Application fee requested on the payment and transferred to the platform account.",+ receipt_email="Email address the receipt for the resulting payment is sent to.",+ review="ID of the Radar review associated with this PaymentIntent, if any.",+ setup_future_usage="Whether the payment method is being saved for future on-session or off-session payments.",+ statement_descriptor="Text shown on the customer's statement for a non-card charge.",+ transfer_group="String identifying the resulting payment as part of a transfer group.",+ ),+ },+ CHECKOUT_SESSION_RESOURCE_NAME: {+ "description": "A customer's session paying through Stripe Checkout or a payment link, including sessions that were never completed.",+ "docs_url": "https://stripe.com/docs/api/checkout/sessions",+ "columns": _columns(+ amount_subtotal="Total of all items before discounts and taxes are applied.",+ amount_total="Total of all items after discounts and taxes are applied.",+ currency="Three-letter ISO currency code, in lowercase.",+ customer="ID of the customer for this session.",+ customer_email="Email used to create the Customer object, if provided up front.",+ client_reference_id="Your own reference for the session, used to reconcile it with your systems.",+ expires_at="Time at which the session expires, as a Unix timestamp.",+ invoice="ID of the invoice created by the session, if it exists.",+ mode="Mode of the session: payment, setup, or subscription.",+ payment_intent="ID of the PaymentIntent for sessions in payment mode.",+ payment_link="ID of the payment link that created this session.",+ payment_status="Payment status of the session: paid, unpaid, or no_payment_required.",+ setup_intent="ID of the SetupIntent for sessions in setup mode.",+ status="Status of the session: open, complete, or expired.",+ subscription="ID of the subscription for sessions in subscription mode.",+ success_url="URL the customer is sent to after a successful payment or subscription creation.",+ cancel_url="URL the customer is sent to if they cancel and return to your site.",+ url="URL of the hosted Checkout page for this session.",+ total_details="Tax and discount breakdown for the computed total.",+ ),+ },+ SUBSCRIPTION_ITEM_RESOURCE_NAME: {+ "description": "One priced line on a subscription, so multi-product subscriptions can be split by price.",+ "docs_url": "https://stripe.com/docs/api/subscription_items",+ "columns": _columns(+ subscription="ID of the subscription this item belongs to.",+ price="The price object this subscription item is billed against.",+ quantity="Quantity of the price the customer is subscribed to.",+ current_period_start="Start time of this subscription item's current billing period.",+ current_period_end="End time of this subscription item's current billing period.",+ billed_until="The time period the subscription item has been billed for.",+ discounts="Discounts applied to this subscription item, before subscription-level discounts.",+ tax_rates="Tax rates that apply to this subscription item, overriding the subscription defaults.",+ billing_thresholds="Usage thresholds that trigger an invoice and advance the billing period.",+ ),+ },+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME: {+ "description": "A predefined plan of phased changes to a subscription over time.",+ "docs_url": "https://stripe.com/docs/api/subscription_schedules",+ "columns": _columns(+ customer="ID of the customer who owns the subscription schedule.",+ subscription="ID of the subscription managed by the schedule.",+ status="Present status of the schedule: not_started, active, completed, released, or canceled.",+ phases="Configuration for each phase of the schedule.",+ current_phase="Start and end dates of the phase currently in effect, when the schedule is active.",+ default_settings="Settings applied to every phase that doesn't override them.",+ end_behavior="What happens when the schedule ends: release or cancel.",+ canceled_at="Time at which the schedule was canceled, as a Unix timestamp.",+ completed_at="Time at which the schedule completed, as a Unix timestamp.",+ released_at="Time at which the schedule was released, as a Unix timestamp.",+ released_subscription="ID of the subscription the schedule used to manage, once released.",+ application="ID of the Connect application that created the schedule.",+ test_clock="ID of the test clock this schedule belongs to.",+ ),+ },+ PROMOTION_CODE_RESOURCE_NAME: {+ "description": "A customer-redeemable code for a coupon, so you can see which code was actually used.",+ "docs_url": "https://stripe.com/docs/api/promotion_codes",+ "columns": _columns(+ code="The customer-facing code, unique across active promotion codes.",+ active="Whether the promotion code is currently active — it is only active if the coupon is also valid.",+ customer="ID of the customer who can use this promotion code, if it is restricted to one.",+ expires_at="Date after which the promotion code can no longer be redeemed, as a Unix timestamp.",+ max_redemptions="Maximum number of times this promotion code can be redeemed.",+ times_redeemed="Number of times this promotion code has been used.",+ restrictions="Restrictions on when the code applies (minimum amount, first-time customers, currency).",+ ),+ },+ PLAN_RESOURCE_NAME: {+ "description": "The legacy pricing model for recurring purchases, superseded by Price but still widely used.",+ "docs_url": "https://stripe.com/docs/api/plans",+ "columns": _columns(+ active="Whether the plan can be used for new purchases.",+ amount="Unit amount charged, in the smallest currency unit. Only set when billing_scheme is per_unit.",+ amount_decimal="Unit amount charged as a decimal string with up to 12 decimal places.",+ billing_scheme="How the price per period is computed: per_unit or tiered.",+ currency="Three-letter ISO currency code, in lowercase.",+ interval="Billing frequency: day, week, month, or year.",+ interval_count="Number of intervals between billings.",+ meter="ID of the meter tracking usage for a metered plan.",+ nickname="Brief internal description of the plan, hidden from customers.",+ product="ID of the product whose pricing this plan determines.",+ tiers="Pricing tiers, when billing_scheme is tiered.",+ tiers_mode="Whether tiering is graduated or volume based.",+ transform_usage="Transformation applied to reported usage before the amount is computed.",+ trial_period_days="Default number of trial days when subscribing with trial_from_plan.",+ usage_type="Whether the quantity per period is metered or licensed.",+ ),+ },+ TAX_RATE_RESOURCE_NAME: {+ "description": "A tax rate that can be applied to invoices, subscriptions, and Checkout Sessions.",+ "docs_url": "https://stripe.com/docs/api/tax_rates",+ "columns": _columns(+ active="Whether the tax rate can be used with new applications or Checkout Sessions.",+ display_name="Name of the tax rate as it appears to customers on receipts and invoices.",+ description="Internal description of the tax rate, not visible to customers.",+ percentage="Tax rate percentage out of 100.",+ effective_percentage="Effective tax rate percentage actually used in the calculation.",+ flat_amount="Amount charged when rate_type is flat_amount.",+ rate_type="Type of rate applied to the taxable amount, set for tax rates created by Stripe Tax.",+ inclusive="Whether the tax rate is inclusive or exclusive of the price.",+ country="Two-letter ISO country code for the tax rate.",+ state="ISO 3166-2 subdivision code, without the country prefix.",+ jurisdiction="Label for the jurisdiction imposing the tax rate, shown on invoices.",+ jurisdiction_level="Level of the jurisdiction imposing this rate — null for manually defined rates.",+ tax_type="High-level tax type, such as vat or sales_tax.",+ ),+ },+ TAX_ID_RESOURCE_NAME: {+ "description": "A tax identification number registered on the account (customer-owned tax IDs live on the customer).",+ "docs_url": "https://stripe.com/docs/api/tax_ids",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "type": "Type of the tax ID, such as eu_vat, us_ein, or gb_vat.",+ "value": "Value of the tax ID.",+ "country": "Two-letter ISO country code representing the country of the tax ID.",+ "owner": "The account or customer the tax ID belongs to.",+ "customer": "ID of the customer the tax ID belongs to, when owned by a customer.",+ "verification": "Verification status and verified details for the tax ID.",+ },+ },+ QUOTE_RESOURCE_NAME: {+ "description": "A proposed set of prices for a customer that creates an invoice, subscription, or schedule once accepted.",+ "docs_url": "https://stripe.com/docs/api/quotes",+ "columns": _columns(+ amount_subtotal="Total before any discounts or taxes are applied.",+ amount_total="Total after discounts and taxes are applied.",+ currency="Three-letter ISO currency code, in lowercase.",+ customer="ID of the customer who received this quote.",+ number="Unique number identifying the quote, assigned once it is finalized.",+ status="Status of the quote: draft, open, accepted, or canceled.",+ status_transitions="Timestamps of the quote's status changes.",+ expires_at="Date the quote is canceled if still open or draft, as a Unix timestamp.",+ description="Description displayed on the quote PDF.",+ footer="Footer displayed on the quote PDF.",+ header="Header displayed on the quote PDF.",+ invoice="ID of the invoice created from this quote.",+ subscription="ID of the subscription created or updated from this quote.",+ subscription_schedule="ID of the subscription schedule created or updated from this quote.",+ collection_method="Whether invoices are charged automatically or sent to the customer.",+ default_tax_rates="Tax rates applied to this quote.",+ discounts="Discounts applied to this quote.",+ total_details="Tax and discount breakdown for the total.",+ from_quote="Details of the quote this one was cloned from.",+ test_clock="ID of the test clock this quote belongs to.",+ ),+ },+ EVENT_RESOURCE_NAME: {+ "description": "Stripe's own log of activity in your account — a generic change feed across every resource. Stripe retains events for 30 days.",+ "docs_url": "https://stripe.com/docs/api/events",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "type": "Description of the event, for example invoice.created or charge.refunded.",+ "data": "The object affected by the event, plus the fields that changed.",+ "api_version": "Stripe API version used to render the event's data.",+ "account": "ID of the connected account the event originates from.",+ "request": "Information about the API request that triggered the event.",+ "pending_webhooks": "Number of webhooks that have not yet been delivered successfully.",+ "context": "Authentication context needed to fetch the event or related object.",+ },+ },+ BILLING_METER_RESOURCE_NAME: {+ "description": "A definition of how usage events are aggregated over a billing period for usage-based pricing.",+ "docs_url": "https://stripe.com/docs/api/billing/meter",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "display_name": "The meter's name.",+ "event_name": "Name of the meter event whose usage this meter records.",+ "event_time_window": "Time window meter events are pre-aggregated over, if any.",+ "status": "The meter's status: active or inactive.",+ "status_transitions": "Timestamps of the meter's status changes.",+ "default_aggregation": "How meter events are aggregated by default, for example sum or count.",+ "customer_mapping": "How meter events are mapped onto customers.",+ "value_settings": "Which payload key on the meter event holds the value to aggregate.",+ "updated": "Time at which the meter was last updated, as a Unix timestamp.",+ },+ },+ BILLING_CREDIT_GRANT_RESOURCE_NAME: {+ "description": "An allocation of billing credits to a customer for usage-based billing.",+ "docs_url": "https://stripe.com/docs/api/billing/credit-grant",+ "columns": _columns(+ name="Descriptive name for the credit grant, shown in the dashboard.",+ customer="ID of the customer receiving the billing credits.",+ amount="Amount of credits granted, with its monetary or custom pricing unit.",+ category="Category of the grant, for tracking purposes and not shown to the customer.",+ applicability_config="Which prices the credits can be applied to.",+ effective_at="Time the credits become eligible for use, as a Unix timestamp.",+ expires_at="Time the credits expire, as a Unix timestamp. Absent when they do not expire.",+ voided_at="Time the grant was voided, as a Unix timestamp. Absent when it has not been voided.",+ priority="Priority for applying this grant, where 0 is highest and 100 lowest.",+ test_clock="ID of the test clock this credit grant belongs to.",+ updated="Time at which the credit grant was last updated, as a Unix timestamp.",+ ),+ },+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: {+ "description": "A credit or debit against an existing billing credit grant.",+ "docs_url": "https://stripe.com/docs/api/billing/credit-balance-transaction",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "type": "Whether the transaction is a credit or a debit.",+ "credit_grant": "ID of the credit grant this transaction applies to.",+ "credit": "Credit details, present only when type is credit.",+ "debit": "Debit details, present only when type is debit.",+ "effective_at": "Effective time of this transaction, as a Unix timestamp.",+ "test_clock": "ID of the test clock this transaction belongs to.",+ },+ },+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME: {+ "description": "A customer's current billing credit balance, scoped to one credit grant.",+ "docs_url": "https://stripe.com/docs/api/billing/credit-balance-summary",+ "columns": {+ "object": _COMMON_COLUMNS["object"],+ "livemode": _COMMON_COLUMNS["livemode"],+ "customer": "ID of the customer the balance belongs to.",+ "balances": "Available and ledger balances for the credit grant, by applicability scope.",+ "credit_grant": "ID of the credit grant this summary was fetched for.",+ },+ },+ ENTITLEMENTS_FEATURE_RESOURCE_NAME: {+ "description": "A monetizable capability in your product that customers can be entitled to.",+ "docs_url": "https://stripe.com/docs/api/entitlements/feature",+ "columns": {+ **_COMMON_COLUMNS_NO_CREATED,+ "name": "The feature's internal name, not meant to be shown to customers.",+ "lookup_key": "Your own system identifier for the feature, up to 80 characters.",+ "active": "Whether the feature can still be attached to new products.",+ },+ },+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME: {+ "description": "A customer's current access to a feature, granted by the products they have purchased.",+ "docs_url": "https://stripe.com/docs/api/entitlements/active-entitlement",+ "columns": {+ "id": _COMMON_COLUMNS["id"],+ "object": _COMMON_COLUMNS["object"],+ "livemode": _COMMON_COLUMNS["livemode"],+ "feature": "ID of the feature the customer is entitled to.",+ "lookup_key": "Your own system identifier for the entitled feature.",+ "customer": "ID of the customer this entitlement was fetched for.",+ },+ },+ INVOICE_PAYMENT_RESOURCE_NAME: {+ "description": "A payment made against an invoice, mapping the invoice to the payment object that settled it.",+ "docs_url": "https://stripe.com/docs/api/invoice-payment",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "invoice": "ID of the invoice that was paid.",+ "payment": "The payment object, such as a PaymentIntent, that paid the invoice.",+ "amount_requested": "Amount intended to be paid toward this invoice, in the smallest currency unit.",+ "amount_paid": "Amount actually paid, in the smallest currency unit. Null until the payment is paid.",+ "currency": "Three-letter ISO currency code, in lowercase.",+ "status": "Status of the payment: open, paid, or canceled.",+ "status_transitions": "Timestamps of the payment's status changes.",+ "is_default": "Whether this is the default payment Stripe keeps in sync with the invoice's amount remaining.",+ },+ },+ SETUP_INTENT_RESOURCE_NAME: {+ "description": "The flow for saving a customer's payment credentials for later payments.",+ "docs_url": "https://stripe.com/docs/api/setup_intents",+ "columns": _columns(+ customer="ID of the customer this SetupIntent belongs to, if one exists.",+ description="Arbitrary free-form description attached to the SetupIntent.",+ status="Status of the SetupIntent: requires_payment_method, requires_confirmation, requires_action, processing, canceled, or succeeded.",+ cancellation_reason="Why the SetupIntent was canceled: abandoned, requested_by_customer, or duplicate.",+ payment_method="ID of the payment method used with this SetupIntent.",+ payment_method_types="Payment method types this SetupIntent is allowed to set up.",+ latest_attempt="ID of the most recent SetupAttempt for this SetupIntent.",+ last_setup_error="The error from the previous confirmation attempt, if any.",+ mandate="ID of the multi-use mandate generated by the SetupIntent.",+ single_use_mandate="ID of the single-use mandate generated by the SetupIntent.",+ usage="Whether the payment method is intended for on_session or off_session reuse.",+ flow_directions="Directions of money movement the payment method is intended for.",+ on_behalf_of="ID of the connected account the setup is intended for.",+ ),+ },+ SETUP_ATTEMPT_RESOURCE_NAME: {+ "description": "One attempt to confirm a SetupIntent, successful or not.",+ "docs_url": "https://stripe.com/docs/api/setup_attempts",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "setup_intent": "ID of the SetupIntent this attempt belongs to.",+ "status": "Status of the attempt: requires_confirmation, requires_action, processing, succeeded, failed, or abandoned.",+ "customer": "The SetupIntent's customer at the time of this confirmation.",+ "payment_method": "ID of the payment method used with this attempt.",+ "payment_method_details": "Details of the payment method at the time of this attempt.",+ "setup_error": "The error encountered during this attempt, if any.",+ "usage": "The SetupIntent's usage at the time of this confirmation: off_session or on_session.",+ "flow_directions": "Directions of money movement the payment method is intended for.",+ "application": "The SetupIntent's Connect application at the time of this confirmation.",+ "on_behalf_of": "The SetupIntent's on_behalf_of account at the time of this confirmation.",+ },+ },+ PAYMENT_LINK_RESOURCE_NAME: {+ "description": "A shareable URL that opens a hosted payment page and can be used repeatedly.",+ "docs_url": "https://stripe.com/docs/api/payment_links/payment_links",+ "columns": {+ **_COMMON_COLUMNS_NO_CREATED,+ "url": "The public URL that can be shared with customers.",+ "active": "Whether the payment link's URL is still active.",+ "currency": "Three-letter ISO currency code, in lowercase.",+ "line_items": "The line items representing what is being sold.",+ "allow_promotion_codes": "Whether customers can redeem promotion codes.",+ "after_completion": "What happens after the customer completes the payment.",+ "customer_creation": "Whether checkout creates a Customer for this link.",+ "payment_method_types": "Payment method types customers can use, or null for dynamic selection.",+ "payment_method_collection": "Whether a payment method is collected during checkout.",+ "subscription_data": "Configuration used when the link creates a subscription.",+ "inactive_message": "Message shown to customers when the link is no longer active.",+ "restrictions": "Settings that restrict how the payment link can be used.",+ "application_fee_amount": "Application fee requested on the payment and transferred to the platform account.",+ },+ },+ TRANSFER_RESOURCE_NAME: {+ "description": "A movement of funds between Stripe accounts as part of Connect.",+ "docs_url": "https://stripe.com/docs/api/transfers",+ "columns": _columns(+ amount="Amount transferred, in the smallest currency unit.",+ amount_reversed="Amount reversed, in the smallest currency unit.",+ currency="Three-letter ISO currency code, in lowercase.",+ description="Arbitrary free-form description attached to the transfer.",+ destination="ID of the Stripe account the transfer was sent to.",+ destination_payment="ID of the payment the destination account received for the transfer.",+ balance_transaction="ID of the balance transaction describing this transfer's impact on your balance.",+ source_transaction="ID of the charge that funded the transfer, if it was not funded from the available balance.",+ source_type="Balance the transfer came from: card, fpx, or bank_account.",+ reversals="Reversals applied to the transfer.",+ reversed="Whether the transfer has been fully reversed.",+ transfer_group="String identifying this transaction as part of a transfer group.",+ ),+ },+ APPLICATION_FEE_RESOURCE_NAME: {+ "description": "A fee a Connect platform earned on a charge made by a connected account.",+ "docs_url": "https://stripe.com/docs/api/application_fees",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "account": "ID of the Stripe account this fee was taken from.",+ "amount": "Amount earned, in the smallest currency unit.",+ "amount_refunded": "Amount of the fee refunded, in the smallest currency unit.",+ "currency": "Three-letter ISO currency code, in lowercase.",+ "application": "ID of the Connect application that earned the fee.",+ "charge": "ID of the charge the application fee was taken from.",+ "balance_transaction": "ID of the balance transaction describing this fee's impact on your balance.",+ "originating_transaction": "ID of the corresponding charge on the platform account, for destination charges.",+ "refunded": "Whether the fee has been fully refunded.",+ "refunds": "Refunds applied to the fee.",+ "fee_source": "The object the application fee was created from.",+ },+ },+ TOPUP_RESOURCE_NAME: {+ "description": "A top-up that adds funds to your Stripe balance.",+ "docs_url": "https://stripe.com/docs/api/topups",+ "columns": _columns(+ amount="Amount transferred, in the smallest currency unit.",+ currency="Three-letter ISO currency code, in lowercase.",+ description="Arbitrary free-form description attached to the top-up.",+ status="Status of the top-up: canceled, failed, pending, reversed, or succeeded.",+ balance_transaction="ID of the balance transaction describing this top-up's impact on your balance.",+ expected_availability_date="Date the funds are expected to arrive in your Stripe account.",+ failure_code="Error code explaining why the top-up failed, if it did.",+ failure_message="Message explaining why the top-up failed, if it did.",+ statement_descriptor="Extra information shown on the source's bank statement.",+ transfer_group="String identifying this top-up as part of a group.",+ ),+ },+ REVIEW_RESOURCE_NAME: {+ "description": "A Radar review of a payment, used to supplement automated fraud detection with human decisions.",+ "docs_url": "https://stripe.com/docs/api/radar/reviews",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "charge": "ID of the charge associated with this review.",+ "payment_intent": "ID of the PaymentIntent associated with this review, if one exists.",+ "open": "Whether the review still needs action.",+ "opened_reason": "Why the review was opened: rule or manual.",+ "closed_reason": "Why the review was closed, or null if it is still open.",+ "reason": "Why the review is currently open or closed.",+ "billing_zip": "ZIP or postal code of the card used, if applicable.",+ "ip_address": "IP address the payment originated from.",+ "ip_address_location": "Approximate location derived from the payment's IP address.",+ "session": "Information about the browsing session of the user who initiated the payment.",+ },+ },+ EARLY_FRAUD_WARNING_RESOURCE_NAME: {+ "description": "A notice from the card issuer that a charge may be fraudulent, usually ahead of a dispute.",+ "docs_url": "https://stripe.com/docs/api/radar/early_fraud_warnings",+ "columns": {+ **_COMMON_COLUMNS_NO_METADATA,+ "charge": "ID of the charge this early fraud warning is for.",+ "payment_intent": "ID of the PaymentIntent this early fraud warning is for.",+ "fraud_type": "Type of fraud labelled by the issuer, such as made_with_stolen_card or unauthorized_use_of_card.",+ "actionable": "Whether the warning has not yet received a dispute and has not been fully refunded.",+ },+ },+ SHIPPING_RATE_RESOURCE_NAME: {+ "description": "The price of shipping presented to customers and applied to a purchase.",+ "docs_url": "https://stripe.com/docs/api/shipping_rates",+ "columns": _columns(+ display_name="Name of the shipping rate shown to the customer.",+ active="Whether the shipping rate can be used for new purchases.",+ type="Calculation used for the shipping rate.",+ fixed_amount="Fixed amount and currency charged for shipping.",+ delivery_estimate="Estimated range for how long shipping takes, shown to the customer.",+ tax_behavior="Whether the rate is inclusive of, exclusive of, or unspecified for taxes.",+ tax_code="Tax code ID for the shipping rate.",+ ),+ },}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 8325823ae617..bed13941b9e9 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@@ -15,12 +15,45 @@ CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME = "CustomerBalanceTransaction"CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME = "CustomerPaymentMethod"COUPON_RESOURCE_NAME = "Coupon"DISCOUNT_RESOURCE_NAME = "Discount"+PAYMENT_INTENT_RESOURCE_NAME = "PaymentIntent"+CHECKOUT_SESSION_RESOURCE_NAME = "CheckoutSession"+SUBSCRIPTION_ITEM_RESOURCE_NAME = "SubscriptionItem"+SUBSCRIPTION_SCHEDULE_RESOURCE_NAME = "SubscriptionSchedule"+PROMOTION_CODE_RESOURCE_NAME = "PromotionCode"+PLAN_RESOURCE_NAME = "Plan"+TAX_RATE_RESOURCE_NAME = "TaxRate"+TAX_ID_RESOURCE_NAME = "TaxId"+QUOTE_RESOURCE_NAME = "Quote"+EVENT_RESOURCE_NAME = "Event"+BILLING_METER_RESOURCE_NAME = "BillingMeter"+BILLING_CREDIT_GRANT_RESOURCE_NAME = "BillingCreditGrant"+BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME = "BillingCreditBalanceTransaction"+BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME = "BillingCreditBalanceSummary"+ENTITLEMENTS_FEATURE_RESOURCE_NAME = "EntitlementsFeature"+ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME = "EntitlementsActiveEntitlement"+INVOICE_PAYMENT_RESOURCE_NAME = "InvoicePayment"+SETUP_INTENT_RESOURCE_NAME = "SetupIntent"+SETUP_ATTEMPT_RESOURCE_NAME = "SetupAttempt"+PAYMENT_LINK_RESOURCE_NAME = "PaymentLink"+TRANSFER_RESOURCE_NAME = "Transfer"+APPLICATION_FEE_RESOURCE_NAME = "ApplicationFee"+TOPUP_RESOURCE_NAME = "Topup"+REVIEW_RESOURCE_NAME = "Review"+EARLY_FRAUD_WARNING_RESOURCE_NAME = "EarlyFraudWarning"+SHIPPING_RATE_RESOURCE_NAME = "ShippingRate"# Vendor API version the sync pipeline pins by default. One constant so the source's version# declaration (`StripeSource.supported_versions`) and the request layer share a single label.STRIPE_API_VERSION_ACACIA = "2024-09-30.acacia"# 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+# event and looks the value up here to find the table to write into. A resource missing from this+# map can never be fed by a webhook, no matter how many events the endpoint subscribes to.+#+# 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.RESOURCE_TO_STRIPE_OBJECT_TYPE: dict[str, str] = {ACCOUNT_RESOURCE_NAME: "account",BALANCE_TRANSACTION_RESOURCE_NAME: "balance_transaction",@@ -39,6 +72,27 @@ RESOURCE_TO_STRIPE_OBJECT_TYPE: dict[str, str] = {CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: "payment_method",COUPON_RESOURCE_NAME: "coupon",DISCOUNT_RESOURCE_NAME: "discount",+ PAYMENT_INTENT_RESOURCE_NAME: "payment_intent",+ CHECKOUT_SESSION_RESOURCE_NAME: "checkout.session",+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME: "subscription_schedule",+ PROMOTION_CODE_RESOURCE_NAME: "promotion_code",+ PLAN_RESOURCE_NAME: "plan",+ TAX_RATE_RESOURCE_NAME: "tax_rate",+ # Stripe namespaces the event as `customer.tax_id.*` but puts a bare `tax_id` object on it, so+ # this map and RESOURCE_TO_STRIPE_WEBHOOK_EVENT deliberately disagree for this one resource.+ TAX_ID_RESOURCE_NAME: "tax_id",+ QUOTE_RESOURCE_NAME: "quote",+ BILLING_METER_RESOURCE_NAME: "billing.meter",+ BILLING_CREDIT_GRANT_RESOURCE_NAME: "billing.credit_grant",+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: "billing.credit_balance_transaction",+ INVOICE_PAYMENT_RESOURCE_NAME: "invoice_payment",+ SETUP_INTENT_RESOURCE_NAME: "setup_intent",+ PAYMENT_LINK_RESOURCE_NAME: "payment_link",+ TRANSFER_RESOURCE_NAME: "transfer",+ APPLICATION_FEE_RESOURCE_NAME: "application_fee",+ TOPUP_RESOURCE_NAME: "topup",+ REVIEW_RESOURCE_NAME: "review",+ EARLY_FRAUD_WARNING_RESOURCE_NAME: "radar.early_fraud_warning",}RESOURCE_TO_STRIPE_WEBHOOK_EVENT: dict[str, str] = {@@ -64,4 +118,41 @@ RESOURCE_TO_STRIPE_WEBHOOK_EVENT: dict[str, str] = {CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: "payment_method",COUPON_RESOURCE_NAME: "coupon",DISCOUNT_RESOURCE_NAME: "customer.discount",+ PAYMENT_INTENT_RESOURCE_NAME: "payment_intent",+ CHECKOUT_SESSION_RESOURCE_NAME: "checkout.session",+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME: "subscription_schedule",+ PROMOTION_CODE_RESOURCE_NAME: "promotion_code",+ PLAN_RESOURCE_NAME: "plan",+ TAX_RATE_RESOURCE_NAME: "tax_rate",+ # `customer.tax_id.*` events were already arriving via the CUSTOMER "customer" prefix; they+ # simply had nowhere to route until TaxId joined RESOURCE_TO_STRIPE_OBJECT_TYPE. Naming the+ # narrower prefix here is what makes the schema advertise `supports_webhooks` in the picker.+ TAX_ID_RESOURCE_NAME: "customer.tax_id",+ QUOTE_RESOURCE_NAME: "quote",+ BILLING_METER_RESOURCE_NAME: "billing.meter",+ BILLING_CREDIT_GRANT_RESOURCE_NAME: "billing.credit_grant",+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: "billing.credit_balance_transaction",+ INVOICE_PAYMENT_RESOURCE_NAME: "invoice_payment",+ SETUP_INTENT_RESOURCE_NAME: "setup_intent",+ PAYMENT_LINK_RESOURCE_NAME: "payment_link",+ # Duplicates the "transfer" prefix BalanceTransaction already carries. Harmless: this map's+ # values are collapsed to a set to build the subscription, and the two tables stay distinct+ # because routing keys off the object type (`balance_transaction` vs `transfer`), not the event.+ TRANSFER_RESOURCE_NAME: "transfer",+ APPLICATION_FEE_RESOURCE_NAME: "application_fee",+ TOPUP_RESOURCE_NAME: "topup",+ REVIEW_RESOURCE_NAME: "review",+ EARLY_FRAUD_WARNING_RESOURCE_NAME: "radar.early_fraud_warning",+ # Deliberately absent, because Stripe emits no event carrying these objects. Verified against+ # the `enabled_events` literal in the pinned SDK, which is the same list `_all_known_webhook_events`+ # filters. They stay API-sweep-only:+ # SubscriptionItem - changes ride along on `customer.subscription.*` as nested `items`+ # SetupAttempt - no `setup_attempt.*` events exist+ # ShippingRate - no `shipping_rate.*` events exist+ # Event - the event log itself; subscribing to it to populate it is circular+ # BillingCreditBalanceSummary - only reachable as a retrieve off a credit grant+ # EntitlementsFeature - no `entitlements.feature.*` events exist+ # EntitlementsActiveEntitlement - the one entitlements event carries an+ # `entitlements.active_entitlement_summary` object (a per-customer summary), not an+ # individual active entitlement, so routing it here would write the wrong shape.}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 24c2720ffc7e..a2c7ae309188 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@@ -6,8 +6,14 @@from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (ACCOUNT_RESOURCE_NAME,+ APPLICATION_FEE_RESOURCE_NAME,BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_GRANT_RESOURCE_NAME,+ BILLING_METER_RESOURCE_NAME,CHARGE_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,@@ -15,13 +21,33 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.conCUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,DISPUTE_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,+ ENTITLEMENTS_FEATURE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,INVOICE_ITEM_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,INVOICE_RESOURCE_NAME,+ PAYMENT_INTENT_RESOURCE_NAME,+ PAYMENT_LINK_RESOURCE_NAME,PAYOUT_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,PRICE_RESOURCE_NAME,PRODUCT_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ QUOTE_RESOURCE_NAME,REFUND_RESOURCE_NAME,+ REVIEW_RESOURCE_NAME,+ SETUP_ATTEMPT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,+ SUBSCRIPTION_ITEM_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ TAX_ID_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -42,6 +68,32 @@ ENDPOINTS = (CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,COUPON_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,+ PAYMENT_INTENT_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,+ SUBSCRIPTION_ITEM_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ TAX_ID_RESOURCE_NAME,+ QUOTE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,+ BILLING_METER_RESOURCE_NAME,+ BILLING_CREDIT_GRANT_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+ ENTITLEMENTS_FEATURE_RESOURCE_NAME,+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ SETUP_ATTEMPT_RESOURCE_NAME,+ PAYMENT_LINK_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,+ APPLICATION_FEE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ REVIEW_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,)@@ -60,11 +112,44 @@ INCREMENTAL_ENDPOINTS = (SUBSCRIPTION_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,COUPON_RESOURCE_NAME,+ PAYMENT_INTENT_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,+ APPLICATION_FEE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ REVIEW_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,)# Endpoints that have no API list path — populated only via webhooks.WEBHOOK_ONLY_ENDPOINTS = (DISCOUNT_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.+NON_PARTITIONED_ENDPOINTS = (+ ENTITLEMENTS_FEATURE_RESOURCE_NAME,+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,+ PAYMENT_LINK_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+)++# 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.+PRIMARY_KEYS: dict[str, list[str]] = {+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME: ["credit_grant"],+}+DEFAULT_PRIMARY_KEYS = ["id"]+APPEND_ONLY_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {ACCOUNT_RESOURCE_NAME: [{@@ -189,4 +274,36 @@ APPEND_ONLY_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"field_type": IncrementalFieldType.Integer,}],+ **{+ # Every one of these list endpoints accepts the server-side `created` range filter+ # (`created[gt]` / `created[lt]`), which is what `get_rows` sends for an append sync, and+ # every object carries a `created` Unix timestamp. Endpoints whose list path has no+ # `created` filter (e.g. Quote, TaxId, the billing.* resources) stay full refresh and simply+ # partition on the object's own `created` via the fallback in `stripe_source`.+ endpoint: [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created",+ "field_type": IncrementalFieldType.Integer,+ }+ ]+ for endpoint in (+ PAYMENT_INTENT_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,+ APPLICATION_FEE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ REVIEW_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,+ )+ },}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 94f7517d2763..4847df2a8625 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@@ -16,7 +16,10 @@ from structlog.types import FilteringBoundLoggerfrom posthog.temporal.common.logger import get_logger-from products.warehouse_sources.backend.models.external_table_definitions import get_dlt_mapping_for_external_table+from products.warehouse_sources.backend.models.external_table_definitions import (+ external_tables,+ get_dlt_mapping_for_external_table,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (@@ -31,26 +34,55 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (ACCOUNT_RESOURCE_NAME,+ APPLICATION_FEE_RESOURCE_NAME,BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_GRANT_RESOURCE_NAME,+ BILLING_METER_RESOURCE_NAME,CHARGE_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISPUTE_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,+ ENTITLEMENTS_FEATURE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,INVOICE_ITEM_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,INVOICE_RESOURCE_NAME,+ PAYMENT_INTENT_RESOURCE_NAME,+ PAYMENT_LINK_RESOURCE_NAME,PAYOUT_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,PRICE_RESOURCE_NAME,PRODUCT_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ QUOTE_RESOURCE_NAME,REFUND_RESOURCE_NAME,RESOURCE_TO_STRIPE_WEBHOOK_EVENT,+ REVIEW_RESOURCE_NAME,+ SETUP_ATTEMPT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,+ SUBSCRIPTION_ITEM_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ TAX_ID_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLinesfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (APPEND_ONLY_INCREMENTAL_FIELDS,+ DEFAULT_PRIMARY_KEYS,+ NON_PARTITIONED_ENDPOINTS,+ PRIMARY_KEYS,WEBHOOK_ONLY_ENDPOINTS,)@@ -306,6 +338,10 @@ class StripeNestedResource:parent: StripeResourceparent_name: str = ""params: dict[str, Any] = dataclasses.field(default_factory=dict)+ # Optional builder for request params that depend on fields of the parent object beyond its id+ # (e.g. the credit balance summary needs the grant's customer as well as the grant id). Merged+ # over the resource's static params; unset for every resource keyed solely by the parent id.+ nested_params_from_parent: Optional[Callable[[dict[str, Any]], dict[str, Any]]] = None# Optional predicate over a parent object. When set and it returns False, we skip the nested# API call for that parent entirely. Stripe has no top-level list for these nested resources, so# the default behaviour fans out one call per parent — most of which return nothing. A cheap@@ -313,6 +349,46 @@ class StripeNestedResource:parent_has_nested: Optional[Callable[[dict[str, Any]], bool]] = None+class _SingleObjectList:+ """Presents one retrieved Stripe object through the ``auto_paging_iter`` interface every other+ resource in ``_build_resources`` exposes, so a retrieve-only endpoint rides the same fan-out+ path as the list endpoints instead of needing its own branch in ``get_rows``."""++ def __init__(self, obj: Any) -> None:+ self._obj = obj++ def auto_paging_iter(self):+ yield self._obj+++def _credit_balance_summary_lister(client: StripeClient) -> Callable[..., ListObject[Any]]:+ """`/v1/billing/credit_balance_summary` is a retrieve, not a list: it returns the balance for one+ customer under a required `filter`. We scope it to a single credit grant so each row is the+ current balance of a grant we already sync."""++ def _retrieve(credit_grant: str, params: dict[str, Any]) -> ListObject[Any]:+ summary = client.billing.credit_balance_summary.retrieve(+ params={+ "customer": params["customer"],+ "filter": {"type": "credit_grant", "credit_grant": credit_grant},+ }+ )+ return cast(ListObject[Any], _SingleObjectList(summary))++ return _retrieve+++def _credit_grant_customer_params(credit_grant: dict[str, Any]) -> dict[str, Any]:+ return {"customer": credit_grant.get("customer")}+++def _credit_grant_has_customer(credit_grant: dict[str, Any]) -> bool:+ """Credit grants issued to an Account rather than a Customer carry `customer_account` instead of+ `customer`. The summary endpoint takes one or the other, and we scope on `customer`, so skip the+ rest rather than sending a request Stripe would reject."""+ return bool(credit_grant.get("customer"))++def _customer_might_have_balance_transactions(customer: dict[str, Any]) -> bool:"""Skip the per-customer balance-transactions call when the customer's credit balance is exactly 0.@@ -334,6 +410,28 @@ class StripeResumeConfig:starting_after: str+def _scrub_client_secrets(obj: Any) -> Any:+ """Recursively strip Stripe ``client_secret`` values before an object is persisted to a warehouse table.++ PaymentIntent, SetupIntent, and embedded/custom Checkout Session objects carry a ``client_secret``+ that authorizes Stripe's client-side API to retrieve or confirm that specific payment or setup flow.+ Stripe requires it never be stored, logged, or exposed to anyone but the customer it belongs to, so+ persisting it into a queryable table would let anyone with warehouse access act on another customer's+ flow. Event objects embed full copies of these resources under ``data.object`` and+ ``data.previous_attributes``, so the walk descends into every nested mapping and list rather than only+ checking the top level.++ Returns scrubbed plain ``dict``/``list`` structures (scalars pass through unchanged). ``StripeObject``+ is a ``dict`` subclass, so nested SDK objects flatten into plain dicts, which the batcher already+ serializes the same way it handles the nested-resource dicts.+ """+ if isinstance(obj, Mapping):+ return {key: _scrub_client_secrets(value) for key, value in obj.items() if key != "client_secret"}+ if isinstance(obj, list):+ return [_scrub_client_secrets(value) for value in obj]+ return obj++def _batch_and_yield(objects: Any,batcher: Batcher,@@ -347,7 +445,7 @@ def _batch_and_yield(if stop_at_or_before is not None and incremental_field_name is not None:if obj[incremental_field_name] <= stop_at_or_before:break- batcher.batch(obj)+ batcher.batch(_scrub_client_secrets(obj))while batcher.should_yield():yield batcher.get_table()@@ -417,6 +515,68 @@ def _build_resources(parent=StripeResource(method=client.customers.list),parent_name=CUSTOMER_RESOURCE_NAME,),+ 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),+ PROMOTION_CODE_RESOURCE_NAME: StripeResource(method=client.promotion_codes.list),+ # Tiers are only returned when expanded, same as Price. Key must be "expand[]" for a single+ # string value (see the Subscription note above for the list-valued form).+ PLAN_RESOURCE_NAME: StripeResource(method=client.plans.list, params={"expand[]": "data.tiers"}),+ TAX_RATE_RESOURCE_NAME: StripeResource(method=client.tax_rates.list),+ # `/v1/tax_ids` without an `owner` filter lists the account's own tax IDs. Customer-owned tax+ # IDs live under the customer and are not part of this list.+ TAX_ID_RESOURCE_NAME: StripeResource(method=client.tax_ids.list),+ QUOTE_RESOURCE_NAME: StripeResource(method=client.quotes.list),+ 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),+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: StripeResource(+ method=client.billing.credit_balance_transactions.list+ ),+ ENTITLEMENTS_FEATURE_RESOURCE_NAME: StripeResource(method=client.entitlements.features.list),+ INVOICE_PAYMENT_RESOURCE_NAME: StripeResource(method=client.invoice_payments.list),+ SETUP_INTENT_RESOURCE_NAME: StripeResource(method=client.setup_intents.list),+ PAYMENT_LINK_RESOURCE_NAME: StripeResource(method=client.payment_links.list),+ TRANSFER_RESOURCE_NAME: StripeResource(method=client.transfers.list),+ APPLICATION_FEE_RESOURCE_NAME: StripeResource(method=client.application_fees.list),+ TOPUP_RESOURCE_NAME: StripeResource(method=client.topups.list),+ REVIEW_RESOURCE_NAME: StripeResource(method=client.reviews.list),+ EARLY_FRAUD_WARNING_RESOURCE_NAME: StripeResource(method=client.radar.early_fraud_warnings.list),+ 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.+ SUBSCRIPTION_ITEM_RESOURCE_NAME: StripeNestedResource(+ method=client.subscription_items.list,+ nested_parent_param="subscription",+ parent_id="id",+ parent=StripeResource(method=client.subscriptions.list, params={"status": "all"}),+ parent_name=SUBSCRIPTION_RESOURCE_NAME,+ ),+ # `/v1/entitlements/active_entitlements` requires a `customer`.+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME: StripeNestedResource(+ method=client.entitlements.active_entitlements.list,+ nested_parent_param="customer",+ parent_id="id",+ parent=StripeResource(method=client.customers.list),+ parent_name=CUSTOMER_RESOURCE_NAME,+ ),+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME: StripeNestedResource(+ method=_credit_balance_summary_lister(client),+ nested_parent_param="credit_grant",+ parent_id="id",+ parent=StripeResource(method=client.billing.credit_grants.list),+ parent_name=BILLING_CREDIT_GRANT_RESOURCE_NAME,+ parent_has_nested=_credit_grant_has_customer,+ nested_params_from_parent=_credit_grant_customer_params,+ ),+ # `/v1/setup_attempts` requires a `setup_intent`.+ SETUP_ATTEMPT_RESOURCE_NAME: StripeNestedResource(+ method=client.setup_attempts.list,+ nested_parent_param="setup_intent",+ parent_id="id",+ parent=StripeResource(method=client.setup_intents.list),+ parent_name=SETUP_INTENT_RESOURCE_NAME,+ ),}@@ -489,18 +649,21 @@ def get_rows(if resource.parent_has_nested is not None and not resource.parent_has_nested(obj):skipped_parents += 1continue+ parent_params = resource.nested_params_from_parent(obj) if resource.nested_params_from_parent else {}try:stripe_nested_objects = _call_stripe(resource.method,**{resource.nested_parent_param: parent_obj_id},- params={**default_params, **resource.params},+ params={**default_params, **resource.params, **parent_params},)for nested_obj in stripe_nested_objects.auto_paging_iter():batcher.batch(- {- **nested_obj,- **{resource.nested_parent_param: parent_obj_id},- }+ _scrub_client_secrets(+ {+ **nested_obj,+ **{resource.nested_parent_param: parent_obj_id},+ }+ ))# A single batch can split into several ready chunks, so drain them all@@ -528,7 +691,7 @@ def get_rows(resource.method, params={**default_params, **resource.params, **resume_params})for obj in stripe_objects.auto_paging_iter():- batcher.batch(obj)+ batcher.batch(_scrub_client_secrets(obj))while batcher.should_yield():py_table = batcher.get_table()@@ -607,7 +770,7 @@ def _webhook_table_transformer(table: pa.Table) -> pa.Table:if existing is None or ts > existing[0]:best_by_id[obj_id] = (ts, obj)- rows = [obj for _, obj in best_by_id.values()]+ rows = [_scrub_client_secrets(obj) for _, obj in best_by_id.values()]return table_from_py_list(rows)@@ -623,7 +786,10 @@ def stripe_source(api_version: str,should_use_incremental_field: bool = False,):- column_mapping = get_dlt_mapping_for_external_table(f"stripe_{endpoint.lower()}")+ # 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.+ table_name = f"stripe_{endpoint.lower()}"+ column_mapping = get_dlt_mapping_for_external_table(table_name) if table_name in external_tables else {}column_hints = {key: value.get("data_type") for key, value in column_mapping.items()}# Get the incremental field name for partition keys@@ -652,19 +818,23 @@ def stripe_source(api_version=api_version,)+ # A few Stripe objects carry no timestamp at all, so there is nothing to partition on — the+ # datetime partitioner would KeyError looking for the fallback `created` field.+ partitioned = endpoint not in NON_PARTITIONED_ENDPOINTS+return SourceResponse(items=items,- primary_keys=["id"],+ primary_keys=PRIMARY_KEYS.get(endpoint, DEFAULT_PRIMARY_KEYS),name=endpoint,column_hints=column_hints,webhook_only=webhook_only,# Stripe data is returned in descending timestamp ordersort_mode="desc",- partition_count=1, # this enables partitioning- partition_size=1, # this enables partitioning- partition_mode="datetime",- partition_format="week",- partition_keys=[incremental_field_name],+ partition_count=1 if partitioned else None, # this enables partitioning+ partition_size=1 if partitioned else None, # this enables partitioning+ partition_mode="datetime" if partitioned else None,+ partition_format="week" if partitioned else None,+ partition_keys=[incremental_field_name] if partitioned else None,)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 6012554318c5..9a392eb5f82d 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@@ -7,6 +7,7 @@ from unittest import mockfrom unittest.mock import MagicMock, patchimport stripe as stripe_lib+from parameterized import parameterizedfrom stripe import ListObjectfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager@@ -16,15 +17,48 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe import stripe as stripe_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (+ APPLICATION_FEE_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,+ BILLING_CREDIT_GRANT_RESOURCE_NAME,+ BILLING_METER_RESOURCE_NAME,+ CHARGE_RESOURCE_NAME,+ CHECKOUT_SESSION_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,+ EARLY_FRAUD_WARNING_RESOURCE_NAME,+ ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,+ ENTITLEMENTS_FEATURE_RESOURCE_NAME,+ EVENT_RESOURCE_NAME,+ INVOICE_PAYMENT_RESOURCE_NAME,+ PAYMENT_INTENT_RESOURCE_NAME,+ PAYMENT_LINK_RESOURCE_NAME,+ PLAN_RESOURCE_NAME,+ PROMOTION_CODE_RESOURCE_NAME,+ QUOTE_RESOURCE_NAME,+ RESOURCE_TO_STRIPE_OBJECT_TYPE,RESOURCE_TO_STRIPE_WEBHOOK_EVENT,+ REVIEW_RESOURCE_NAME,+ SETUP_ATTEMPT_RESOURCE_NAME,+ SETUP_INTENT_RESOURCE_NAME,+ SHIPPING_RATE_RESOURCE_NAME,STRIPE_API_VERSION_ACACIA,+ SUBSCRIPTION_ITEM_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,+ SUBSCRIPTION_SCHEDULE_RESOURCE_NAME,+ TAX_ID_RESOURCE_NAME,+ TAX_RATE_RESOURCE_NAME,+ TOPUP_RESOURCE_NAME,+ TRANSFER_RESOURCE_NAME,)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLines+from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (+ ENDPOINTS,+ NON_PARTITIONED_ENDPOINTS,+ WEBHOOK_ONLY_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (SUBSCRIPTION_PAGE_LIMIT,@@ -36,6 +70,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.str_is_non_list_stripe_response,_is_truncated_stripe_list_response,_RateLimitRetryingRequestsClient,+ _scrub_client_secrets,get_rows,)@@ -433,6 +468,80 @@ class TestInvoiceListWithAllLines:list(InvoiceListWithAllLines(client, params={}, logger=MagicMock()).auto_paging_iter())+class TestScrubClientSecrets:+ @parameterized.expand(+ [+ # PaymentIntent / SetupIntent expose client_secret at the top level.+ (+ {"id": "pi_1", "client_secret": "pi_1_secret_abc", "amount": 500},+ {"id": "pi_1", "amount": 500},+ ),+ # A Checkout Session nests the flow's client_secret alongside other fields.+ (+ {"id": "cs_1", "client_secret": "cs_1_secret", "url": "https://checkout"},+ {"id": "cs_1", "url": "https://checkout"},+ ),+ # Event objects embed a full copy of the resource under data.object AND the pre-change+ # values under data.previous_attributes — both must be scrubbed.+ (+ {+ "id": "evt_1",+ "type": "payment_intent.succeeded",+ "data": {+ "object": {"id": "pi_2", "client_secret": "pi_2_secret", "status": "succeeded"},+ "previous_attributes": {"client_secret": "pi_2_secret", "status": "processing"},+ },+ },+ {+ "id": "evt_1",+ "type": "payment_intent.succeeded",+ "data": {+ "object": {"id": "pi_2", "status": "succeeded"},+ "previous_attributes": {"status": "processing"},+ },+ },+ ),+ # Secrets buried inside a list are reached too.+ (+ {"id": "obj_1", "items": [{"client_secret": "leak", "keep": 1}]},+ {"id": "obj_1", "items": [{"keep": 1}]},+ ),+ # Nothing to scrub — the object passes through unchanged.+ (+ {"id": "cus_1", "email": "[email protected]"},+ {"id": "cus_1", "email": "[email protected]"},+ ),+ ]+ )+ def test_removes_client_secret_everywhere(self, obj, expected):+ assert _scrub_client_secrets(obj) == expected++ def test_get_rows_scrubs_client_secret_from_flat_resource(self):+ # Wiring guard: PaymentIntent/SetupIntent/CheckoutSession rows flow through the flat get_rows+ # path, so a dropped scrub there would persist the secret to the warehouse table.+ objects = [{"id": "pi_1", "created": 1700000000, "client_secret": "pi_1_secret_abc", "amount": 500}]+ resource = StripeResource(method=lambda params: cast(ListObject[Any], _FakeStripeList(objects)))+ resumable_source_manager = MagicMock()+ resumable_source_manager.can_resume.return_value = False++ with patch.object(stripe_module, "_build_resources", return_value={PAYMENT_INTENT_RESOURCE_NAME: resource}):+ tables = list(+ get_rows(+ api_key="sk_test_123",+ endpoint=PAYMENT_INTENT_RESOURCE_NAME,+ 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 = [row for table in tables for row in table.to_pylist()]+ assert rows == [{"id": "pi_1", "created": 1700000000, "amount": 500}]++class TestSubscriptionPageSize:def test_build_resources_caps_subscription_page_size(self):# Subscriptions expand discounts at two levels, so a full DEFAULT_LIMIT page can grow past the@@ -581,16 +690,88 @@ class TestWebhookEventMapping:# the event map — otherwise we'd subscribe the source webhook to unrelated events.assert CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME not in RESOURCE_TO_STRIPE_WEBHOOK_EVENT- def test_no_billing_events_subscribed(self):- # The removed "billing" mapping was the only thing pulling in billing.* events (credit- # grants, meters, alerts) — none of which can populate any table we sync.- assert not any(e.startswith("billing.") or e.startswith("billing_") for e in _all_known_webhook_events())+ def test_billing_alert_events_not_subscribed(self):+ # Narrowed from a blanket "no billing.* events" assertion now that BillingMeter,+ # BillingCreditGrant and BillingCreditBalanceTransaction are real tables. The original bug+ # it guards against was subscribing to billing.* events nothing could consume, and+ # billing.alert.* is the remaining example: there is no BillingAlert table.+ subscribed = _all_known_webhook_events()+ assert not any(e.startswith("billing.alert.") for e in subscribed)+ assert any(e.startswith("billing.meter.") for e in subscribed)++ def test_every_subscribed_event_can_populate_a_table(self):+ # The general form of the bug above: an event the endpoint subscribes to but whose object+ # type no table claims is pure inbound traffic the HogFunction drops. Each subscribed event+ # must be prefixed by a resource that also has a routing entry.+ routable_prefixes = {+ RESOURCE_TO_STRIPE_WEBHOOK_EVENT[resource]+ for resource in RESOURCE_TO_STRIPE_WEBHOOK_EVENT+ if resource in RESOURCE_TO_STRIPE_OBJECT_TYPE+ }+ unroutable = [+ event+ for event in _all_known_webhook_events()+ if not any(event.startswith(f"{prefix}.") for prefix in routable_prefixes)+ ]+ assert unroutable == []def test_payment_method_events_still_subscribed(self):# CustomerPaymentMethod keeps its mapping, so payment_method.* events stay subscribed.assert RESOURCE_TO_STRIPE_WEBHOOK_EVENT[CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME] == "payment_method"assert any(e.startswith("payment_method.") for e in _all_known_webhook_events())+ @parameterized.expand(+ [+ (PAYMENT_INTENT_RESOURCE_NAME, "payment_intent", "payment_intent"),+ (CHECKOUT_SESSION_RESOURCE_NAME, "checkout.session", "checkout.session"),+ (SUBSCRIPTION_SCHEDULE_RESOURCE_NAME, "subscription_schedule", "subscription_schedule"),+ (PROMOTION_CODE_RESOURCE_NAME, "promotion_code", "promotion_code"),+ (PLAN_RESOURCE_NAME, "plan", "plan"),+ (TAX_RATE_RESOURCE_NAME, "tax_rate", "tax_rate"),+ # Event prefix and object type diverge for this one.+ (TAX_ID_RESOURCE_NAME, "customer.tax_id", "tax_id"),+ (QUOTE_RESOURCE_NAME, "quote", "quote"),+ (BILLING_METER_RESOURCE_NAME, "billing.meter", "billing.meter"),+ (BILLING_CREDIT_GRANT_RESOURCE_NAME, "billing.credit_grant", "billing.credit_grant"),+ (+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,+ "billing.credit_balance_transaction",+ "billing.credit_balance_transaction",+ ),+ (INVOICE_PAYMENT_RESOURCE_NAME, "invoice_payment", "invoice_payment"),+ (SETUP_INTENT_RESOURCE_NAME, "setup_intent", "setup_intent"),+ (PAYMENT_LINK_RESOURCE_NAME, "payment_link", "payment_link"),+ (TRANSFER_RESOURCE_NAME, "transfer", "transfer"),+ (APPLICATION_FEE_RESOURCE_NAME, "application_fee", "application_fee"),+ (TOPUP_RESOURCE_NAME, "topup", "topup"),+ (REVIEW_RESOURCE_NAME, "review", "review"),+ (EARLY_FRAUD_WARNING_RESOURCE_NAME, "radar.early_fraud_warning", "radar.early_fraud_warning"),+ ]+ )+ def test_new_resource_is_webhook_routable(self, resource: str, event_prefix: str, object_type: str) -> None:+ # Both halves are needed: the event map drives what the endpoint subscribes to, the object+ # map drives where the HogFunction writes the payload. One without the other is a no-op.+ assert RESOURCE_TO_STRIPE_WEBHOOK_EVENT[resource] == event_prefix+ assert RESOURCE_TO_STRIPE_OBJECT_TYPE[resource] == object_type+ assert any(e.startswith(f"{event_prefix}.") for e in _all_known_webhook_events())++ @parameterized.expand(+ [+ (SUBSCRIPTION_ITEM_RESOURCE_NAME,),+ (SETUP_ATTEMPT_RESOURCE_NAME,),+ (SHIPPING_RATE_RESOURCE_NAME,),+ (EVENT_RESOURCE_NAME,),+ (BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,),+ (ENTITLEMENTS_FEATURE_RESOURCE_NAME,),+ (ENTITLEMENTS_ACTIVE_ENTITLEMENT_RESOURCE_NAME,),+ ]+ )+ def test_resource_without_stripe_event_stays_api_sweep_only(self, resource: str) -> None:+ # Stripe emits no event carrying these objects, so mapping them would only subscribe the+ # endpoint to traffic that can never populate the table.+ assert resource not in RESOURCE_TO_STRIPE_WEBHOOK_EVENT+ assert resource not in RESOURCE_TO_STRIPE_OBJECT_TYPE+class TestWebhookOnlyResponseWiring:def _make_manager(self, enabled: bool) -> MagicMock:@@ -634,6 +815,145 @@ class TestWebhookOnlyResponseWiring:assert response.partition_keys == ["start"]+class TestEndpointCatalogWiring:+ def setup_method(self):+ self.resources = stripe_module._build_resources(MagicMock(), logger=None)++ @pytest.mark.parametrize("endpoint", [e for e in ENDPOINTS if e not in WEBHOOK_ONLY_ENDPOINTS])+ def test_every_pollable_endpoint_has_a_resource(self, endpoint):+ # get_rows raises "Stripe endpoint does not exist" for anything listed in ENDPOINTS but not+ # wired into _build_resources, failing the sync for that table only once a user enables it.+ assert endpoint in self.resources++ def test_nested_resources_declare_a_registered_parent(self):+ # _resolve_to_flat looks the parent up in the same map to pick the endpoint it probes for+ # permissions, so an unregistered parent name KeyErrors during credential validation.+ for name, resource in self.resources.items():+ if isinstance(resource, StripeNestedResource):+ assert resource.parent_name in self.resources, name+++class TestPartitioningAndColumnHints:+ def _source(self, endpoint: str) -> Any:+ manager = MagicMock(spec=WebhookSourceManager)+ manager.webhook_enabled = mock.AsyncMock(return_value=False)+ 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,+ )++ @pytest.mark.parametrize("endpoint", NON_PARTITIONED_ENDPOINTS)+ def test_timestampless_endpoints_are_not_partitioned(self, endpoint):+ # These Stripe objects carry no timestamp at all. Partitioning them would fall back to+ # "created" and the datetime partitioner KeyErrors on the first row, killing the sync.+ response = self._source(endpoint)+ assert response.partition_keys is None+ assert response.partition_mode is None+ assert response.partition_count is None++ @pytest.mark.parametrize(+ "endpoint,expected_key",+ [+ (PAYMENT_INTENT_RESOURCE_NAME, "created"),+ (SUBSCRIPTION_ITEM_RESOURCE_NAME, "created"),+ (CUSTOMER_RESOURCE_NAME, "created"),+ ],+ )+ def test_timestamped_endpoints_keep_weekly_partitioning(self, endpoint, expected_key):+ response = self._source(endpoint)+ assert response.partition_keys == [expected_key]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "week"++ def test_endpoint_without_managed_schema_gets_no_column_hints(self):+ # Only the original Stripe tables have a canonical schema in external_table_definitions.+ # Looking one up for a table that has none used to KeyError before the source ran a row.+ assert self._source(PAYMENT_INTENT_RESOURCE_NAME).column_hints == {}++ def test_endpoint_with_managed_schema_keeps_its_column_hints(self):+ column_hints = self._source(CHARGE_RESOURCE_NAME).column_hints+ assert column_hints+ assert column_hints["amount"] is not None++ def test_credit_balance_summary_keys_on_the_credit_grant(self):+ # The summary is a per-customer view rather than a stored object, so it has no `id`. Keying+ # it on "id" would merge every row onto a null key and collapse the table to one row.+ assert self._source(BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME).primary_keys == ["credit_grant"]++ def test_other_endpoints_keep_the_id_primary_key(self):+ assert self._source(CHARGE_RESOURCE_NAME).primary_keys == ["id"]+++class TestCreditBalanceSummaryFanout:+ def _run(self, grants: list[dict[str, Any]]) -> tuple[list[dict], list[dict]]:+ retrieved: list[dict] = []++ def retrieve(params):+ retrieved.append(params)+ return {"object": "billing.credit_balance_summary", "customer": params["customer"], "balances": []}++ client = MagicMock()+ client.billing.credit_balance_summary.retrieve.side_effect = retrieve+ client.billing.credit_grants.list.return_value = _list_object(grants)++ resource = stripe_module._build_resources(client, logger=None)[BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME]+ resumable_source_manager = MagicMock()+ resumable_source_manager.can_resume.return_value = False++ with (+ patch.object(stripe_module, "StripeClient"),+ patch.object(+ stripe_module,+ "_build_resources",+ return_value={BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME: resource},+ ),+ ):+ rows: list[dict] = []+ for table in get_rows(+ api_key="sk_test_123",+ endpoint=BILLING_CREDIT_BALANCE_SUMMARY_RESOURCE_NAME,+ 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())+ return rows, retrieved++ def test_scopes_each_retrieve_to_its_grant_and_customer(self):+ # The retrieve needs the grant's customer as well as its id, so the fan-out has to read a+ # field off the parent object — passing the parent id alone would 400 on the missing filter.+ rows, retrieved = self._run([{"id": "credgr_1", "customer": "cus_1"}])++ assert retrieved == [+ {"customer": "cus_1", "filter": {"type": "credit_grant", "credit_grant": "credgr_1"}},+ ]+ assert [row["credit_grant"] for row in rows] == ["credgr_1"]+ assert [row["customer"] for row in rows] == ["cus_1"]++ def test_skips_grants_issued_to_an_account(self):+ # Grants made to an Account carry `customer_account` instead of `customer`; scoping the+ # summary on a missing customer would make Stripe reject the request.+ rows, retrieved = self._run(+ [+ {"id": "credgr_acct", "customer": None, "customer_account": "acct_1"},+ {"id": "credgr_cus", "customer": "cus_1"},+ ]+ )++ assert [params["filter"]["credit_grant"] for params in retrieved] == ["credgr_cus"]+ assert [row["credit_grant"] for row in rows] == ["credgr_cus"]++class TestSchemaWebhookCapability:def setup_method(self):self.source = StripeSource()diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_webhook_table_transformer.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_webhook_table_transformer.pyindex 2ed44454afa1..69332eaaa24d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_webhook_table_transformer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/stripe/test_webhook_table_transformer.py@@ -113,3 +113,13 @@ class TestWebhookTableTransformer:assert result.num_rows == 1assert result.column("id").to_pylist() == ["cus_1"]++ def test_client_secret_scrubbed_from_webhook_object(self):+ # payment_intent.* / setup_intent.* / checkout.session.* webhooks carry the resource's+ # client_secret; it must never land in the warehouse table.+ event = _make_event("evt_1", "pi_1", 1000, {"client_secret": "pi_1_secret_abc", "amount": 500})+ result = _webhook_table_transformer(_build_table([event]))++ assert result.num_rows == 1+ assert "client_secret" not in result.column_names+ assert result.column("amount").to_pylist() == [500]diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 5a5283586056..b1af0ff4023d 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -91,10 +91,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_adsfrom products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME,- COUPON_RESOURCE_NAME as STRIPE_COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME as STRIPE_CREDIT_NOTE_RESOURCE_NAME,- CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,- CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME as STRIPE_CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME as STRIPE_CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME as STRIPE_DISCOUNT_RESOURCE_NAME,DISPUTE_RESOURCE_NAME as STRIPE_DISPUTE_RESOURCE_NAME,@@ -166,34 +163,7 @@ class TestExternalDataSource(APIBaseTest):"payload": {"auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},"schemas": [- {- "name": STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,- "should_sync": True,- "sync_type": "full_refresh",- },- {"name": STRIPE_SUBSCRIPTION_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_CUSTOMER_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_PRODUCT_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_PRICE_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_INVOICE_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_CHARGE_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_REFUND_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_CREDIT_NOTE_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_INVOICE_ITEM_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_PAYOUT_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_DISPUTE_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {- "name": STRIPE_CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,- "should_sync": True,- "sync_type": "full_refresh",- },- {- "name": STRIPE_CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,- "should_sync": True,- "sync_type": "full_refresh",- },- {"name": STRIPE_COUPON_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},- {"name": STRIPE_DISCOUNT_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},+ {"name": name, "should_sync": True, "sync_type": "full_refresh"} for name in STRIPE_ENDPOINTS],},},@@ -201,7 +171,8 @@ class TestExternalDataSource(APIBaseTest):payload = response.json()self.assertEqual(response.status_code, 201)- # number of schemas should match default schemas for Stripe+ # every schema in the request becomes a row, so a source created with the full Stripe+ # endpoint catalog ends up with one schema per endpointself.assertEqual(ExternalDataSchema.objects.filter(source_id=payload["id"]).count(),len(STRIPE_ENDPOINTS),