: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): implement tremendous import source (#69377)
Tom Owersabaca2cd3b60
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e3a0e6157e9a..55c8cecea01a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -345,6 +345,7 @@ the row lists both.| tmdb | HTTP | requests | ✅ || todoist | HTTP | requests | ✅ || trello | HTTP | requests | ✅ |+| tremendous | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || ubidots | HTTP | requests | ✅ |@@ -727,7 +728,6 @@ doesn't conflict with concurrent PRs.- together_ai- toggl- track_pms-- tremendous- trustpilot- tvmaze- twelve_datadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex d911a99d8cb0..7d3653468f25 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3486,7 +3486,8 @@ class TrelloSourceConfig(config.Config):@config.configclass TremendousSourceConfig(config.Config):- pass+ api_key: str+ environment: Literal["production", "sandbox"] = config.value(default="production")@config.configdiff --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.pynew file mode 100644index 000000000000..cdf9a761323f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/canonical_descriptions.py@@ -0,0 +1,110 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official Tremendous API reference+# (https://developers.tremendous.com/reference).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "orders": {+ "description": "An order wraps around the fulfilment of one or more rewards.",+ "docs_url": "https://developers.tremendous.com/reference/list-orders",+ "columns": {+ "id": "Tremendous ID of the order.",+ "external_id": "Customer-supplied idempotency reference for this order.",+ "campaign_id": "ID of the campaign in your account that defines the products the recipient can choose from.",+ "created_at": "Date the order was created.",+ "status": "Execution status of the order (e.g. CART, EXECUTED, FAILED, CANCELED).",+ "channel": "Name of the channel in which the order was created (e.g. API, UI, EMBED).",+ "payment": "Cost breakdown of the order (cost of rewards plus fees), denominated in the organization's currency.",+ "invoice_id": "ID of the invoice associated with this order.",+ "rewards": "Rewards fulfilled by this order.",+ },+ },+ "rewards": {+ "description": "A single reward, sent to a recipient. A reward is always part of an order.",+ "docs_url": "https://developers.tremendous.com/reference/get-rewards",+ "columns": {+ "id": "Tremendous ID of the reward.",+ "order_id": "Tremendous ID of the order this reward is part of.",+ "created_at": "Date the reward was created.",+ "expires_at": "Expiration date of the reward. Null if the reward does not expire.",+ "value": "Monetary value of the reward (denomination and currency code).",+ "recipient": "Details of the recipient of the reward (name, email, phone).",+ "deliver_at": "Scheduled delivery date of the reward.",+ "custom_fields": "Custom field values attached to the reward.",+ "delivery": "Details on how the reward is delivered to the recipient (method and status).",+ },+ },+ "invoices": {+ "description": "Invoices are instruments to fund your Tremendous account's balance. Once paid, the respective funds are added to the account balance.",+ "docs_url": "https://developers.tremendous.com/reference/core-invoices-list",+ "columns": {+ "id": "The invoice number.",+ "po_number": "Reference to the purchase order number within your organization.",+ "amount": "Amount of the invoice.",+ "currency_code": "Currency of the invoice.",+ "international": "Whether the invoice is international.",+ "status": "Status of the invoice (e.g. OPEN, PAID, DELETED).",+ "orders": "List of order IDs related to the invoice.",+ "rewards": "List of reward IDs related to the invoice.",+ "created_at": "Timestamp of when the invoice was created.",+ "paid_at": "Timestamp of when the invoice was paid.",+ },+ },+ "members": {+ "description": "Users that can access and manage the organization through the Tremendous dashboard.",+ "docs_url": "https://developers.tremendous.com/reference/core-members-list",+ "columns": {+ "id": "Tremendous ID of the member.",+ "email": "Email address of the member.",+ "name": "Full name of the member.",+ "active": "Whether this member is currently active in the organization.",+ "role": "The role ID associated with the member within the organization.",+ "status": "Current status of the member's account (INVITED or REGISTERED).",+ "created_at": "Timestamp when this member was created.",+ "last_login_at": "Timestamp when this member most recently logged into the dashboard.",+ },+ },+ "campaigns": {+ "description": "Campaigns define the look and feel of how rewards are sent out and the products recipients can choose from.",+ "docs_url": "https://developers.tremendous.com/reference/core-campaigns-list",+ "columns": {+ "id": "Tremendous ID of the campaign.",+ "name": "Name of the campaign.",+ "description": "Description of the campaign.",+ "products": "List of IDs of products (gift cards, charity, etc.) available in this campaign.",+ "fee_charged_to": "Whether premium product fees are added to the order total (SENDER) or deducted from the recipient's reward (RECIPIENT).",+ "webpage_style": "Definition of the reward redemption webpage style.",+ "email_style": "Definition of the reward email style.",+ },+ },+ "products": {+ "description": "A product represents one way to pay out a reward to its recipient, e.g. a specific gift card, charity donation, or prepaid card.",+ "docs_url": "https://developers.tremendous.com/reference/core-products-index",+ "columns": {+ "id": "Tremendous ID of the product.",+ "name": "Name of the product.",+ "description": "Detailed description of the product.",+ "category": "Category of the product (e.g. ach, charity, merchant_card, paypal, visa_card).",+ "subcategory": "Additional classification for merchant card products.",+ "disclosure": "Legal disclosures for this product.",+ "skus": "Denomination bands in which this product may be used for payouts.",+ "currency_codes": "Available currencies for this product.",+ "countries": "Countries in which this product is available to recipients.",+ "images": "Product images (e.g. logos or images of the gift cards).",+ "usage_instructions": "Instructions for how to use the product, if applicable.",+ },+ },+ "funding_sources": {+ "description": "Payment methods used to fund rewards in the organization's account.",+ "docs_url": "https://developers.tremendous.com/reference/core-funding-source-list",+ "columns": {+ "id": "Tremendous ID of the funding source.",+ "method": "Payment method of the funding source (e.g. balance, bank_account, credit_card, invoice).",+ "usage_permissions": "Which actions this funding source can perform.",+ "status": "Status of the funding source.",+ "type": "Invoice type; only available when method is invoice.",+ "meta": "Method-specific metadata (e.g. current balance, card details).",+ },+ },+}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.pynew file mode 100644index 000000000000..4ed67485a05a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/settings.py@@ -0,0 +1,68 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class TremendousEndpointConfig:+ path: str+ # Top-level key the list of records is nested under in the response body (e.g. {"orders": [...]}).+ data_key: str+ # Endpoints without offset/limit params return the whole collection in one response.+ paginated: bool = False+ page_size: int = 500+ # Stable creation timestamp used for datetime partitioning. Never an updated_at-style field.+ partition_key: Optional[str] = None+ 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"])+++# 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.+TREMENDOUS_ENDPOINTS: dict[str, TremendousEndpointConfig] = {+ "orders": TremendousEndpointConfig(+ path="/orders",+ data_key="orders",+ paginated=True,+ page_size=500, # /orders caps `limit` at 500+ partition_key="created_at",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "rewards": TremendousEndpointConfig(+ path="/rewards",+ data_key="rewards",+ paginated=True,+ page_size=500, # /rewards caps `limit` at 500+ partition_key="created_at",+ ),+ "invoices": TremendousEndpointConfig(+ path="/invoices",+ data_key="invoices",+ paginated=True,+ page_size=10, # /invoices caps `limit` at 10+ partition_key="created_at",+ ),+ "members": TremendousEndpointConfig(path="/members", data_key="members"),+ "campaigns": TremendousEndpointConfig(path="/campaigns", data_key="campaigns"),+ "products": TremendousEndpointConfig(path="/products", data_key="products"),+ "funding_sources": TremendousEndpointConfig(path="/funding_sources", data_key="funding_sources"),+}++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+}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.pyindex 39e540dda5bc..3b25afcc6396 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@@ -1,19 +1,47 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TremendousSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ TREMENDOUS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.tremendous import (+ TremendousResumeConfig,+ tremendous_source,+ validate_credentials as validate_tremendous_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Pull-only for now: Tremendous supports webhooks, but every organization can have exactly ONE+# webhook endpoint, so auto-creating ours would clobber any webhook the customer already relies on.@SourceRegistry.register-class TremendousSource(SimpleSource[TremendousSourceConfig]):+class TremendousSource(ResumableSource[TremendousSourceConfig, TremendousResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TREMENDOUS@@ -24,7 +52,104 @@ class TremendousSource(SimpleSource[TremendousSourceConfig]):name=SchemaExternalDataSourceType.TREMENDOUS,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Tremendous",- iconPath="/static/services/tremendous.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Tremendous API key to pull your rewards and payouts data into the PostHog Data warehouse.++You can create an API key under **Team settings → Developers** in [Tremendous](https://www.tremendous.com). Sandbox and production are separate environments with separate API keys — make sure the environment matches the key.""",+ iconPath="/static/services/tremendous.png",+ docsUrl="https://posthog.com/docs/cdp/sources/tremendous",+ keywords=["rewards", "gift cards", "incentives", "payouts"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production", value="production"),+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),+ ],+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://www.tremendous.com": "Your Tremendous API key is invalid or has been revoked. Generate a new key under Team settings → Developers, then reconnect.",+ "401 Client Error: Unauthorized for url: https://testflight.tremendous.com": "Your Tremendous sandbox API key is invalid or has been revoked. Generate a new key under Team settings → Developers, then reconnect.",+ "403 Client Error: Forbidden for url: https://www.tremendous.com": "Your Tremendous API key does not have access to this data. Check the key's permissions, then reconnect.",+ "403 Client Error: Forbidden for url: https://testflight.tremendous.com": "Your Tremendous sandbox API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: TremendousSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only /orders exposes a server-side timestamp filter (`created_at[gte]`); everything else+ # is full refresh (see settings.py).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_FIELDS,+ supports_append=endpoint in INCREMENTAL_FIELDS,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: TremendousSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is organization-wide, so a single probe validates access to every schema.+ return validate_tremendous_credentials(config.api_key, config.environment)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TremendousResumeConfig]:+ return ResumableSourceManager[TremendousResumeConfig](inputs, TremendousResumeConfig)++ def source_for_pipeline(+ self,+ config: TremendousSourceConfig,+ resumable_source_manager: ResumableSourceManager[TremendousResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in TREMENDOUS_ENDPOINTS:+ raise ValueError(f"Unknown Tremendous schema '{inputs.schema_name}'")++ return tremendous_source(+ api_key=config.api_key,+ environment=config.environment,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)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.pynew file mode 100644index 000000000000..b4717a2e5c74--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous.py@@ -0,0 +1,338 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous import tremendous+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.settings import (+ ENDPOINTS,+ TREMENDOUS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.tremendous import (+ TremendousResumeConfig,+ TremendousRetryableError,+ _to_iso_datetime,+ base_url_for_environment,+ check_access,+ get_rows,+ tremendous_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = tremendous._fetch_page.__wrapped__ # type: ignore[attr-defined]++ORDERS_PAGE_SIZE = TREMENDOUS_ENDPOINTS["orders"].page_size+++class _FakeResumableManager:+ def __init__(self, state: TremendousResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[TremendousResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> TremendousResumeConfig | None:+ return self._state++ def save_state(self, data: TremendousResumeConfig) -> None:+ self.saved.append(data)+++def _page(size: int) -> list[dict]:+ return [{"id": f"ID{i}"} for i in range(size)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[int, list[dict]],+ endpoint: str = "orders",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict], list[dict[str, Any]]]:+ requested_params: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, data_key: str, params: dict[str, Any], logger: Any) -> list[dict]:+ requested_params.append(params)+ return pages[params["offset"]] if "offset" in params else pages[0]++ monkeypatch.setattr(tremendous, "_fetch_page", fake_fetch)+ monkeypatch.setattr(tremendous, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="tremendous-key",+ environment="production",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows, requested_params++ def test_pins_redirects_off(self, monkeypatch: Any) -> None:+ # Redirect-following would replay the Bearer key to whatever host Tremendous redirects to.+ captured: list[dict[str, Any]] = []++ def fake_session(**kwargs: Any) -> Any:+ captured.append(kwargs)+ return MagicMock()++ monkeypatch.setattr(tremendous, "_fetch_page", lambda *a, **k: [])+ monkeypatch.setattr(tremendous, "make_tracked_session", fake_session)+ list(+ get_rows(+ api_key="tremendous-key",+ environment="production",+ endpoint="orders",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert captured and captured[0]["allow_redirects"] is False++ def test_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, params = self._collect(manager, monkeypatch, {0: [{"id": "A"}, {"id": "B"}]})+ assert rows == [{"id": "A"}, {"id": "B"}]+ assert params == [{"limit": ORDERS_PAGE_SIZE, "offset": 0}]+ # The page was short, so we stopped without persisting resume state.+ assert manager.saved == []++ def test_advances_offset_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {0: _page(ORDERS_PAGE_SIZE), ORDERS_PAGE_SIZE: [{"id": "LAST"}]}+ rows, params = self._collect(manager, monkeypatch, pages)+ assert len(rows) == ORDERS_PAGE_SIZE + 1+ assert [p["offset"] for p in params] == [0, ORDERS_PAGE_SIZE]+ # State is saved after yielding the full first page, then the short page terminates.+ assert [s.offset for s in manager.saved] == [ORDERS_PAGE_SIZE]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(TremendousResumeConfig(offset=1000))+ rows, params = self._collect(manager, monkeypatch, {1000: [{"id": "X"}]})+ assert rows == [{"id": "X"}]+ # The initial (offset=0) page must never be re-fetched on resume.+ assert [p["offset"] for p in params] == [1000]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(manager, monkeypatch, {0: []})+ assert rows == []+ assert manager.saved == []++ def test_incremental_watermark_sent_as_created_at_gte_on_every_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ watermark = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)+ pages = {0: _page(ORDERS_PAGE_SIZE), ORDERS_PAGE_SIZE: []}+ _, params = self._collect(+ manager,+ monkeypatch,+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ assert all(p["created_at[gte]"] == "2026-01-02T03:04:05+00:00" for p in params)++ def test_full_refresh_sends_no_created_at_filter(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ _, params = self._collect(manager, monkeypatch, {0: [{"id": "A"}]})+ assert all("created_at[gte]" not in p for p in params)++ def test_unpaginated_endpoint_fetches_once_without_params(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, params = self._collect(manager, monkeypatch, {0: [{"id": "M1"}, {"id": "M2"}]}, endpoint="members")+ assert rows == [{"id": "M1"}, {"id": "M2"}]+ assert params == [{}]+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"orders": [], "total_count": 0}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(TremendousRetryableError):+ _fetch_page_unwrapped(session, "https://www.tremendous.com/api/v2/orders", "orders", {}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "https://www.tremendous.com/api/v2/orders", "orders", {}, MagicMock())++ def test_success_returns_items_under_data_key(self) -> None:+ session = self._session_returning(200, {"orders": [{"id": "A"}], "total_count": 1})+ items = _fetch_page_unwrapped(session, "https://www.tremendous.com/api/v2/orders", "orders", {}, MagicMock())+ assert items == [{"id": "A"}]++ @parameterized.expand(+ [+ ("non_dict_body", [{"id": "A"}]),+ ("missing_data_key", {"total_count": 0}),+ ("data_key_not_a_list", {"orders": {"id": "A"}}),+ ]+ )+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(TremendousRetryableError):+ _fetch_page_unwrapped(session, "https://www.tremendous.com/api/v2/orders", "orders", {}, MagicMock())+++class TestHelpers:+ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05+00:00"),+ ("naive_datetime", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05+00:00"),+ ("date", date(2026, 1, 2), "2026-01-02T00:00:00+00:00"),+ ("string_passthrough", "2026-01-02T00:00:00Z", "2026-01-02T00:00:00Z"),+ ("none", None, None),+ ("empty_string", "", None),+ ]+ )+ def test_to_iso_datetime(self, _name: str, value: Any, expected: str | None) -> None:+ assert _to_iso_datetime(value) == expected++ @parameterized.expand(+ [+ ("production", "https://www.tremendous.com/api/v2"),+ ("sandbox", "https://testflight.tremendous.com/api/v2"),+ # Unknown values fall back to production rather than building a bad URL.+ ("bogus", "https://www.tremendous.com/api/v2"),+ ]+ )+ def test_base_url_for_environment(self, environment: str, expected: str) -> None:+ assert base_url_for_environment(environment) == expected+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Tremendous returned HTTP 500"),+ ]+ )+ @patch(f"{tremendous.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("tremendous-key", "production") == (expected_status, expected_message)++ @patch(f"{tremendous.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("tremendous-key", "production")+ assert status == 0+ assert message is not None and "boom" in message++ @patch(f"{tremendous.__name__}.make_tracked_session")+ def test_pins_redirects_off(self, mock_session: MagicMock) -> None:+ # Redirect-following would replay the Bearer key to whatever host Tremendous redirects to.+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ mock_session.return_value = self._session(response)+ check_access("tremendous-key", "production")+ assert mock_session.call_args.kwargs["allow_redirects"] is False++ @patch(f"{tremendous.__name__}.make_tracked_session")+ def test_probe_targets_selected_environment(self, mock_session: MagicMock) -> None:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session = self._session(response)+ mock_session.return_value = session+ check_access("tremendous-key", "sandbox")+ url = session.get.call_args.args[0]+ assert url.startswith("https://testflight.tremendous.com/api/v2")++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Tremendous API key (check that it matches the selected environment)"),+ ("forbidden", 403, False, "Invalid Tremendous API key (check that it matches the selected environment)"),+ ("server_error", 500, False, "Tremendous returned HTTP 500"),+ ]+ )+ @patch(f"{tremendous.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("tremendous-key", "production") == (expected_valid, expected_message)+++class TestTremendousSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = tremendous_source(+ api_key="tremendous-key",+ environment="production",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Tremendous lists are creation-date DESC; declaring asc would corrupt the incremental watermark.+ assert response.sort_mode == "desc"+ if TREMENDOUS_ENDPOINTS[endpoint].partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ else:+ assert response.partition_mode is None++ def test_partition_keys_are_stable_creation_timestamps(self) -> None:+ # Partition keys must never be updated_at-style fields, which rewrite partitions every sync.+ assert {c.partition_key for c in TREMENDOUS_ENDPOINTS.values()} == {"created_at", None}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.pynew file mode 100644index 000000000000..60f4ddaac6cd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tests/test_tremendous_source.py@@ -0,0 +1,170 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TremendousSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.source import TremendousSource+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.tremendous import (+ TremendousResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestTremendousSource:+ def setup_method(self) -> None:+ self.source = TremendousSource()+ self.team_id = 123+ self.config = TremendousSourceConfig(api_key="tremendous-key", environment="sandbox")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TREMENDOUS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Tremendous"+ assert config.label == "Tremendous"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/tremendous"++ field_names = [f.name for f in config.fields]+ assert field_names == ["environment", "api_key"]++ def test_environment_field_defaults_to_production(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))+ assert field.defaultValue == "production"+ assert {o.value for o in field.options} == {"production", "sandbox"}++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_only_orders_is_incremental(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"]+ for name, schema in by_name.items():+ if name != "orders":+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ 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+ assert schemas[0].name == "rewards"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ 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"]+ assert all(t["description"] for t in tables)++ @parameterized.expand(+ [+ (+ "production_unauthorized",+ "401 Client Error: Unauthorized for url: https://www.tremendous.com/api/v2/orders?limit=500&offset=0",+ ),+ (+ "sandbox_unauthorized",+ "401 Client Error: Unauthorized for url: https://testflight.tremendous.com/api/v2/rewards?limit=500&offset=0",+ ),+ (+ "production_forbidden",+ "403 Client Error: Forbidden for url: https://www.tremendous.com/api/v2/members",+ ),+ (+ "sandbox_forbidden",+ "403 Client Error: Forbidden for url: https://testflight.tremendous.com/api/v2/members",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://www.tremendous.com/api/v2/orders",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://testflight.tremendous.com/api/v2/rewards",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.source.validate_tremendous_credentials"+ )+ def test_validate_credentials_delegates_with_key_and_environment(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in tremendous.validate_credentials; here we only assert+ # the source probes with the configured key and environment and returns the verdict unchanged.+ mock_validate.return_value = (False, "Invalid Tremendous API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("tremendous-key", "sandbox")+ assert result == (False, "Invalid Tremendous API key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TremendousResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.source.tremendous_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "tremendous-key"+ assert kwargs["environment"] == "sandbox"+ assert kwargs["endpoint"] == "orders"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.source.tremendous_source")+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark left on the schema must not leak into a full-refresh run and window the sync.+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Tremendous schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)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.pynew file mode 100644index 000000000000..3785ba6bdae6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tremendous/tremendous.py@@ -0,0 +1,201 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.tremendous.settings import TREMENDOUS_ENDPOINTS++# Sandbox and production are separate hosts with separate API keys.+TREMENDOUS_BASE_URLS: dict[str, str] = {+ "production": "https://www.tremendous.com/api/v2",+ "sandbox": "https://testflight.tremendous.com/api/v2",+}+REQUEST_TIMEOUT_SECONDS = 60+# 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"+++class TremendousRetryableError(Exception):+ pass+++class TremendousResumeConfig:+ # Number of rows already yielded for the current offset/limit page chain. Tremendous paginates+ # by creation date DESC, so rows created mid-sync shift the window and can re-appear on a later+ # page — merge dedupes them on `id`; rows are never skipped.+ offset: int = 0+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def base_url_for_environment(environment: str) -> str:+ return TREMENDOUS_BASE_URLS.get(environment, TREMENDOUS_BASE_URLS["production"])+++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:+ return None+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ if isinstance(value, str) and value:+ return value+ return None+++@retry(+ retry=retry_if_exception_type((TremendousRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ data_key: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ # Tremendous rate-limits per organization; 429 and transient 5xx back off exponentially.+ if response.status_code == 429 or response.status_code >= 500:+ raise TremendousRetryableError(f"Tremendous API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Tremendous API error: status={response.status_code}, body={response.text[:200]!r}, url={url}")+ response.raise_for_status()++ data = response.json()+ # List responses wrap records under the plural resource name, e.g. {"orders": [...], "total_count": N}.+ if not isinstance(data, dict) or not isinstance(data.get(data_key), list):+ raise TremendousRetryableError(f"Tremendous returned an unexpected payload for {url}: {type(data).__name__}")++ return data[data_key]+++def get_rows(+ api_key: str,+ environment: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TremendousResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = TREMENDOUS_ENDPOINTS[endpoint]+ # Pin redirects off so the Bearer key never replays to a host Tremendous redirects us to.+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)+ url = f"{base_url_for_environment(environment)}{config.path}"++ if not config.paginated:+ # Members, campaigns, products, and funding sources return the whole collection in one+ # response — no offset/limit params, so there is no resume state to track.+ items = _fetch_page(session, url, config.data_key, {}, logger)+ if items:+ yield items+ return++ base_params: dict[str, Any] = {"limit": config.page_size}+ # `created_at[gte]` is inclusive, so the watermark row itself is re-fetched — merge dedupes it+ # on the primary key. The filter applies on every page, so pagination stays bounded to the window.+ incremental_cursor = _to_iso_datetime(db_incremental_field_last_value) if should_use_incremental_field else None+ if incremental_cursor is not None:+ base_params["created_at[gte]"] = incremental_cursor++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume and resume.offset:+ logger.debug(f"Tremendous: resuming {endpoint} from offset {offset}")++ while True:+ items = _fetch_page(session, url, config.data_key, {**base_params, "offset": offset}, logger)+ if items:+ yield items++ # A page shorter than the limit (or empty) marks the end of the collection.+ if len(items) < config.page_size:+ break++ offset += len(items)+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes any re-pulled rows on the primary key.+ resumable_source_manager.save_state(TremendousResumeConfig(offset=offset))+++def tremendous_source(+ api_key: str,+ environment: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TremendousResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = TREMENDOUS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ environment=environment,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Tremendous lists are ordered by creation date DESC and expose no sort param, so the+ # incremental watermark is finalized at the end of a completed sync.+ sort_mode="desc",+ )+++def check_access(api_key: str, environment: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)+ try:+ response = session.get(f"{base_url_for_environment(environment)}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Tremendous: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Tremendous returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, environment: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key, environment)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Tremendous API key (check that it matches the selected environment)"+ return False, message or "Could not validate Tremendous API key"