: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 ortto import source (#62993)
Tom Owerse2db13ab6be3
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 43fd6e5aff18..e8cb9ac51a85 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -125,6 +125,7 @@ the row lists both.| okta | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |+| ortto | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || optimizely | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ |@@ -280,7 +281,6 @@ doesn't conflict with concurrent PRs.- oracle- oracle_ebs- oracle_fusion-- ortto- outbrain- outreach- pagerdutydiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex af395d903d59..2ea5af6a75d7 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -964,7 +964,8 @@ class OracleSourceConfig(config.Config):@config.configclass OrttoSourceConfig(config.Config):- pass+ api_key: str+ region: Literal["global", "au", "eu"] = config.value(default="global")@config.configdiff --git a/posthog/temporal/data_imports/sources/ortto/ortto.py b/posthog/temporal/data_imports/sources/ortto/ortto.pynew file mode 100644index 000000000000..db40b9cb85a9--- /dev/null+++ b/posthog/temporal/data_imports/sources/ortto/ortto.py@@ -0,0 +1,171 @@+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.ortto.settings import ORTTO_ENDPOINTS, ORTTO_REGION_HOSTS++REQUEST_TIMEOUT_SECONDS = 60+# Plan-dependent rate limits (10-30 req/s) plus per-IP caps; back off on 429.+MAX_RETRY_ATTEMPTS = 5+++class OrttoRetryableError(Exception):+ pass+++class OrttoResumeConfig:+ # Pagination position within a single full-refresh sync. `cursor_id` pins+ # the result set for the people/accounts endpoints; offset-only endpoints+ # leave it None.+ next_offset: int+ cursor_id: Optional[str] = None+++def _get_session(api_key: str) -> requests.Session:+ return make_tracked_session(headers={"X-Api-Key": api_key}, redact_values=(api_key,))+++def _base_url(region: str) -> str:+ return ORTTO_REGION_HOSTS.get(region, ORTTO_REGION_HOSTS["global"])+++def _flatten_custom_field(entry: dict[str, Any]) -> dict[str, Any]:+ # Person custom fields arrive wrapped ({"field": {...}, "tracked_value": ...});+ # account custom fields arrive flat.+ if isinstance(entry.get("field"), dict):+ return {**entry["field"], "tracked_value": entry.get("tracked_value")}+ return entry+++def validate_credentials(region: str, api_key: str) -> bool:+ """Confirm the API key works with a cheap custom-field listing probe."""+ try:+ response = _get_session(api_key).post(+ f"{_base_url(region)}/v1/person/custom-field/get",+ json={},+ timeout=15,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ region: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OrttoResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ORTTO_ENDPOINTS[endpoint]+ session = _get_session(api_key)+ base_url = _base_url(region)++ @retry(+ retry=retry_if_exception_type((OrttoRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def fetch(path: str, body: dict[str, Any]) -> Any:+ response = session.post(f"{base_url}{path}", json=body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise OrttoRetryableError(f"Ortto API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Ortto API error: status={response.status_code}, body={response.text[:500]}, path={path}")+ response.raise_for_status()++ return response.json()++ def extract_items(data: Any) -> list[dict[str, Any]]:+ if config.data_key is not None:+ items = data.get(config.data_key) if isinstance(data, dict) else None+ else:+ items = data+ return items if isinstance(items, list) else []++ if config.pagination == "none":+ data = fetch(config.path, {})+ items = extract_items(data)+ if config.data_key == "fields":+ items = [_flatten_custom_field(item) for item in items]+ if items:+ yield items+ return++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.next_offset if resume_config is not None else 0+ cursor_id = resume_config.cursor_id if resume_config is not None else None+ if resume_config is not None:+ logger.debug(f"Ortto: resuming {endpoint} from offset {offset}")++ # Every retrieval endpoint is a POST with pagination in the JSON body.+ fields: Optional[list[str]] = None+ if config.builtin_fields is not None:+ fields = list(config.builtin_fields)+ if config.custom_fields_path is not None:+ custom_fields_body = fetch(config.custom_fields_path, {})+ custom_entries = custom_fields_body.get("fields") if isinstance(custom_fields_body, dict) else None+ for entry in custom_entries or []:+ field_id = _flatten_custom_field(entry).get("id")+ if field_id:+ fields.append(field_id)++ while True:+ body: dict[str, Any] = {"limit": config.page_size, "offset": offset}+ if fields is not None:+ body["fields"] = fields+ if cursor_id is not None:+ body["cursor_id"] = cursor_id++ data = fetch(config.path, body)+ items = extract_items(data)++ if items:+ yield items++ if config.pagination == "cursor":+ if not isinstance(data, dict) or not data.get("has_more"):+ break+ offset = data.get("next_offset", offset + len(items))+ cursor_id = data.get("cursor_id") or cursor_id+ else:+ if len(items) < config.page_size:+ break+ offset += len(items)++ # Save state AFTER yielding so a crash re-yields the in-flight page+ # (merge dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(OrttoResumeConfig(next_offset=offset, cursor_id=cursor_id))+++def ortto_source(+ region: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OrttoResumeConfig],+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ region=region,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=["id"],+ partition_count=1,+ partition_size=1,+ )diff --git a/posthog/temporal/data_imports/sources/ortto/settings.py b/posthog/temporal/data_imports/sources/ortto/settings.pynew file mode 100644index 000000000000..2bd42edfa0f2--- /dev/null+++ b/posthog/temporal/data_imports/sources/ortto/settings.py@@ -0,0 +1,103 @@+from dataclasses import dataclass+from typing import Literal++from products.data_warehouse.backend.types import IncrementalField++OrttoPaginationMode = Literal["cursor", "offset", "none"]++# Region-specific API hosts — an API key only works against its instance's region.+ORTTO_REGION_HOSTS: dict[str, str] = {+ "global": "https://api.ap3api.com",+ "au": "https://api.au.ap3api.com",+ "eu": "https://api.eu.ap3api.com",+}++# Built-in person field IDs documented for /v1/person/get. Custom fields+# (str:cm:*, int:cm:*, ...) are discovered at runtime and appended.+PERSON_BUILTIN_FIELDS: list[str] = [+ "str::first",+ "str::last",+ "str::email",+ "str::postal",+ "str::ei",+ "phn::phone",+ "geo::city",+ "geo::region",+ "geo::country",+ "bol::gdpr",+ "bol::p",+ "bol::sp",+ "dtz::b",+ "u4s::t",+ "idt::o",+]++# Built-in account (organization) field IDs documented for /v1/accounts/get.+ACCOUNT_BUILTIN_FIELDS: list[str] = [+ "str:o:name",+ "str:o:website",+ "str:o:industry",+ "int:o:employees",+]+++@dataclass+class OrttoEndpointConfig:+ path: str+ # Key holding the row list in the response body; None when the body is the list.+ data_key: str | None+ pagination: OrttoPaginationMode+ page_size: int = 500+ # Built-in field IDs to request; merged with runtime-discovered custom+ # fields from this custom-field listing path.+ builtin_fields: list[str] | None = None+ custom_fields_path: str | None = None+++# Every Ortto retrieval endpoint is a POST with pagination in the JSON body.+# There is no server-side updated-since filter (Fivetran's connector re-imports+# every table per sync for the same reason), so all streams are full refresh;+# resume state persists the pagination position within a single sync.+ORTTO_ENDPOINTS: dict[str, OrttoEndpointConfig] = {+ "people": OrttoEndpointConfig(+ path="/v1/person/get",+ data_key="contacts",+ pagination="cursor",+ builtin_fields=PERSON_BUILTIN_FIELDS,+ custom_fields_path="/v1/person/custom-field/get",+ ),+ "accounts": OrttoEndpointConfig(+ path="/v1/accounts/get",+ data_key="accounts",+ pagination="cursor",+ builtin_fields=ACCOUNT_BUILTIN_FIELDS,+ custom_fields_path="/v1/accounts/custom-field/get",+ ),+ "audiences": OrttoEndpointConfig(+ path="/v1/audiences/get",+ data_key=None,+ pagination="offset",+ # Documented max page size for audiences.+ page_size=40,+ ),+ "tags": OrttoEndpointConfig(+ path="/v1/tags/get",+ data_key=None,+ pagination="none",+ ),+ "person_custom_fields": OrttoEndpointConfig(+ path="/v1/person/custom-field/get",+ data_key="fields",+ pagination="none",+ ),+ "account_custom_fields": OrttoEndpointConfig(+ path="/v1/accounts/custom-field/get",+ data_key="fields",+ pagination="none",+ ),+}++ENDPOINTS = tuple(ORTTO_ENDPOINTS.keys())++# No endpoint exposes a server-side updated-since filter, so nothing is honestly incremental.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/posthog/temporal/data_imports/sources/ortto/source.py b/posthog/temporal/data_imports/sources/ortto/source.pyindex 10b4d5965485..1c250594030b 100644--- a/posthog/temporal/data_imports/sources/ortto/source.py+++ b/posthog/temporal/data_imports/sources/ortto/source.py@@ -1,29 +1,125 @@-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 OrttoSourceConfig+from posthog.temporal.data_imports.sources.ortto.ortto import (+ OrttoResumeConfig,+ ortto_source,+ validate_credentials as validate_ortto_credentials,+)+from posthog.temporal.data_imports.sources.ortto.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class OrttoSource(SimpleSource[OrttoSourceConfig]):+class OrttoSource(ResumableSource[OrttoSourceConfig, OrttoResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ORTTO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Ortto authentication failed. Please check your API key (and that it matches the selected region).",+ "403 Client Error: Forbidden for url": "Ortto denied access. Please check your API key's permissions.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ORTTO,label="Ortto",+ caption="""Connect your Ortto account to pull your marketing data into the PostHog Data warehouse.++Create a custom API key in Ortto under Settings > API keys, and pick the region your Ortto instance lives in. Ortto's API has no updated-since filter, so all tables fully refresh on each sync.""",iconPath="/static/services/ortto.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/ortto",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="global",+ options=[+ SourceFieldSelectConfigOption(label="Global", value="global"),+ SourceFieldSelectConfigOption(label="Australia", value="au"),+ SourceFieldSelectConfigOption(label="Europe", value="eu"),+ ],+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: OrttoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ 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: OrttoSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_ortto_credentials(config.region, config.api_key):+ return True, None++ return False, "Invalid Ortto credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OrttoResumeConfig]:+ return ResumableSourceManager[OrttoResumeConfig](inputs, OrttoResumeConfig)++ def source_for_pipeline(+ self,+ config: OrttoSourceConfig,+ resumable_source_manager: ResumableSourceManager[OrttoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return ortto_source(+ region=config.region,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/ortto/tests/test_ortto.py b/posthog/temporal/data_imports/sources/ortto/tests/test_ortto.pynew file mode 100644index 000000000000..1e52cca65b08--- /dev/null+++ b/posthog/temporal/data_imports/sources/ortto/tests/test_ortto.py@@ -0,0 +1,229 @@+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.ortto.ortto import (+ OrttoResumeConfig,+ _base_url,+ _flatten_custom_field,+ get_rows,+ ortto_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.ortto.settings import (+ ACCOUNT_BUILTIN_FIELDS,+ ENDPOINTS,+ ORTTO_ENDPOINTS,+ PERSON_BUILTIN_FIELDS,+)++_MODULE = "posthog.temporal.data_imports.sources.ortto.ortto"+++def _make_manager(resume_state: OrttoResumeConfig | 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 _response(body: Any) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = 200+ resp.ok = True+ return resp+++def _contacts_page(+ contacts: list[dict[str, Any]], has_more: bool, next_offset: int = 0, cursor_id: str | None = None+) -> dict[str, Any]:+ return {"contacts": contacts, "has_more": has_more, "next_offset": next_offset, "cursor_id": cursor_id}+++class TestBaseUrl:+ @pytest.mark.parametrize(+ "region, expected",+ [+ ("global", "https://api.ap3api.com"),+ ("au", "https://api.au.ap3api.com"),+ ("eu", "https://api.eu.ap3api.com"),+ ("unknown", "https://api.ap3api.com"),+ ],+ )+ def test_region_hosts(self, region, expected):+ assert _base_url(region) == expected+++class TestFlattenCustomField:+ def test_wrapped_person_field_is_flattened(self):+ entry = {"field": {"id": "str:cm:plan", "name": "Plan"}, "tracked_value": True}+ assert _flatten_custom_field(entry) == {"id": "str:cm:plan", "name": "Plan", "tracked_value": True}++ def test_flat_account_field_passes_through(self):+ entry = {"id": "str:oc:industry", "name": "Industry"}+ assert _flatten_custom_field(entry) == entry+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.post.return_value = response++ assert validate_credentials("global", "key") is expected++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_probes_region_specific_host(self, mock_session):+ response = mock.MagicMock()+ response.status_code = 200+ mock_session.return_value.post.return_value = response++ validate_credentials("eu", "key")++ url = mock_session.return_value.post.call_args.args[0]+ assert url == "https://api.eu.ap3api.com/v1/person/custom-field/get"+++class TestGetRowsCursorPagination:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_people_requests_builtin_plus_discovered_custom_fields(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"fields": [{"field": {"id": "str:cm:plan"}, "tracked_value": False}]}),+ _response(_contacts_page([{"id": "p1", "fields": {}}], has_more=False)),+ ]++ batches = list(get_rows("global", "key", "people", mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == ["p1"]+ page_body = mock_session.return_value.post.call_args_list[1].kwargs["json"]+ assert page_body["fields"] == [*PERSON_BUILTIN_FIELDS, "str:cm:plan"]+ assert page_body["limit"] == 500+ assert page_body["offset"] == 0+ assert "cursor_id" not in page_body++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_with_cursor_until_has_more_is_false(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"fields": []}),+ _response(_contacts_page([{"id": "p1"}], has_more=True, next_offset=500, cursor_id="cur-1")),+ _response(_contacts_page([{"id": "p2"}], has_more=False)),+ ]++ manager = _make_manager()+ batches = list(get_rows("global", "key", "people", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["p1", "p2"]+ second_page_body = mock_session.return_value.post.call_args_list[2].kwargs["json"]+ assert second_page_body["offset"] == 500+ assert second_page_body["cursor_id"] == "cur-1"+ # State saved once, after the first page yielded.+ saved = manager.save_state.call_args_list+ assert [(call.args[0].next_offset, call.args[0].cursor_id) for call in saved] == [(500, "cur-1")]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_offset_and_cursor(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"fields": []}),+ _response(_contacts_page([{"id": "p3"}], has_more=False)),+ ]++ manager = _make_manager(OrttoResumeConfig(next_offset=1000, cursor_id="cur-9"))+ list(get_rows("global", "key", "people", mock.MagicMock(), manager))++ page_body = mock_session.return_value.post.call_args_list[1].kwargs["json"]+ assert page_body["offset"] == 1000+ assert page_body["cursor_id"] == "cur-9"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_accounts_use_account_builtin_fields(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"fields": [{"id": "str:oc:industry"}]}),+ _response({"accounts": [{"id": "a1"}], "has_more": False}),+ ]++ batches = list(get_rows("global", "key", "accounts", mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == ["a1"]+ page_body = mock_session.return_value.post.call_args_list[1].kwargs["json"]+ assert page_body["fields"] == [*ACCOUNT_BUILTIN_FIELDS, "str:oc:industry"]+++class TestGetRowsOffsetPagination:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_audiences_paginate_by_offset_until_short_page(self, mock_session):+ page_size = ORTTO_ENDPOINTS["audiences"].page_size+ full_page = [{"id": f"aud-{i}"} for i in range(page_size)]+ mock_session.return_value.post.side_effect = [+ _response(full_page),+ _response([{"id": "aud-last"}]),+ ]++ manager = _make_manager()+ batches = list(get_rows("global", "key", "audiences", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [page_size, 1]+ second_body = mock_session.return_value.post.call_args_list[1].kwargs["json"]+ assert second_body["offset"] == page_size+ assert "fields" not in second_body+ assert [call.args[0].next_offset for call in manager.save_state.call_args_list] == [page_size]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_first_page_yields_nothing(self, mock_session):+ mock_session.return_value.post.side_effect = [_response([])]++ assert list(get_rows("global", "key", "audiences", mock.MagicMock(), _make_manager())) == []+++class TestGetRowsSingleRequest:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_tags_single_post_returns_all(self, mock_session):+ mock_session.return_value.post.side_effect = [_response([{"id": 1, "name": "VIP"}])]++ manager = _make_manager()+ batches = list(get_rows("global", "key", "tags", mock.MagicMock(), manager))++ assert batches == [[{"id": 1, "name": "VIP"}]]+ assert mock_session.return_value.post.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_person_custom_fields_are_flattened(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"fields": [{"field": {"id": "int:cm:rating", "name": "Rating"}, "tracked_value": False}]}),+ ]++ batches = list(get_rows("global", "key", "person_custom_fields", mock.MagicMock(), _make_manager()))++ assert batches == [[{"id": "int:cm:rating", "name": "Rating", "tracked_value": False}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_account_custom_fields_pass_through_flat(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _response({"fields": [{"id": "str:oc:industry", "name": "Industry"}]}),+ ]++ batches = list(get_rows("global", "key", "account_custom_fields", mock.MagicMock(), _make_manager()))++ assert batches == [[{"id": "str:oc:industry", "name": "Industry"}]]+++class TestOrttoSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ response = ortto_source("global", "key", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/ortto/tests/test_ortto_source.py b/posthog/temporal/data_imports/sources/ortto/tests/test_ortto_source.pynew file mode 100644index 000000000000..9e2e20cbae73--- /dev/null+++ b/posthog/temporal/data_imports/sources/ortto/tests/test_ortto_source.py@@ -0,0 +1,121 @@+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 OrttoSourceConfig+from posthog.temporal.data_imports.sources.ortto.ortto import OrttoResumeConfig+from posthog.temporal.data_imports.sources.ortto.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.ortto.source import OrttoSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestOrttoSource:+ def setup_method(self):+ self.source = OrttoSource()+ self.team_id = 123+ self.config = OrttoSourceConfig(api_key="key", region="eu")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.ORTTO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Ortto"+ assert config.label == "Ortto"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/ortto.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["region", "api_key"]++ def test_region_field_is_a_select_with_default(self):+ config = self.source.get_source_config+ region_field = next(f for f in config.fields if f.name == "region")+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "global"+ assert {option.value for option in region_field.options} == {"global", "au", "eu"}++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.ap3api.com/v1/person/get",+ "403 Client Error: Forbidden for url: https://api.eu.ap3api.com/v1/accounts/get",+ ],+ )+ 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)++ def test_non_retryable_errors_does_not_match_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ error = "500 Server Error for url: https://api.ap3api.com/v1/person/get"+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # No endpoint exposes a server-side updated-since filter — everything full refresh.+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append 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=["people"])+ assert len(schemas) == 1+ assert schemas[0].name == "people"++ 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(+ "mock_return, expected_valid",+ [+ (True, True),+ (False, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.ortto.source.validate_ortto_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if not expected_valid:+ assert error_message == "Invalid Ortto credentials"+ mock_validate.assert_called_once_with("eu", "key")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OrttoResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.ortto.source.ortto_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_ortto_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "people"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_ortto_source.assert_called_once()+ kwargs = mock_ortto_source.call_args.kwargs+ assert kwargs["region"] == "eu"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "people"+ assert kwargs["resumable_source_manager"] is manager