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(data-warehouse): add tremendous balance_transactions table (#80000)

jake sciotto9f8cc002118d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/canonical_descriptions.py
index cdf9a761323f..c76c17203468 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/canonical_descriptions.py
@@ -107,4 +107,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"meta": "Method-specific metadata (e.g. current balance, card details).",
},
},
+ "balance_transactions": {
+ "description": "Ledger of every transaction against the organization's Tremendous balance, including order payments, refunds, fees, and deposits.",
+ "docs_url": "https://developers.tremendous.com/reference/list-balance-transactions",
+ "columns": {
+ "id": "Stable identifier computed by PostHog from the transaction's unchanging fields; the Tremendous API returns no ID for balance transactions.",
+ "created_at": "Date the transaction was created.",
+ "amount": "Amount of the transaction, denominated in currency_code.",
+ "currency_code": "Currency of the transaction and the balance. Always matches the organization's currency.",
+ "balance": "Running account balance after the transaction. May be delayed and contain null.",
+ "action": "The action that was performed (e.g. Deposit).",
+ "description": "Brief description of the transaction.",
+ "order": "Details of the order associated with the transaction, if any (ID, external ID, and payment breakdown).",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/settings.py
index 4ed67485a05a..502313ad1b7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/settings.py
@@ -17,14 +17,16 @@ class TremendousEndpointConfig:
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Tremendous IDs are unique within an organization, so `id` is a safe primary key.
primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # False for tables that start disabled in the schema picker and one-shot setup.
+ should_sync_default: bool = True
# Tremendous API v2 list endpoints (https://developers.tremendous.com). Paginated lists are ordered
-# by creation date DESC and offset/limit paginated. Only /orders exposes a server-side timestamp
-# filter (`created_at[gte]`, ISO 8601), so it is the only incremental endpoint; nothing exposes an
-# updated_at cursor, so every other endpoint is full refresh (see the implementing-warehouse-sources
-# skill). /balance_transactions also filters on created_at but its rows carry no id, so it is
-# deliberately excluded until a reliable composite key is confirmed.
+# by creation date DESC and offset/limit paginated. Only /orders and /balance_transactions expose a
+# server-side timestamp filter (`created_at[gte]`, ISO 8601), so they are the only incremental
+# endpoints; nothing exposes an updated_at cursor, so every other endpoint is full refresh (see the
+# implementing-warehouse-sources skill). /balance_transactions rows carry no id, so one is
+# synthesized from the row's stable fields (see tremendous.py).
TREMENDOUS_ENDPOINTS: dict[str, TremendousEndpointConfig] = {
"orders": TremendousEndpointConfig(
path="/orders",
@@ -59,6 +61,29 @@ TREMENDOUS_ENDPOINTS: dict[str, TremendousEndpointConfig] = {
"campaigns": TremendousEndpointConfig(path="/campaigns", data_key="campaigns"),
"products": TremendousEndpointConfig(path="/products", data_key="products"),
"funding_sources": TremendousEndpointConfig(path="/funding_sources", data_key="funding_sources"),
+ # The account ledger: every debit/credit including fees, refunds, and balance adjustments.
+ "balance_transactions": TremendousEndpointConfig(
+ path="/balance_transactions",
+ # Response wraps rows under "transactions", not the endpoint name.
+ data_key="transactions",
+ paginated=True,
+ # The docs state only the default `limit` of 10 and no maximum. A limit above an
+ # undocumented server cap would make every page look short and end pagination early,
+ # silently truncating the table — so stay at the documented default.
+ page_size=10,
+ partition_key="created_at",
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ # Rows have no API id; the synthesized primary key (see tremendous.py) is designed from
+ # the API docs but unconfirmed against live accounts, so the table starts opt-in.
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(TREMENDOUS_ENDPOINTS.keys())
@@ -66,3 +91,7 @@ ENDPOINTS = tuple(TREMENDOUS_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in TREMENDOUS_ENDPOINTS.items() if config.incremental_fields
}
+
+SHOULD_SYNC_DEFAULT: dict[str, bool] = {
+ name: config.should_sync_default for name, config in TREMENDOUS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/source.py
index d5bf50c3e4b8..c7e396dd6957 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/source.py
@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SHOULD_SYNC_DEFAULT,
TREMENDOUS_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.tremendous import (
@@ -113,9 +114,9 @@ You can create an API key under **Team settings → Developers** in [Tremendous]
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Only /orders exposes a server-side timestamp filter (`created_at[gte]`); everything else
- # is full refresh (see settings.py).
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ # Only /orders and /balance_transactions expose a server-side timestamp filter
+ # (`created_at[gte]`); everything else is full refresh (see settings.py).
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)
def validate_credentials(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous.py
index df2ffbe34419..1208839d3862 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous
from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.tremendous import (
DEFAULT_PROBE_PATH,
TremendousResumeConfig,
+ _balance_transaction_row_id,
_to_iso_datetime,
base_url_for_environment,
tremendous_source,
@@ -152,15 +153,21 @@ class TestPagination:
# The initial (offset=0) page must never be re-fetched on resume.
assert [p["offset"] for p in params] == [1000]
+ @parameterized.expand([("orders",), ("balance_transactions",)])
@mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_watermark_sent_as_created_at_gte_on_every_page(self, MockSession: mock.MagicMock) -> None:
+ def test_incremental_watermark_sent_as_created_at_gte_on_every_page(
+ self, endpoint: str, MockSession: mock.MagicMock
+ ) -> None:
session = MockSession.return_value
- full_page = [{"id": f"o_{i}"} for i in range(TREMENDOUS_ENDPOINTS["orders"].page_size)]
- params = _wire(session, [_response(full_page), _response([])])
+ config = TREMENDOUS_ENDPOINTS[endpoint]
+ full_page = [{"created_at": f"2026-01-03T00:00:{i:02d}Z"} for i in range(config.page_size)]
+ params = _wire(
+ session, [_response(full_page, data_key=config.data_key), _response([], data_key=config.data_key)]
+ )
_rows(
_source(
- "orders",
+ endpoint,
_make_manager(),
should_use_incremental_field=True,
db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
@@ -258,6 +265,71 @@ class TestHelpers:
assert base_url_for_environment(environment) == expected
+def _bt_row(**overrides: Any) -> dict[str, Any]:
+ row: dict[str, Any] = {
+ "created_at": "2026-01-02T03:04:05Z",
+ "amount": 25.0,
+ "currency_code": "USD",
+ "action": "Order",
+ "description": "Order payment",
+ "balance": 975.0,
+ "order": {"id": "ORDER123", "external_id": None, "payment": {"subtotal": 25.0, "total": 25.0, "fees": 0.0}},
+ }
+ row.update(overrides)
+ return row
+
+
+class TestBalanceTransactionRowId:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rows_come_out_with_synthetic_id(self, MockSession: mock.MagicMock) -> None:
+ # Rows are wrapped under "transactions" (not the endpoint name) and carry no API id;
+ # without the row map the table has no primary key and incremental merges break.
+ session = MockSession.return_value
+ _wire(session, [_response([_bt_row(), _bt_row(action="Refund")], data_key="transactions")])
+
+ rows = _rows(_source("balance_transactions", _make_manager()))
+
+ assert len(rows) == 2
+ assert all(isinstance(r["id"], str) and len(r["id"]) == 64 for r in rows)
+ assert rows[0]["id"] != rows[1]["id"]
+
+ @parameterized.expand(
+ [
+ # `balance` may be backfilled late (null -> value); re-keying on it would duplicate
+ # every backfilled row on the next incremental fetch.
+ ("balance_backfilled", {"balance": None}, {"balance": 975.0}, True),
+ # The embedded order payment grows a refund block once an order is canceled.
+ (
+ "order_refund_added",
+ {},
+ {
+ "order": {
+ "id": "ORDER123",
+ "payment": {"total": 25.0, "refund": {"total": 25.0, "currency_code": "USD"}},
+ }
+ },
+ True,
+ ),
+ # int/float representation drift must not re-key existing rows.
+ ("amount_int_vs_float", {"amount": 25}, {"amount": 25.0}, True),
+ # Dropping any discriminator from the hash would collapse distinct ledger rows.
+ ("different_created_at", {}, {"created_at": "2026-01-02T03:04:06Z"}, False),
+ ("different_amount", {}, {"amount": 26.0}, False),
+ ("different_currency", {}, {"currency_code": "EUR"}, False),
+ ("different_action", {}, {"action": "Refund"}, False),
+ ("different_description", {}, {"description": "Something else"}, False),
+ ("different_order_id", {}, {"order": {"id": "ORDER999"}}, False),
+ ("order_absent", {}, {"order": None}, False),
+ ]
+ )
+ def test_id_tracks_stable_fields_only(
+ self, _name: str, left: dict[str, Any], right: dict[str, Any], same: bool
+ ) -> None:
+ left_id = _balance_transaction_row_id(_bt_row(**left))["id"]
+ right_id = _balance_transaction_row_id(_bt_row(**right))["id"]
+ assert (left_id == right_id) is same
+
+
class TestValidateCredentials:
@staticmethod
def _session(response: Any) -> mock.MagicMock:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous_source.py
index f8ca65b1d0dc..4db52f2f7e32 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous_source.py
@@ -49,18 +49,29 @@ class TestTremendousSource:
assert field.secret is True
assert field.required is True
- def test_get_schemas_only_orders_is_incremental(self) -> None:
+ def test_get_schemas_incremental_endpoints(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id)
assert {s.name for s in schemas} == set(ENDPOINTS)
by_name = {s.name: s for s in schemas}
- # /orders is the only endpoint with a server-side timestamp filter (created_at[gte]).
- assert by_name["orders"].supports_incremental is True
- assert [f["field"] for f in by_name["orders"].incremental_fields] == ["created_at"]
+ # /orders and /balance_transactions are the only endpoints with a server-side timestamp
+ # filter (created_at[gte]).
+ incremental = {"orders", "balance_transactions"}
for name, schema in by_name.items():
- if name != "orders":
+ if name in incremental:
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]
+ else:
assert schema.supports_incremental is False
assert schema.incremental_fields == []
+ def test_balance_transactions_starts_opt_in(self) -> None:
+ # Its synthesized primary key is designed from the API docs but unconfirmed against live
+ # accounts, so the ledger table must not silently auto-enable at source creation.
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ by_name = {s.name: s for s in schemas}
+ assert by_name["balance_transactions"].should_sync_default is False
+ assert all(s.should_sync_default for name, s in by_name.items() if name != "balance_transactions")
+
def test_get_schemas_filtered_by_names(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id, names=["rewards"])
assert len(schemas) == 1
@@ -73,8 +84,9 @@ class TestTremendousSource:
tables = self.source.get_documented_tables()
assert {t["name"] for t in tables} == set(ENDPOINTS)
assert all("Full refresh" in t["sync_methods"] for t in tables)
- orders = next(t for t in tables if t["name"] == "orders")
- assert "Incremental" in orders["sync_methods"]
+ for name in ("orders", "balance_transactions"):
+ table = next(t for t in tables if t["name"] == name)
+ assert "Incremental" in table["sync_methods"]
assert all(t["description"] for t in tables)
@parameterized.expand(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tremendous.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tremendous.py
index d3e30e753147..10a949cdba5e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tremendous.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tremendous.py
@@ -1,10 +1,13 @@
+import hashlib
import dataclasses
+from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
Endpoint,
+ EndpointResource,
RESTAPIConfig,
rest_api_resource,
)
@@ -25,8 +28,8 @@ TREMENDOUS_BASE_URLS: dict[str, str] = {
# Cheap authenticated probe used to confirm an API key is genuine. The key is organization-wide, so
# one probe validates access to every list endpoint.
DEFAULT_PROBE_PATH = "/organizations"
-# Only /orders exposes a server-side timestamp filter; it is inclusive (`created_at[gte]`), so the
-# watermark row itself is re-fetched — merge dedupes it on the primary key.
+# Only /orders and /balance_transactions expose a server-side timestamp filter; it is inclusive
+# (`created_at[gte]`), so the watermark row itself is re-fetched — merge dedupes it on the primary key.
INCREMENTAL_START_PARAM = "created_at[gte]"
@@ -42,6 +45,45 @@ def base_url_for_environment(environment: str) -> str:
return TREMENDOUS_BASE_URLS.get(environment, TREMENDOUS_BASE_URLS["production"])
+# Identity fields for the synthesized /balance_transactions primary key. Only fields that never
+# change after the row is written: `balance` is excluded because the docs allow it to be backfilled
+# late (null first, populated later), and the nested order payload is excluded because
+# `order.payment.refund` appears once an order or reward is canceled — keying on either would
+# re-key the row on a later fetch and duplicate it. `order.id` (hashed separately below) is the
+# stable discriminator for order-driven rows.
+_BALANCE_TRANSACTION_ID_FIELDS = ("created_at", "amount", "currency_code", "action", "description")
+
+
+def _hash_part(value: Any) -> str:
+ if value is None:
+ return "\x00"
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ # JSON numbers can arrive as int or float depending on the serializer (100 vs 100.0);
+ # normalize so a representation change cannot re-key existing rows.
+ return str(float(value))
+ return str(value)
+
+
+def _balance_transaction_row_id(row: dict[str, Any]) -> dict[str, Any]:
+ """Synthesize a stable id for a /balance_transactions row — the API returns none.
+
+ Deterministic across fetches, so the inclusive `created_at[gte]` re-fetch of the watermark row
+ merges onto the existing row instead of duplicating it. Rows identical across every hashed
+ field collapse into one; the API offers nothing to tell such rows apart.
+ """
+ order = row.get("order") or {}
+ parts = [*(row.get(field) for field in _BALANCE_TRANSACTION_ID_FIELDS), order.get("id")]
+ joined = "|".join(_hash_part(part) for part in parts)
+ row["id"] = hashlib.sha256(joined.encode()).hexdigest()
+ return row
+
+
+# Per-endpoint row normalization applied after the data_selector, before the pipeline sees rows.
+ROW_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
+ "balance_transactions": _balance_transaction_row_id,
+}
+
+
def _to_iso_datetime(value: Any) -> Optional[str]:
"""Coerce an incremental cursor value to the ISO 8601 string `created_at[gte]` expects."""
if value is None:
@@ -95,6 +137,11 @@ def tremendous_source(
}
incremental_value = db_incremental_field_last_value
+ endpoint_resource: EndpointResource = {"name": endpoint, "endpoint": endpoint_config}
+ row_map = ROW_MAPS.get(endpoint)
+ if row_map is not None:
+ endpoint_resource["data_map"] = row_map
+
rest_config: RESTAPIConfig = {
"client": {
"base_url": base_url_for_environment(environment),
@@ -105,12 +152,7 @@ def tremendous_source(
"allow_redirects": False,
},
"resource_defaults": {},
- "resources": [
- {
- "name": endpoint,
- "endpoint": endpoint_config,
- }
- ],
+ "resources": [endpoint_resource],
}
initial_paginator_state: Optional[dict[str, Any]] = None