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 lattice import source (#62911)

Tom Owers8a873f8f4629
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 6c07e0be1ffd..981575f78959 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -97,6 +97,7 @@ the row lists both.
| klaviyo | HTTP | requests | ✅ |
| launchdarkly | HTTP | requests | ✅ |
| kustomer | HTTP | requests | ✅ |
+| lattice | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
| lever | HTTP | requests | ✅ |
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
@@ -258,7 +259,6 @@ doesn't conflict with concurrent PRs.
- hibob
- instagram
- kafka
-- lattice
- lever
- lightspeed_retail
- marketo
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index a9f0a0e310cf..9ab11e8218cd 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -747,7 +747,8 @@ class KustomerSourceConfig(config.Config):
@config.config
class LatticeSourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "emea"] = config.value(default="us")
@config.config
diff --git a/posthog/temporal/data_imports/sources/lattice/lattice.py b/posthog/temporal/data_imports/sources/lattice/lattice.py
new file mode 100644
index 000000000000..f7999a7c3b59
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lattice/lattice.py
@@ -0,0 +1,151 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+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.lattice.settings import LATTICE_ENDPOINTS
+
+LATTICE_HOSTS = {
+ "us": "https://api.latticehq.com",
+ "emea": "https://api.emea.latticehq.com",
+}
+# Lattice's default page size is only 10; always request the max of 100.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# 240 req/min rate limit; 429s carry Retry-After but exponential backoff suffices.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class LatticeRetryableError(Exception):
+ pass
+
+
+class LatticeResumeConfig:
+ # Lattice cursor pagination: pass the previous page's endingCursor as
+ # startingAfter; static params are rebuilt deterministically on resume.
+ starting_after: str
+
+
+def _get_session(api_key: str) -> requests.Session:
+ return make_tracked_session(headers={"Authorization": f"Bearer {api_key}"}, redact_values=(api_key,))
+
+
+def _base_url(region: str) -> str:
+ host = LATTICE_HOSTS.get(region)
+ if host is None:
+ raise ValueError(f"Invalid Lattice region: {region}")
+ return host
+
+
+def validate_credentials(region: str, api_key: str) -> tuple[bool, str | None]:
+ """Confirm the API key is valid with a cheap one-user probe.
+
+ Keys inherit the creating user's privileges, so a key may lack access to a
+ specific stream (403); only 401 means the key itself is bad."""
+ try:
+ base_url = _base_url(region)
+ except ValueError as e:
+ return False, str(e)
+
+ try:
+ response = _get_session(api_key).get(
+ f"{base_url}/v1/users?{urlencode({'limit': 1})}",
+ timeout=10,
+ )
+ except requests.RequestException as e:
+ # Transport failures (timeouts, connection resets) are not auth failures;
+ # surface the real error instead of mislabeling the key as invalid.
+ return False, f"Could not reach Lattice: {e}"
+
+ if response.status_code == 401:
+ return False, "Invalid Lattice API key"
+ return True, None
+
+
+def get_rows(
+ region: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LatticeResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = LATTICE_ENDPOINTS[endpoint]
+ session = _get_session(api_key)
+ base_url = _base_url(region)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ starting_after: Optional[str] = resume_config.starting_after if resume_config is not None else None
+ if starting_after is not None:
+ logger.debug(f"Lattice: resuming {endpoint} from cursor {starting_after}")
+
+ @retry(
+ retry=retry_if_exception_type((LatticeRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise LatticeRetryableError(f"Lattice API error (retryable): status={response.status_code}, url={page_url}")
+
+ if not response.ok:
+ # Omit the response body: Lattice error payloads can carry field-level
+ # validation context or user-identifying data we don't want in logs.
+ logger.error(f"Lattice API error: status={response.status_code}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if starting_after is not None:
+ params["startingAfter"] = starting_after
+ data = fetch_page(f"{base_url}{config.path}?{urlencode(params)}")
+ items = data.get("data", []) or []
+
+ if items:
+ yield items
+
+ ending_cursor = data.get("endingCursor")
+ if not data.get("hasMore") or not ending_cursor or not items:
+ break
+
+ starting_after = ending_cursor
+ # Save state AFTER yielding the page so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(LatticeResumeConfig(starting_after=starting_after))
+
+
+def lattice_source(
+ region: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LatticeResumeConfig],
+) -> SourceResponse:
+ config = LATTICE_ENDPOINTS[endpoint]
+
+ 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=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/lattice/settings.py b/posthog/temporal/data_imports/sources/lattice/settings.py
new file mode 100644
index 000000000000..550e643d2c75
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lattice/settings.py
@@ -0,0 +1,42 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class LatticeEndpointConfig:
+ name: str
+ path: str
+ primary_key: str = "id"
+
+
+# The Lattice Talent API v1 has no server-side incremental filters on any list
+# endpoint (Fivetran's connector re-imports every table each sync for the same
+# reason), so every stream is an honest full refresh. Per-cycle fan-out streams
+# (reviews/reviewees) are a possible follow-up.
+LATTICE_ENDPOINTS: dict[str, LatticeEndpointConfig] = {
+ "users": LatticeEndpointConfig(
+ name="users",
+ path="/v1/users",
+ ),
+ "departments": LatticeEndpointConfig(
+ name="departments",
+ path="/v1/departments",
+ ),
+ "goals": LatticeEndpointConfig(
+ name="goals",
+ path="/v1/goals",
+ ),
+ "feedbacks": LatticeEndpointConfig(
+ name="feedbacks",
+ path="/v1/feedbacks",
+ ),
+ "review_cycles": LatticeEndpointConfig(
+ name="review_cycles",
+ path="/v1/reviewCycles",
+ ),
+ "updates": LatticeEndpointConfig(
+ name="updates",
+ path="/v1/updates",
+ ),
+}
+
+ENDPOINTS = tuple(LATTICE_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/lattice/source.py b/posthog/temporal/data_imports/sources/lattice/source.py
index 150a8d5afae8..59d2665fbf12 100644
--- a/posthog/temporal/data_imports/sources/lattice/source.py
+++ b/posthog/temporal/data_imports/sources/lattice/source.py
@@ -1,29 +1,125 @@
-from typing import cast
+from typing import Optional, cast
from 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, ResumableSource
from 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 SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import LatticeSourceConfig
+from posthog.temporal.data_imports.sources.lattice.lattice import (
+ LatticeResumeConfig,
+ lattice_source,
+ validate_credentials as validate_lattice_credentials,
+)
+from posthog.temporal.data_imports.sources.lattice.settings import ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LatticeSource(SimpleSource[LatticeSourceConfig]):
+class LatticeSource(ResumableSource[LatticeSourceConfig, LatticeResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LATTICE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.latticehq.com": "Lattice authentication failed. Please check your API key.",
+ "401 Client Error: Unauthorized for url: https://api.emea.latticehq.com": "Lattice authentication failed. Please check your API key (and that it matches the selected region).",
+ "403 Client Error: Forbidden for url: https://api.latticehq.com": "Lattice denied access. API keys inherit the creating user's privileges — please check the key owner can access this data.",
+ "403 Client Error: Forbidden for url: https://api.emea.latticehq.com": "Lattice denied access. API keys inherit the creating user's privileges — please check the key owner can access this data.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.LATTICE,
label="Lattice",
+ caption="""Enter your Lattice API key to pull your Lattice performance management data into the PostHog Data warehouse.
+
+A Lattice admin can generate an API key under Admin > Settings > API Keys (Lattice may require requesting API access first). Pick the region that matches your Lattice data residency.""",
iconPath="/static/services/lattice.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/lattice",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.latticehq.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EMEA (api.emea.latticehq.com)", value="emea"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: LatticeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # No Lattice list endpoint exposes a server-side timestamp filter;
+ # full refresh only.
+ 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: LatticeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_lattice_credentials(config.region, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LatticeResumeConfig]:
+ return ResumableSourceManager[LatticeResumeConfig](inputs, LatticeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LatticeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LatticeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return lattice_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/lattice/tests/test_lattice.py b/posthog/temporal/data_imports/sources/lattice/tests/test_lattice.py
new file mode 100644
index 000000000000..c3562568a753
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lattice/tests/test_lattice.py
@@ -0,0 +1,163 @@
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.lattice.lattice import (
+ PAGE_SIZE,
+ LatticeResumeConfig,
+ _base_url,
+ get_rows,
+ lattice_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.lattice.settings import ENDPOINTS, LATTICE_ENDPOINTS
+
+
+def _make_manager(resume_state: LatticeResumeConfig | 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(items: list[dict[str, Any]], has_more: bool = False, ending_cursor: str | None = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {"data": items, "hasMore": has_more, "endingCursor": ending_cursor}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestBaseUrl:
+ def test_us_and_emea_hosts(self):
+ assert _base_url("us") == "https://api.latticehq.com"
+ assert _base_url("emea") == "https://api.emea.latticehq.com"
+
+ def test_invalid_region_raises(self):
+ with pytest.raises(ValueError):
+ _base_url("evil.example.com")
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid, expected_message",
+ [
+ (200, True, None),
+ # Keys inherit the creating user's privileges; 403 means a scope
+ # gap, not a bad key.
+ (403, True, None),
+ (401, False, "Invalid Lattice API key"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected_valid, expected_message):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("us", "key") == (expected_valid, expected_message)
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_validate_credentials_rejects_bad_region_without_request(self, mock_session):
+ is_valid, error = validate_credentials("evil", "key")
+ assert is_valid is False
+ assert error is not None
+ mock_session.return_value.get.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_validate_credentials_transport_error_is_not_invalid_key(self, mock_session):
+ # A transient connectivity failure must not be reported as a bad key.
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+
+ is_valid, error = validate_credentials("us", "key")
+ assert is_valid is False
+ assert error is not None
+ assert "Invalid Lattice API key" not in error
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_paginates_via_ending_cursor(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": "1"}], has_more=True, ending_cursor="cur_abc"),
+ _response([{"id": "2"}], has_more=False),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("us", "key", "users", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].starting_after == "cur_abc"
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert parse_qs(urlparse(second_url).query)["startingAfter"] == ["cur_abc"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_first_request_uses_max_page_size(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ list(get_rows("us", "key", "goals", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ parsed = urlparse(url)
+ assert parsed.path == "/v1/goals"
+ assert parse_qs(parsed.query)["limit"] == [str(PAGE_SIZE)]
+ assert "startingAfter" not in parse_qs(parsed.query)
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_emea_region_uses_emea_host(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ list(get_rows("emea", "key", "users", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(url).netloc == "api.emea.latticehq.com"
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager(LatticeResumeConfig(starting_after="cur_resume"))
+ list(get_rows("us", "key", "users", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["startingAfter"] == ["cur_resume"]
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_has_more_without_cursor_stops(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "1"}], has_more=True, ending_cursor=None)
+
+ manager = _make_manager()
+ batches = list(get_rows("us", "key", "users", mock.MagicMock(), manager))
+
+ assert len(batches) == 1
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.lattice.make_tracked_session")
+ def test_empty_response_stops_without_saving_state(self, mock_session):
+ mock_session.return_value.get.return_value = _response([], has_more=True, ending_cursor="cur_loop")
+
+ manager = _make_manager()
+ batches = list(get_rows("us", "key", "users", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+
+class TestLatticeSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = LATTICE_ENDPOINTS[endpoint]
+ response = lattice_source("us", "key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/lattice/tests/test_lattice_source.py b/posthog/temporal/data_imports/sources/lattice/tests/test_lattice_source.py
new file mode 100644
index 000000000000..15b561bbab9f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lattice/tests/test_lattice_source.py
@@ -0,0 +1,127 @@
+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 LatticeSourceConfig
+from posthog.temporal.data_imports.sources.lattice.lattice import LatticeResumeConfig
+from posthog.temporal.data_imports.sources.lattice.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.lattice.source import LatticeSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestLatticeSource:
+ def setup_method(self):
+ self.source = LatticeSource()
+ self.team_id = 123
+ self.config = LatticeSourceConfig(region="us", api_key="api-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LATTICE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Lattice"
+ assert config.label == "Lattice"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/lattice.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 == "us"
+ assert {option.value for option in region_field.options} == {"us", "emea"}
+
+ 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.latticehq.com/v1/users?limit=100",
+ "401 Client Error: Unauthorized for url: https://api.emea.latticehq.com/v1/goals",
+ "403 Client Error: Forbidden for url: https://api.latticehq.com/v1/feedbacks",
+ ],
+ )
+ 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_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.latticehq.com/v1/users",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No Lattice list endpoint has a server-side timestamp filter.
+ 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=["users"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "users"
+
+ 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",
+ [
+ (True, None),
+ (False, "Invalid Lattice API key"),
+ (False, "Could not reach Lattice: boom"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.source.validate_lattice_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id)
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with("us", "api-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 LatticeResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.lattice.source.lattice_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_lattice_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_lattice_source.assert_called_once()
+ kwargs = mock_lattice_source.call_args.kwargs
+ assert kwargs["region"] == "us"
+ assert kwargs["api_key"] == "api-key"
+ assert kwargs["endpoint"] == "users"
+ assert kwargs["resumable_source_manager"] is manager