Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement hightouch import source (#72631)

Tom Owers2412e33c343d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 9d114661db94..64fbcc516f39 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -268,6 +268,7 @@ the row lists both.
| hetzner | HTTP | requests | ✅ |
| hex | HTTP | requests + `rest_source.RESTClient` | ✅ |
| hibob | HTTP | requests | ✅ |
+| hightouch | HTTP | requests + `rest_source.RESTClient` | ✅ |
| honeybadger | HTTP | requests | ✅ |
| honeycomb | HTTP | requests | ✅ |
| hoorayhr | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -778,7 +779,6 @@ doesn't conflict with concurrent PRs.
- heygen
- hibob
- high_level
-- hightouch
- honeybadger
- honeycomb
- hubplanner
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
index 890643cfc998..121c3bd4c7ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py
@@ -64,6 +64,8 @@ def build_dependent_resource(
child_endpoint_extra: Endpoint | None = None,
child_params_extra: dict[str, Any] | None = None,
page_size_param: str | None = "limit",
+ resume_hook: Callable[[dict[str, Any] | None], None] | None = None,
+ initial_paginator_state: dict[str, Any] | None = None,
) -> Iterable[Any]:
parent_config = endpoint_configs[fanout.parent_name]
child_config = endpoint_configs[child_endpoint]
@@ -146,6 +148,13 @@ def build_dependent_resource(
"resources": [parent_resource, child_resource],
}
- resources = rest_api_resources(config, team_id, job_id, db_incremental_field_last_value)
+ resources = rest_api_resources(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_paginator_state,
+ )
child_dlt_resource = next(r for r in resources if getattr(r, "name", None) == child_endpoint)
return child_dlt_resource.add_map(rename_parent_fields(fanout.parent_name, fanout.parent_field_renames))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py
index 39da52c689fa..fc6632251143 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py
@@ -145,6 +145,37 @@ def test_build_dependent_resource_backwards_compatible_defaults(mock_rest_api_re
assert "data_selector" not in child_resource["endpoint"]
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
+def test_build_dependent_resource_threads_resume_state(mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = []
+ resume_hook = Mock()
+ initial_state = {"completed": ["/parents/a/children"], "current": None, "child_state": None}
+ try:
+ build_dependent_resource(
+ endpoint_configs=_build_endpoint_configs(),
+ child_endpoint="children",
+ fanout=DependentEndpointConfig(
+ parent_name="parents",
+ resolve_param="parent_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ ),
+ client_config={"base_url": "https://example.com"},
+ path_format_values={},
+ team_id=1,
+ job_id="job-1",
+ db_incremental_field_last_value=None,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_state,
+ )
+ except StopIteration:
+ pass
+
+ kwargs = mock_rest_api_resources.call_args.kwargs
+ assert kwargs["resume_hook"] is resume_hook
+ assert kwargs["initial_paginator_state"] == initial_state
+
+
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
def test_build_dependent_resource_rejects_params_in_endpoint_extras(mock_rest_api_resources) -> None:
mock_rest_api_resources.return_value = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hightouch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hightouch.py
index 03ce690241df..f89253c2d512 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hightouch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hightouch.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class HightouchSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/canonical_descriptions.py
new file mode 100644
index 000000000000..524c37d1d32d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/canonical_descriptions.py
@@ -0,0 +1,93 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "syncs": {
+ "description": "Syncs define how data from models is mapped to destinations. Each time a sync runs, Hightouch calculates the rows that changed since the last run and syncs them to the destination.",
+ "docs_url": "https://hightouch.com/docs/api-reference",
+ "columns": {
+ "id": "The sync's id.",
+ "slug": "The sync's slug.",
+ "workspaceId": "The id of the workspace that the sync belongs to.",
+ "createdAt": "The timestamp when the sync was created.",
+ "updatedAt": "The timestamp when the sync was last updated.",
+ "destinationId": "The id of the destination that the sync is connected to.",
+ "modelId": "The id of the model that the sync is connected to.",
+ "schedule": "The scheduling configuration: interval, cron expression, visual cron, or dbt Cloud job.",
+ "status": "The sync's status (e.g. disabled, pending, cancelled, failed, queued, success, warning, querying, processing, reporting, interrupted).",
+ "disabled": "Whether the sync has been disabled by the user.",
+ "lastRunAt": "The timestamp of the last sync run.",
+ "primaryKey": "The primary key the sync uses to identify data from the source.",
+ "referencedColumns": "The reference columns that the sync depends on to sync data from the source.",
+ },
+ },
+ "sync_runs": {
+ "description": "One row per execution of a sync: its status, row counts, and timing. Runs are fetched per sync and carry the parent sync id in `sync_id`.",
+ "docs_url": "https://hightouch.com/docs/api-reference",
+ "columns": {
+ "id": "The sync run's id, unique within its sync.",
+ "sync_id": "The id of the sync this run belongs to (from the parent sync).",
+ "status": "The status of the sync run (e.g. queued, querying, processing, reporting, success, failed, cancelled, warning, interrupted).",
+ "createdAt": "The timestamp when the sync run was created. Usually equal to startedAt, but earlier if the run was queued behind another run.",
+ "startedAt": "The timestamp when the sync run started.",
+ "finishedAt": "The timestamp when the sync run finished.",
+ "plannedRows": "The number of rows (added/changed/removed) that this run was supposed to execute.",
+ "successfulRows": "The number of rows (added/changed/removed) successfully processed by the destination.",
+ "failedRows": "The number of rows (added/changed/removed) that were attempted but rejected by the destination.",
+ "querySize": "The number of rows in the query.",
+ "completionRatio": "The completion ratio of the sync run, showing its progress.",
+ "error": "Error message if the sync run didn't finish successfully.",
+ },
+ },
+ "models": {
+ "description": "Models define the data to pull from a source, via raw SQL, a table reference, a dbt model, or a visual (audience) query.",
+ "docs_url": "https://hightouch.com/docs/api-reference",
+ "columns": {
+ "id": "The id of the model.",
+ "name": "The name of the model.",
+ "slug": "The slug of the model.",
+ "workspaceId": "The id of the workspace the model belongs to.",
+ "createdAt": "The timestamp when the model was created.",
+ "updatedAt": "The timestamp when the model was last updated.",
+ "sourceId": "The id of the source the model is connected to.",
+ "queryType": "The type of the query: custom, raw_sql, table, dbt, or visual.",
+ "primaryKey": "The model's primary key. Null if the query isn't directly synced (e.g. a relationship table for visual querying).",
+ "isSchema": "Whether the model is only used to build other models (as part of visual querying, or as the root of a visual query).",
+ "raw": "The raw SQL query, for raw_sql models.",
+ "table": "The table reference, for table-based models.",
+ "dbt": "The dbt model reference, for dbt-based models.",
+ "visual": "The visual (audience) query definition.",
+ "custom": "Custom query for sources that don't support SQL (e.g. Airtable).",
+ "syncs": "The ids of syncs that use this model.",
+ "tags": "The tags of the model.",
+ },
+ },
+ "sources": {
+ "description": "Sources are the databases and warehouses Hightouch reads data from (e.g. Snowflake, BigQuery, Postgres).",
+ "docs_url": "https://hightouch.com/docs/api-reference",
+ "columns": {
+ "id": "The source's id.",
+ "name": "The source's name.",
+ "slug": "The source's slug.",
+ "type": "The source's type (e.g. snowflake or postgres).",
+ "workspaceId": "The id of the workspace that the source belongs to.",
+ "createdAt": "The timestamp when the source was created.",
+ "updatedAt": "The timestamp when the source was last updated.",
+ },
+ },
+ "destinations": {
+ "description": "Destinations are the SaaS tools and services Hightouch syncs data into (e.g. Salesforce, HubSpot, Google Ads).",
+ "docs_url": "https://hightouch.com/docs/api-reference",
+ "columns": {
+ "id": "The destination's id.",
+ "name": "The destination's name.",
+ "slug": "The destination's slug.",
+ "type": "The destination's type (e.g. salesforce or hubspot).",
+ "workspaceId": "The id of the workspace that the destination belongs to.",
+ "createdAt": "The timestamp when the destination was created.",
+ "updatedAt": "The timestamp when the destination was last updated.",
+ "syncs": "The ids of syncs that sync to this destination.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/hightouch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/hightouch.py
new file mode 100644
index 000000000000..0e4ce15313d4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/hightouch.py
@@ -0,0 +1,245 @@
+import dataclasses
+from collections.abc import Callable, Iterable
+from typing import Any, Optional, cast
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+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.hightouch.settings import (
+ HIGHTOUCH_BASE_URL,
+ HIGHTOUCH_ENDPOINTS,
+ HightouchEndpointConfig,
+)
+
+
+class HightouchResumeConfig:
+ # Opaque framework checkpoint (offset state for top-level endpoints, per-parent fan-out
+ # state for sync_runs), round-tripped into `initial_paginator_state` on resume.
+ paginator_state: dict[str, Any]
+
+
+class HightouchPaginator(OffsetPaginator):
+ """Limit/offset paginator that also honors Hightouch's `hasMore` response flag.
+
+ Every Hightouch list response is `{"data": [...], "hasMore": bool}`, so a full page
+ with `hasMore: false` stops immediately instead of paying one extra empty-page request.
+ The inherited empty/short-page checks still terminate if `hasMore` is ever absent.
+ """
+
+ def __init__(self, limit: int) -> None:
+ super().__init__(limit=limit, total_path=None)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if not self._has_next_page:
+ return
+ try:
+ res = response.json()
+ except Exception:
+ return
+ if isinstance(res, dict) and res.get("hasMore") is False:
+ self._has_next_page = False
+
+
+def _format_hightouch_datetime(value: Any) -> str:
+ """Format the incremental watermark for Hightouch's ISO `after` filter.
+
+ Truncates to whole seconds, which rounds the lower bound *down* — so a sync re-fetches
+ at most a few boundary rows (the merge dedupes them) rather than skipping any run whose
+ startedAt equals the watermark.
+ """
+ normalized_value = coerce_datetime_to_utc(value)
+ if normalized_value is None:
+ return str(value)
+ return normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _hightouch_incremental_window(cursor_path: str) -> IncrementalConfig:
+ # `after` is a server-side filter on startedAt that persists across offset pages, so
+ # pagination is bounded by the filtered set and terminates at the watermark.
+ return {
+ "cursor_path": cursor_path,
+ "start_param": "after",
+ "initial_value": "1970-01-01T00:00:00Z",
+ "convert": _format_hightouch_datetime,
+ }
+
+
+def _drop_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:
+ for field in fields:
+ row.pop(field, None)
+ return row
+
+ return _mapper
+
+
+def _auth_headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": HIGHTOUCH_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "headers": {"Accept": "application/json"},
+ # `capture=False`: sync/source/destination responses carry `configuration` objects with
+ # third-party credentials the name-based sample scrubbers can't recognise, so keep the
+ # raw bodies out of HTTP sample capture (still metered and logged).
+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),
+ }
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # `capture=False` for the same reason as in `_client_config`: the probe response can carry
+ # credential-bearing sync `configuration` objects.
+ res = make_tracked_session(capture=False, redact_values=(api_key,)).get(
+ f"{HIGHTOUCH_BASE_URL}/syncs",
+ headers=_auth_headers(api_key),
+ params={"limit": 1},
+ timeout=10,
+ )
+ if res.status_code == 200:
+ return True, None
+ if res.status_code == 401:
+ return False, "Invalid Hightouch API key"
+ if res.status_code == 403:
+ return False, "Hightouch API key is missing the required permissions"
+ return False, f"Hightouch API returned an unexpected status: {res.status_code}"
+
+
+def get_resource(endpoint: str) -> EndpointResource:
+ config = HIGHTOUCH_ENDPOINTS[endpoint]
+ if config.fanout:
+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ # `orderBy=id` pins a strictly monotonic, unique sort so offset pages don't skip or
+ # duplicate rows if the API's implicit ordering shifts as rows are inserted mid-walk.
+ "params": {"orderBy": "id"},
+ "data_selector": "data",
+ "paginator": HightouchPaginator(limit=config.page_size),
+ }
+
+ resource: EndpointResource = {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+ if config.strip_fields:
+ resource["data_map"] = _drop_fields(config.strip_fields)
+ return resource
+
+
+def _make_source_response(endpoint_config: HightouchEndpointConfig, items_fn: Any) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=items_fn,
+ primary_keys=endpoint_config.primary_key
+ if isinstance(endpoint_config.primary_key, list)
+ else [endpoint_config.primary_key],
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def hightouch_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[HightouchResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = HIGHTOUCH_ENDPOINTS[endpoint]
+
+ 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 = resume_config.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's somewhere to resume to; the Redis TTL handles cleanup.
+ if state:
+ resumable_source_manager.save_state(HightouchResumeConfig(paginator_state=dict(state)))
+
+ if endpoint_config.fanout:
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=HIGHTOUCH_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=endpoint_config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=_hightouch_incremental_window,
+ page_size_param="limit",
+ parent_endpoint_extra={
+ "paginator": HightouchPaginator(
+ limit=HIGHTOUCH_ENDPOINTS[endpoint_config.fanout.parent_name].page_size
+ ),
+ "data_selector": "data",
+ },
+ child_endpoint_extra={
+ "paginator": HightouchPaginator(limit=endpoint_config.page_size),
+ "data_selector": "data",
+ },
+ child_params_extra={"orderBy": "id"},
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ return _make_source_response(endpoint_config, lambda: dependent_resource)
+
+ config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {"write_disposition": "replace"},
+ "resources": [get_resource(endpoint=endpoint)],
+ }
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return _make_source_response(endpoint_config, lambda: resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/settings.py
new file mode 100644
index 000000000000..6278fcf5f931
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/settings.py
@@ -0,0 +1,104 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+HIGHTOUCH_BASE_URL = "https://api.hightouch.com/api/v1"
+
+# Hightouch list endpoints document `limit` with a default of 100; no higher cap is documented.
+PAGE_SIZE = 100
+
+# Sync runs keep mutating after they start (status, finishedAt, row counts), and the `after`
+# filter selects on startedAt — so each incremental sync re-reads a trailing window and the
+# merge refreshes runs that were still in progress when we first saw them.
+SYNC_RUNS_LOOKBACK_SECONDS = 24 * 60 * 60
+
+STARTED_AT_INCREMENTAL: IncrementalField = {
+ "label": "startedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "startedAt",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+
+@dataclass
+class HightouchEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ partition_key: str | None = None
+ page_size: int = PAGE_SIZE
+ sort_mode: Literal["asc", "desc"] = "asc"
+ primary_key: str | list[str] = "id"
+ fanout: DependentEndpointConfig | None = None
+ # Response fields dropped from every row before it is yielded. Hightouch `configuration`
+ # objects carry connection details (database credentials on sources, hostnames/usernames
+ # and API secrets on destinations, custom auth headers on HTTP-destination syncs), which
+ # must not be copied into warehouse tables any project member can query.
+ strip_fields: tuple[str, ...] = ()
+
+
+HIGHTOUCH_ENDPOINTS: dict[str, HightouchEndpointConfig] = {
+ # Config tables (syncs, models, sources, destinations) have no server-side timestamp
+ # filter — `after`/`before` on /syncs select by last-run time, not updatedAt — so they
+ # stay full refresh. They are small (workspace configuration), so this is cheap.
+ "syncs": HightouchEndpointConfig(
+ name="syncs",
+ path="/syncs",
+ strip_fields=("configuration",),
+ ),
+ "sync_runs": HightouchEndpointConfig(
+ name="sync_runs",
+ path="/syncs/{sync_id}/runs",
+ # `after` is a genuine server-side filter on startedAt, so incremental sync reduces
+ # the pages fetched instead of just changing the write disposition.
+ incremental_fields=[STARTED_AT_INCREMENTAL],
+ default_incremental_field="startedAt",
+ # createdAt is fixed at run creation, so it is a stable partition key (startedAt is
+ # too, but createdAt exists on every run even before it starts).
+ partition_key="createdAt",
+ # The run id is only documented per sync, and this table aggregates runs across every
+ # sync, so the parent sync id is part of the key to keep it unique table-wide.
+ primary_key=["sync_id", "id"],
+ # Fan-out interleaves parents, so rows are never globally ascending by startedAt even
+ # if each sync's runs were: desc mode makes the pipeline persist the incremental
+ # watermark only when a sync completes, so a partial run can't advance the watermark
+ # past runs of syncs it never reached.
+ sort_mode="desc",
+ fanout=DependentEndpointConfig(
+ parent_name="syncs",
+ resolve_param="sync_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "sync_id"},
+ # `orderBy=id` pins a strictly monotonic, unique sort so offset pages don't skip
+ # or duplicate rows if the API's implicit ordering shifts while rows are inserted
+ # mid-walk (Hightouch documents orderBy fields but not the direction).
+ parent_params={"orderBy": "id"},
+ ),
+ ),
+ "models": HightouchEndpointConfig(
+ name="models",
+ path="/models",
+ ),
+ "sources": HightouchEndpointConfig(
+ name="sources",
+ path="/sources",
+ strip_fields=("configuration",),
+ ),
+ "destinations": HightouchEndpointConfig(
+ name="destinations",
+ path="/destinations",
+ strip_fields=("configuration",),
+ ),
+}
+
+ENDPOINTS = tuple(HIGHTOUCH_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in HIGHTOUCH_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/source.py
index 44724cb809ff..755f40d3319d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/source.py
@@ -1,32 +1,137 @@
-from typing import cast
+from typing import Optional, cast
from 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.hightouch import (
HightouchSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch import (
+ HightouchResumeConfig,
+ hightouch_source,
+ validate_credentials as validate_hightouch_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SYNC_RUNS_LOOKBACK_SECONDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HightouchSource(SimpleSource[HightouchSourceConfig]):
+class HightouchSource(ResumableSource[HightouchSourceConfig, HightouchResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://hightouch.com/docs/api-reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HIGHTOUCH
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Hightouch API key is invalid or was revoked. Create a new key in your Hightouch workspace settings and reconnect.",
+ "403 Client Error": "Your Hightouch API key is missing the required permissions. Check the key in your Hightouch workspace settings and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: HightouchSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # sync_runs is merge-only: runs still in progress mutate (status, finishedAt, row
+ # counts) and the trailing lookback window re-reads them, so append mode would
+ # duplicate rows instead of upserting.
+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=("sync_runs",))
+ for schema in schemas:
+ if schema.name == "sync_runs":
+ schema.default_incremental_lookback_seconds = SYNC_RUNS_LOOKBACK_SECONDS
+ return schemas
+
+ def validate_credentials(
+ self, config: HightouchSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Hightouch API keys are workspace-scoped with no per-resource permissions, so a
+ # single probe validates access to every endpoint.
+ return validate_hightouch_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HightouchResumeConfig]:
+ return ResumableSourceManager[HightouchResumeConfig](inputs, HightouchResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HightouchSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HightouchResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return hightouch_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,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.HIGHTOUCH,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Hightouch",
+ caption="""Enter a Hightouch API key to sync your syncs, sync runs, models, sources, and destinations.
+
+You can create an API key in Hightouch under **Settings → API keys**. Only workspace admins can create API keys, and the key is shown once at creation.
+""",
+ keywords=["reverse etl", "data activation"],
+ docsUrl="https://posthog.com/docs/cdp/sources/hightouch",
iconPath="/static/services/hightouch.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/tests/test_hightouch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/tests/test_hightouch.py
new file mode 100644
index 000000000000..e795342290e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/tests/test_hightouch.py
@@ -0,0 +1,298 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import Mock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch import (
+ HightouchPaginator,
+ HightouchResumeConfig,
+ _format_hightouch_datetime,
+ _hightouch_incremental_window,
+ get_resource,
+ hightouch_source,
+ validate_credentials,
+)
+
+
+class _FakeDltResource:
+ def __init__(self, name: str, rows: list[dict]) -> None:
+ self.name = name
+ self._rows = rows
+
+ def add_map(self, mapper):
+ self._rows = [mapper(dict(row)) for row in self._rows]
+ return self
+
+ def __iter__(self):
+ return iter(self._rows)
+
+
+def _make_manager(resume_state: HightouchResumeConfig | None = None) -> Mock:
+ manager = Mock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+class TestHightouchTransport:
+ @parameterized.expand(
+ [
+ # Full page and the API says there's more — keep paging.
+ ("full_page_has_more", [{"id": i} for i in range(100)], {"hasMore": True}, True),
+ # Full page but hasMore is false — stop without paying an extra empty request.
+ ("full_page_no_more", [{"id": i} for i in range(100)], {"hasMore": False}, False),
+ # hasMore missing entirely — fall back to the inherited full-page heuristic.
+ ("full_page_missing_flag", [{"id": i} for i in range(100)], {}, True),
+ # Short page — stop even if the API claims more (avoids an infinite loop on a
+ # server that always returns hasMore=true).
+ ("short_page", [{"id": 1}], {"hasMore": True}, False),
+ ("empty_page", [], {"hasMore": True}, False),
+ ]
+ )
+ def test_paginator_termination(self, _name, data, body, expected_has_next) -> None:
+ paginator = HightouchPaginator(limit=100)
+ request = Mock()
+ request.params = {}
+ paginator.init_request(request)
+
+ response = Mock()
+ response.json.return_value = {"data": data, **body}
+ paginator.update_state(response, data=data)
+
+ assert paginator.has_next_page is expected_has_next
+
+ def test_paginator_advances_offset(self) -> None:
+ paginator = HightouchPaginator(limit=100)
+ request = Mock()
+ request.params = {"orderBy": "id"}
+ paginator.init_request(request)
+
+ assert request.params["offset"] == 0
+ assert request.params["limit"] == 100
+ assert request.params["orderBy"] == "id"
+
+ response = Mock()
+ response.json.return_value = {"data": [], "hasMore": True}
+ paginator.update_state(response, data=[{"id": i} for i in range(100)])
+ paginator.update_request(request)
+
+ assert request.params["offset"] == 100
+
+ def test_paginator_resume_state_roundtrip(self) -> None:
+ paginator = HightouchPaginator(limit=100)
+ response = Mock()
+ response.json.return_value = {"data": [], "hasMore": True}
+ paginator.update_state(response, data=[{"id": i} for i in range(100)])
+
+ state = paginator.get_resume_state()
+ assert state == {"offset": 100}
+
+ resumed = HightouchPaginator(limit=100)
+ resumed.set_resume_state(cast(dict[str, Any], state))
+ request = Mock()
+ request.params = {}
+ resumed.init_request(request)
+ assert request.params["offset"] == 100
+
+ @parameterized.expand(
+ [
+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01T12:30:45Z"),
+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),
+ ("passthrough_string", "1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),
+ ]
+ )
+ def test_format_hightouch_datetime(self, _name, value, expected) -> None:
+ assert _format_hightouch_datetime(value) == expected
+
+ def test_incremental_window_filters_server_side_via_after(self) -> None:
+ window = _hightouch_incremental_window("startedAt")
+ assert window["start_param"] == "after"
+ assert window["cursor_path"] == "startedAt"
+ assert window["convert"] is _format_hightouch_datetime
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid Hightouch API key"),
+ (403, False, "Hightouch API key is missing the required permissions"),
+ (500, False, "Hightouch API returned an unexpected status: 500"),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, status, expected_valid, expected_message, mock_session) -> None:
+ mock_session.return_value.get.return_value = Mock(status_code=status)
+
+ result = validate_credentials(api_key="key")
+
+ assert result == (expected_valid, expected_message)
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.hightouch.com/api/v1/syncs"
+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"
+
+ def test_get_resource_full_refresh(self) -> None:
+ resource = cast(dict[str, Any], get_resource(endpoint="syncs"))
+ assert resource["name"] == "syncs"
+ assert resource["write_disposition"] == "replace"
+ assert resource["endpoint"]["path"] == "/syncs"
+ assert resource["endpoint"]["data_selector"] == "data"
+ assert resource["endpoint"]["params"]["orderBy"] == "id"
+ assert isinstance(resource["endpoint"]["paginator"], HightouchPaginator)
+ assert resource["table_format"] == "delta"
+
+ def test_get_resource_rejects_sync_runs_fanout(self) -> None:
+ with pytest.raises(ValueError, match="Fan-out endpoint"):
+ get_resource(endpoint="sync_runs")
+
+ @parameterized.expand([("syncs",), ("sources",), ("destinations",)])
+ def test_get_resource_strips_credential_bearing_configuration(self, endpoint) -> None:
+ # `configuration` objects carry third-party credentials (database passwords, API
+ # secrets, custom auth headers) that must not land in queryable warehouse tables.
+ resource = cast(dict[str, Any], get_resource(endpoint=endpoint))
+ row = resource["data_map"]({"id": 1, "slug": "prod", "configuration": {"password": "hunter2"}})
+ assert row == {"id": 1, "slug": "prod"}
+
+ def test_get_resource_models_keeps_all_fields(self) -> None:
+ resource = cast(dict[str, Any], get_resource(endpoint="models"))
+ assert "data_map" not in resource
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch.rest_api_resource")
+ def test_hightouch_source_top_level_response(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ response = hightouch_source(
+ api_key="key",
+ endpoint="models",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ assert response.name == "models"
+ assert response.primary_keys == ["id"]
+ # Config tables are tiny and full refresh, so they are not partitioned.
+ assert response.partition_mode is None
+ assert response.sort_mode == "asc"
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch.rest_api_resource")
+ def test_hightouch_source_resumes_from_saved_state(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = _make_manager(HightouchResumeConfig(paginator_state={"offset": 200}))
+
+ hightouch_source(
+ api_key="key",
+ endpoint="models",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ kwargs = mock_rest_api_resource.call_args.kwargs
+ assert kwargs["initial_paginator_state"] == {"offset": 200}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch.rest_api_resource")
+ def test_hightouch_source_saves_checkpoints_after_batches(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = _make_manager()
+
+ hightouch_source(
+ api_key="key",
+ endpoint="models",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]
+ resume_hook({"offset": 100})
+ manager.save_state.assert_called_once_with(HightouchResumeConfig(paginator_state={"offset": 100}))
+
+ # A terminal (None) checkpoint is not persisted — the Redis TTL handles cleanup.
+ manager.save_state.reset_mock()
+ resume_hook(None)
+ manager.save_state.assert_not_called()
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
+ )
+ def test_sync_runs_fanout_row_format(self, mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [
+ _FakeDltResource("syncs", [{"id": 42}]),
+ _FakeDltResource("sync_runs", [{"id": 7, "status": "success", "_syncs_id": 42}]),
+ ]
+
+ response = hightouch_source(
+ api_key="key",
+ endpoint="sync_runs",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ rows = list(cast(Any, response.items()))
+ assert rows == [{"id": 7, "status": "success", "sync_id": 42}]
+ # Run ids are only documented per sync, so the parent sync id is part of the key.
+ assert response.primary_keys == ["sync_id", "id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+ # Fan-out interleaves parents, so rows are never globally ascending: desc mode makes
+ # the pipeline persist the watermark only when a sync completes.
+ assert response.sort_mode == "desc"
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch.build_dependent_resource"
+ )
+ def test_sync_runs_fanout_wiring(self, mock_build_dependent_resource) -> None:
+ mock_build_dependent_resource.return_value = iter([])
+ manager = _make_manager(HightouchResumeConfig(paginator_state={"completed": [], "current": None}))
+
+ hightouch_source(
+ api_key="key",
+ endpoint="sync_runs",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["page_size_param"] == "limit"
+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "data"
+ assert kwargs["child_endpoint_extra"]["data_selector"] == "data"
+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], HightouchPaginator)
+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], HightouchPaginator)
+ assert kwargs["child_params_extra"] == {"orderBy": "id"}
+ assert kwargs["incremental_config_factory"] is _hightouch_incremental_window
+ assert kwargs["resume_hook"] is not None
+ assert kwargs["initial_paginator_state"] == {"completed": [], "current": None}
+
+ @parameterized.expand(
+ [
+ ("incremental", True, datetime(2026, 3, 1, tzinfo=UTC)),
+ ("first_sync", True, None),
+ ("non_incremental", False, datetime(2026, 3, 1, tzinfo=UTC)),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch.build_dependent_resource"
+ )
+ def test_sync_runs_passes_watermark(
+ self, _name, should_use_incremental_field, last_value, mock_build_dependent_resource
+ ) -> None:
+ mock_build_dependent_resource.return_value = iter([])
+
+ hightouch_source(
+ api_key="key",
+ endpoint="sync_runs",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ incremental_field="startedAt",
+ )
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field
+ assert kwargs["db_incremental_field_last_value"] == last_value
+ assert kwargs["incremental_field"] == "startedAt"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/tests/test_hightouch_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/tests/test_hightouch_source.py
new file mode 100644
index 000000000000..b14298ce68cf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hightouch/tests/test_hightouch_source.py
@@ -0,0 +1,143 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hightouch import (
+ HightouchSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.hightouch import HightouchResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.settings import (
+ ENDPOINTS,
+ SYNC_RUNS_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.source import HightouchSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestHightouchSource:
+ def setup_method(self) -> None:
+ self.source = HightouchSource()
+ self.team_id = 123
+ self.config = HightouchSourceConfig(api_key="hightouch-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HIGHTOUCH
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Hightouch"
+ assert config.label == "Hightouch"
+ assert config.category == DataWarehouseSourceCategory.ANALYTICS
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # The source ships visible: unreleasedSource hides the connector from every user.
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/hightouch.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hightouch"
+
+ 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_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_semantics(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ # Config tables have no server-side timestamp filter, so they are full refresh only.
+ for name in ("syncs", "models", "sources", "destinations"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ # sync_runs supports incremental via the server-side `after` filter on startedAt,
+ # and is merge-only because in-progress runs mutate and the lookback re-reads them.
+ assert schemas["sync_runs"].supports_incremental is True
+ assert schemas["sync_runs"].supports_append is False
+ assert [f["field"] for f in schemas["sync_runs"].incremental_fields] == ["startedAt"]
+ assert schemas["sync_runs"].default_incremental_lookback_seconds == SYNC_RUNS_LOOKBACK_SECONDS
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["sync_runs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "sync_runs"
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.hightouch.com/api/v1/syncs",
+ "403 Client Error: Forbidden for url: https://api.hightouch.com/api/v1/syncs",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ def test_non_retryable_errors_ignore_transient_failures(self) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(
+ key in "500 Server Error for url: https://api.hightouch.com/api/v1/syncs" for key in non_retryable
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.source.validate_hightouch_credentials"
+ )
+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="sync_runs")
+
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("hightouch-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is HightouchResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.source.hightouch_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_hightouch_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "sync_runs"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "startedAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_hightouch_source.call_args.kwargs
+ assert kwargs["api_key"] == "hightouch-key"
+ assert kwargs["endpoint"] == "sync_runs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["incremental_field"] == "startedAt"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hightouch.source.hightouch_source")
+ def test_source_for_pipeline_omits_watermark_when_not_incremental(
+ self, mock_hightouch_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "sync_runs"
+ 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_hightouch_source.call_args.kwargs
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)