Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(stripe): sync balance transactions for every customer (#118547)

Daniel RC45e0662088b6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stripe.py
index 7609841ebad3..562f88f46e58 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stripe.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/stripe.py
@@ -13,7 +13,13 @@ class StripeAuthMethodConfig(config.Config):
stripe_secret_key: str | None = None
+class StripeBalanceHistoryAllCustomersConfig(config.Config):
+ enabled: bool = config.value(converter=config.str_to_bool, default=False)
+
+
@config.config
class StripeSourceConfig(config.Config):
auth_method: StripeAuthMethodConfig
stripe_account_id: str | None = None
+ balance_history_all_customers: StripeBalanceHistoryAllCustomersConfig | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
index c426597b6036..142eebbb47e3 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
@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldOauthConfig,
SourceFieldSelectConfig,
SourceFieldSelectConfigOption,
+ SourceFieldSwitchGroupConfig,
SuggestedTable,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -322,6 +323,13 @@ class StripeSource(
caption="Leave blank in most cases, including when connecting with OAuth. Only set this if you use a Stripe Connect platform key and want to sync a specific connected account. You can find it under Account details in your [Stripe account settings](https://dashboard.stripe.com/settings/account).",
secret=False,
),
+ SourceFieldSwitchGroupConfig(
+ name="balance_history_all_customers",
+ label="Sync balance history for every customer",
+ caption="By default, the CustomerBalanceTransaction table only includes customers whose balance isn't zero. Turn this on to also include customers whose balance went back to zero. The sync then makes one Stripe request per customer, so it takes longer.",
+ default=False,
+ fields=[],
+ ),
],
),
suggestedTables=[
@@ -712,6 +720,9 @@ If automatic creation failed with a permissions error, the fix depends on how yo
# conversion that declares a parent without threading these silently keeps polling
# the parent API while the fan-out telemetry reports otherwise.
use_warehouse_parent=inputs.fanout_warehouse_reuse,
+ include_zero_balance_customers=bool(
+ config.balance_history_all_customers and config.balance_history_all_customers.enabled
+ ),
)
def get_required_parent_schemas(self, schema_name: str) -> list[str]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
index 9c60a9aea039..ec116cf79c4d 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
@@ -474,9 +474,9 @@ def _customer_might_have_balance_transactions(customer: dict[str, Any]) -> bool:
(one call each, almost all empty) into a handful of calls.
Tradeoff: a customer whose balance was credited and then fully consumed back to 0 has ledger
- entries but a 0 balance, so we won't fetch their history. This is rare and an accepted cost of
- avoiding the per-customer fan-out. A missing ``balance`` (unexpected payload shape) is treated as
- "might have" so we never silently drop data."""
+ entries but a 0 balance, so we won't fetch their history. The `balance_history_all_customers`
+ source setting turns this skip off for accounts where that history matters. A missing ``balance``
+ (unexpected payload shape) is treated as "might have" so we never silently drop data."""
balance = customer.get("balance")
return balance is None or balance != 0
@@ -726,6 +726,7 @@ def _build_resources(
client: StripeClient,
logger: Optional[FilteringBoundLogger] = None,
client_factory: Optional[ClientFactory] = None,
+ include_zero_balance_customers: bool = False,
) -> dict[str, Union[StripeResource, StripeNestedResource]]:
"""Single source of truth for the resources we sync from Stripe and how they relate.
@@ -781,7 +782,7 @@ def _build_resources(
parent_id="id",
parent=StripeResource(method=client.customers.list),
parent_name=CUSTOMER_RESOURCE_NAME,
- parent_has_nested=_customer_might_have_balance_transactions,
+ parent_has_nested=None if include_zero_balance_customers else _customer_might_have_balance_transactions,
),
# Stays on the parent API: one child call per customer with no skip signal, so the
# listing is a small fraction of the run and reusing the parent table saves ~nothing.
@@ -894,6 +895,7 @@ def get_rows(
api_version: str,
should_use_incremental_field: bool = False,
warehouse_parent: Optional["ParentTableRef"] = None,
+ include_zero_balance_customers: bool = False,
):
def new_client(on_rate_limited: Optional[RateLimitCallback] = None) -> StripeClient:
return StripeClient(
@@ -907,7 +909,12 @@ def get_rows(
client = new_client()
default_params = {"limit": DEFAULT_LIMIT}
- resources = _build_resources(client, logger=logger, client_factory=new_client)
+ resources = _build_resources(
+ client,
+ logger=logger,
+ client_factory=new_client,
+ include_zero_balance_customers=include_zero_balance_customers,
+ )
batcher = Batcher(logger=logger, chunk_size=STRIPE_CHUNK_SIZE)
@@ -1310,6 +1317,7 @@ def stripe_source(
team_id: Optional[int] = None,
source_id: Optional[str] = None,
use_warehouse_parent: bool = False,
+ include_zero_balance_customers: bool = False,
):
# Only the endpoints with a PostHog-managed canonical schema have column hints; the rest let the
# pipeline infer their columns from the rows Stripe returns.
@@ -1350,6 +1358,7 @@ def stripe_source(
resumable_source_manager=resumable_source_manager,
api_version=api_version,
warehouse_parent=warehouse_parent,
+ include_zero_balance_customers=include_zero_balance_customers,
)
# A few Stripe objects carry no timestamp at all, so there is nothing to partition on — the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
index 268c1f6290c1..2f8e71a08ca7 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
@@ -27,9 +27,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.fan
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (
ParentTableRef,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import SourceDriver
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.fake_network import RecordedRequest
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.responders import ScriptedResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stripe import (
StripeAuthMethodConfig,
+ StripeBalanceHistoryAllCustomersConfig,
StripeSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe import stripe as stripe_module
@@ -967,6 +971,27 @@ class TestInvoiceListWithAllLines:
)
[email protected]([("switch_off", False, ["cus_credit"]), ("switch_on", True, ["cus_credit", "cus_zero"])])
+def test_balance_history_switch_decides_which_customers_are_swept(_name, enabled, expected_customers):
+ def script(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == "/v1/customers":
+ customers = [{"id": "cus_zero", "balance": 0}, {"id": "cus_credit", "balance": -500}]
+ return ScriptedResponse(json={"object": "list", "data": customers, "has_more": False, "url": request.path})
+ customer = request.path.split("/")[3]
+ transaction = {"id": f"cbtxn_{customer}", "object": "customer_balance_transaction", "created": 1700000000}
+ return ScriptedResponse(json={"object": "list", "data": [transaction], "has_more": False, "url": request.path})
+
+ config = StripeSourceConfig(
+ auth_method=StripeAuthMethodConfig(selection="api_key", stripe_secret_key="sk_test"),
+ balance_history_all_customers=StripeBalanceHistoryAllCustomersConfig(enabled=enabled),
+ )
+ result = SourceDriver(StripeSource(), config).run(CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME, script)
+
+ assert result.raised is None
+ rows = [row for table in result.rows for row in table.to_pylist()]
+ assert sorted(row["customer"] for row in rows) == expected_customers
+
+
class TestScrubClientSecrets:
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
index 3891a552b8af..eecc4da7e692 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
@@ -14,7 +14,7 @@ import contextlib
import dataclasses
from collections.abc import Callable, Iterator
from pathlib import Path
-from typing import Any, Literal
+from typing import Any, Literal, get_args
from posthog.dataclasses import frozen
@@ -219,7 +219,8 @@ def _placeholder_config(config_class: type, text: str | None, fill_optional: boo
continue
annotation = annotations.get(field.name, field.type)
required = field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING
- if not required and not (fill_optional and field.default is None and "str" in str(annotation)):
+ is_optional_str = str in get_args(annotation) or annotation in ("str | None", "Optional[str]")
+ if not required and not (fill_optional and field.default is None and is_optional_str):
continue
if isinstance(annotation, type) and is_config(annotation):
kwargs[field.name] = _placeholder_config(annotation, text, fill_optional)