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(braintree): sync customers, subscriptions and merchant accounts (#99805)

Tom Owersbf5b9cd3cc5c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index d0378eec7cf5..91c13b26e844 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -902,14 +902,14 @@ Note: Remaining GETs are file downloads (document/template/audit-log PDFs), sing
## Braintree — gaps
-Today (3): `disputes`, `refunds`, `transactions`
+Today (6): `customers`, `disputes`, `merchant_accounts`, `recurring_billing_subscriptions`, `refunds`, `transactions`
Diffed against: <https://graphql.braintreepayments.com/reference/>
-- [ ] `search.customers / Query.customers (CustomerConnection)` — lookup table resolving the customer behind every synced transaction and refund (high)
-- [ ] `Query.recurringBillingSubscriptions` — recurring revenue / subscription state, unavailable from one-off transactions (high)
-- [ ] `Query.report.transactionLevelFees (TransactionLevelFeeReport)` — per-transaction processing fees — the net-revenue side of transactions we already sync (high)
-- [ ] `Merchant.merchantAccounts (MerchantAccountConnection)` — lookup resolving the merchantAccountId carried on every transaction (high)
+- [x] `search.customers / Query.customers (CustomerConnection)` — lookup table resolving the customer behind every synced transaction and refund (high)
+- [x] `Query.recurringBillingSubscriptions` — recurring revenue / subscription state, unavailable from one-off transactions (high)
+- [ ] `Query.report.transactionLevelFees (TransactionLevelFeeReport)` — per-transaction processing fees — the net-revenue side of transactions we already sync (high). Not a table: the field is deprecated in favour of `report.paymentLevelFees`, and both return only a `url` to a per-date report file rather than a connection of rows.
+- [x] `Merchant.merchantAccounts (MerchantAccountConnection)` — lookup resolving the merchantAccountId carried on every transaction (high)
- [ ] `Query.recurringBillingSubscriptionPlans` — lookup resolving the plan a subscription references (high)
- [ ] `Query.verifications (VerificationConnection)` — payment method verification attempts and decline reasons (medium)
- [ ] `search.payments (PaymentConnection)` — superset of all payment types, including ones never surfacing as card transactions (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/braintree.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/braintree.py
index 1258733ae523..0fb5fbe97692 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/braintree.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/braintree.py
@@ -77,10 +77,14 @@ def _format_created_at(value: Any) -> str:
def _build_query(config: BraintreeEndpointConfig) -> str:
# Braintree's search fields declare `input` as non-null, even though every
# field within the input type is optional (an empty object matches everything).
+ input_variable = f"$input: {config.input_type}!, " if config.input_type else ""
+ input_argument = "input: $input, " if config.input_type else ""
+ opening = " ".join(f"{wrapper} {{" for wrapper in config.query_path)
+ closing = " ".join("}" for _ in config.query_path)
return f"""
-query ($input: {config.input_type}!, $first: Int!, $after: String) {{
- search {{
- {config.search_field} (input: $input, first: $first, after: $after) {{
+query ({input_variable}$first: Int!, $after: String) {{
+ {opening}
+ {config.connection_field} ({input_argument}first: $first, after: $after) {{
pageInfo {{ hasNextPage }}
edges {{
cursor
@@ -89,11 +93,32 @@ query ($input: {config.input_type}!, $first: Int!, $after: String) {{
}}
}}
}}
- }}
+ {closing}
}}
"""
+def _normalize_node(node: dict[str, Any], config: BraintreeEndpointConfig) -> dict[str, Any]:
+ """Copy a nested creation timestamp to the node root.
+
+ `RecurringBillingSubscription` exposes its timestamps under `timeline` rather than at
+ the node root, and GraphQL cannot select a nested scalar into the root, so without this
+ the incremental cursor and the partition key have no column to read.
+ """
+ if config.created_at_path == ("createdAt",):
+ return node
+
+ value: Any = node
+ for key in config.created_at_path:
+ if not isinstance(value, dict):
+ return node
+ value = value.get(key)
+
+ if value is None:
+ return node
+ return {**node, "createdAt": value}
+
+
def _execute(
session: requests.Session,
url: str,
@@ -181,10 +206,17 @@ def get_rows(
return _execute(session, url, query, variables, logger)
while True:
- data = execute({"input": search_input, "first": PAGE_SIZE, "after": after})
- connection = ((data.get("search") or {}).get(config.search_field)) or {}
+ variables: dict[str, Any] = {"first": PAGE_SIZE, "after": after}
+ if config.input_type:
+ variables["input"] = search_input
+ data = execute(variables)
+
+ container: Any = data
+ for wrapper in config.query_path:
+ container = (container or {}).get(wrapper) or {}
+ connection = container.get(config.connection_field) or {}
edges = connection.get("edges") or []
- items = [edge.get("node") for edge in edges if edge.get("node")]
+ items = [_normalize_node(edge["node"], config) for edge in edges if edge.get("node")]
if items:
yield items
@@ -212,6 +244,18 @@ def braintree_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = BRAINTREE_ENDPOINTS[endpoint]
+ # A lookup stream with no timestamp has nothing to partition on, so it stays unpartitioned.
+ partitioning: dict[str, Any] = (
+ {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [config.partition_key],
+ }
+ if config.partition_key
+ else {}
+ )
return SourceResponse(
name=endpoint,
@@ -227,12 +271,8 @@ def braintree_source(
db_incremental_field_last_value=db_incremental_field_last_value,
),
primary_keys=[config.primary_key],
- partition_count=1,
- partition_size=1,
- partition_mode="datetime",
- partition_format="month",
- partition_keys=[config.partition_key],
# Search result ordering is undocumented, so the pipeline defers the
# watermark commit until a run completes.
sort_mode="desc",
+ **partitioning,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/canonical_descriptions.py
index 9c2e7eb4940b..4cc5fd84ecbb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/canonical_descriptions.py
@@ -51,4 +51,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"amountDisputed": "Monetary amount being disputed, with value and currency code.",
},
},
+ "customers": {
+ "description": "A person or business you have stored in the Braintree vault, resolving the customer behind transactions and subscriptions.",
+ "docs_url": "https://graphql.braintreepayments.com/reference/#object--Customer",
+ "columns": {
+ "id": "Globally unique GraphQL identifier of the customer.",
+ "legacyId": "Legacy customer id from the classic Braintree API.",
+ "createdAt": "Time at which the customer was created.",
+ "company": "Company or business name associated with this customer.",
+ "email": "Email address for this customer.",
+ "firstName": "Customer's first name.",
+ "lastName": "Customer's last name.",
+ "phoneNumber": "Phone number for this customer.",
+ "website": "Customer's website.",
+ },
+ },
+ "recurring_billing_subscriptions": {
+ "description": "A recurring billing subscription charging a payment method on a repeating schedule, with its current state and billing timeline.",
+ "docs_url": "https://graphql.braintreepayments.com/reference/#object--RecurringBillingSubscription",
+ "columns": {
+ "id": "Globally unique GraphQL identifier of the subscription.",
+ "legacyId": "Legacy subscription id from the classic Braintree API.",
+ "status": "Current lifecycle state of the subscription (ACTIVE, CANCELED, EXPIRED, PAST_DUE, PENDING).",
+ "planId": "Identifier of the plan the subscription is based on.",
+ "merchantAccountId": "Identifier of the merchant account used for the subscription.",
+ "paymentMethodId": "Identifier of the payment method charged for the subscription.",
+ "price": "Base price and currency for this subscription.",
+ "balance": "Outstanding charges associated with the subscription.",
+ "nextBillingPeriodAmount": "Total amount for the next billing period, including add-ons and discounts but not the current balance.",
+ "billingDayOfMonth": "Day of the month the subscription is charged on in every billing cycle.",
+ "currentBillingCycle": "The subscription's current billing cycle, incremented at the end of each billing period.",
+ "numberOfBillingCycles": "Number of billing cycles to execute; 0 means the subscription never expires.",
+ "failureCount": "Number of consecutive failed charge attempts, reset to 0 after a successful charge.",
+ "daysPastDue": "Number of days the subscription is past due.",
+ "timeline": "Billing dates and payment status, including createdAt, updatedAt, firstBillingDate, nextBillingDate and paidThroughDate.",
+ "createdAt": "Time at which the subscription was created, copied from the timeline so it can be used as a cursor.",
+ },
+ },
+ "merchant_accounts": {
+ "description": "A merchant account funds settle into, resolving the merchantAccountId carried on transactions and subscriptions.",
+ "docs_url": "https://graphql.braintreepayments.com/reference/#object--MerchantAccount",
+ "columns": {
+ "id": "Unique identifier for the merchant account, used to determine which account processed a payment.",
+ "currencyCode": "ISO code for the currency the merchant account uses.",
+ "dbaName": "Business name of the account.",
+ "externalId": "Unique identifier for this account in external systems.",
+ "status": "Status of the merchant account, determining whether it can be used to create a payment.",
+ "isDefault": "Whether this is the merchant's default account, used when a payment specifies no merchant account id.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/settings.py
index 12fb8a03f4f0..df119a819610 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/settings.py
@@ -46,47 +46,129 @@ _DISPUTE_FIELDS = """
amountDisputed { value currencyCode }
"""
+_CUSTOMER_FIELDS = """
+ id
+ legacyId
+ createdAt
+ company
+ email
+ firstName
+ lastName
+ phoneNumber
+ website
+"""
+
+_RECURRING_BILLING_SUBSCRIPTION_FIELDS = """
+ id
+ legacyId
+ status
+ planId
+ merchantAccountId
+ paymentMethodId
+ price { value currencyCode }
+ balance { value currencyCode }
+ nextBillingPeriodAmount { value currencyCode }
+ billingDayOfMonth
+ currentBillingCycle
+ numberOfBillingCycles
+ failureCount
+ daysPastDue
+ timeline {
+ createdAt
+ updatedAt
+ firstBillingDate
+ nextBillingDate
+ billingPeriodStartDate
+ billingPeriodEndDate
+ paidThroughDate
+ }
+"""
+
+# `accountType` and `capabilities` only exist from Braintree-Version 2026-08-04, so they
+# stay out of the selection while older versions are still pinnable.
+_MERCHANT_ACCOUNT_FIELDS = """
+ id
+ currencyCode
+ dbaName
+ externalId
+ status
+ isDefault
+"""
+
@frozen
class BraintreeEndpointConfig:
- # Field on the GraphQL `search` root.
- search_field: str
- # GraphQL input type name for the `search` field (e.g. TransactionSearchInput).
- input_type: str
+ # Field exposing the Relay connection, resolved under `query_path`.
+ connection_field: str
+ # GraphQL input type name for the connection's `input` argument (e.g.
+ # TransactionSearchInput), or None for connections that take no search input.
+ input_type: str | None
node_fields: str
+ # Wrapper fields the connection is nested under in the query and the response.
+ query_path: tuple[str, ...] = ("search",)
primary_key: str = "id"
incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_CREATED_AT_INCREMENTAL_FIELDS))
- partition_key: str = "createdAt"
+ partition_key: str | None = "createdAt"
# Field on `input_type` that filters on the node's `createdAt`, or None when the
# vendor's search input declares no equivalent. Sending a field the input type
# doesn't define is a GraphQL validation error, not an ignored filter.
created_at_search_field: str | None = "createdAt"
+ # Where the node exposes its creation timestamp. When it is not at the node root,
+ # the value is copied there so the incremental cursor and the partition key have a
+ # top-level column to read.
+ created_at_path: tuple[str, ...] = ("createdAt",)
-# `TransactionSearchInput` and `RefundSearchInput` both accept a createdAt range
-# filter, giving those streams genuine server-side incremental. `DisputeSearchInput`
-# does not (it filters on receivedDate/replyByDate/effectiveDate instead), so disputes
-# re-read the full set each run and rely on the primary-key merge to dedupe — the node
-# still exposes createdAt, so the incremental cursor and partition key are unchanged.
+# `TransactionSearchInput`, `RefundSearchInput`, `CustomerSearchInput` and
+# `RecurringBillingSubscriptionSearchInput` all accept a createdAt range filter, giving
+# those streams genuine server-side incremental. `DisputeSearchInput` does not (it filters
+# on receivedDate/replyByDate/effectiveDate instead), so disputes re-read the full set each
+# run and rely on the primary-key merge to dedupe — the node still exposes createdAt, so the
+# incremental cursor and partition key are unchanged. `merchantAccounts` is a small lookup
+# with no timestamp at all, so it is full refresh and unpartitioned.
# Result ordering is not documented, so incremental streams declare sort_mode="desc" —
# the pipeline then commits the watermark only when a run completes.
+#
+# Braintree deprecated the `search` root in favour of identically shaped top-level queries
+# on 2026-07-07, but those queries do not exist on the older versions this source still
+# supports, so every search-backed stream stays on `search`.
BRAINTREE_ENDPOINTS: dict[str, BraintreeEndpointConfig] = {
"transactions": BraintreeEndpointConfig(
- search_field="transactions",
+ connection_field="transactions",
input_type="TransactionSearchInput",
node_fields=_TRANSACTION_FIELDS,
),
"refunds": BraintreeEndpointConfig(
- search_field="refunds",
+ connection_field="refunds",
input_type="RefundSearchInput",
node_fields=_REFUND_FIELDS,
),
"disputes": BraintreeEndpointConfig(
- search_field="disputes",
+ connection_field="disputes",
input_type="DisputeSearchInput",
node_fields=_DISPUTE_FIELDS,
created_at_search_field=None,
),
+ "customers": BraintreeEndpointConfig(
+ connection_field="customers",
+ input_type="CustomerSearchInput",
+ node_fields=_CUSTOMER_FIELDS,
+ ),
+ "recurring_billing_subscriptions": BraintreeEndpointConfig(
+ connection_field="recurringBillingSubscriptions",
+ input_type="RecurringBillingSubscriptionSearchInput",
+ node_fields=_RECURRING_BILLING_SUBSCRIPTION_FIELDS,
+ created_at_path=("timeline", "createdAt"),
+ ),
+ "merchant_accounts": BraintreeEndpointConfig(
+ connection_field="merchantAccounts",
+ input_type=None,
+ node_fields=_MERCHANT_ACCOUNT_FIELDS,
+ query_path=("viewer", "merchant"),
+ incremental_fields=[],
+ partition_key=None,
+ created_at_search_field=None,
+ ),
}
ENDPOINTS = tuple(BRAINTREE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/tests/test_braintree.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/tests/test_braintree.py
index c15f8eb1ced0..ccc4c2e7b6fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/tests/test_braintree.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braintree/tests/test_braintree.py
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.braintree.
_base_url,
_build_query,
_format_created_at,
+ _normalize_node,
braintree_source,
get_rows,
validate_credentials,
@@ -35,11 +36,14 @@ def _make_manager(resume_state: BraintreeResumeConfig | None = None) -> mock.Mag
return manager
-def _search_response(search_field: str, edges: list[dict[str, Any]], has_next: bool = False) -> mock.MagicMock:
+def _search_response(endpoint: str, edges: list[dict[str, Any]], has_next: bool = False) -> mock.MagicMock:
+ config = BRAINTREE_ENDPOINTS[endpoint]
+ payload: Any = {config.connection_field: {"pageInfo": {"hasNextPage": has_next}, "edges": edges}}
+ for wrapper in reversed(config.query_path):
+ payload = {wrapper: payload}
+
resp = mock.MagicMock()
- resp.json.return_value = {
- "data": {"search": {search_field: {"pageInfo": {"hasNextPage": has_next}, "edges": edges}}}
- }
+ resp.json.return_value = {"data": payload}
resp.status_code = 200
resp.ok = True
return resp
@@ -66,6 +70,8 @@ class TestBuildQuery:
("transactions", "TransactionSearchInput"),
("refunds", "RefundSearchInput"),
("disputes", "DisputeSearchInput"),
+ ("customers", "CustomerSearchInput"),
+ ("recurring_billing_subscriptions", "RecurringBillingSubscriptionSearchInput"),
],
)
def test_query_uses_correct_input_type(self, endpoint, input_type):
@@ -73,7 +79,40 @@ class TestBuildQuery:
# Braintree's search fields declare `input` as non-null; a nullable
# declaration here fails GraphQL validation (VariableTypeMismatch).
assert f"$input: {input_type}!" in query
- assert BRAINTREE_ENDPOINTS[endpoint].search_field in query
+ assert BRAINTREE_ENDPOINTS[endpoint].connection_field in query
+
+ def test_query_nests_connection_under_its_wrappers(self):
+ # `merchantAccounts` hangs off `viewer.merchant`, not the `search` root.
+ query = _build_query(BRAINTREE_ENDPOINTS["merchant_accounts"])
+ assert "viewer {" in query
+ assert "merchant {" in query
+ assert "search" not in query
+
+ def test_query_omits_input_when_the_connection_takes_none(self):
+ # `Merchant.merchantAccounts` declares `input` as nullable, so declaring an
+ # unused non-null variable would fail validation on every request.
+ query = _build_query(BRAINTREE_ENDPOINTS["merchant_accounts"])
+ assert "$input" not in query
+ assert "input:" not in query
+
+
+class TestNormalizeNode:
+ def test_hoists_nested_created_at_to_the_node_root(self):
+ config = BRAINTREE_ENDPOINTS["recurring_billing_subscriptions"]
+ node = {"id": "s1", "timeline": {"createdAt": "2024-01-02T03:04:05Z"}}
+
+ assert _normalize_node(node, config)["createdAt"] == "2024-01-02T03:04:05Z"
+
+ @pytest.mark.parametrize("node", [{"id": "s1"}, {"id": "s1", "timeline": None}, {"id": "s1", "timeline": {}}])
+ def test_leaves_node_untouched_when_the_nested_timestamp_is_missing(self, node):
+ # A null timestamp must not seed a `createdAt` column holding None for every row.
+ config = BRAINTREE_ENDPOINTS["recurring_billing_subscriptions"]
+ assert "createdAt" not in _normalize_node(node, config)
+
+ def test_leaves_root_level_nodes_alone(self):
+ config = BRAINTREE_ENDPOINTS["transactions"]
+ node = {"id": "t1", "createdAt": "2024-01-02T03:04:05Z"}
+ assert _normalize_node(node, config) is node
class TestFormatCreatedAt:
@@ -140,9 +179,10 @@ class TestGetRows:
requested = call.kwargs["json"]["variables"]["first"]
assert 0 < requested <= MAX_PAGE_SIZE
+ @pytest.mark.parametrize("endpoint", ["transactions", "refunds", "customers", "recurring_billing_subscriptions"])
@mock.patch(f"{_MODULE}.make_tracked_session")
- def test_incremental_search_input_has_gte_filter(self, mock_session):
- mock_session.return_value.post.return_value = _search_response("transactions", [])
+ def test_incremental_search_input_has_gte_filter(self, mock_session, endpoint):
+ mock_session.return_value.post.return_value = _search_response(endpoint, [])
manager = _make_manager()
list(
@@ -150,7 +190,7 @@ class TestGetRows:
"production",
"pub",
"priv",
- "transactions",
+ endpoint,
_VERSION,
mock.MagicMock(),
manager,
@@ -162,6 +202,37 @@ class TestGetRows:
variables = mock_session.return_value.post.call_args.kwargs["json"]["variables"]
assert variables["input"] == {"createdAt": {"greaterThanOrEqualTo": "2024-01-02T00:00:00Z"}}
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_reads_rows_nested_under_the_connection_wrappers(self, mock_session):
+ mock_session.return_value.post.return_value = _search_response(
+ "merchant_accounts", [{"cursor": "c1", "node": {"id": "ma1"}}]
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "pub", "priv", "merchant_accounts", _VERSION, mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["ma1"]
+ # A connection taking no search input must not send an `input` variable the
+ # query never declares.
+ assert "input" not in mock_session.return_value.post.call_args.kwargs["json"]["variables"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_yields_subscriptions_with_a_root_level_created_at(self, mock_session):
+ mock_session.return_value.post.return_value = _search_response(
+ "recurring_billing_subscriptions",
+ [{"cursor": "c1", "node": {"id": "s1", "timeline": {"createdAt": "2024-01-02T03:04:05Z"}}}],
+ )
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "production", "pub", "priv", "recurring_billing_subscriptions", _VERSION, mock.MagicMock(), manager
+ )
+ )
+
+ # The partition key and the incremental cursor both read `createdAt` off the row.
+ assert batches[0][0]["createdAt"] == "2024-01-02T03:04:05Z"
+
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_incremental_omits_filter_when_search_input_lacks_created_at(self, mock_session):
mock_session.return_value.post.return_value = _search_response("disputes", [])
@@ -251,5 +322,12 @@ class TestBraintreeSourceResponse:
assert response.primary_keys == [config.primary_key]
# Search ordering is undocumented — watermark commits only at run end.
assert response.sort_mode == "desc"
- assert response.partition_mode == "datetime"
- assert response.partition_keys == ["createdAt"]
+
+ if config.partition_key is None:
+ # Partitioning on a column the nodes never carry writes every row to a
+ # partition keyed on null.
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]