: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 mercury import source (#72617)
Tom Owersa9d0449e142c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0d017af93790..94ed03b4d693 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -347,6 +347,7 @@ the row lists both.| matomo | HTTP | requests | ✅ || maxio | HTTP | requests + `rest_source.RESTClient` | ✅ || mention | HTTP | requests | ✅ |+| mercury | HTTP | requests + `rest_source.RESTClient` | ✅ || meta_ads | HTTP | requests | ✅ || metabase | HTTP | requests | ✅ || metaplane | HTTP | requests | ✅ |@@ -815,7 +816,6 @@ doesn't conflict with concurrent PRs.- marketo- mendeley- mercado_ads-- mercury- merge- metricool- metriportdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mercury.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mercury.pyindex d2d5ff04e922..da4c73095682 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mercury.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/mercury.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass MercurySourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.pynew file mode 100644index 000000000000..c348731f74e7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.py@@ -0,0 +1,192 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Accounts": {+ "description": "A bank account (checking or savings) in your Mercury organization, including balances and routing details.",+ "docs_url": "https://docs.mercury.com/reference/getaccounts",+ "columns": {+ "id": "Unique identifier for the Mercury account.",+ "accountNumber": "Bank account number for the account.",+ "routingNumber": "Bank routing number for the account.",+ "availableBalance": "Balance available for spending, in dollars.",+ "currentBalance": "Current ledger balance, in dollars.",+ "canReceiveTransactions": "Whether the account can receive incoming transactions.",+ "createdAt": "When the account was created.",+ "kind": "The kind of account, such as checking or savings.",+ "legalBusinessName": "Legal business name associated with the account.",+ "name": "Name of the account.",+ "nickname": "User-assigned nickname for the account.",+ "status": "Current status of the account.",+ "type": "The account type, such as mercury.",+ "dashboardLink": "Link to view the account in the Mercury dashboard.",+ },+ },+ "Cards": {+ "description": "A debit or credit card issued in your Mercury organization, with spend controls and lifecycle state.",+ "docs_url": "https://docs.mercury.com/reference/listcards",+ "columns": {+ "id": "Unique identifier for the card.",+ "accountId": "The Mercury account this card is associated with.",+ "userId": "Mercury user who owns the card.",+ "createdAt": "Timestamp when the card was issued.",+ "updatedAt": "Timestamp of the last modification to the card or its settings.",+ "expiration": "Month and year the card expires.",+ "kind": "Whether the card is a debit or credit card.",+ "type": "Whether the card is virtual (digital-only) or physical.",+ "lastFour": "Last four digits of the card's primary account number.",+ "nameOnCard": "Cardholder name printed on the card.",+ "nickname": "Optional user-assigned label for the card.",+ "physicalCardStatus": "Activation state of a physical card. Null for virtual cards.",+ "spendLimit": "Spending controls applied to this card.",+ "status": "Current lifecycle state of the card.",+ "merchantLock": "Merchant lock applied to this card, when the card is locked to a single merchant.",+ "categoryLocks": "Mercury spend-category locks applied to this card.",+ },+ },+ "Categories": {+ "description": "A custom expense category used to classify transactions in your Mercury organization.",+ "docs_url": "https://docs.mercury.com/reference/listcategories",+ "columns": {+ "id": "The ID of the category.",+ "name": "The name of the category.",+ "visibleForCardSpend": "Whether this category is applicable to card transactions.",+ "visibleForOther": "Whether this category is applicable to all other transaction kinds.",+ "visibleForReimbursements": "Whether this category is applicable to expense reimbursement transactions.",+ },+ },+ "CreditAccounts": {+ "description": "A credit account in your Mercury organization, including balances and status.",+ "docs_url": "https://docs.mercury.com/reference/listcredit",+ "columns": {+ "id": "Unique identifier for the credit account.",+ "availableBalance": "Balance available for spending, in dollars.",+ "currentBalance": "Current ledger balance, in dollars.",+ "createdAt": "When the credit account was created.",+ "status": "Current status of the credit account.",+ },+ },+ "Customers": {+ "description": "An accounts-receivable customer that invoices can be sent to.",+ "docs_url": "https://docs.mercury.com/reference/listcustomers",+ "columns": {+ "id": "Unique identifier for the customer.",+ "name": "Name of the customer.",+ "email": "Email of the customer.",+ "address": "Address of the customer.",+ "deletedAt": "The time the customer was deleted, if it was deleted.",+ },+ },+ "Events": {+ "description": "An audit event capturing a change to a Mercury resource, with before and after values as a JSON merge patch.",+ "docs_url": "https://docs.mercury.com/reference/getevents",+ "columns": {+ "id": "Unique identifier for this event.",+ "resourceId": "The ID of the resource that was affected.",+ "resourceType": "The type of resource that was affected, such as transaction or account.",+ "resourceVersion": "Version number of the resource after this change.",+ "operationType": "The type of operation performed, such as create, update, or delete.",+ "occurredAt": "Timestamp when the event occurred.",+ "changedPaths": "List of JSON paths that were modified in this event.",+ "mergePatch": "JSON object containing the fields that were changed and their new values.",+ "previousValues": "JSON object containing the changed fields' previous values before the update.",+ },+ },+ "Invoices": {+ "description": "An accounts-receivable invoice issued by your Mercury organization.",+ "docs_url": "https://docs.mercury.com/reference/listinvoices",+ "columns": {+ "id": "The ID of the invoice.",+ "customerId": "ID of the customer the invoice was sent to.",+ "destinationAccountId": "The Mercury account where invoice payments will be deposited.",+ "amount": "The total amount of the invoice line items plus taxes.",+ "currencyCode": "ISO 4217 currency code for the invoice.",+ "status": "The status of the invoice.",+ "invoiceNumber": "The payer-facing invoice number.",+ "invoiceDate": "The date of the invoice, set by the invoice creator.",+ "dueDate": "The due date the invoice should be paid by.",+ "createdAt": "The timestamp when the invoice was created.",+ "updatedAt": "The timestamp when the invoice was updated.",+ "canceledAt": "The time when the invoice was canceled.",+ "achDebitEnabled": "Whether the invoice can be paid via ACH debit.",+ "creditCardEnabled": "Whether the invoice can be paid via credit card.",+ "internalNote": "Internal note for the invoice, not visible to payers.",+ "payerMemo": "Memo for the payer of the invoice.",+ "poNumber": "Purchase order number for the invoice, if applicable.",+ "slug": "Unique identifier used to build public payment URLs for this invoice.",+ },+ },+ "Recipients": {+ "description": "A payment recipient saved in your Mercury organization, with routing and payment method details.",+ "docs_url": "https://docs.mercury.com/reference/getrecipients",+ "columns": {+ "id": "Unique identifier for the recipient.",+ "name": "Name of the recipient.",+ "nickname": "User-assigned nickname for the recipient.",+ "status": "Current status of the recipient.",+ "emails": "Email addresses associated with the recipient.",+ "contactEmail": "Contact email for the recipient.",+ "dateLastPaid": "When the recipient was last paid.",+ "defaultPaymentMethod": "Default payment method used to pay the recipient.",+ "isBusiness": "Whether the recipient is a business.",+ "electronicRoutingInfo": "ACH routing details for the recipient.",+ "domesticWireRoutingInfo": "Domestic wire routing details for the recipient.",+ "internationalWireRoutingInfo": "International wire routing details for the recipient.",+ },+ },+ "Transactions": {+ "description": "A money movement on any account in your Mercury organization, across all payment rails.",+ "docs_url": "https://docs.mercury.com/reference/listtransactions",+ "columns": {+ "id": "Unique identifier for the transaction.",+ "accountId": "The Mercury account that owns this transaction.",+ "amount": "Amount of the transaction in dollars; negative for money leaving the account.",+ "status": "Current status of the transaction, such as pending, sent, or failed.",+ "kind": "The kind of transaction, such as externalTransfer or internalTransfer.",+ "createdAt": "When the transaction was created.",+ "postedAt": "When the transaction posted to the account. Null while pending.",+ "failedAt": "When the transaction failed, if it failed.",+ "estimatedDeliveryDate": "Estimated date the transaction will be delivered.",+ "counterpartyId": "ID of the counterparty.",+ "counterpartyName": "Name of the counterparty.",+ "counterpartyNickname": "Nickname of the counterparty.",+ "bankDescription": "Bank-provided description of the transaction.",+ "externalMemo": "Externally visible memo for the transaction.",+ "note": "Internal note attached to the transaction.",+ "categoryData": "Expense category assigned to the transaction.",+ "mercuryCategory": "Mercury's automatic category for the transaction.",+ "merchant": "Merchant information for card transactions, including the merchant category code.",+ "checkNumber": "Present for check deposits and mailed checks.",+ "trackingNumber": "Tracking number for transactions that have one, such as RTP, ACH, or wires.",+ "reasonForFailure": "Reason the transaction failed, if it failed.",+ "requestId": "ID of the send-money request that created this transaction, if any.",+ "creditAccountPeriodId": "ID of the credit statement period.",+ "glAllocations": "General ledger code allocations assigned via a connected accounting integration.",+ "dashboardLink": "Link to view the transaction in the Mercury dashboard.",+ },+ },+ "TreasuryAccounts": {+ "description": "A treasury account in your Mercury organization, including balances and net returns.",+ "docs_url": "https://docs.mercury.com/reference/gettreasury",+ "columns": {+ "id": "Unique identifier for the treasury account.",+ "availableBalance": "Balance available for withdrawal, in dollars.",+ "currentBalance": "Current balance, in dollars.",+ "createdAt": "When the treasury account was created.",+ "status": "Current status of the treasury account.",+ "netReturns": "Monthly net return breakdown with dividend and fee details.",+ },+ },+ "Users": {+ "description": "A user in your Mercury organization.",+ "docs_url": "https://docs.mercury.com/reference/getusers",+ "columns": {+ "userId": "Unique identifier for the user.",+ "email": "User's email address.",+ "firstName": "User's first name.",+ "lastName": "User's last name.",+ "organizationRole": "User's role within the organization.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.pynew file mode 100644index 000000000000..5a3a5014ff28--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.py@@ -0,0 +1,145 @@+import dataclasses+from datetime import 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 (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.settings import (+ DEFAULT_PAGE_SIZE,+ MERCURY_BASE_URL,+ MERCURY_ENDPOINTS,+)+++class MercuryResumeConfig:+ # `page.nextPage` cursor from the last fully-yielded page, replayed as `start_after`.+ cursor: str+++def format_incremental_value(value: Any) -> str | None:+ """Format the incremental watermark as ISO 8601, which Mercury's date filters accept."""+ if value is None:+ return None+ if isinstance(value, datetime | date):+ return value.isoformat()+ return str(value)+++def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+ config = MERCURY_ENDPOINTS[name]++ params: dict[str, Any] = {}+ if config.paginated:+ params["limit"] = DEFAULT_PAGE_SIZE+ # Explicit ascending order so cursor pages arrive oldest-first and the incremental+ # watermark only ever advances.+ params["order"] = "asc"++ if should_use_incremental_field and config.incremental_param is not None:+ params[config.incremental_param] = {+ "type": "incremental",+ "cursor_path": "createdAt",+ "initial_value": None,+ "convert": format_incremental_value,+ }++ endpoint: Endpoint = {+ "path": config.path,+ "data_selector": config.data_selector,+ "params": params,+ "paginator": JSONResponseCursorPaginator(cursor_path="page.nextPage", cursor_param="start_after")+ if config.paginated+ else SinglePagePaginator(),+ }++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.name.lower(),+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }++ if config.timestamp_columns:+ resource["columns"] = {column: {"data_type": "timestamp"} for column in config.timestamp_columns}++ return resource+++def mercury_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[MercuryResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> Resource:+ config: RESTAPIConfig = {+ "client": {+ "base_url": MERCURY_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "headers": {+ "Accept": "application/json",+ },+ },+ "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_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.cursor}++ 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("cursor"):+ resumable_source_manager.save_state(MercuryResumeConfig(cursor=str(state["cursor"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def check_credentials(api_key: str) -> int:+ """Probe the cheapest authenticated endpoint and return the HTTP status code."""+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{MERCURY_BASE_URL}/accounts",+ headers={+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ },+ params={"limit": 1},+ timeout=30,+ )+ return response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.pynew file mode 100644index 000000000000..f1577180de60--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.py@@ -0,0 +1,115 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++MERCURY_BASE_URL = "https://api.mercury.com/api/v1"++# Mercury allows limit between 1 and 1000 (default 1000). Kept below the max so a page of+# wide transaction rows stays comfortably sized.+DEFAULT_PAGE_SIZE = 500++# Pending transactions change status/postedAt for a while after creation, and incremental+# sync cursors on the stable createdAt field. Re-read a trailing window each run so those+# late mutations get merged in.+TRANSACTIONS_LOOKBACK_SECONDS = 30 * 24 * 60 * 60+++@dataclass(frozen=True)+class MercuryEndpointConfig:+ name: str+ path: str+ data_selector: str+ primary_key: str = "id"+ # Stable datetime field used for Delta partitioning; None disables partitioning.+ partition_key: str | None = None+ # Cursor-paginated endpoints accept limit/order/start_after; /credit returns one page.+ paginated: bool = True+ # ISO 8601 string columns parsed into timestamps by the rest_source type conversion.+ timestamp_columns: tuple[str, ...] = ()+ # Server-side query param mapped from the user's incremental field, when the API has one.+ incremental_param: str | None = None+++MERCURY_ENDPOINTS: dict[str, MercuryEndpointConfig] = {+ "Accounts": MercuryEndpointConfig(+ name="Accounts",+ path="/accounts",+ data_selector="accounts",+ partition_key="createdAt",+ timestamp_columns=("createdAt",),+ ),+ "Cards": MercuryEndpointConfig(+ name="Cards",+ path="/cards",+ data_selector="cards",+ partition_key="createdAt",+ timestamp_columns=("createdAt", "updatedAt"),+ ),+ "Categories": MercuryEndpointConfig(+ name="Categories",+ path="/categories",+ data_selector="categories",+ ),+ "CreditAccounts": MercuryEndpointConfig(+ name="CreditAccounts",+ path="/credit",+ data_selector="accounts",+ paginated=False,+ timestamp_columns=("createdAt",),+ ),+ "Customers": MercuryEndpointConfig(+ name="Customers",+ path="/ar/customers",+ data_selector="customers",+ timestamp_columns=("deletedAt",),+ ),+ "Events": MercuryEndpointConfig(+ name="Events",+ path="/events",+ data_selector="events",+ partition_key="occurredAt",+ timestamp_columns=("occurredAt",),+ ),+ "Invoices": MercuryEndpointConfig(+ name="Invoices",+ path="/ar/invoices",+ data_selector="invoices",+ partition_key="createdAt",+ timestamp_columns=("createdAt", "updatedAt", "canceledAt"),+ ),+ "Recipients": MercuryEndpointConfig(+ name="Recipients",+ path="/recipients",+ data_selector="recipients",+ ),+ "Transactions": MercuryEndpointConfig(+ name="Transactions",+ path="/transactions",+ data_selector="transactions",+ partition_key="createdAt",+ timestamp_columns=("createdAt", "postedAt", "failedAt"),+ # `start` filters on the earliest createdAt to include, per the Mercury API docs.+ incremental_param="start",+ ),+ "TreasuryAccounts": MercuryEndpointConfig(+ name="TreasuryAccounts",+ path="/treasury",+ data_selector="accounts",+ timestamp_columns=("createdAt",),+ ),+ "Users": MercuryEndpointConfig(+ name="Users",+ path="/users",+ data_selector="users",+ primary_key="userId",+ ),+}++ENDPOINTS = tuple(MERCURY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ # Only /transactions exposes a server-side timestamp filter (`start`/`end` on createdAt).+ # The other endpoints are small dimension lists synced with full refresh.+ "Transactions": [incremental_field("createdAt")],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.pyindex 46f3a70f7e2f..03c14c77bf94 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py@@ -1,32 +1,169 @@-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.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 (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mercury import (MercurySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.mercury import (+ MercuryResumeConfig,+ check_credentials,+ mercury_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MERCURY_ENDPOINTS,+ TRANSACTIONS_LOOKBACK_SECONDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MercurySource(SimpleSource[MercurySourceConfig]):+class MercurySource(ResumableSource[MercurySourceConfig, MercuryResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://docs.mercury.com/reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MERCURY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.mercury.com": "Your Mercury API token is invalid or has been revoked. Please generate a new token in Mercury under Settings > API tokens and reconnect.",+ "403 Client Error: Forbidden for url: https://api.mercury.com": "Your Mercury API token does not have permission to read this data. Please use a token with Read Only access or grant the missing scope.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: MercurySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ for schema in schemas:+ if schema.name == "Transactions":+ # Pending transactions mutate (status, postedAt) after creation; re-read a+ # trailing window so those updates get merged despite the createdAt cursor.+ schema.default_incremental_lookback_seconds = TRANSACTIONS_LOOKBACK_SECONDS+ return schemas++ def validate_credentials(+ self, config: MercurySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ status = check_credentials(config.api_key)+ except Exception as e:+ return False, str(e)++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Mercury API token. Generate a token in Mercury under Settings > API tokens."+ if status == 403:+ # A custom-scoped token can be valid without access to /accounts. Accept it at+ # source-create; per-endpoint scope problems surface at sync time.+ if schema_name is None:+ return True, None+ return False, f"Your Mercury API token does not have permission to read {schema_name}."+ return False, f"Mercury API returned an unexpected status ({status}). Please try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MercuryResumeConfig]:+ return ResumableSourceManager[MercuryResumeConfig](inputs, MercuryResumeConfig)++ def source_for_pipeline(+ self,+ config: MercurySourceConfig,+ resumable_source_manager: ResumableSourceManager[MercuryResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint_config = MERCURY_ENDPOINTS[inputs.schema_name]+ resource = mercury_source(+ api_key=config.api_key,+ 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,+ )++ if endpoint_config.partition_key is not None:+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=[endpoint_config.primary_key],+ column_hints=resource.column_hints,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint_config.partition_key],+ sort_mode="asc",+ )++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=[endpoint_config.primary_key],+ column_hints=resource.column_hints,+ sort_mode="asc",+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MERCURY,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Mercury",+ caption="Sync your Mercury business banking data, including accounts, transactions, cards, and invoices.\n\nCreate an API token with Read Only access in Mercury under [Settings > API tokens](https://app.mercury.com/settings/tokens). Read Only tokens do not require an IP allowlist.",+ docsUrl="https://posthog.com/docs/cdp/sources/mercury",iconPath="/static/services/mercury.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["banking", "bank"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.pynew file mode 100644index 000000000000..ea432397e154--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.py@@ -0,0 +1,243 @@+import json+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.mercury import (+ MercuryResumeConfig,+ format_incremental_value,+ get_resource,+ mercury_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.settings import (+ ENDPOINTS,+ MERCURY_ENDPOINTS,+)+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (None, None),+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05+00:00"),+ (date(2026, 1, 2), "2026-01-02"),+ ("2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),+ ],+ )+ def test_formats_watermark_for_the_api(self, value: Any, expected: str | None) -> None:+ assert format_incremental_value(value) == expected+++class TestGetResource:+ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_resource_shape_per_endpoint(self, endpoint: str) -> None:+ config = MERCURY_ENDPOINTS[endpoint]+ resource = get_resource(endpoint, should_use_incremental_field=False)++ assert resource["name"] == endpoint+ assert resource["write_disposition"] == "replace"+ assert resource["table_format"] == "delta"++ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ assert endpoint_config["path"] == config.path+ assert endpoint_config["data_selector"] == config.data_selector++ params = endpoint_config["params"]+ if config.paginated:+ assert isinstance(endpoint_config["paginator"], JSONResponseCursorPaginator)+ assert params["limit"] > 0+ assert params["order"] == "asc"+ else:+ assert isinstance(endpoint_config["paginator"], SinglePagePaginator)+ assert "limit" not in params++ def test_incremental_adds_server_side_start_filter(self) -> None:+ resource = get_resource("Transactions", should_use_incremental_field=True)++ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ start_param = endpoint_config["params"]["start"]+ assert start_param["type"] == "incremental"+ assert start_param["cursor_path"] == "createdAt"+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ def test_incremental_disabled_omits_start_filter(self) -> None:+ resource = get_resource("Transactions", should_use_incremental_field=False)++ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ assert "start" not in endpoint_config["params"]++ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if name != "Transactions"])+ def test_full_refresh_endpoints_never_get_incremental_params(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=True)++ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ assert not any(+ isinstance(value, dict) and value.get("type") == "incremental"+ for value in endpoint_config["params"].values()+ )++ def test_timestamp_columns_hinted_for_type_conversion(self) -> None:+ resource = get_resource("Transactions", should_use_incremental_field=False)++ assert resource["columns"] == {+ "createdAt": {"data_type": "timestamp"},+ "postedAt": {"data_type": "timestamp"},+ "failedAt": {"data_type": "timestamp"},+ }+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestMercurySourceResumeBehavior:+ """End-to-end pagination and resume behaviour of ``mercury_source`` via ``rest_api_resource``."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict[str, Any]], list[Any]]:+ """Drive ``mercury_source`` with a mocked HTTP session.++ Returns ``(sent_params, rows)`` where ``sent_params`` are shallow copies of+ ``request.params`` captured at send-time — the Request object is mutated in place+ by the paginator between pages.+ """+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = mercury_source(+ api_key="test-token",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ pages = list(cast(Iterable[Any], resource))+ rows = [row for page in pages for row in page]+ return sent_params, rows++ def test_fresh_run_saves_cursor_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"transactions": [{"id": "t1"}], "page": {"nextPage": "t1"}}),+ _make_http_response({"transactions": [{"id": "t2"}], "page": {"nextPage": "t2"}}),+ _make_http_response({"transactions": [{"id": "t3"}], "page": {"nextPage": None}}),+ ]+ sent_params, rows = self._drive("Transactions", manager, responses)++ assert [p.get("start_after") for p in sent_params] == [None, "t1", "t2"]+ assert [row["id"] for row in rows] == ["t1", "t2", "t3"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ MercuryResumeConfig(cursor="t1"),+ MercuryResumeConfig(cursor="t2"),+ ]++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = MercuryResumeConfig(cursor="t42")++ responses = [+ _make_http_response({"transactions": [{"id": "t43"}], "page": {"nextPage": None}}),+ ]+ sent_params, _ = self._drive("Transactions", manager, responses)++ assert [p.get("start_after") for p in sent_params] == ["t42"]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"transactions": [{"id": "only"}], "page": {"nextPage": None}}),+ ]+ self._drive("Transactions", manager, responses)++ manager.save_state.assert_not_called()++ def test_incremental_sync_sends_iso_start_watermark(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"transactions": [{"id": "t1"}], "page": {"nextPage": None}}),+ ]+ sent_params, _ = self._drive(+ "Transactions",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ )++ assert sent_params[0]["start"] == "2026-01-02T03:04:05+00:00"+ assert sent_params[0]["order"] == "asc"++ def test_first_incremental_sync_without_watermark_omits_start(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"transactions": [{"id": "t1"}], "page": {"nextPage": None}}),+ ]+ sent_params, _ = self._drive(+ "Transactions",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert sent_params[0].get("start") is None++ def test_single_page_endpoint_yields_rows_without_pagination(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"accounts": [{"id": "c1"}, {"id": "c2"}]}),+ ]+ sent_params, rows = self._drive("CreditAccounts", manager, responses)++ assert len(sent_params) == 1+ assert [row["id"] for row in rows] == ["c1", "c2"]+ manager.save_state.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury_source.pynew file mode 100644index 000000000000..ce3299e4d7f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury_source.py@@ -0,0 +1,238 @@+from typing import Optional, cast++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mercury import (+ MercurySourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.mercury import MercuryResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.settings import (+ ENDPOINTS,+ TRANSACTIONS_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.source import MercurySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(+ schema_name: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[str] = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="createdAt" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job-id",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestMercurySource:+ def setup_method(self) -> None:+ self.source = MercurySource()+ self.config = MercurySourceConfig(api_key="test-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.MERCURY++ def test_source_config_is_released_with_alpha_status(self) -> None:+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/mercury"++ def test_source_config_requires_secret_api_key(self) -> None:+ fields = self.source.get_source_config.fields++ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_key"+ assert field.required is True+ assert field.secret is True++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["Accounts", "Transactions"])++ assert {schema.name for schema in schemas} == {"Accounts", "Transactions"}++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_only_transactions_supports_incremental(self, endpoint: str) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=[endpoint])+ schema = schemas[0]++ if endpoint == "Transactions":+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["createdAt"]+ assert schema.default_incremental_lookback_seconds == TRANSACTIONS_LOOKBACK_SECONDS+ else:+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []+ assert schema.default_incremental_lookback_seconds is None++ def test_documented_tables_available_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ tables = self.source.get_documented_tables()++ assert {table["name"] for table in tables} == set(ENDPOINTS)+ transactions = next(table for table in tables if table["name"] == "Transactions")+ assert transactions["description"]++ @pytest.mark.parametrize(+ ("status", "schema_name", "expected_valid"),+ [+ (200, None, True),+ (200, "Transactions", True),+ (401, None, False),+ (401, "Transactions", False),+ # A custom-scoped token can be valid without /accounts access, so 403 passes+ # at source-create but fails the per-schema check.+ (403, None, True),+ (403, "Transactions", False),+ (500, None, False),+ ],+ )+ def test_validate_credentials_status_mapping(+ self, status: int, schema_name: Optional[str], expected_valid: bool+ ) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mercury.source.check_credentials",+ return_value=status,+ ):+ valid, error = self.source.validate_credentials(self.config, team_id=1, schema_name=schema_name)++ assert valid is expected_valid+ if not expected_valid:+ assert error++ def test_validate_credentials_handles_network_error(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mercury.source.check_credentials",+ side_effect=ConnectionError("connection refused"),+ ):+ valid, error = self.source.validate_credentials(self.config, team_id=1)++ assert valid is False+ assert "connection refused" in str(error)++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs("Transactions"))++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MercuryResumeConfig++ @pytest.mark.parametrize(+ ("error_message", "should_match"),+ [+ ("401 Client Error: Unauthorized for url: https://api.mercury.com/api/v1/transactions", True),+ ("403 Client Error: Forbidden for url: https://api.mercury.com/api/v1/accounts", True),+ ("500 Server Error: Internal Server Error for url: https://api.mercury.com/api/v1/accounts", False),+ ],+ )+ def test_non_retryable_errors_match_auth_failures_only(self, error_message: str, should_match: bool) -> None:+ patterns = self.source.get_non_retryable_errors()++ assert any(pattern in error_message for pattern in patterns) is should_match+++class TestMercurySourceForPipeline:+ def setup_method(self) -> None:+ self.source = MercurySource()+ self.config = MercurySourceConfig(api_key="test-token")+ self.manager = MagicMock(spec=ResumableSourceManager)++ def _run(self, inputs: SourceInputs) -> tuple[MagicMock, SourceResponse]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mercury.source.mercury_source"+ ) as mock_source:+ mock_source.return_value.name = inputs.schema_name+ mock_source.return_value.column_hints = None+ response = self.source.source_for_pipeline(self.config, self.manager, inputs)+ return cast(MagicMock, mock_source), response++ def test_plumbs_arguments_to_transport(self) -> None:+ inputs = _make_inputs(+ "Transactions", should_use_incremental_field=True, db_incremental_field_last_value="2026-01-01"+ )+ mock_source, _ = self._run(inputs)++ mock_source.assert_called_once_with(+ api_key="test-token",+ endpoint="Transactions",+ team_id=1,+ job_id="job-id",+ resumable_source_manager=self.manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ )++ def test_drops_incremental_value_when_full_refresh(self) -> None:+ inputs = _make_inputs(+ "Transactions", should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01"+ )+ mock_source, _ = self._run(inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @pytest.mark.parametrize(+ ("endpoint", "expected_primary_key"),+ [+ ("Accounts", "id"),+ ("Transactions", "id"),+ ("Users", "userId"),+ ],+ )+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_primary_key: str) -> None:+ _, response = self._run(_make_inputs(endpoint))++ assert response.primary_keys == [expected_primary_key]++ @pytest.mark.parametrize(+ ("endpoint", "expected_partition_key"),+ [+ ("Transactions", "createdAt"),+ ("Events", "occurredAt"),+ ("Recipients", None),+ ("Users", None),+ ],+ )+ def test_partitioning_uses_stable_datetime_fields(+ self, endpoint: str, expected_partition_key: Optional[str]+ ) -> None:+ _, response = self._run(_make_inputs(endpoint))++ if expected_partition_key is None:+ assert response.partition_keys is None+ assert response.partition_mode is None+ else:+ assert response.partition_keys == [expected_partition_key]+ assert response.partition_mode == "datetime"++ def test_sort_mode_is_ascending(self) -> None:+ _, response = self._run(_make_inputs("Transactions"))++ assert response.sort_mode == "asc"