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 smartreach import source (#68569)

Tom Owersc46bc15fa2e6
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 949162638268..3151a7a0e79e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -307,6 +307,7 @@ the row lists both.
| simplecast | HTTP | requests | ✅ |
| simplesat | HTTP | requests | ✅ |
| slack | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| smartreach | HTTP | requests | ✅ |
| smartsheet | HTTP | requests | ✅ |
| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| snowflake | DB protocol | snowflake-connector-python | ➖ |
@@ -662,7 +663,6 @@ doesn't conflict with concurrent PRs.
- simplesat
- smaily
- smartengage
-- smartreach
- smartwaiver
- solarwinds_service_desk
- sonar_cloud
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 0953da1db094..445b8d736759 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -3050,7 +3050,7 @@ class SmartEngageSourceConfig(config.Config):
@config.config
class SmartreachSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/canonical_descriptions.py
new file mode 100644
index 000000000000..fed98b9f3c2d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/canonical_descriptions.py
@@ -0,0 +1,46 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the SmartReach API docs (https://smartreach.io/apidocs).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "prospects": {
+ "description": "A SmartReach prospect — a contact stored in the account, targetable by outreach campaigns.",
+ "docs_url": "https://smartreach.io/apidocs",
+ "columns": {
+ "id": "The unique ID of the prospect.",
+ "email": "The primary email address of the prospect.",
+ "first_name": "The prospect's first name.",
+ "last_name": "The prospect's last name.",
+ "company": "The company the prospect is associated with.",
+ "title": "The prospect's job title.",
+ "phone": "The prospect's phone number.",
+ "city": "The prospect's city.",
+ "state": "The prospect's state or region.",
+ "country": "The prospect's country.",
+ "timezone": "The prospect's time zone.",
+ "linkedin_url": "The prospect's LinkedIn profile URL.",
+ "category": "The prospect's category or status (e.g. active, bounced, unsubscribed).",
+ "list_id": "The ID of the prospect list the prospect belongs to.",
+ "owner_id": "The ID of the account user who owns the prospect.",
+ "created_at": "The timestamp when the prospect was created.",
+ "updated_at": "The timestamp when the prospect was last updated.",
+ },
+ },
+ "campaigns": {
+ "description": "A SmartReach campaign — an outreach sequence that sends steps to enrolled prospects.",
+ "docs_url": "https://smartreach.io/apidocs",
+ "columns": {
+ "id": "The unique ID of the campaign.",
+ "name": "The name of the campaign.",
+ "status": "The current status of the campaign (e.g. active, paused, completed, draft).",
+ "type": "The channel/type of the campaign (e.g. email).",
+ "owner_id": "The ID of the account user who owns the campaign.",
+ "team_id": "The ID of the team the campaign belongs to.",
+ "prospect_count": "The number of prospects enrolled in the campaign.",
+ "created_at": "The timestamp when the campaign was created.",
+ "updated_at": "The timestamp when the campaign was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/settings.py
new file mode 100644
index 000000000000..249e8d346203
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/settings.py
@@ -0,0 +1,29 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class SmartreachEndpointConfig:
+ name: str
+ path: str
+ # SmartReach nests the row list inside the `data` object under a per-endpoint key
+ # (e.g. `data.prospects`, `data.campaigns`), so each endpoint records which key to read.
+ data_key: str
+ # SmartReach object IDs are unique within an account, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # A stable (never-rewritten) datetime field to partition by. Only set where the object
+ # exposes a genuine creation timestamp — never an "updated" field, which changes on edit.
+ partition_key: Optional[str] = None
+
+
+# SmartReach v1 API list endpoints. All are full-refresh only: while the prospects endpoint does
+# expose `newer_than`/`older_than` epoch filters, we ship full refresh to avoid depending on
+# ordering we cannot verify (see the implementing-warehouse-sources skill).
+SMARTREACH_ENDPOINTS: dict[str, SmartreachEndpointConfig] = {
+ "prospects": SmartreachEndpointConfig(name="prospects", path="/prospects", data_key="prospects"),
+ "campaigns": SmartreachEndpointConfig(name="campaigns", path="/campaigns", data_key="campaigns"),
+}
+
+ENDPOINTS = tuple(SMARTREACH_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/smartreach.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/smartreach.py
new file mode 100644
index 000000000000..42b94e1b64dd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/smartreach.py
@@ -0,0 +1,173 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.settings import SMARTREACH_ENDPOINTS
+
+SMARTREACH_BASE_URL = "https://api.smartreach.io/api/v1"
+# `links.next` is echoed back from the API response, so it can't be trusted blindly: a tampered
+# response could point it at an arbitrary host and leak the user's API key there. Only follow next
+# URLs that stay on SmartReach's own origin.
+SMARTREACH_ALLOWED_ORIGIN = ("https", "api.smartreach.io")
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API key is genuine. The user key is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_ENDPOINT = "campaigns"
+
+
+class SmartreachRetryableError(Exception):
+ pass
+
+
+class SmartreachResumeConfig:
+ # Full URL of the next page, taken verbatim from `links.next`. None means "start at the
+ # endpoint's first page". The next URL already carries every pagination param, so the original
+ # query params must NOT be re-sent alongside it (doing so can restart pagination from the top).
+ next_url: str | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"X-API-KEY": api_key, "Accept": "application/json"}
+
+
+def _extract_rows(data: dict[str, Any], data_key: str) -> list[dict[str, Any]]:
+ # SmartReach wraps the list in `{"data": {"<data_key>": [...]}, "links": {"next": ...}}`.
+ # Tolerate a bare `{"data": [...]}` shape too, in case an endpoint returns the list directly.
+ payload = data.get("data")
+ if isinstance(payload, dict):
+ rows = payload.get(data_key)
+ return rows if isinstance(rows, list) else []
+ if isinstance(payload, list):
+ return payload
+ return []
+
+
+def _is_same_origin(url: str) -> bool:
+ parts = urlsplit(url)
+ return (parts.scheme, parts.hostname) == SMARTREACH_ALLOWED_ORIGIN
+
+
+def _next_url(data: dict[str, Any]) -> Optional[str]:
+ links = data.get("links")
+ if not isinstance(links, dict):
+ return None
+ next_url = links.get("next")
+ if not isinstance(next_url, str) or not next_url:
+ return None
+ if not _is_same_origin(next_url):
+ # Refuse to follow (and to persist) an off-origin cursor: fetching it would send the API key
+ # to whatever host the response named. Fail loudly rather than silently truncating the sync.
+ raise ValueError(f"SmartReach returned an off-origin pagination URL: {next_url}")
+ return next_url
+
+
+@retry(
+ retry=retry_if_exception_type((SmartreachRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ # `url` is either the endpoint's first-page URL or a `links.next` URL that already encodes its
+ # own pagination params, so no query params are passed here.
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SmartreachRetryableError(f"SmartReach API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"SmartReach API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SmartreachResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SMARTREACH_ENDPOINTS[endpoint]
+ # `redact_values` masks the user key in logged URLs and captured samples. `allow_redirects=False`
+ # keeps a redirect from bouncing the key off-origin (see `_next_url` for the same concern).
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume and resume.next_url:
+ url = resume.next_url
+ logger.debug(f"SmartReach: resuming {endpoint} from saved cursor URL")
+ else:
+ url = f"{SMARTREACH_BASE_URL}{config.path}"
+
+ while True:
+ data = _fetch_page(session, url, logger)
+
+ rows = _extract_rows(data, config.data_key)
+ if rows:
+ yield rows
+
+ next_url = _next_url(data)
+ if not next_url:
+ break
+
+ url = next_url
+ # Save AFTER yielding so a crash re-fetches from the next cursor (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(SmartreachResumeConfig(next_url=next_url))
+
+
+def smartreach_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SmartreachResumeConfig],
+) -> SourceResponse:
+ config = SMARTREACH_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def check_access(api_key: str, endpoint: str = DEFAULT_PROBE_ENDPOINT) -> tuple[int, Optional[str]]:
+ """Probe a single list endpoint to validate the user key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ config = SMARTREACH_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)
+ try:
+ response = session.get(f"{SMARTREACH_BASE_URL}{config.path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to SmartReach: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"SmartReach returned HTTP {response.status_code}"
+
+ return 200, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/source.py
index e8d73a528eb3..b9c265df6411 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/source.py
@@ -1,19 +1,42 @@
-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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SmartreachSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.settings import (
+ ENDPOINTS,
+ SMARTREACH_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.smartreach import (
+ SmartreachResumeConfig,
+ check_access,
+ smartreach_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SmartreachSource(SimpleSource[SmartreachSourceConfig]):
+class SmartreachSource(ResumableSource[SmartreachSourceConfig, SmartreachResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SMARTREACH
@@ -24,7 +47,95 @@ class SmartreachSource(SimpleSource[SmartreachSourceConfig]):
name=SchemaExternalDataSourceType.SMARTREACH,
category=DataWarehouseSourceCategory.SALES,
label="Smartreach",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your SmartReach API key to pull your SmartReach data into the PostHog Data warehouse.
+
+You can find your API key under **Settings → Integrations** in the [SmartReach app](https://app.smartreach.io/). The key is scoped to your user and grants read access to your prospects and campaigns.
+""",
iconPath="/static/services/smartreach.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/smartreach",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked user key surfaces as a requests HTTPError when `_fetch_page`
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop
+ # the sync. Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.smartreach.io": "Your SmartReach API key is invalid or has been revoked. Generate a new key under Settings → Integrations, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.smartreach.io": "Your SmartReach API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SmartreachSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — we deliberately do not use SmartReach's
+ # newer_than/older_than filters, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: SmartreachSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The user key is account-wide, so a single probe validates access to every schema; there is
+ # no per-endpoint scope to check.
+ status, message = check_access(config.api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid SmartReach API key"
+ return False, message or "Could not validate SmartReach API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SmartreachResumeConfig]:
+ return ResumableSourceManager[SmartreachResumeConfig](inputs, SmartreachResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SmartreachSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SmartreachResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SMARTREACH_ENDPOINTS:
+ raise ValueError(f"Unknown SmartReach schema '{inputs.schema_name}'")
+
+ return smartreach_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/tests/test_smartreach.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/tests/test_smartreach.py
new file mode 100644
index 000000000000..0316b4d84645
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/tests/test_smartreach.py
@@ -0,0 +1,276 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach import smartreach
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.settings import (
+ ENDPOINTS,
+ SMARTREACH_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.smartreach import (
+ SmartreachResumeConfig,
+ SmartreachRetryableError,
+ check_access,
+ get_rows,
+ smartreach_source,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = smartreach._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SmartreachResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SmartreachResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SmartreachResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SmartreachResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(rows: list[dict], data_key: str, next_url: str | None) -> dict[str, Any]:
+ return {"data": {data_key: rows}, "links": {"next": next_url}}
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages_by_url: dict[str, dict],
+ endpoint: str = "prospects",
+ ) -> tuple[list[dict], list[str]]:
+ fetched_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> dict:
+ fetched_urls.append(url)
+ return pages_by_url[url]
+
+ monkeypatch.setattr(smartreach, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(smartreach, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="uk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows, fetched_urls
+
+ def test_single_page_yields_rows_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ start = "https://api.smartreach.io/api/v1/prospects"
+ rows, urls = self._collect(
+ manager, monkeypatch, {start: _page([{"id": 1}, {"id": 2}], "prospects", next_url=None)}
+ )
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert urls == [start]
+ # No further pages, so no resume state is persisted.
+ assert manager.saved == []
+
+ def test_follows_links_next_until_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ start = "https://api.smartreach.io/api/v1/prospects"
+ p2 = "https://api.smartreach.io/api/v1/prospects?cursor=abc"
+ p3 = "https://api.smartreach.io/api/v1/prospects?cursor=def"
+ pages = {
+ start: _page([{"id": 1}], "prospects", next_url=p2),
+ p2: _page([{"id": 2}], "prospects", next_url=p3),
+ p3: _page([{"id": 3}], "prospects", next_url=None),
+ }
+ rows, urls = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]
+ # The follow-up requests hit the verbatim links.next URLs.
+ assert urls == [start, p2, p3]
+
+ def test_saves_next_url_after_yielding_each_batch(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ start = "https://api.smartreach.io/api/v1/prospects"
+ p2 = "https://api.smartreach.io/api/v1/prospects?cursor=abc"
+ pages = {
+ start: _page([{"id": 1}], "prospects", next_url=p2),
+ p2: _page([{"id": 2}], "prospects", next_url=None),
+ }
+ self._collect(manager, monkeypatch, pages)
+ # State is saved AFTER page 1 is yielded (pointing at the next URL), never for the final page.
+ assert [s.next_url for s in manager.saved] == [p2]
+
+ def test_resumes_from_saved_cursor_url(self, monkeypatch: Any) -> None:
+ p2 = "https://api.smartreach.io/api/v1/prospects?cursor=abc"
+ p3 = "https://api.smartreach.io/api/v1/prospects?cursor=def"
+ manager = _FakeResumableManager(SmartreachResumeConfig(next_url=p2))
+ pages = {
+ # The first-page URL must never be fetched on resume.
+ p2: _page([{"id": 2}], "prospects", next_url=p3),
+ p3: _page([{"id": 3}], "prospects", next_url=None),
+ }
+ rows, urls = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 2}, {"id": 3}]
+ assert urls == [p2, p3]
+
+ def test_empty_page_does_not_yield(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ start = "https://api.smartreach.io/api/v1/prospects"
+ rows, _urls = self._collect(manager, monkeypatch, {start: _page([], "prospects", next_url=None)})
+ assert rows == []
+
+ def test_reads_rows_from_endpoint_specific_data_key(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ start = "https://api.smartreach.io/api/v1/campaigns"
+ rows, _urls = self._collect(
+ manager,
+ monkeypatch,
+ {start: _page([{"id": 9}], "campaigns", next_url=None)},
+ endpoint="campaigns",
+ )
+ assert rows == [{"id": 9}]
+
+
+class TestExtractRows:
+ def test_reads_nested_data_key(self) -> None:
+ data = {"data": {"prospects": [{"id": 1}]}}
+ assert smartreach._extract_rows(data, "prospects") == [{"id": 1}]
+
+ def test_tolerates_bare_data_list(self) -> None:
+ data = {"data": [{"id": 1}]}
+ assert smartreach._extract_rows(data, "prospects") == [{"id": 1}]
+
+ @parameterized.expand([("missing_data", {}), ("null_data", {"data": None}), ("wrong_key", {"data": {"other": []}})])
+ def test_returns_empty_when_rows_absent(self, _name: str, data: dict[str, Any]) -> None:
+ assert smartreach._extract_rows(data, "prospects") == []
+
+
+class TestNextUrl:
+ @parameterized.expand(
+ [
+ ("cursor", "https://api.smartreach.io/api/v1/prospects?cursor=abc"),
+ ("plain", "https://api.smartreach.io/api/v1/prospects"),
+ ]
+ )
+ def test_same_origin_url_is_returned(self, _name: str, url: str) -> None:
+ assert smartreach._next_url({"links": {"next": url}}) == url
+
+ @parameterized.expand([("missing_links", {}), ("null_next", {"links": {"next": None}}), ("empty", {"links": {}})])
+ def test_absent_next_returns_none(self, _name: str, data: dict[str, Any]) -> None:
+ assert smartreach._next_url(data) is None
+
+ @parameterized.expand(
+ [
+ ("other_host", "https://evil.example.com/api/v1/prospects"),
+ ("subdomain_spoof", "https://api.smartreach.io.evil.com/api/v1/prospects"),
+ ("http_downgrade", "http://api.smartreach.io/api/v1/prospects"),
+ ]
+ )
+ def test_off_origin_next_url_raises(self, _name: str, url: str) -> None:
+ # Following an off-origin cursor would send the user's API key to an attacker-named host.
+ with pytest.raises(ValueError):
+ smartreach._next_url({"links": {"next": url}})
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body or {}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(SmartreachRetryableError):
+ _fetch_page_unwrapped(session, "https://api.smartreach.io/api/v1/prospects", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "https://api.smartreach.io/api/v1/prospects", MagicMock())
+
+ def test_success_returns_json_body(self) -> None:
+ body = _page([{"id": 1}], "prospects", next_url=None)
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "https://api.smartreach.io/api/v1/prospects", MagicMock())
+ assert result == body
+
+ def test_follows_next_url_verbatim_without_extra_params(self) -> None:
+ # A links.next URL already carries its pagination params; the fetch must not add its own.
+ session = self._session_returning(200, _page([], "prospects", next_url=None))
+ next_url = "https://api.smartreach.io/api/v1/prospects?cursor=abc"
+ _fetch_page_unwrapped(session, next_url, MagicMock())
+ args, kwargs = session.get.call_args
+ assert args[0] == next_url
+ assert "params" not in kwargs
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(smartreach, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @pytest.mark.parametrize(
+ "status, ok, expected_status, expected_message",
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "SmartReach returned HTTP 500"),
+ ],
+ )
+ def test_status_mapping(
+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ self._patch_session(monkeypatch, response)
+ assert check_access("uk_test") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("uk_test")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestSmartreachSourceResponse:
+ @parameterized.expand([("prospects",), ("campaigns",)])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = smartreach_source(
+ api_key="uk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Full refresh only: no datetime partitioning is configured.
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in SMARTREACH_ENDPOINTS.values())
+ assert set(SMARTREACH_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/tests/test_smartreach_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/tests/test_smartreach_source.py
new file mode 100644
index 000000000000..a5c5049ec63e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartreach/tests/test_smartreach_source.py
@@ -0,0 +1,155 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import 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 import SmartreachSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.smartreach import (
+ SmartreachResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.source import SmartreachSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSmartreachSource:
+ def setup_method(self) -> None:
+ self.source = SmartreachSource()
+ self.team_id = 123
+ self.config = SmartreachSourceConfig(api_key="uk_test")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SMARTREACH
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Smartreach"
+ assert config.label == "Smartreach"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/smartreach"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ 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_no_connection_host_fields(self) -> None:
+ # The only field is the secret `api_key` itself; the base URL is hardcoded and the account is
+ # implicit in the key. There is no non-secret field that retargets where the key is sent.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["campaigns"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "campaigns"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # Exercises the credential-free catalog path used by the posthog.com docs.
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.smartreach.io/api/v1/prospects?cursor=abc",
+ "403 Client Error: Forbidden for url: https://api.smartreach.io/api/v1/campaigns",
+ ],
+ )
+ 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)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ [
+ "500 Server Error: Internal Server Error for url: https://api.smartreach.io/api/v1/prospects",
+ "HTTPSConnectionPool(host='api.smartreach.io', port=443): Read timed out.",
+ "429 Client Error: Too Many Requests for url: https://api.smartreach.io/api/v1/campaigns",
+ ],
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid SmartReach API key"),
+ (403, False, "Invalid SmartReach API key"),
+ (500, False, "SmartReach returned HTTP 500"),
+ (0, False, "Could not connect to SmartReach: boom"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.source.check_access")
+ def test_validate_credentials(
+ self,
+ mock_check: mock.MagicMock,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ message = (
+ "SmartReach returned HTTP 500"
+ if status == 500
+ else ("Could not connect to SmartReach: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.source.check_access")
+ def test_validate_credentials_probes_the_user_key(self, mock_check: mock.MagicMock) -> None:
+ # The user key is account-wide, so validation probes the key, not a per-schema scope.
+ mock_check.return_value = (200, None)
+ self.source.validate_credentials(self.config, self.team_id, schema_name="campaigns")
+ mock_check.assert_called_once_with("uk_test")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SmartreachResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.smartreach.source.smartreach_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_smartreach_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "prospects"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_smartreach_source.assert_called_once()
+ kwargs = mock_smartreach_source.call_args.kwargs
+ assert kwargs["api_key"] == "uk_test"
+ assert kwargs["endpoint"] == "prospects"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown SmartReach schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)