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 planhat import source (#68575)

Tom Owers3cfaafcdedd3
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 87adb3bf86e4..c834dc9d68e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -273,6 +273,7 @@ the row lists both.
| pinterest_ads | HTTP | requests | ✅ |
| pipedrive | HTTP | requests | ✅ |
| plain | HTTP | requests | ✅ |
+| planhat | HTTP | requests | ✅ |
| plausible | HTTP | requests | ✅ |
| polar | HTTP | requests | ✅ |
| plaid | HTTP | requests | ✅ |
@@ -593,7 +594,6 @@ doesn't conflict with concurrent PRs.
- pivotal_tracker
- piwik
- planetscale
-- planhat
- plunk
- pocket
- podium
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 fef9aa5990b2..74650dca97a4 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
@@ -2533,7 +2533,7 @@ class PlanetScaleSourceConfig(config.Config):
@config.config
class PlanhatSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/canonical_descriptions.py
new file mode 100644
index 000000000000..3b498eee9878
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/canonical_descriptions.py
@@ -0,0 +1,92 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Planhat API docs (https://docs.planhat.com).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "companies": {
+ "description": "A customer account (company) tracked in Planhat, the core object health scores and revenue attach to.",
+ "docs_url": "https://docs.planhat.com/#companies",
+ "columns": {
+ "_id": "The unique ID of the company.",
+ "name": "The company name.",
+ "externalId": "Your own identifier for the company, used to match it against your systems.",
+ "phase": "The lifecycle phase of the customer.",
+ "status": "The account status (for example active or churned).",
+ "ownerId": "The ID of the Planhat user who owns the account.",
+ "mrr": "The current monthly recurring revenue for the company.",
+ "h": "The company's current health score.",
+ "createDate": "When the company was created.",
+ "lastUpdated": "When the company was last modified.",
+ },
+ },
+ "endusers": {
+ "description": "A contact (end user) at one of your customer companies.",
+ "docs_url": "https://docs.planhat.com/#endusers",
+ "columns": {
+ "_id": "The unique ID of the end user.",
+ "name": "The end user's full name.",
+ "email": "The end user's email address.",
+ "companyId": "The ID of the company the end user belongs to.",
+ "companyName": "The name of the company the end user belongs to.",
+ "phone": "The end user's phone number.",
+ "position": "The end user's job title or role.",
+ "createDate": "When the end user was created.",
+ "lastUpdated": "When the end user was last modified.",
+ },
+ },
+ "users": {
+ "description": "A Planhat team member (internal user) in your workspace.",
+ "docs_url": "https://docs.planhat.com/#users",
+ "columns": {
+ "_id": "The unique ID of the user.",
+ "email": "The user's email address.",
+ "firstName": "The user's first name.",
+ "lastName": "The user's last name.",
+ "nickName": "The user's display name.",
+ "isActive": "Whether the user account is active.",
+ "roles": "The roles assigned to the user.",
+ },
+ },
+ "licenses": {
+ "description": "A license or subscription line item attached to a company, driving recurring revenue.",
+ "docs_url": "https://docs.planhat.com/#licenses",
+ "columns": {
+ "_id": "The unique ID of the license.",
+ "companyId": "The ID of the company the license belongs to.",
+ "product": "The product the license is for.",
+ "value": "The monetary value of the license.",
+ "mrr": "The monthly recurring revenue from the license.",
+ "fromDate": "When the license term starts.",
+ "toDate": "When the license term ends.",
+ "renewalStatus": "The renewal status of the license.",
+ },
+ },
+ "assets": {
+ "description": "An asset (a sub-unit of a company such as a product instance, project, or store) tracked in Planhat.",
+ "docs_url": "https://docs.planhat.com/#assets",
+ "columns": {
+ "_id": "The unique ID of the asset.",
+ "name": "The asset name.",
+ "companyId": "The ID of the company the asset belongs to.",
+ "externalId": "Your own identifier for the asset.",
+ "createDate": "When the asset was created.",
+ "lastUpdated": "When the asset was last modified.",
+ },
+ },
+ "nps": {
+ "description": "An NPS survey response collected from an end user.",
+ "docs_url": "https://docs.planhat.com/#nps",
+ "columns": {
+ "_id": "The unique ID of the NPS response.",
+ "companyId": "The ID of the company the respondent belongs to.",
+ "enduserId": "The ID of the end user who responded.",
+ "campaignId": "The ID of the NPS campaign the response belongs to.",
+ "score": "The NPS score given by the respondent (0-10).",
+ "comment": "The free-text comment left with the score.",
+ "followUp": "The follow-up status for the response.",
+ "date": "When the response was submitted.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/planhat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/planhat.py
new file mode 100644
index 000000000000..fe2851690d79
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/planhat.py
@@ -0,0 +1,150 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.settings import PLANHAT_ENDPOINTS
+
+PLANHAT_BASE_URL = "https://api.planhat.com"
+# Planhat list endpoints default to a `limit` of 100; the largest common page minimises round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API token is genuine. The token is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/companies"
+
+
+class PlanhatRetryableError(Exception):
+ pass
+
+
+class PlanhatResumeConfig:
+ # Offset of the next page to fetch. Offset pagination is deterministic, so a crashed
+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `_id`.
+ offset: int = 0
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((PlanhatRetryableError, 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,
+ path: str,
+ offset: int,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ response = session.get(
+ f"{PLANHAT_BASE_URL}{path}",
+ params={"limit": limit, "offset": offset},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PlanhatRetryableError(f"Planhat API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Planhat API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Planhat list endpoints return a bare JSON array of records.
+ if not isinstance(data, list):
+ raise PlanhatRetryableError(f"Planhat returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PlanhatResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = PLANHAT_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume else 0
+ if resume and resume.offset > 0:
+ logger.debug(f"Planhat: resuming {endpoint} from offset {offset}")
+
+ while True:
+ items = _fetch_page(session, config.path, offset, PAGE_SIZE, logger)
+ if items:
+ yield items
+
+ # A short page (or an empty one) means we've reached the end of the collection.
+ if len(items) < PAGE_SIZE:
+ break
+
+ offset += PAGE_SIZE
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(PlanhatResumeConfig(offset=offset))
+
+
+def planhat_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PlanhatResumeConfig],
+) -> SourceResponse:
+ config = PLANHAT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+ try:
+ # Ask for a single row so the probe stays cheap regardless of account size.
+ response = session.get(f"{PLANHAT_BASE_URL}{path}", params={"limit": 1, "offset": 0}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Planhat: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Planhat returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_token)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Planhat API token"
+ return False, message or "Could not validate Planhat API token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/settings.py
new file mode 100644
index 000000000000..dec312afefe1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/settings.py
@@ -0,0 +1,27 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class PlanhatEndpointConfig:
+ name: str
+ path: str
+ # Planhat objects are backed by MongoDB, so each record carries a globally unique `_id`.
+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])
+
+
+# Planhat REST API list endpoints. All are full-refresh only: Planhat exposes no server-side
+# updated-since filter, and while every object carries a `lastUpdated` field, its ordering
+# guarantees aren't documented well enough to advance an incremental cursor safely, so a
+# client-side scan would cost the same as a full refresh (see the implementing-warehouse-sources skill).
+PLANHAT_ENDPOINTS: dict[str, PlanhatEndpointConfig] = {
+ "companies": PlanhatEndpointConfig(name="companies", path="/companies"),
+ "endusers": PlanhatEndpointConfig(name="endusers", path="/endusers"),
+ "users": PlanhatEndpointConfig(name="users", path="/users"),
+ "licenses": PlanhatEndpointConfig(name="licenses", path="/licenses"),
+ "assets": PlanhatEndpointConfig(name="assets", path="/assets"),
+ "nps": PlanhatEndpointConfig(name="nps", path="/nps"),
+}
+
+ENDPOINTS = tuple(PLANHAT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/source.py
index 294cc751f476..b25aee2f7b98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/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 PlanhatSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.planhat import (
+ PlanhatResumeConfig,
+ planhat_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.settings import (
+ ENDPOINTS,
+ PLANHAT_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PlanhatSource(SimpleSource[PlanhatSourceConfig]):
+class PlanhatSource(ResumableSource[PlanhatSourceConfig, PlanhatResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PLANHAT
@@ -24,7 +47,86 @@ class PlanhatSource(SimpleSource[PlanhatSourceConfig]):
name=SchemaExternalDataSourceType.PLANHAT,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Planhat",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Planhat API access token to pull your customer success data into the PostHog Data warehouse.
+
+You can create an API access token from a Private App under **Settings → Service Accounts** in [Planhat](https://app.planhat.com). The token is shown once, so copy it immediately. It grants read access to your companies, end users, users, licenses, assets, and NPS responses.
+""",
iconPath="/static/services/planhat.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/planhat",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.planhat.com": "Your Planhat API access token is invalid or has been revoked. Generate a new token from a Private App under Settings → Service Accounts, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.planhat.com": "Your Planhat API access token does not have access to this data. Check the Private App's scopes, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: PlanhatSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Planhat's list endpoints expose no reliably
+ # ordered server-side timestamp filter, 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: PlanhatSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API token is account-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PlanhatResumeConfig]:
+ return ResumableSourceManager[PlanhatResumeConfig](inputs, PlanhatResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PlanhatSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PlanhatResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in PLANHAT_ENDPOINTS:
+ raise ValueError(f"Unknown Planhat schema '{inputs.schema_name}'")
+
+ return planhat_source(
+ api_token=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/planhat/tests/test_planhat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/tests/test_planhat.py
new file mode 100644
index 000000000000..ed7bf920100b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/tests/test_planhat.py
@@ -0,0 +1,225 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat import planhat
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.planhat import (
+ PAGE_SIZE,
+ PlanhatResumeConfig,
+ PlanhatRetryableError,
+ check_access,
+ get_rows,
+ planhat_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.settings import (
+ ENDPOINTS,
+ PLANHAT_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = planhat._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PlanhatResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PlanhatResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PlanhatResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PlanhatResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _full_page(start_id: int) -> list[dict]:
+ return [{"_id": str(start_id + i)} for i in range(PAGE_SIZE)]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, list[dict]], endpoint: str = "companies"
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, offset: int, limit: int, logger: Any) -> list[dict]:
+ return pages[offset]
+
+ monkeypatch.setattr(planhat, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(planhat, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="ph-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: [{"_id": "1"}, {"_id": "2"}]})
+ assert rows == [{"_id": "1"}, {"_id": "2"}]
+ # The page is short (< PAGE_SIZE), so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_offset_pagination_until_short_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {0: _full_page(0), PAGE_SIZE: [{"_id": "999"}]}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == PAGE_SIZE + 1
+ # State is saved after the first full page (offset advances to PAGE_SIZE), then we stop.
+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(PlanhatResumeConfig(offset=PAGE_SIZE))
+ # Offset 0 must never be fetched on resume.
+ pages = {PAGE_SIZE: [{"_id": "5"}]}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"_id": "5"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: []})
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ 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(PlanhatRetryableError):
+ _fetch_page_unwrapped(session, "/companies", 0, PAGE_SIZE, 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, "/companies", 0, PAGE_SIZE, MagicMock())
+
+ def test_success_returns_list_body(self) -> None:
+ body = [{"_id": "1"}]
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "/companies", 0, PAGE_SIZE, MagicMock())
+ assert result == body
+
+ def test_non_list_body_is_retryable(self) -> None:
+ session = self._session_returning(200, {"error": "nope"})
+ with pytest.raises(PlanhatRetryableError):
+ _fetch_page_unwrapped(session, "/companies", 0, PAGE_SIZE, MagicMock())
+
+ def test_request_uses_limit_and_offset_params(self) -> None:
+ session = self._session_returning(200, [])
+ _fetch_page_unwrapped(session, "/endusers", 200, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE, "offset": 200}
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @staticmethod
+ def _patch_session(session: MagicMock) -> Any:
+ # A context manager rather than the monkeypatch fixture — parameterized.expand hides the
+ # fixture from pytest's injector, so patch explicitly instead.
+ return mock.patch.object(planhat, "make_tracked_session", lambda **kwargs: session)
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Planhat returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with self._patch_session(self._session(response)):
+ assert check_access("ph-token") == (expected_status, expected_message)
+
+ def test_probe_uses_limit_one(self) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ session = self._session(response)
+ with self._patch_session(session):
+ check_access("ph-token")
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": 1, "offset": 0}
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ with self._patch_session(self._session(requests.ConnectionError("boom"))):
+ status, message = check_access("ph-token")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Planhat API token"),
+ ("forbidden", 403, False, "Invalid Planhat API token"),
+ ("server_error", 500, False, "Planhat returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ with self._patch_session(self._session(response)):
+ assert validate_credentials("ph-token") == (expected_valid, expected_message)
+
+
+class TestPlanhatSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = planhat_source(
+ api_token="ph-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["_id"]
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["_id"] for config in PLANHAT_ENDPOINTS.values())
+ assert set(PLANHAT_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/tests/test_planhat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/tests/test_planhat_source.py
new file mode 100644
index 000000000000..8c21a9f15182
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planhat/tests/test_planhat_source.py
@@ -0,0 +1,126 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+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 PlanhatSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.planhat import PlanhatResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.planhat.source import PlanhatSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestPlanhatSource:
+ def setup_method(self) -> None:
+ self.source = PlanhatSource()
+ self.team_id = 123
+ self.config = PlanhatSourceConfig(api_key="ph-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.PLANHAT
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Planhat"
+ assert config.label == "Planhat"
+ 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/planhat"
+
+ 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 token; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved token against another account.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ 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=["endusers"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "endusers"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.planhat.com/companies?limit=100&offset=0",
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.planhat.com/endusers?limit=100&offset=0"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.planhat.com/companies"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.planhat.com/endusers"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.planhat.source.validate_credentials")
+ def test_validate_credentials_delegates_to_planhat(self, mock_validate: mock.MagicMock) -> None:
+ # source.py owns no mapping logic — it forwards the account-wide token and returns the result verbatim.
+ mock_validate.return_value = (False, "Invalid Planhat API token")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("ph-token")
+ assert result == (False, "Invalid Planhat API token")
+
+ 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 PlanhatResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.planhat.source.planhat_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "companies"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "ph-token"
+ assert kwargs["endpoint"] == "companies"
+ 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 Planhat schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)