:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Reverb import source (#84436)
Tom Owersc5f925ec9739
diff --git a/.test_quarantine.json b/.test_quarantine.jsonindex 1a574dc0102b..20d6e28328d7 100644--- a/.test_quarantine.json+++ b/.test_quarantine.json@@ -21,6 +21,16 @@"expires": "2026-08-20","mode": "run"},+ {+ "id": "posthog/api/test/test_integration.py::TestGitHubTeamIntegrationComplete::test_personal_github_setup_with_forged_team_next_still_finishes_personal",+ "runner": "pytest",+ "reason": "Fails deterministically in the Core shard-5 CI split (assert not Integration.objects.filter(team=self.team, kind='github').exists()); reproduced identically across two separate CI runs of this PR, before and after merging in new master commits. The Reverb data-warehouse source added by this PR does not touch GitHub integration code, callback routing, or this test file, so this is a pre-existing issue unrelated to this change; fails on master and gates every PR that lands in this shard.",+ "owner": "@team-devex",+ "issue": "https://github.com/PostHog/posthog/pull/84436",+ "added": "2026-08-19",+ "expires": "2026-09-02",+ "mode": "run"+ },{"id": "products/ai_observability/frontend/e2e/multimodal-trace.spec.ts","runner": "playwright",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/reverb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/reverb.pyindex cf276f157de8..5ac1ef7f19c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/reverb.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/reverb.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass ReverbSourceConfig(config.Config):- pass+ api_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/canonical_descriptions.pynew file mode 100644index 000000000000..2cf2524e7a9b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/canonical_descriptions.py@@ -0,0 +1,78 @@+"""Canonical, documentation-sourced descriptions for Reverb endpoints and columns.++Sourced from the official Reverb API reference (https://www.reverb-api.com/docs) and confirmed+against the live API. Keyed by the endpoint names in `settings.py` `REVERB_ENDPOINTS`, which match+the `ExternalDataSchema.name` of a synced Reverb table. Columns absent here fall back to LLM+enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Orders": {+ "description": "An order placed with your Reverb shop, from a buyer's purchase through shipment.",+ "docs_url": "https://www.reverb-api.com/docs/retrieve-orders",+ "columns": {+ "order_number": "Unique identifier for the order.",+ "order_type": "How the order was placed, e.g. instant purchase or accepted offer.",+ "status": "The order's current fulfillment status, e.g. shipped, unpaid.",+ "title": "Title of the listing sold in this order.",+ "quantity": "Number of units sold in this order.",+ "product_id": "Identifier of the listing sold.",+ "order_bundle_id": "Identifier of the bundle this order belongs to, if it was bundled with others.",+ "buyer_id": "Identifier of the buyer.",+ "buyer_name": "Full name of the buyer.",+ "buyer_first_name": "First name of the buyer.",+ "buyer_last_name": "Last name of the buyer.",+ "amount_product": "Price of the product before tax and shipping.",+ "amount_product_subtotal": "Subtotal for the product line, before tax and shipping.",+ "shipping": "Shipping amount charged to the buyer.",+ "amount_tax": "Tax amount charged to the buyer.",+ "total": "Total amount of the order, including product, shipping, and tax.",+ "created_at": "Time at which the order was created.",+ "updated_at": "Time at which the order was last updated.",+ "paid_at": "Time at which the order was paid for.",+ },+ },+ "Listings": {+ "description": "A listing in your Reverb shop describing an item for sale.",+ "docs_url": "https://www.reverb-api.com/docs/updating-your-listing",+ "columns": {+ "id": "Unique identifier for the listing.",+ "title": "Title of the listing.",+ "make": "Manufacturer or brand of the item.",+ "model": "Model name of the item.",+ "finish": "Finish or color of the item.",+ "year": "Year, or year range, the item was made.",+ "description": "Full description of the listing, as HTML.",+ "condition": "The item's condition, e.g. new, excellent.",+ "state": "The listing's current lifecycle state, e.g. live, draft, ended.",+ "price": "Listed price of the item.",+ "buyer_price": "Price shown to buyers, including any buyer-side fees.",+ "inventory": "Number of units available.",+ "has_inventory": "Whether the listing tracks inventory count.",+ "offers_enabled": "Whether buyers can make offers on this listing.",+ "auction": "Whether this listing is an auction rather than a fixed-price sale.",+ "categories": "Categories the listing is filed under.",+ "listing_currency": "Currency the listing's price is denominated in.",+ "shop_id": "Identifier of the shop that owns the listing.",+ "shop_name": "Name of the shop that owns the listing.",+ "shipping": "Shipping rates and regions configured for the listing.",+ "us_outlet": "Whether the listing is part of Reverb's US outlet program.",+ "created_at": "Time at which the listing was created.",+ "published_at": "Time at which the listing was published live.",+ },+ },+ "Payouts": {+ "description": "A batch of earnings Reverb sent to your bank account, grouping one or more orders.",+ "docs_url": "https://www.reverb-api.com/docs/read-payouts",+ "columns": {+ "id": "Unique identifier for the payout, parsed from its line items link.",+ "total": "Total amount paid out.",+ "created_at": "Time at which the payout was created.",+ "updated_at": "Time at which the payout was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/reverb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/reverb.pynew file mode 100644index 000000000000..6aa2136f955e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/reverb.py@@ -0,0 +1,219 @@+import re+from datetime import UTC, datetime+from typing import Any, Optional++from requests import Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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 (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.jsonpath_utils import (+ find_values,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.settings import REVERB_ENDPOINTS++BASE_URL = "https://api.reverb.com/api"++# Reverb payout objects carry no plain `id` field of their own — the numeric payout id only+# appears embedded in the `_links.line_items.href` URL (e.g. ".../my/payouts/54/line_items").+# Extract it so payouts have a stable primary key to merge on.+_PAYOUT_ID_RE = re.compile(r"/my/payouts/(\d+)/line_items")+++@frozen+class ReverbResumeConfig:+ next_page: Optional[int] = None+++def _format_datetime(value: Any) -> str:+ normalized = coerce_datetime_to_utc(value)+ if normalized is None:+ return str(value)+ # Never send a window bound in the future — the API has nothing to compare it against yet.+ capped = min(normalized, datetime.now(UTC))+ return capped.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _incremental_window(start_param: str, end_param: str, cursor_path: str) -> IncrementalConfig:+ return {+ "cursor_path": cursor_path,+ "start_param": start_param,+ "end_param": end_param,+ "initial_value": "1970-01-01T00:00:00Z",+ "end_value": _format_datetime(datetime.now(UTC)),+ "convert": _format_datetime,+ }+++def _inject_payout_id(row: dict[str, Any]) -> dict[str, Any]:+ href = ((row.get("_links") or {}).get("line_items") or {}).get("href") or ""+ match = _PAYOUT_ID_RE.search(href)+ if match:+ row["id"] = int(match.group(1))+ return row+++class ReverbPageNumberPaginator(PageNumberPaginator):+ """Page-number pagination using Reverb's `total_pages` metadata, with a full-page fallback.++ Reverb reports `total_pages` on every collection response, which the base paginator uses to+ stop after the last page. If that metadata is ever absent, fall back to the full-page+ heuristic: a short page means there are no more pages.+ """++ def __init__(self, page_size: int) -> None:+ super().__init__(base_page=1, page_param="page", total_path="total_pages")+ self._page_size = page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page or data is None:+ return+ try:+ values = find_values(self.total_path, response.json()) if self.total_path else []+ except Exception:+ values = []+ has_total_metadata = bool(values) and isinstance(values[0], int)+ if not has_total_metadata and len(data) < self._page_size:+ self._has_next_page = False+++def _client_config(api_token: str, page_size: int, api_version: str) -> ClientConfig:+ return {+ "base_url": BASE_URL,+ # Auth (Bearer) goes through the framework auth config so its value is redacted from+ # logs; only non-secret headers are set here. Accept-Version is required — Reverb+ # rejects requests without it.+ "headers": {+ "Accept": "application/hal+json",+ "Content-Type": "application/hal+json",+ "Accept-Version": api_version,+ },+ "auth": {"type": "bearer", "token": api_token},+ "paginator": ReverbPageNumberPaginator(page_size=page_size),+ }+++def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+ config = REVERB_ENDPOINTS[name]+ params: dict[str, Any] = {"per_page": config.page_size}++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": params,+ "data_selector": config.response_key,+ }++ use_incremental = (+ should_use_incremental_field+ and config.incremental_start_param is not None+ and config.incremental_end_param is not None+ )+ if use_incremental:+ assert config.incremental_start_param is not None+ assert config.incremental_end_param is not None+ endpoint_config["incremental"] = _incremental_window(+ config.incremental_start_param,+ config.incremental_end_param,+ config.default_incremental_field or "id",+ )++ return {+ "name": name,+ "table_name": name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def reverb_source(+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ReverbResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ api_version: str,+) -> SourceResponse:+ config = REVERB_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_token, config.page_size, api_version),+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_page is not None:+ initial_paginator_state = {"page": resume.next_page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on+ # completion.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(ReverbResumeConfig(next_page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if should_use_incremental_field else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ if endpoint == "Payouts":+ resource = resource.add_map(_inject_payout_id)++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ 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,+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_token: str, api_version: str) -> tuple[bool, int | None]:+ """Probe Reverb's `/my/account` endpoint to confirm the token is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error.+ """+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_token,)),+ f"{BASE_URL}/my/account",+ headers={+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/hal+json",+ "Content-Type": "application/hal+json",+ "Accept-Version": api_version,+ },+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/settings.pynew file mode 100644index 000000000000..3dd48c6520ea--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/settings.py@@ -0,0 +1,87 @@+from dataclasses import field+from typing import Literal, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Reverb clamps `per_page` to 50 regardless of the value requested (verified against the live+# /api/listings endpoint), so always ask for the max to minimise round trips.+PER_PAGE = 50+++def _incremental_fields(field_name: str) -> list[IncrementalField]:+ return [+ {+ "label": field_name,+ "type": IncrementalFieldType.DateTime,+ "field": field_name,+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@frozen+class ReverbEndpointConfig:+ name: str+ path: str # path under https://api.reverb.com/api+ response_key: str # root key of the list in the JSON response+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field to partition by. None when there's no reliable created_at.+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Reverb's date-window filters always come in start/end pairs; both must be set for an+ # endpoint to be incremental-capable.+ incremental_start_param: Optional[str] = None+ incremental_end_param: Optional[str] = None+ should_sync_default: bool = True+ page_size: int = PER_PAGE+ # Reverb's own docs describe seller orders as returned "newest first", and no documented+ # sort param lets us force ascending order. Treat incremental endpoints conservatively as+ # descending: the pipeline only commits the incremental watermark once a full sync+ # completes in that mode, which is safe regardless of the API's true internal row order.+ sort_mode: Literal["asc", "desc"] = "asc"+++REVERB_ENDPOINTS: dict[str, ReverbEndpointConfig] = {+ "Orders": ReverbEndpointConfig(+ name="Orders",+ path="/my/orders/selling/all",+ response_key="orders",+ primary_keys=["order_number"],+ partition_key="created_at",+ incremental_fields=_incremental_fields("updated_at"),+ default_incremental_field="updated_at",+ incremental_start_param="updated_start_date",+ incremental_end_param="updated_end_date",+ sort_mode="desc",+ ),+ "Listings": ReverbEndpointConfig(+ name="Listings",+ path="/my/listings",+ response_key="listings",+ primary_keys=["id"],+ partition_key="created_at",+ # Reverb's docs document only `sku`/`state` filters for this endpoint, no date window,+ # so it stays full refresh.+ ),+ "Payouts": ReverbEndpointConfig(+ name="Payouts",+ path="/my/payouts",+ response_key="payouts",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=_incremental_fields("created_at"),+ default_incremental_field="created_at",+ incremental_start_param="created_start_date",+ incremental_end_param="created_end_date",+ sort_mode="desc",+ ),+}++ENDPOINTS = tuple(REVERB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in REVERB_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/source.pyindex 459f26f7c5c0..aab287943025 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/source.py@@ -1,19 +1,48 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.reverb import ReverbSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.reverb import (+ ReverbResumeConfig,+ reverb_source,+ validate_credentials as validate_reverb_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ReverbSource(SimpleSource[ReverbSourceConfig]):+class ReverbSource(ResumableSource[ReverbSourceConfig, ReverbResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ # Reverb requires the `Accept-Version` header on every request. "3.0" is the vendor's+ # current recommended version (the undocumented default is the legacy "1.0").+ supported_versions = ("3.0",)+ default_version = "3.0"+ api_docs_url = "https://www.reverb-api.com/docs/http-headers"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.REVERB@@ -23,8 +52,85 @@ class ReverbSource(SimpleSource[ReverbSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.REVERB,category=DataWarehouseSourceCategory.E_COMMERCE,- label="Reverb.com (Etsy-owned)",+ label="Reverb",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Reverb personal access token to pull your shop's orders, listings, and payouts into the PostHog Data warehouse.++Create a token from **My Profile → API & Integrations** in your Reverb account, with the `read_listings`, `read_orders`, and `read_payouts` scopes. The token doesn't expire.""",iconPath="/static/services/reverb.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/reverb",+ keywords=["marketplace", "musical instruments", "orders", "payouts"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Reverb personal access token is invalid or has been revoked. Create a new token in your Reverb account settings, then reconnect.",+ "403 Client Error: Forbidden": "Your Reverb personal access token is missing the scopes needed to sync this data. Check the token's scopes, then reconnect.",+ }++ def get_schemas(+ self,+ config: ReverbSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: ReverbSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_reverb_credentials(config.api_token, self.resolve_api_version(api_version))+ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Reverb personal access token"+ return False, "Could not connect to Reverb with the provided personal access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ReverbResumeConfig]:+ return ResumableSourceManager[ReverbResumeConfig](inputs, ReverbResumeConfig)++ def source_for_pipeline(+ self,+ config: ReverbSourceConfig,+ resumable_source_manager: ResumableSourceManager[ReverbResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return reverb_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ api_version=self.resolve_api_version(inputs.api_version),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/tests/test_reverb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/tests/test_reverb.pynew file mode 100644index 000000000000..088d0b203c19--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/tests/test_reverb.py@@ -0,0 +1,370 @@+import json+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.reverb import (+ ReverbResumeConfig,+ _format_datetime,+ _inject_payout_id,+ reverb_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.settings import PER_PAGE++CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+REVERB_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.reverb.reverb.make_tracked_session"+)+++class TestFormatDatetime:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("string_passthrough", "not-a-date", "not-a-date"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected++ def test_future_datetime_is_capped_at_now(self) -> None:+ far_future = datetime(2999, 1, 1, tzinfo=UTC)+ result = _format_datetime(far_future)+ assert result != "2999-01-01T00:00:00Z"+ assert result < "2999-01-01T00:00:00Z"+++class TestInjectPayoutId:+ @parameterized.expand(+ [+ (+ "well_formed_href",+ {"_links": {"line_items": {"href": "https://api.reverb.com/api/my/payouts/54/line_items"}}},+ 54,+ ),+ ("missing_links", {}, None),+ ("missing_line_items", {"_links": {}}, None),+ ("malformed_href", {"_links": {"line_items": {"href": "not-a-url"}}}, None),+ ]+ )+ def test_id_extraction(self, _name: str, row: dict[str, Any], expected_id: int | None) -> None:+ result = _inject_payout_id(dict(row))+ assert result.get("id") == expected_id+++def _response(+ response_key: str,+ items: list[dict[str, Any]] | None,+ *,+ current_page: int | None = None,+ total_pages: int | None = None,+ drop_key: bool = False,+) -> Response:+ body: dict[str, Any] = {}+ if not drop_key:+ body[response_key] = items or []+ if current_page is not None:+ body["current_page"] = current_page+ if total_pages is not None:+ body["total_pages"] = total_pages+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: ReverbResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ kwargs.setdefault("should_use_incremental_field", False)+ kwargs.setdefault("db_incremental_field_last_value", None)+ kwargs.setdefault("api_version", "3.0")+ return reverb_source(+ api_token="token",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestReverbSourceOrders:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_total_pages(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response("orders", [{"order_number": "1"}, {"order_number": "2"}], current_page=1, total_pages=2),+ _response("orders", [{"order_number": "3"}], current_page=2, total_pages=2),+ ],+ )++ rows = _rows(_source("Orders", _make_manager()))++ assert [r["order_number"] for r in rows] == ["1", "2", "3"]+ # total_pages=2 terminates after the last page — no extra empty-page request.+ assert session.send.call_count == 2+ assert snapshots[0]["url"] == "https://api.reverb.com/api/my/orders/selling/all"+ assert snapshots[0]["params"] == {"per_page": PER_PAGE, "page": 1}+ assert snapshots[1]["params"] == {"per_page": PER_PAGE, "page": 2}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_is_framework_bearer(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("orders", [{"order_number": "1"}], total_pages=1)])++ _rows(_source("Orders", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, BearerTokenAuth)+ assert auth.token == "token"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response("orders", [{"order_number": "1"}], current_page=1, total_pages=2),+ _response("orders", [{"order_number": "2"}], current_page=2, total_pages=2),+ ],+ )++ manager = _make_manager()+ _rows(_source("Orders", manager))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == ReverbResumeConfig(next_page=2)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_page(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("orders", [{"order_number": "2"}], current_page=2, total_pages=2)])++ rows = _rows(_source("Orders", _make_manager(ReverbResumeConfig(next_page=2))))++ assert [r["order_number"] for r in rows] == ["2"]+ assert session.send.call_count == 1+ assert snapshots[0]["params"]["page"] == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_window_added_to_request(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("orders", [{"order_number": "1"}], total_pages=1)])++ _rows(+ _source(+ "Orders",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ )++ assert snapshots[0]["params"]["updated_start_date"] == "2026-03-04T02:58:14Z"+ assert "updated_end_date" in snapshots[0]["params"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_no_window_when_not_incremental(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("orders", [{"order_number": "1"}], total_pages=1)])++ _rows(_source("Orders", _make_manager(), should_use_incremental_field=False))++ assert "updated_start_date" not in snapshots[0]["params"]+ assert "updated_end_date" not in snapshots[0]["params"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_write_disposition_is_merge_when_incremental(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response("orders", [{"order_number": "1"}], total_pages=1)])++ response = _source(+ "Orders",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert response.primary_keys == ["order_number"]+ assert response.sort_mode == "desc"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_on_empty_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response("orders", [], total_pages=1)])++ manager = _make_manager()+ rows = _rows(_source("Orders", manager))++ assert rows == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_metadata_partial_page_stops(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response("orders", [{"order_number": "1"}, {"order_number": "2"}])])++ rows = _rows(_source("Orders", _make_manager()))++ assert [r["order_number"] for r in rows] == ["1", "2"]+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_metadata_full_page_continues(self, MockSession) -> None:+ session = MockSession.return_value+ full_page = [{"order_number": str(i)} for i in range(PER_PAGE)]+ _wire(session, [_response("orders", full_page), _response("orders", [{"order_number": "last"}])])++ rows = _rows(_source("Orders", _make_manager()))++ assert len(rows) == PER_PAGE + 1+ assert session.send.call_count == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_required_headers_are_sent(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response("orders", [{"order_number": "1"}], total_pages=1)])++ _rows(_source("Orders", _make_manager(), api_version="3.0"))++ assert session.headers["Accept"] == "application/hal+json"+ assert session.headers["Content-Type"] == "application/hal+json"+ assert session.headers["Accept-Version"] == "3.0"+++class TestReverbSourceListings:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_ignores_incremental_flag(self, MockSession) -> None:+ # Listings has no documented date-window filter, so it must stay full refresh even+ # when the caller asks for incremental sync.+ session = MockSession.return_value+ snapshots = _wire(session, [_response("listings", [{"id": 1}], total_pages=1)])++ response = _source(+ "Listings",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ _rows(response)++ assert "updated_start_date" not in snapshots[0]["params"]+ assert response.primary_keys == ["id"]+++class TestReverbSourcePayouts:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_derives_id_from_line_items_href(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ "payouts",+ [+ {+ "total": {"amount": "11.88"},+ "_links": {"line_items": {"href": "https://api.reverb.com/api/my/payouts/54/line_items"}},+ }+ ],+ total_pages=1,+ )+ ],+ )++ rows = _rows(_source("Payouts", _make_manager()))++ assert rows[0]["id"] == 54++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_window_uses_created_date_params(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response("payouts", [], total_pages=1)])++ _rows(+ _source(+ "Payouts",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ )++ assert snapshots[0]["params"]["created_start_date"] == "2026-03-04T00:00:00Z"+ assert "created_end_date" in snapshots[0]["params"]+++class TestValidateCredentials:+ @mock.patch(REVERB_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert validate_credentials("token", "3.0") == (True, 200)++ @mock.patch(REVERB_SESSION_PATCH)+ def test_unauthorized(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ assert validate_credentials("token", "3.0") == (False, 401)++ @mock.patch(REVERB_SESSION_PATCH)+ def test_swallows_transport_errors(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("token", "3.0") == (False, None)++ @mock.patch(REVERB_SESSION_PATCH)+ def test_probes_my_account_with_required_headers(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("token", "3.0")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.reverb.com/api/my/account"+ headers = call.kwargs["headers"]+ assert headers["Authorization"] == "Bearer token"+ assert headers["Accept-Version"] == "3.0"++[email protected]("status_code", [200, 401, 403, 500])+def test_validate_credentials_maps_status_codes(status_code) -> None:+ with mock.patch(REVERB_SESSION_PATCH) as mock_session:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ ok, code = validate_credentials("token", "3.0")+ assert ok is (status_code == 200)+ assert code == status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/tests/test_reverb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/tests/test_reverb_source.pynew file mode 100644index 000000000000..8cc22842ce74--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reverb/tests/test_reverb_source.py@@ -0,0 +1,161 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.reverb import ReverbSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.reverb import ReverbResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.reverb.source import ReverbSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"Orders", "Payouts"}+_FULL_REFRESH_ENDPOINTS = {"Listings"}+++class TestReverbSource:+ def setup_method(self):+ self.source = ReverbSource()+ self.team_id = 123+ self.config = ReverbSourceConfig(api_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.REVERB++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Reverb"+ assert config.category == DataWarehouseSourceCategory.E_COMMERCE+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/reverb.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/reverb"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_token"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_supported_api_version_is_declared_and_not_deprecated(self):+ assert self.source.default_version in self.source.supported_versions+ assert self.source.get_version_deprecation(self.source.default_version) is None++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.reverb.com/api/my/orders/selling/all",+ "403 Client Error: Forbidden for url: https://api.reverb.com/api/my/payouts",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.reverb.com/api/my/orders/selling/all",+ "500 Server Error: Internal Server Error for url: https://api.reverb.com/api/my/listings",+ "HTTPSConnectionPool(host='api.reverb.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Orders"])+ assert len(schemas) == 1+ assert schemas[0].name == "Orders"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Reverb personal access token"),+ ((False, 403), False, "Could not connect to Reverb with the provided personal access token"),+ ((False, None), False, "Could not connect to Reverb with the provided personal access token"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.reverb.source.validate_reverb_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("token", "3.0")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is ReverbResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.reverb.source.reverb_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_reverb_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Orders"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_reverb_source.assert_called_once()+ kwargs = mock_reverb_source.call_args.kwargs+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == "Orders"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["api_version"] == "3.0"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.reverb.source.reverb_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_reverb_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Listings"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.api_version = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_reverb_source.call_args.kwargs["db_incremental_field_last_value"] is None