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 partnerstack import source (#68578)

Tom Owersf4ea3cda7a49
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 17466e719071..6601918549f7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -260,6 +260,7 @@ the row lists both.
| pagerduty | HTTP | requests | ✅ |
| pandadoc | HTTP | requests | ✅ |
| papersign | HTTP | requests | ✅ |
+| partnerstack | HTTP | requests | ✅ |
| paystack | HTTP | requests + `rest_source.RESTClient` | ✅ |
| pendo | HTTP | requests | ✅ |
| persistiq | HTTP | requests | ✅ |
@@ -578,7 +579,6 @@ doesn't conflict with concurrent PRs.
- paperform
- pardot
- partnerize
-- partnerstack
- payfit
- paylocity
- paypal
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 53f7eeb52107..9f4b7b439da9 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
@@ -2391,7 +2391,8 @@ class PardotSourceConfig(config.Config):
@config.config
class PartnerStackSourceConfig(config.Config):
- pass
+ public_key: str
+ private_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/canonical_descriptions.py
new file mode 100644
index 000000000000..e5b6f492d994
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/canonical_descriptions.py
@@ -0,0 +1,63 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the PartnerStack Vendor API v2 docs (https://docs.partnerstack.com/reference).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "partnerships": {
+ "description": "A partner enrolled in your PartnerStack program, including their profile and enrolment details.",
+ "docs_url": "https://docs.partnerstack.com/reference/get_v2-partnerships",
+ "columns": {
+ "key": "The unique key of the partnership.",
+ "email": "The partner's email address.",
+ "first_name": "The partner's first name.",
+ "last_name": "The partner's last name.",
+ "company_name": "The partner's company name.",
+ "group": "The partner group the partnership belongs to.",
+ "stats": "Aggregate performance stats for the partnership.",
+ "created": "When the partnership was created (epoch milliseconds).",
+ "updated_at": "When the partnership was last updated (epoch milliseconds).",
+ },
+ },
+ "customers": {
+ "description": "A customer referred through your PartnerStack program and attributed to a partner.",
+ "docs_url": "https://docs.partnerstack.com/reference/get_v2-customers",
+ "columns": {
+ "key": "The unique key of the customer.",
+ "name": "The customer's name.",
+ "email": "The customer's email address.",
+ "provider_key": "The customer's identifier in your own system.",
+ "partnership": "The partnership the customer is attributed to.",
+ "created": "When the customer was created (epoch milliseconds).",
+ "updated_at": "When the customer was last updated (epoch milliseconds).",
+ },
+ },
+ "deals": {
+ "description": "A deal submitted or attributed within your PartnerStack program.",
+ "docs_url": "https://docs.partnerstack.com/reference/get_v2-deals",
+ "columns": {
+ "key": "The unique key of the deal.",
+ "name": "The name of the deal.",
+ "stage": "The current stage of the deal.",
+ "amount": "The monetary value of the deal.",
+ "currency": "The currency of the deal amount.",
+ "partnership": "The partnership the deal is attributed to.",
+ "created": "When the deal was created (epoch milliseconds).",
+ "updated_at": "When the deal was last updated (epoch milliseconds).",
+ },
+ },
+ "leads": {
+ "description": "A lead submitted by a partner in your PartnerStack program.",
+ "docs_url": "https://docs.partnerstack.com/reference/get_v2-leads",
+ "columns": {
+ "key": "The unique key of the lead.",
+ "name": "The lead's name.",
+ "email": "The lead's email address.",
+ "company_name": "The lead's company name.",
+ "partnership": "The partnership the lead is attributed to.",
+ "created": "When the lead was created (epoch milliseconds).",
+ "updated_at": "When the lead was last updated (epoch milliseconds).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/partnerstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/partnerstack.py
new file mode 100644
index 000000000000..08d7084fb32f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/partnerstack.py
@@ -0,0 +1,183 @@
+import base64
+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.partnerstack.settings import (
+ PARTNERSTACK_ENDPOINTS,
+)
+
+PARTNERSTACK_BASE_URL = "https://api.partnerstack.com/api/v2"
+# The Vendor API caps `limit` at 250; the largest page minimises round trips.
+PAGE_SIZE = 250
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm the key pair is genuine. The credentials are account-wide, so one
+# probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/partnerships"
+# Cursor pagination keys on each object's `key`, which is also the primary key of every object.
+CURSOR_FIELD = "key"
+
+
+class PartnerStackRetryableError(Exception):
+ pass
+
+
+class PartnerStackResumeConfig:
+ # The `key` of the last object yielded. On resume the next request passes it as `starting_after`,
+ # so a crashed full-refresh sync continues after the last object persisted; merge dedupes on `key`.
+ starting_after: str | None = None
+
+
+def _headers(public_key: str, private_key: str) -> dict[str, str]:
+ token = base64.b64encode(f"{public_key}:{private_key}".encode("ascii")).decode("ascii")
+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((PartnerStackRetryableError, 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,
+ starting_after: str | None,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], bool]:
+ params: dict[str, Any] = {"limit": limit}
+ if starting_after is not None:
+ params["starting_after"] = starting_after
+
+ response = session.get(
+ f"{PARTNERSTACK_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PartnerStackRetryableError(
+ f"PartnerStack API error (retryable): status={response.status_code}, path={path}"
+ )
+
+ if not response.ok:
+ logger.error(f"PartnerStack API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ body = response.json()
+ # The Vendor API wraps rows under `data.items` and signals continuation with `data.has_more`.
+ if not isinstance(body, dict) or not isinstance(body.get("data"), dict):
+ raise PartnerStackRetryableError(
+ f"PartnerStack returned an unexpected payload for {path}: {type(body).__name__}"
+ )
+ data = body["data"]
+ items = data.get("items")
+ if not isinstance(items, list):
+ raise PartnerStackRetryableError(
+ f"PartnerStack returned a non-list items field for {path}: {type(items).__name__}"
+ )
+ return items, bool(data.get("has_more", False))
+
+
+def get_rows(
+ public_key: str,
+ private_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PartnerStackResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = PARTNERSTACK_ENDPOINTS[endpoint]
+ session = make_tracked_session(
+ headers=_headers(public_key, private_key),
+ redact_values=(public_key, private_key),
+ )
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ starting_after = resume.starting_after if resume else None
+ if starting_after is not None:
+ logger.debug(f"PartnerStack: resuming {endpoint} after cursor {starting_after}")
+
+ while True:
+ items, has_more = _fetch_page(session, config.path, starting_after, PAGE_SIZE, logger)
+ if items:
+ yield items
+
+ # An empty page or a cleared `has_more` flag means we've reached the end of the collection.
+ if not items or not has_more:
+ break
+
+ starting_after = items[-1].get(CURSOR_FIELD)
+ if starting_after is None:
+ # Without a cursor from the last object we cannot advance safely, so stop.
+ logger.warning(f"PartnerStack: {endpoint} object missing '{CURSOR_FIELD}', stopping pagination")
+ break
+
+ # 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(PartnerStackResumeConfig(starting_after=starting_after))
+
+
+def partnerstack_source(
+ public_key: str,
+ private_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PartnerStackResumeConfig],
+) -> SourceResponse:
+ config = PARTNERSTACK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ public_key=public_key,
+ private_key=private_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(public_key: str, private_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the key pair.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(
+ headers=_headers(public_key, private_key),
+ redact_values=(public_key, private_key),
+ )
+ try:
+ response = session.get(f"{PARTNERSTACK_BASE_URL}{path}", params={"limit": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to PartnerStack: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"PartnerStack returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(public_key: str, private_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(public_key, private_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid PartnerStack API keys"
+ return False, message or "Could not validate PartnerStack API keys"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/settings.py
new file mode 100644
index 000000000000..6464dcfbd194
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/settings.py
@@ -0,0 +1,25 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class PartnerStackEndpointConfig:
+ name: str
+ path: str
+ # PartnerStack objects are identified by a globally unique `key`, so it is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["key"])
+
+
+# PartnerStack Vendor API v2 list endpoints. All are full-refresh only: while most objects expose
+# `min_updated`/`max_updated` filters on `updated_at`, we don't ship incremental sync here because
+# the ordering guarantees can't be curl-verified, so a client-side scan would cost the same as a
+# full refresh (see the implementing-warehouse-sources skill).
+PARTNERSTACK_ENDPOINTS: dict[str, PartnerStackEndpointConfig] = {
+ "partnerships": PartnerStackEndpointConfig(name="partnerships", path="/partnerships"),
+ "customers": PartnerStackEndpointConfig(name="customers", path="/customers"),
+ "deals": PartnerStackEndpointConfig(name="deals", path="/deals"),
+ "leads": PartnerStackEndpointConfig(name="leads", path="/leads"),
+}
+
+ENDPOINTS = tuple(PARTNERSTACK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/source.py
index 8aaed06c84c3..13cc7ddbb0c3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/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 PartnerStackSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.partnerstack import (
+ PartnerStackResumeConfig,
+ partnerstack_source,
+ validate_credentials as _validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.settings import (
+ ENDPOINTS,
+ PARTNERSTACK_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PartnerStackSource(SimpleSource[PartnerStackSourceConfig]):
+class PartnerStackSource(ResumableSource[PartnerStackSourceConfig, PartnerStackResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PARTNERSTACK
@@ -24,7 +47,95 @@ class PartnerStackSource(SimpleSource[PartnerStackSourceConfig]):
name=SchemaExternalDataSourceType.PARTNER_STACK,
category=DataWarehouseSourceCategory.SALES,
label="PartnerStack",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your PartnerStack Vendor API keys to pull your partner program data into the PostHog Data warehouse.
+
+You can find your **public key** and **private key** under **Settings → Integrations → PartnerStack API Keys** in [PartnerStack](https://dash.partnerstack.com/). The keys grant read access to your partnerships, customers, deals, and leads.
+""",
iconPath="/static/services/partnerstack.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/partnerstack",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="public_key",
+ label="Public key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="private_key",
+ label="Private key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.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.partnerstack.com": "Your PartnerStack API keys are invalid or have been revoked. Generate a new key pair under Settings → Integrations → PartnerStack API Keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.partnerstack.com": "Your PartnerStack API keys do not have access to this data. Check the keys' permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: PartnerStackSourceConfig,
+ 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 don't ship incremental sync for PartnerStack, so
+ # there is no cursor to advance across syncs.
+ 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: PartnerStackSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The key pair is account-wide, so a single probe validates access to every schema.
+ return _validate_credentials(config.public_key, config.private_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PartnerStackResumeConfig]:
+ return ResumableSourceManager[PartnerStackResumeConfig](inputs, PartnerStackResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PartnerStackSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PartnerStackResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in PARTNERSTACK_ENDPOINTS:
+ raise ValueError(f"Unknown PartnerStack schema '{inputs.schema_name}'")
+
+ return partnerstack_source(
+ public_key=config.public_key,
+ private_key=config.private_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/partnerstack/tests/test_partnerstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/tests/test_partnerstack.py
new file mode 100644
index 000000000000..1fa18bb693e7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/tests/test_partnerstack.py
@@ -0,0 +1,255 @@
+import base64
+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.partnerstack import partnerstack
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.partnerstack import (
+ PAGE_SIZE,
+ PartnerStackResumeConfig,
+ PartnerStackRetryableError,
+ _headers,
+ check_access,
+ get_rows,
+ partnerstack_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.settings import (
+ ENDPOINTS,
+ PARTNERSTACK_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = partnerstack._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PartnerStackResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PartnerStackResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PartnerStackResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PartnerStackResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestHeaders:
+ def test_builds_basic_auth_header(self) -> None:
+ headers = _headers("pub", "priv")
+ expected = base64.b64encode(b"pub:priv").decode("ascii")
+ assert headers["Authorization"] == f"Basic {expected}"
+ assert headers["Accept"] == "application/json"
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str | None, tuple[list[dict], bool]],
+ endpoint: str = "partnerships",
+ ) -> list[dict]:
+ def fake_fetch(
+ session: Any, path: str, starting_after: str | None, limit: int, logger: Any
+ ) -> tuple[list[dict], bool]:
+ return pages[starting_after]
+
+ monkeypatch.setattr(partnerstack, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(partnerstack, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ public_key="pub",
+ private_key="priv",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_no_more_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([{"key": "a"}, {"key": "b"}], False)})
+ assert rows == [{"key": "a"}, {"key": "b"}]
+ # has_more is false, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_cursor_until_has_more_false(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ None: ([{"key": "a"}, {"key": "b"}], True),
+ "b": ([{"key": "c"}], False),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"key": "a"}, {"key": "b"}, {"key": "c"}]
+ # State is saved after the first page (cursor advances to the last key "b"), then we stop.
+ assert [s.starting_after for s in manager.saved] == ["b"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(PartnerStackResumeConfig(starting_after="b"))
+ # The initial (cursor=None) page must never be fetched on resume.
+ pages: dict[str | None, tuple[list[dict], bool]] = {"b": ([{"key": "c"}], False)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"key": "c"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([], False)})
+ assert rows == []
+ assert manager.saved == []
+
+ def test_stops_when_last_object_missing_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ # has_more is true but the last object has no `key`, so we can't advance and must stop.
+ rows = self._collect(manager, monkeypatch, {None: ([{"no_key": 1}], True)})
+ assert rows == [{"no_key": 1}]
+ 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 {"data": {"items": [], "has_more": False}}
+ 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(PartnerStackRetryableError):
+ _fetch_page_unwrapped(session, "/partnerships", None, 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, "/partnerships", None, PAGE_SIZE, MagicMock())
+
+ def test_success_returns_items_and_has_more(self) -> None:
+ body = {"data": {"items": [{"key": "a"}], "has_more": True}}
+ session = self._session_returning(200, body)
+ items, has_more = _fetch_page_unwrapped(session, "/partnerships", None, PAGE_SIZE, MagicMock())
+ assert items == [{"key": "a"}]
+ assert has_more is True
+
+ def test_missing_has_more_defaults_to_false(self) -> None:
+ body = {"data": {"items": [{"key": "a"}]}}
+ session = self._session_returning(200, body)
+ _, has_more = _fetch_page_unwrapped(session, "/partnerships", None, PAGE_SIZE, MagicMock())
+ assert has_more is False
+
+ @parameterized.expand(
+ [
+ ("bare_list", [{"key": "a"}]),
+ ("missing_data", {"items": []}),
+ ("data_not_dict", {"data": []}),
+ ]
+ )
+ def test_unexpected_envelope_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(PartnerStackRetryableError):
+ _fetch_page_unwrapped(session, "/partnerships", None, PAGE_SIZE, MagicMock())
+
+ def test_non_list_items_is_retryable(self) -> None:
+ session = self._session_returning(200, {"data": {"items": "nope", "has_more": False}})
+ with pytest.raises(PartnerStackRetryableError):
+ _fetch_page_unwrapped(session, "/partnerships", None, PAGE_SIZE, MagicMock())
+
+ def test_request_omits_cursor_on_first_page(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE}
+
+ def test_request_includes_cursor_when_set(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/customers", "abc", PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE, "starting_after": "abc"}
+
+
+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
+
+ @parameterized.expand(
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "PartnerStack 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
+ session = self._session(response)
+ with patch.object(partnerstack, "make_tracked_session", lambda **kwargs: session):
+ assert check_access("pub", "priv") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(partnerstack, "make_tracked_session", lambda **kwargs: session):
+ status, message = check_access("pub", "priv")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid PartnerStack API keys"),
+ (403, False, "Invalid PartnerStack API keys"),
+ (500, False, "PartnerStack 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
+ session = self._session(response)
+ with patch.object(partnerstack, "make_tracked_session", lambda **kwargs: session):
+ assert validate_credentials("pub", "priv") == (expected_valid, expected_message)
+
+
+class TestPartnerStackSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = partnerstack_source(
+ public_key="pub",
+ private_key="priv",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["key"]
+ # 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_key_primary_key(self) -> None:
+ assert all(config.primary_keys == ["key"] for config in PARTNERSTACK_ENDPOINTS.values())
+ assert set(PARTNERSTACK_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/tests/test_partnerstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/tests/test_partnerstack_source.py
new file mode 100644
index 000000000000..4e7cae051767
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/tests/test_partnerstack_source.py
@@ -0,0 +1,133 @@
+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 PartnerStackSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.partnerstack import (
+ PartnerStackResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.source import PartnerStackSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestPartnerStackSource:
+ def setup_method(self) -> None:
+ self.source = PartnerStackSource()
+ self.team_id = 123
+ self.config = PartnerStackSourceConfig(public_key="pub", private_key="priv")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.PARTNERSTACK
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "PartnerStack"
+ assert config.label == "PartnerStack"
+ 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/partnerstack"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["public_key", "private_key"]
+
+ def test_both_key_fields_are_secret_passwords(self) -> None:
+ config = self.source.get_source_config
+ for name in ("public_key", "private_key"):
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == name)
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # Both fields are secret keys; 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=["customers"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "customers"
+
+ 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(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.partnerstack.com/api/v2/partnerships?limit=250",),
+ ("403 Client Error: Forbidden for url: https://api.partnerstack.com/api/v2/customers?limit=250",),
+ ]
+ )
+ 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)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.partnerstack.com/api/v2/partnerships",),
+ ("429 Client Error: Too Many Requests for url: https://api.partnerstack.com/api/v2/customers",),
+ ]
+ )
+ 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)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.source._validate_credentials"
+ )
+ def test_validate_credentials_delegates(self, mock_validate: mock.MagicMock) -> None:
+ # The source method is a thin wrapper; the status-to-message matrix is covered in
+ # test_partnerstack.py::TestCheckAccess. Here we only guard the wiring: the key pair is
+ # forwarded in order and the module function's result is returned unchanged.
+ mock_validate.return_value = (False, "Invalid PartnerStack API keys")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("pub", "priv")
+ assert result == (False, "Invalid PartnerStack API keys")
+
+ 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 PartnerStackResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.partnerstack.source.partnerstack_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "partnerships"
+ 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["public_key"] == "pub"
+ assert kwargs["private_key"] == "priv"
+ assert kwargs["endpoint"] == "partnerships"
+ 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 PartnerStack schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)