: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 pendo import source (#61657)
Tom Owersa0ca0bd50bbf
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 7adfad885824..c45604752afd 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -100,6 +100,7 @@ the row lists both.| omnisend | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ |+| pendo | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ || pipedrive | HTTP | requests | ✅ || plain | HTTP | requests | ✅ |diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 8fc22b09d9d8..fe68e2b07ad3 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -643,7 +643,8 @@ class PayPalSourceConfig(config.Config):@config.configclass PendoSourceConfig(config.Config):- pass+ integration_key: str+ region: Literal["us", "us1", "eu", "jp", "au"] = config.value(default="us")@config.configdiff --git a/posthog/temporal/data_imports/sources/pendo/pendo.py b/posthog/temporal/data_imports/sources/pendo/pendo.pynew file mode 100644index 000000000000..0bef8196ef0b--- /dev/null+++ b/posthog/temporal/data_imports/sources/pendo/pendo.py@@ -0,0 +1,219 @@+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.pendo.settings import DEFAULT_REGION, PENDO_ENDPOINTS, PENDO_REGION_BASE_URLS++AGGREGATION_PATH = "/api/v1/aggregation"+# Pendo's aggregation endpoint isn't a bulk export tool (4 GB / 5-minute caps), so we page+# through it in bounded chunks via skip/limit pipeline stages.+AGGREGATION_PAGE_SIZE = 5000+# List endpoints return the whole array in one response; chunk it so we don't hold an+# unbounded list in memory and so resume state can advance per chunk.+LIST_CHUNK_SIZE = 1000+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class PendoRetryableError(Exception):+ pass+++class PendoResumeConfig:+ # Number of rows already yielded for this schema; on resume we skip past them.+ offset: int = 0+++def get_base_url(region: Optional[str]) -> str:+ return PENDO_REGION_BASE_URLS.get((region or DEFAULT_REGION).lower(), PENDO_REGION_BASE_URLS[DEFAULT_REGION])+++def _get_headers(integration_key: str) -> dict[str, str]:+ return {+ "x-pendo-integration-key": integration_key,+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++@retry(+ retry=retry_if_exception_type((PendoRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _request(+ session: requests.Session,+ method: str,+ url: str,+ logger: FilteringBoundLogger,+ **kwargs: Any,+) -> requests.Response:+ response = session.request(method, url, timeout=REQUEST_TIMEOUT_SECONDS, **kwargs)++ if response.status_code == 429 or response.status_code >= 500:+ raise PendoRetryableError(f"Pendo API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Cap the body so an HTML error page (e.g. a WAF 503) can't blow up the log line.+ logger.error(f"Pendo API error: status={response.status_code}, body={response.text[:500]!r}, url={url}")+ response.raise_for_status()++ return response+++def validate_credentials(integration_key: str, region: Optional[str]) -> tuple[bool, str | None]:+ # Probe a real list endpoint we also sync: a valid key returns 200 (even with an empty+ # array), a bad/insufficient key returns 401/403.+ url = f"{get_base_url(region)}/api/v1/page"+ try:+ # `redact_values` masks the integration key from logged URLs and captured HTTP samples.+ session = make_tracked_session(redact_values=(integration_key,))+ response = session.get(url, headers=_get_headers(integration_key), timeout=10)+ except (requests.RequestException, OSError):+ return False, "Could not reach Pendo. Check your network connection and the selected region."++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Pendo integration key, or the key is missing the required permissions."+ return False, f"Pendo returned an unexpected status code: {response.status_code}"+++def _iter_list_endpoint(+ session: requests.Session,+ base_url: str,+ path: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PendoResumeConfig],+ start_offset: int,+) -> Iterator[list[dict[str, Any]]]:+ # `expand=*` returns objects across every app in a multi-app subscription rather than+ # just the default app.+ url = f"{base_url}{path}?expand=*"+ response = _request(session, "GET", url, logger)+ data = response.json()+ items: list[dict[str, Any]] = data if isinstance(data, list) else data.get("results", [])++ offset = start_offset+ for i in range(offset, len(items), LIST_CHUNK_SIZE):+ chunk = items[i : i + LIST_CHUNK_SIZE]+ yield chunk+ offset += len(chunk)+ resumable_source_manager.save_state(PendoResumeConfig(offset=offset))+++def _iter_aggregation(+ session: requests.Session,+ base_url: str,+ aggregation_source: str,+ sort_field: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PendoResumeConfig],+ start_offset: int,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{base_url}{AGGREGATION_PATH}"+ offset = start_offset++ while True:+ body = {+ "response": {"mimeType": "application/json"},+ "request": {+ "requestId": f"posthog-{aggregation_source}",+ "pipeline": [+ {"source": {aggregation_source: None}},+ # Sort on a stable id so skip/limit paging is deterministic across requests.+ {"sort": [sort_field]},+ {"skip": offset},+ {"limit": AGGREGATION_PAGE_SIZE},+ ],+ },+ }+ response = _request(session, "POST", url, logger, json=body)+ data = response.json()+ rows: list[dict[str, Any]] = data.get("results", []) if isinstance(data, dict) else data++ if not rows:+ break++ yield rows+ offset += len(rows)+ resumable_source_manager.save_state(PendoResumeConfig(offset=offset))++ if len(rows) < AGGREGATION_PAGE_SIZE:+ break+++def get_rows(+ integration_key: str,+ region: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PendoResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PENDO_ENDPOINTS[endpoint]+ base_url = get_base_url(region)+ # `redact_values` masks the integration key from logged URLs and captured HTTP samples.+ session = make_tracked_session(headers=_get_headers(integration_key), redact_values=(integration_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_offset = resume.offset if resume else 0+ if start_offset:+ logger.debug(f"Pendo: resuming endpoint={endpoint} from offset={start_offset}")++ if config.is_aggregation:+ if config.aggregation_source is None:+ raise ValueError(f"Endpoint '{endpoint}' is marked as aggregation but has no aggregation_source")+ yield from _iter_aggregation(+ session,+ base_url,+ config.aggregation_source,+ config.primary_keys[0],+ logger,+ resumable_source_manager,+ start_offset,+ )+ else:+ if config.path is None:+ raise ValueError(f"Endpoint '{endpoint}' is not an aggregation but has no path")+ yield from _iter_list_endpoint(+ session,+ base_url,+ config.path,+ logger,+ resumable_source_manager,+ start_offset,+ )+++def pendo_source(+ integration_key: str,+ region: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PendoResumeConfig],+) -> SourceResponse:+ config = PENDO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ integration_key=integration_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ # No source-level partitioning: Pendo timestamps are epoch-milliseconds, which the+ # datetime partitioner would misread as epoch-seconds, and the aggregation rows carry+ # no stable created_at field. Ship unpartitioned full-refresh tables.+ )diff --git a/posthog/temporal/data_imports/sources/pendo/settings.py b/posthog/temporal/data_imports/sources/pendo/settings.pynew file mode 100644index 000000000000..f2f4fd3b7059--- /dev/null+++ b/posthog/temporal/data_imports/sources/pendo/settings.py@@ -0,0 +1,51 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField++# Pendo hosts each subscription in a region-specific data center and the integration key is+# region-scoped, so the base URL has to match where the subscription lives.+# https://support.pendo.io/hc/en-us/articles/22832528657179-Global-data-hosting+PENDO_REGION_BASE_URLS: dict[str, str] = {+ "us": "https://app.pendo.io",+ "us1": "https://us1.app.pendo.io",+ "eu": "https://app.eu.pendo.io",+ "jp": "https://app.jpn.pendo.io",+ "au": "https://app.au.pendo.io",+}++DEFAULT_REGION = "us"+++@dataclass+class PendoEndpointConfig:+ name: str+ primary_keys: list[str]+ # GET list endpoints (feature/page/guide) set `path`; aggregation endpoints+ # (visitors/accounts) set `aggregation_source` and POST to /api/v1/aggregation.+ path: Optional[str] = None+ aggregation_source: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)++ @property+ def is_aggregation(self) -> bool:+ return self.aggregation_source is not None+++# All endpoints are full refresh: Pendo's list endpoints expose no server-side timestamp+# filter, and the aggregation endpoint's time filters only apply to event sources, not the+# visitor/account metadata we pull here. A client-side cursor would still read every row each+# run, so it would not be a genuine incremental sync.+PENDO_ENDPOINTS: dict[str, PendoEndpointConfig] = {+ "features": PendoEndpointConfig(name="features", path="/api/v1/feature", primary_keys=["id"]),+ "pages": PendoEndpointConfig(name="pages", path="/api/v1/page", primary_keys=["id"]),+ "guides": PendoEndpointConfig(name="guides", path="/api/v1/guide", primary_keys=["id"]),+ "visitors": PendoEndpointConfig(name="visitors", aggregation_source="visitors", primary_keys=["visitorId"]),+ "accounts": PendoEndpointConfig(name="accounts", aggregation_source="accounts", primary_keys=["accountId"]),+}++ENDPOINTS = tuple(PENDO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PENDO_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/pendo/source.py b/posthog/temporal/data_imports/sources/pendo/source.pyindex 16276e3c4849..86e5c072f2e8 100644--- a/posthog/temporal/data_imports/sources/pendo/source.py+++ b/posthog/temporal/data_imports/sources/pendo/source.py@@ -1,19 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import PendoSourceConfig+from posthog.temporal.data_imports.sources.pendo.pendo import (+ PendoResumeConfig,+ pendo_source,+ validate_credentials as validate_pendo_credentials,+)+from posthog.temporal.data_imports.sources.pendo.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PendoSource(SimpleSource[PendoSourceConfig]):+class PendoSource(ResumableSource[PendoSourceConfig, PendoResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PENDO@@ -23,7 +37,96 @@ class PendoSource(SimpleSource[PendoSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.PENDO,label="Pendo",+ caption="""Enter your Pendo integration key to pull your Pendo data into the PostHog Data warehouse.++Create an integration key in Pendo under **Settings > Integrations > Integration Keys** (only Pendo admins can view these). The key is specific to your subscription's data region, so make sure the region below matches the domain you log in with.+""",iconPath="/static/services/pendo.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/pendo",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="integration_key",+ label="Integration key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Pendo integration key",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Data region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (app.pendo.io)", value="us"),+ SourceFieldSelectConfigOption(label="US1 (us1.app.pendo.io)", value="us1"),+ SourceFieldSelectConfigOption(label="EU (app.eu.pendo.io)", value="eu"),+ SourceFieldSelectConfigOption(label="Japan (app.jpn.pendo.io)", value="jp"),+ SourceFieldSelectConfigOption(label="Australia (app.au.pendo.io)", value="au"),+ ],+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: PendoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh: Pendo exposes no server-side timestamp filter for+ # this metadata, so neither incremental nor append would avoid re-reading every row.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ 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: PendoSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_pendo_credentials(config.integration_key, config.region)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": (+ "Your Pendo integration key is invalid or has been revoked. Generate a new key in Pendo "+ "(Settings > Integrations > Integration Keys) and reconnect."+ ),+ "403 Client Error": (+ "Your Pendo integration key is missing the required permissions. Make sure it has read "+ "access (write access is needed for the aggregation endpoint) and reconnect."+ ),+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PendoResumeConfig]:+ return ResumableSourceManager[PendoResumeConfig](inputs, PendoResumeConfig)++ def source_for_pipeline(+ self,+ config: PendoSourceConfig,+ resumable_source_manager: ResumableSourceManager[PendoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return pendo_source(+ integration_key=config.integration_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/pendo/tests/test_pendo.py b/posthog/temporal/data_imports/sources/pendo/tests/test_pendo.pynew file mode 100644index 000000000000..5c998f2d2a14--- /dev/null+++ b/posthog/temporal/data_imports/sources/pendo/tests/test_pendo.py@@ -0,0 +1,235 @@+from typing import Any++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.pendo import pendo as pendo_module+from posthog.temporal.data_imports.sources.pendo.pendo import (+ PendoResumeConfig,+ get_base_url,+ get_rows,+ pendo_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.pendo.settings import ENDPOINTS, PENDO_ENDPOINTS++PENDO_PATH = "posthog.temporal.data_imports.sources.pendo.pendo"+++def _make_manager(resume_state: PendoResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _resp(json_data: Any, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = json_data+ resp.status_code = status+ resp.ok = 200 <= status < 300+ return resp+++class TestGetBaseUrl:+ @pytest.mark.parametrize(+ "region, expected",+ [+ ("us", "https://app.pendo.io"),+ ("US", "https://app.pendo.io"),+ ("us1", "https://us1.app.pendo.io"),+ ("eu", "https://app.eu.pendo.io"),+ ("jp", "https://app.jpn.pendo.io"),+ ("au", "https://app.au.pendo.io"),+ (None, "https://app.pendo.io"),+ ("not-a-region", "https://app.pendo.io"),+ ],+ )+ def test_region_maps_to_base_url(self, region, expected):+ assert get_base_url(region) == expected+++class TestHeaders:+ def test_headers_carry_integration_key(self):+ headers = pendo_module._get_headers("secret-key")+ assert headers["x-pendo-integration-key"] == "secret-key"+ assert headers["Content-Type"] == "application/json"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid, expected_substr",+ [+ (200, True, None),+ (401, False, "Invalid Pendo integration key"),+ (403, False, "Invalid Pendo integration key"),+ (500, False, "unexpected status code"),+ ],+ )+ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_status_mapping(self, mock_session, status, expected_valid, expected_substr):+ mock_session.return_value.get.return_value = _resp({}, status)++ is_valid, message = validate_credentials("key", "us")++ assert is_valid is expected_valid+ if expected_substr is None:+ assert message is None+ else:+ assert message is not None+ assert expected_substr in message++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_probes_the_page_endpoint_for_the_region(self, mock_session):+ mock_session.return_value.get.return_value = _resp({}, 200)++ validate_credentials("key", "eu")++ assert mock_session.return_value.get.call_args.args[0] == "https://app.eu.pendo.io/api/v1/page"++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_swallows_network_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")++ is_valid, message = validate_credentials("key", "us")++ assert is_valid is False+ assert message is not None++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_redacts_the_integration_key(self, mock_session):+ mock_session.return_value.get.return_value = _resp({}, 200)++ validate_credentials("secret-key", "us")++ assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)+++class TestGetRowsListEndpoint:+ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_fetches_list_endpoint_with_expand(self, mock_session):+ items = [{"id": "a"}, {"id": "b"}]+ mock_session.return_value.request.return_value = _resp(items)+ manager = _make_manager()++ batches = list(get_rows("key", "us", "features", mock.MagicMock(), manager))++ assert [row for batch in batches for row in batch] == items+ assert mock_session.return_value.request.call_count == 1+ method, url = mock_session.return_value.request.call_args.args[:2]+ assert method == "GET"+ assert url == "https://app.pendo.io/api/v1/feature?expand=*"+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].offset == 2+ # The integration key is masked from logged URLs and captured HTTP samples.+ assert mock_session.call_args.kwargs["redact_values"] == ("key",)++ @mock.patch(f"{PENDO_PATH}.LIST_CHUNK_SIZE", 2)+ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_chunks_a_large_list_and_advances_offset(self, mock_session):+ items = [{"id": i} for i in range(5)]+ mock_session.return_value.request.return_value = _resp(items)+ manager = _make_manager()++ batches = list(get_rows("key", "us", "pages", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [2, 2, 1]+ offsets = [call.args[0].offset for call in manager.save_state.call_args_list]+ assert offsets == [2, 4, 5]++ @mock.patch(f"{PENDO_PATH}.LIST_CHUNK_SIZE", 2)+ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_resumes_from_saved_offset(self, mock_session):+ items = [{"id": i} for i in range(5)]+ mock_session.return_value.request.return_value = _resp(items)+ manager = _make_manager(PendoResumeConfig(offset=4))++ batches = list(get_rows("key", "us", "pages", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == [4]++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_handles_results_wrapper_object(self, mock_session):+ mock_session.return_value.request.return_value = _resp({"results": [{"id": "x"}]})+ manager = _make_manager()++ batches = list(get_rows("key", "us", "guides", mock.MagicMock(), manager))++ assert [row for batch in batches for row in batch] == [{"id": "x"}]+++class TestGetRowsAggregation:+ @mock.patch(f"{PENDO_PATH}.AGGREGATION_PAGE_SIZE", 2)+ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_paginates_via_skip_and_limit(self, mock_session):+ page1 = {"results": [{"visitorId": "1"}, {"visitorId": "2"}]}+ page2 = {"results": [{"visitorId": "3"}]}+ mock_session.return_value.request.side_effect = [_resp(page1), _resp(page2)]+ manager = _make_manager()++ batches = list(get_rows("key", "us", "visitors", mock.MagicMock(), manager))++ assert [row["visitorId"] for batch in batches for row in batch] == ["1", "2", "3"]++ calls = mock_session.return_value.request.call_args_list+ method, url = calls[0].args[:2]+ assert method == "POST"+ assert url == "https://app.pendo.io/api/v1/aggregation"++ first_pipeline = calls[0].kwargs["json"]["request"]["pipeline"]+ assert {"source": {"visitors": None}} in first_pipeline+ assert {"sort": ["visitorId"]} in first_pipeline+ assert {"skip": 0} in first_pipeline+ assert {"limit": 2} in first_pipeline++ second_pipeline = calls[1].kwargs["json"]["request"]["pipeline"]+ assert {"skip": 2} in second_pipeline++ offsets = [call.args[0].offset for call in manager.save_state.call_args_list]+ assert offsets == [2, 3]++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_accounts_source_sorts_on_account_id(self, mock_session):+ mock_session.return_value.request.return_value = _resp({"results": []})+ manager = _make_manager()++ list(get_rows("key", "us", "accounts", mock.MagicMock(), manager))++ pipeline = mock_session.return_value.request.call_args.kwargs["json"]["request"]["pipeline"]+ assert {"source": {"accounts": None}} in pipeline+ assert {"sort": ["accountId"]} in pipeline++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_empty_first_page_stops_without_saving_state(self, mock_session):+ mock_session.return_value.request.return_value = _resp({"results": []})+ manager = _make_manager()++ batches = list(get_rows("key", "us", "visitors", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch(f"{PENDO_PATH}.make_tracked_session")+ def test_resumes_aggregation_from_saved_offset(self, mock_session):+ mock_session.return_value.request.return_value = _resp({"results": []})+ manager = _make_manager(PendoResumeConfig(offset=10))++ list(get_rows("key", "us", "visitors", mock.MagicMock(), manager))++ pipeline = mock_session.return_value.request.call_args.kwargs["json"]["request"]["pipeline"]+ assert {"skip": 10} in pipeline+++class TestPendoSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = PENDO_ENDPOINTS[endpoint]+ response = pendo_source("key", "us", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ # Pendo timestamps are epoch-ms, so we intentionally ship unpartitioned full-refresh tables.+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/pendo/tests/test_pendo_source.py b/posthog/temporal/data_imports/sources/pendo/tests/test_pendo_source.pynew file mode 100644index 000000000000..0bb1cad03a75--- /dev/null+++ b/posthog/temporal/data_imports/sources/pendo/tests/test_pendo_source.py@@ -0,0 +1,132 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import PendoSourceConfig+from posthog.temporal.data_imports.sources.pendo.pendo import PendoResumeConfig+from posthog.temporal.data_imports.sources.pendo.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.pendo.source import PendoSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestPendoSource:+ def setup_method(self):+ self.source = PendoSource()+ self.team_id = 123+ self.config = PendoSourceConfig(integration_key="integration-key", region="eu")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PENDO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Pendo"+ assert config.label == "Pendo"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/pendo.png"++ input_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert input_names == ["integration_key"]++ select_names = [f.name for f in config.fields if isinstance(f, SourceFieldSelectConfig)]+ assert select_names == ["region"]++ def test_integration_key_field_is_secret_password(self):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "integration_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_region_field_offers_every_data_region(self):+ config = self.source.get_source_config+ region = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")++ assert {option.value for option in region.options} == {"us", "us1", "eu", "jp", "au"}+ assert region.defaultValue == "us"+ assert region.required is True++ def test_get_schemas_are_all_full_refresh(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert all(schema.supports_incremental is False for schema in schemas)+ assert all(schema.supports_append is False for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["visitors"])+ assert len(schemas) == 1+ assert schemas[0].name == "visitors"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://app.pendo.io/api/v1/page",+ "403 Client Error: Forbidden for url: https://app.pendo.io/api/v1/aggregation",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://app.pendo.io/api/v1/page",+ "500 Server Error for url: https://app.pendo.io/api/v1/aggregation",+ ],+ )+ def test_non_retryable_errors_do_not_match_retryable(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "validate_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ (+ (False, "Invalid Pendo integration key, or the key is missing the required permissions."),+ False,+ "Invalid Pendo integration key, or the key is missing the required permissions.",+ ),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.pendo.source.validate_pendo_credentials")+ def test_validate_credentials(self, mock_validate, validate_return, expected_valid, expected_message):+ mock_validate.return_value = validate_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.integration_key, self.config.region)++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PendoResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.pendo.source.pendo_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_pendo_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "visitors"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_pendo_source.assert_called_once()+ kwargs = mock_pendo_source.call_args.kwargs+ assert kwargs["integration_key"] == "integration-key"+ assert kwargs["region"] == "eu"+ assert kwargs["endpoint"] == "visitors"+ assert kwargs["resumable_source_manager"] is manager