:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement persistiq import source (#68579)
Tom Owers02923f50b74c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9a281dfecdae..17466e719071 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -262,6 +262,7 @@ the row lists both.| papersign | HTTP | requests | ✅ || paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ |+| persistiq | HTTP | requests | ✅ || persona | HTTP | requests | ✅ || personio | HTTP | requests | ✅ || pexels | HTTP | requests | ✅ |@@ -585,7 +586,6 @@ doesn't conflict with concurrent PRs.- pennylane- perigon- perk-- persistiq- persona- pexels- phyllodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 79dc05236a9a..53f7eeb52107 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@@ -2442,7 +2442,7 @@ class PerkSourceConfig(config.Config):@config.configclass PersistIqSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/canonical_descriptions.pynew file mode 100644index 000000000000..96a08d77bb02--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/canonical_descriptions.py@@ -0,0 +1,41 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the PersistIQ REST API docs (https://apidocs.persistiq.com).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "leads": {+ "description": "A prospect or contact in PersistIQ, targeted by outbound sales campaigns.",+ "docs_url": "https://apidocs.persistiq.com",+ "columns": {+ "id": "The unique ID of the lead.",+ "status": "The current status of the lead (e.g. active, finished, bounced).",+ "data": "The lead's field values (name, email, company, and any custom fields).",+ "created_at": "When the lead was created.",+ "updated_at": "When the lead was last updated.",+ "owner_id": "The ID of the user who owns the lead.",+ },+ },+ "users": {+ "description": "A member of your PersistIQ account who sends campaigns and owns leads.",+ "docs_url": "https://apidocs.persistiq.com",+ "columns": {+ "id": "The unique ID of the user.",+ "name": "The user's full name.",+ "email": "The user's email address.",+ "active": "Whether the user account is active.",+ "salesforce_id": "The linked Salesforce user ID, if connected.",+ },+ },+ "campaigns": {+ "description": "An outbound sales campaign (sequence of steps) that leads are enrolled in.",+ "docs_url": "https://apidocs.persistiq.com",+ "columns": {+ "id": "The unique ID of the campaign.",+ "name": "The name of the campaign.",+ "creator_id": "The ID of the user who created the campaign.",+ "created_at": "When the campaign was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/persistiq.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/persistiq.pynew file mode 100644index 000000000000..602d95d9dc92--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/persistiq.py@@ -0,0 +1,158 @@+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.persistiq.settings import PERSISTIQ_ENDPOINTS++# The base URL already includes the `/v1` API version segment; endpoint paths are appended to it.+PERSISTIQ_BASE_URL = "https://api.persistiq.com/v1"+# The leads endpoint paginates at 100 records/page. per_page is not a documented parameter, so we+# only advance `page` and rely on the `has_more` flag to terminate.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to every list endpoint. `/users` is typically the smallest collection.+DEFAULT_PROBE_PATH = "/users"+++class PersistiqRetryableError(Exception):+ pass+++class PersistiqResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ next_page: int = 1+++def _headers(api_key: str) -> dict[str, str]:+ return {"x-api-key": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((PersistiqRetryableError, 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,+ page: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ f"{PERSISTIQ_BASE_URL}{path}",+ params={"page": page},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise PersistiqRetryableError(f"PersistIQ API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"PersistIQ API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # Every list endpoint returns an object envelope (`{"<resource>": [...], "has_more": ...}`);+ # a bare array or other type means a malformed response.+ if not isinstance(data, dict):+ raise PersistiqRetryableError(f"PersistIQ returned an unexpected payload for {path}: {type(data).__name__}")+ return data+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PersistiqResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PERSISTIQ_ENDPOINTS[endpoint]+ # `redact_values` masks the API key in logged URLs and captured samples.+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1+ if resume and resume.next_page > 1:+ logger.debug(f"PersistIQ: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, config.path, page, logger)++ # The resource key is always present in a well-formed envelope; missing it means a malformed+ # response, so fail loudly rather than silently advancing the cursor past lost rows.+ items = data.get(config.list_key)+ if not isinstance(items, list):+ raise PersistiqRetryableError(f"PersistIQ response for {endpoint} is missing the '{config.list_key}' list")+ if items:+ yield items++ # `has_more` is the authoritative end-of-collection signal; an empty page is a defensive stop.+ if not data.get("has_more", False) or not items:+ break++ page += 1+ # 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(PersistiqResumeConfig(next_page=page))+++def persistiq_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PersistiqResumeConfig],+) -> SourceResponse:+ config = PERSISTIQ_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,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list endpoint to validate the API key.++ 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_key), redact_values=(api_key,))+ try:+ response = session.get(f"{PERSISTIQ_BASE_URL}{path}", params={"page": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to PersistIQ: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"PersistIQ returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid PersistIQ API key"+ return False, message or "Could not validate PersistIQ API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/settings.pynew file mode 100644index 000000000000..0320c282b92c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/settings.py@@ -0,0 +1,27 @@+from dataclasses import dataclass, field+++@dataclass+class PersistiqEndpointConfig:+ name: str+ path: str+ # PersistIQ wraps each list response in a key named after the resource+ # (e.g. `{"leads": [...], "has_more": ..., "next_page": ...}`), so the row list+ # key varies per endpoint and is stored here.+ list_key: str+ # PersistIQ object IDs are globally unique within an account, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# PersistIQ REST API list endpoints. All are full-refresh only: the list endpoints expose no+# server-side `updated_after`-style filter, so there is no genuine incremental cursor to advance+# (a client-side scan of every page would cost the same as a full refresh — see the skill).+PERSISTIQ_ENDPOINTS: dict[str, PersistiqEndpointConfig] = {+ "leads": PersistiqEndpointConfig(name="leads", path="/leads", list_key="leads"),+ "users": PersistiqEndpointConfig(name="users", path="/users", list_key="users"),+ "campaigns": PersistiqEndpointConfig(name="campaigns", path="/campaigns", list_key="campaigns"),+}++ENDPOINTS = tuple(PERSISTIQ_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/source.pyindex 37f72091077b..bd96497fa5bc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PersistIqSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.persistiq import (+ PersistiqResumeConfig,+ persistiq_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.settings import (+ ENDPOINTS,+ PERSISTIQ_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PersistIqSource(SimpleSource[PersistIqSourceConfig]):+class PersistIqSource(ResumableSource[PersistIqSourceConfig, PersistiqResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PERSISTIQ@@ -24,7 +47,89 @@ class PersistIqSource(SimpleSource[PersistIqSourceConfig]):name=SchemaExternalDataSourceType.PERSIST_IQ,category=DataWarehouseSourceCategory.SALES,label="PersistIq",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your PersistIQ API key to pull your sales engagement data into the PostHog Data warehouse.++You can find your API key under **Profile → Integrations → PersistIQ API** in [PersistIQ](https://app.persistiq.com). The key grants read access to your leads, users, and campaigns.+""",iconPath="/static/services/persistiq.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/persistiq",+ 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.persistiq.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API 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.persistiq.com/v1": "Your PersistIQ API key is invalid or has been revoked. Generate a new key under Profile → Integrations → PersistIQ API, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.persistiq.com/v1": "Your PersistIQ API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: PersistIqSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — PersistIQ's list endpoints expose no 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: PersistIqSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key 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[PersistiqResumeConfig]:+ return ResumableSourceManager[PersistiqResumeConfig](inputs, PersistiqResumeConfig)++ def source_for_pipeline(+ self,+ config: PersistIqSourceConfig,+ resumable_source_manager: ResumableSourceManager[PersistiqResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in PERSISTIQ_ENDPOINTS:+ raise ValueError(f"Unknown PersistIQ schema '{inputs.schema_name}'")++ return persistiq_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/persistiq/tests/test_persistiq.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/tests/test_persistiq.pynew file mode 100644index 000000000000..44964d794f6a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/tests/test_persistiq.py@@ -0,0 +1,242 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq import persistiq+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.persistiq import (+ PersistiqResumeConfig,+ PersistiqRetryableError,+ check_access,+ get_rows,+ persistiq_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.settings import (+ ENDPOINTS,+ PERSISTIQ_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = persistiq._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: PersistiqResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PersistiqResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PersistiqResumeConfig | None:+ return self._state++ def save_state(self, data: PersistiqResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict], has_more: bool, list_key: str = "leads") -> dict[str, Any]:+ return {list_key: items, "has_more": has_more, "next_page": None}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "leads"+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, page: int, logger: Any) -> dict:+ return pages[page]++ monkeypatch.setattr(persistiq, "_fetch_page", fake_fetch)+ monkeypatch.setattr(persistiq, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="pq-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_yields_items_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([{"id": "l_1"}, {"id": "l_2"}], has_more=False)})+ assert rows == [{"id": "l_1"}, {"id": "l_2"}]+ # No further pages, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_has_more_is_false(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": "l_1"}], has_more=True),+ 2: _page([{"id": "l_2"}], has_more=True),+ 3: _page([{"id": "l_3"}], has_more=False),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": "l_1"}, {"id": "l_2"}, {"id": "l_3"}]++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": "l_1"}], has_more=True),+ 2: _page([{"id": "l_2"}], has_more=False),+ }+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER page 1 is yielded (pointing at page 2), and never for the final page.+ assert [s.next_page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PersistiqResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume.+ 2: _page([{"id": "l_2"}], has_more=True),+ 3: _page([{"id": "l_3"}], has_more=False),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": "l_2"}, {"id": "l_3"}]++ def test_empty_items_does_not_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([], has_more=False)})+ assert rows == []++ def test_uses_endpoint_specific_list_key(self, monkeypatch: Any) -> None:+ # `users` reads rows from the "users" envelope key, not "leads".+ manager = _FakeResumableManager()+ pages = {1: _page([{"id": "u_1"}], has_more=False, list_key="users")}+ rows = self._collect(manager, monkeypatch, pages, endpoint="users")+ assert rows == [{"id": "u_1"}]++ def test_missing_list_key_raises(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()++ def fake_fetch(session: Any, path: str, page: int, logger: Any) -> dict:+ return {"has_more": False}++ monkeypatch.setattr(persistiq, "_fetch_page", fake_fetch)+ monkeypatch.setattr(persistiq, "make_tracked_session", lambda **kwargs: MagicMock())++ with pytest.raises(PersistiqRetryableError):+ list(+ get_rows(+ api_key="pq-key",+ endpoint="leads",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )+++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(PersistiqRetryableError):+ _fetch_page_unwrapped(session, "/leads", 1, 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, "/leads", 1, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _page([{"id": "l_1"}], has_more=False)+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/leads", 1, MagicMock())+ assert result == body++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": "l_1"}])+ with pytest.raises(PersistiqRetryableError):+ _fetch_page_unwrapped(session, "/leads", 1, MagicMock())++ def test_request_uses_page_param(self) -> None:+ session = self._session_returning(200, _page([], has_more=False))+ _fetch_page_unwrapped(session, "/campaigns", 3, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3}+++class TestCheckAccess:+ def _patch_session(self, response: Any) -> Any:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return patch.object(persistiq, "make_tracked_session", lambda **kwargs: session)++ @parameterized.expand(+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "PersistIQ returned HTTP 500"),+ ]+ )+ def test_status_mapping(self, 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(response):+ assert check_access("pq-key") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ with self._patch_session(requests.ConnectionError("boom")):+ status, message = check_access("pq-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid PersistIQ API key"),+ (403, False, "Invalid PersistIQ API key"),+ (500, False, "PersistIQ returned HTTP 500"),+ ]+ )+ def test_validate_credentials(self, status: int, expected_valid: bool, expected_message: str | None) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with self._patch_session(response):+ assert validate_credentials("pq-key") == (expected_valid, expected_message)+++class TestPersistiqSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = persistiq_source(+ api_key="pq-key",+ 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 PERSISTIQ_ENDPOINTS.values())+ assert set(PERSISTIQ_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/tests/test_persistiq_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/tests/test_persistiq_source.pynew file mode 100644index 000000000000..7eae194acefd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/persistiq/tests/test_persistiq_source.py@@ -0,0 +1,130 @@+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 PersistIqSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.persistiq import PersistiqResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.source import PersistIqSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPersistIqSource:+ def setup_method(self) -> None:+ self.source = PersistIqSource()+ self.team_id = 123+ self.config = PersistIqSourceConfig(api_key="pq-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PERSISTIQ++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.label == "PersistIq"+ 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/persistiq"++ 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; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key 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=["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:+ 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.persistiq.com/v1/leads?page=1"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.persistiq.com/v1/users?page=1"),+ ]+ )+ 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.persistiq.com/v1/leads"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.persistiq.com/v1/campaigns"),+ ]+ )+ 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)++ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid_key", (False, "Invalid PersistIQ API key")),+ ("connect_error", (False, "Could not connect to PersistIQ: boom")),+ ]+ )+ def test_validate_credentials_delegates_to_probe(self, _name: str, underlying: tuple[bool, str | None]) -> None:+ # The status → message mapping is covered by the persistiq.validate_credentials unit test; here+ # we only guard that the source extracts the API key and returns the probe result unchanged.+ with mock.patch.object(source_module, "validate_credentials", return_value=underlying) as mock_validate:+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == underlying+ mock_validate.assert_called_once_with("pq-key")++ 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 PersistiqResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.persistiq.source.persistiq_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "leads"+ 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_key"] == "pq-key"+ assert kwargs["endpoint"] == "leads"+ 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 PersistIQ schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)