: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 culture amp import source (#63003)
Tom Owersf0aae3a5e4ec
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex d4aefdae6219..3bd8bbba3677 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -79,6 +79,7 @@ the row lists both.| convex | HTTP | requests | ✅ || copper | HTTP | requests | ✅ || crunchbase | HTTP | requests | ✅ |+| culture_amp | HTTP | requests | ✅ || customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) || datadog | HTTP | requests | ✅ || delighted | HTTP | requests | ✅ |@@ -244,7 +245,6 @@ doesn't conflict with concurrent PRs.- cosmosdb- coupa- criteo-- culture_amp- databricks- db2- deeldiff --git a/posthog/temporal/data_imports/sources/culture_amp/culture_amp.py b/posthog/temporal/data_imports/sources/culture_amp/culture_amp.pynew file mode 100644index 000000000000..1aa160cc00a9--- /dev/null+++ b/posthog/temporal/data_imports/sources/culture_amp/culture_amp.py@@ -0,0 +1,214 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, 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.culture_amp.settings import (+ CULTURE_AMP_BASE_URL,+ CULTURE_AMP_ENDPOINTS,+ CULTURE_AMP_TOKEN_URL,+)++REQUEST_TIMEOUT_SECONDS = 60+# Rate limits are undisclosed ("generous"); back off on 429/503.+MAX_RETRY_ATTEMPTS = 5+++class CultureAmpRetryableError(Exception):+ pass+++class CultureAmpResumeConfig:+ # Cursor endpoints: the afterKey of the next unfetched page. Fan-out: the id+ # of the last fully-processed employee, re-located in a freshly-fetched list+ # on resume so an employee added/removed mid-sync can't shift the position.+ cursor: Optional[str] = None+ last_processed_employee_id: Optional[str] = None+++def _get_session(client_secret: str) -> requests.Session:+ return make_tracked_session(redact_values=(client_secret,))+++def _mint_token(session: requests.Session, client_id: str, client_secret: str, account_id: str, scopes: str) -> str:+ """Exchange client credentials for a bearer JWT (~1h lifetime)."""+ response = session.post(+ CULTURE_AMP_TOKEN_URL,+ data={+ "grant_type": "client_credentials",+ "client_id": client_id,+ "client_secret": client_secret,+ "scope": f"target-entity:{account_id}:{scopes}",+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return response.json()["access_token"]+++def _format_timestamp(value: Any) -> str:+ """Format an incremental cursor for the RFC 3339 after_date filter."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def validate_credentials(client_id: str, client_secret: str, account_id: str) -> bool:+ """Confirm the credentials are valid by minting an employees-read token."""+ try:+ _mint_token(_get_session(client_secret), client_id, client_secret, account_id, "employees-read")+ return True+ except Exception:+ return False+++def get_rows(+ client_id: str,+ client_secret: str,+ account_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CultureAmpResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CULTURE_AMP_ENDPOINTS[endpoint]+ session = _get_session(client_secret)+ token = _mint_token(session, client_id, client_secret, account_id, config.scopes)++ @retry(+ retry=retry_if_exception_type((CultureAmpRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def fetch(url: str) -> dict[str, Any]:+ nonlocal token+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ # Tokens expire after ~1h; re-mint once if one expires mid-sync.+ if response.status_code == 401:+ token = _mint_token(session, client_id, client_secret, account_id, config.scopes)+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code in (429, 503) or response.status_code >= 500:+ raise CultureAmpRetryableError(+ f"Culture Amp API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ logger.error(f"Culture Amp API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()++ def paginate(path: str, params: dict[str, Any], on_page_done: Any = None) -> Iterator[list[dict[str, Any]]]:+ cursor = params.pop("cursor", None)+ while True:+ query = dict(params)+ if cursor:+ query["cursor"] = cursor+ url = f"{CULTURE_AMP_BASE_URL}{path}"+ if query:+ url = f"{url}?{urlencode(query)}"++ body = fetch(url)+ items = body.get("data") or []+ if isinstance(items, dict):+ items = [items]+ items = [row for row in items if isinstance(row, dict)]++ if items:+ yield items++ cursor = (body.get("pagination") or {}).get("afterKey")+ if not cursor:+ return+ if on_page_done is not None:+ on_page_done(cursor)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.per_employee:+ employee_ids: list[str] = []+ for page in paginate("/employees", {}):+ employee_ids.extend(str(row["id"]) for row in page)++ start_index = 0+ if resume_config is not None and resume_config.last_processed_employee_id is not None:+ start_id = resume_config.last_processed_employee_id+ logger.debug(f"Culture Amp: resuming {endpoint} from after employee id {start_id}")+ try:+ start_index = employee_ids.index(start_id) + 1+ except ValueError:+ # The saved employee no longer exists; restart from the beginning+ # (merge dedupes on primary key, so re-yielding is safe).+ start_index = 0++ for index in range(start_index, len(employee_ids)):+ employee_id = employee_ids[index]+ path = config.path.format(employee_id=quote(employee_id, safe=""))+ for page in paginate(path, {}):+ yield [{**row, "_employee_id": employee_id} for row in page]+ # Save state AFTER yielding so a crash re-yields the in-flight+ # employee (merge dedupes on primary key).+ resumable_source_manager.save_state(CultureAmpResumeConfig(last_processed_employee_id=employee_id))+ return++ params: dict[str, Any] = {}+ if config.incremental_fields and should_use_incremental_field and db_incremental_field_last_value is not None:+ params["after_date"] = _format_timestamp(db_incremental_field_last_value)+ if resume_config is not None and resume_config.cursor:+ params["cursor"] = resume_config.cursor+ logger.debug(f"Culture Amp: resuming {endpoint} from saved cursor")++ def save_cursor(after_key: str) -> None:+ # Save state AFTER the previous page yielded so a crash re-yields it.+ resumable_source_manager.save_state(CultureAmpResumeConfig(cursor=after_key))++ yield from paginate(config.path, params, on_page_done=save_cursor)+++def culture_amp_source(+ client_id: str,+ client_secret: str,+ account_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CultureAmpResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CULTURE_AMP_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ client_id=client_id,+ client_secret=client_secret,+ account_id=account_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=list(config.primary_keys) if config.primary_keys else None,+ partition_count=1,+ partition_size=1,+ # Result ordering within an after_date window is undocumented, so the+ # pipeline defers incremental watermark commits until a run completes.+ sort_mode="desc" if config.incremental_fields else "asc",+ )diff --git a/posthog/temporal/data_imports/sources/culture_amp/settings.py b/posthog/temporal/data_imports/sources/culture_amp/settings.pynew file mode 100644index 000000000000..d490e96ef4b8--- /dev/null+++ b/posthog/temporal/data_imports/sources/culture_amp/settings.py@@ -0,0 +1,72 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++CULTURE_AMP_BASE_URL = "https://api.cultureamp.com/v1"+CULTURE_AMP_TOKEN_URL = f"{CULTURE_AMP_BASE_URL}/oauth2/token"++# Rows expose `processedAt`, which matches the semantics of the server-side+# `after_date` filter ("processed by the public API after" the timestamp).+_PROCESSED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "processedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "processedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class CultureAmpEndpointConfig:+ name: str+ path: str+ # OAuth scopes minted for this endpoint only, so credentials granted a+ # subset of permissions can still sync the streams they do cover.+ scopes: str+ primary_keys: list[str] | None = None+ # Set when the endpoint supports the server-side after_date filter.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Fan-out endpoints fetch per-employee sub-resources.+ per_employee: bool = False+++CULTURE_AMP_ENDPOINTS: dict[str, CultureAmpEndpointConfig] = {+ # No timestamp filter exists on the employee list — honest full refresh+ # (volumes are small: one row per employee).+ "employees": CultureAmpEndpointConfig(+ name="employees",+ path="/employees",+ scopes="employees-read",+ primary_keys=["id"],+ ),+ # Fan-out: GET /employees/{id}/demographics per employee; rows are+ # {name, value} pairs with the employee id injected.+ "employee_demographics": CultureAmpEndpointConfig(+ name="employee_demographics",+ path="/employees/{employee_id}/demographics",+ scopes="employees-read,employee-demographics-read",+ primary_keys=["_employee_id", "name"],+ per_employee=True,+ ),+ "performance_cycles": CultureAmpEndpointConfig(+ name="performance_cycles",+ path="/performance-cycles",+ scopes="performance-evaluations-read",+ primary_keys=["id"],+ incremental_fields=list(_PROCESSED_AT_INCREMENTAL_FIELDS),+ ),+ "manager_reviews": CultureAmpEndpointConfig(+ name="manager_reviews",+ path="/manager-reviews",+ scopes="performance-evaluations-read",+ primary_keys=["managerReviewId"],+ incremental_fields=list(_PROCESSED_AT_INCREMENTAL_FIELDS),+ ),+}++ENDPOINTS = tuple(CULTURE_AMP_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CULTURE_AMP_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/culture_amp/source.py b/posthog/temporal/data_imports/sources/culture_amp/source.pyindex 571249a88ccb..a5c9dbe8914e 100644--- a/posthog/temporal/data_imports/sources/culture_amp/source.py+++ b/posthog/temporal/data_imports/sources/culture_amp/source.py@@ -1,29 +1,137 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-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 SourceSchema+from posthog.temporal.data_imports.sources.culture_amp.culture_amp import (+ CultureAmpResumeConfig,+ culture_amp_source,+ validate_credentials as validate_culture_amp_credentials,+)+from posthog.temporal.data_imports.sources.culture_amp.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom posthog.temporal.data_imports.sources.generated_configs import CultureAmpSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class CultureAmpSource(SimpleSource[CultureAmpSourceConfig]):+class CultureAmpSource(ResumableSource[CultureAmpSourceConfig, CultureAmpResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CULTUREAMP+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "400 Client Error: Bad Request for url: https://api.cultureamp.com/v1/oauth2/token": "Culture Amp rejected the token request. Please check your client ID, client secret, and account ID, and that the credentials have the required permissions.",+ "401 Client Error: Unauthorized for url: https://api.cultureamp.com/v1/oauth2/token": "Culture Amp authentication failed. Please check your client ID and client secret.",+ "403 Client Error: Forbidden for url: https://api.cultureamp.com": "Culture Amp denied access. Please check that your API credentials have the required permissions for this dataset.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CULTURE_AMP,label="Culture Amp",+ caption="""Connect your Culture Amp account to pull your employee experience data into the PostHog Data warehouse.++An account admin can generate API credentials in Culture Amp under Settings > Integrations > Culture Amp API. Grant the employees, employee demographics, and performance evaluations read permissions. The account ID is the entity ID shown alongside your credentials.""",iconPath="/static/services/culture_amp.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/culture-amp",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="8ed17dce-9eca-4383-a9e1-54f82c362b6d",+ secret=False,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: CultureAmpSourceConfig,+ 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: CultureAmpSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_culture_amp_credentials(config.client_id, config.client_secret, config.account_id):+ return True, None++ return (+ False,+ "Invalid Culture Amp credentials. Check the client ID, client secret, and account ID, and that the credentials have the employees read permission.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CultureAmpResumeConfig]:+ return ResumableSourceManager[CultureAmpResumeConfig](inputs, CultureAmpResumeConfig)++ def source_for_pipeline(+ self,+ config: CultureAmpSourceConfig,+ resumable_source_manager: ResumableSourceManager[CultureAmpResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return culture_amp_source(+ client_id=config.client_id,+ client_secret=config.client_secret,+ account_id=config.account_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/culture_amp/tests/test_culture_amp.py b/posthog/temporal/data_imports/sources/culture_amp/tests/test_culture_amp.pynew file mode 100644index 000000000000..e8e36b5fba70--- /dev/null+++ b/posthog/temporal/data_imports/sources/culture_amp/tests/test_culture_amp.py@@ -0,0 +1,213 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.culture_amp.culture_amp import (+ CultureAmpResumeConfig,+ _format_timestamp,+ culture_amp_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.culture_amp.settings import CULTURE_AMP_ENDPOINTS, ENDPOINTS++_MODULE = "posthog.temporal.data_imports.sources.culture_amp.culture_amp"+++def _make_manager(resume_state: CultureAmpResumeConfig | 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, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ return resp+++def _token_response() -> mock.MagicMock:+ return _response({"access_token": "tok-1", "expires_in": 3599, "token_type": "Bearer"})+++def _page(rows: list[dict[str, Any]], after_key: str | None = None) -> dict[str, Any]:+ body: dict[str, Any] = {"data": rows}+ if after_key:+ body["pagination"] = {"afterKey": after_key, "nextPath": f"/v1/x?cursor={after_key}"}+ return body+++class TestFormatTimestamp:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ ],+ )+ def test_formats(self, value, expected):+ assert _format_timestamp(value) == expected+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_credentials_mint_scoped_token(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()++ assert validate_credentials("cid", "sec", "entity-1") is True+ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body["grant_type"] == "client_credentials"+ assert body["scope"] == "target-entity:entity-1:employees-read"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_credentials(self, mock_session):+ response = _response({}, status_code=401)+ response.raise_for_status.side_effect = Exception("401")+ mock_session.return_value.post.return_value = response++ assert validate_credentials("cid", "bad", "entity-1") is False+++class TestCursorEndpoints:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_employees_follow_after_key_until_absent(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "e1"}], after_key="k1")),+ _response(_page([{"id": "e2"}])),+ ]++ manager = _make_manager()+ batches = list(get_rows("cid", "sec", "entity-1", "employees", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["e1", "e2"]+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert "cursor=k1" in second_url+ assert [call.args[0].cursor for call in manager.save_state.call_args_list] == ["k1"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_passes_after_date(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response(_page([]))++ list(+ get_rows(+ "cid",+ "sec",+ "entity-1",+ "performance_cycles",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ assert "after_date=2024-01-02T03%3A04%3A05Z" in url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response(_page([{"managerReviewId": "r9"}]))++ manager = _make_manager(CultureAmpResumeConfig(cursor="k9"))+ list(get_rows("cid", "sec", "entity-1", "manager_reviews", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert "cursor=k9" in url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_mid_sync_401_re_mints_token(self, mock_session):+ mock_session.return_value.post.side_effect = [_token_response(), _token_response()]+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=401),+ _response(_page([{"id": "e1"}])),+ ]++ batches = list(get_rows("cid", "sec", "entity-1", "employees", mock.MagicMock(), _make_manager()))++ assert batches == [[{"id": "e1"}]]+ assert mock_session.return_value.post.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_endpoint_scopes_are_minted_per_stream(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response(_page([]))++ list(get_rows("cid", "sec", "entity-1", "performance_cycles", mock.MagicMock(), _make_manager()))++ scope = mock_session.return_value.post.call_args.kwargs["data"]["scope"]+ assert scope == "target-entity:entity-1:performance-evaluations-read"+++class TestEmployeeDemographicsFanOut:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_fans_out_per_employee_and_injects_employee_id(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "e1"}, {"id": "e2"}])),+ _response(_page([{"name": "department", "value": "eng"}])),+ _response(_page([{"name": "department", "value": "sales"}])),+ ]++ manager = _make_manager()+ batches = list(get_rows("cid", "sec", "entity-1", "employee_demographics", mock.MagicMock(), manager))++ flat = [row for batch in batches for row in batch]+ assert [(r["_employee_id"], r["value"]) for r in flat] == [("e1", "eng"), ("e2", "sales")]+ assert [call.args[0].last_processed_employee_id for call in manager.save_state.call_args_list] == ["e1", "e2"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_employee_id(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "e1"}, {"id": "e2"}])),+ _response(_page([{"name": "department", "value": "sales"}])),+ ]++ manager = _make_manager(CultureAmpResumeConfig(last_processed_employee_id="e1"))+ batches = list(get_rows("cid", "sec", "entity-1", "employee_demographics", mock.MagicMock(), manager))++ flat = [row for batch in batches for row in batch]+ assert [r["_employee_id"] for r in flat] == ["e2"]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert len(urls) == 2+ assert "/employees/e2/demographics" in urls[1]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_beginning_when_saved_employee_removed(self, mock_session):+ # The employee whose id was saved (e9) is gone from the refetched list,+ # so the sync restarts from the top rather than skipping anyone.+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _response(_page([{"id": "e1"}, {"id": "e2"}])),+ _response(_page([{"name": "department", "value": "eng"}])),+ _response(_page([{"name": "department", "value": "sales"}])),+ ]++ manager = _make_manager(CultureAmpResumeConfig(last_processed_employee_id="e9"))+ batches = list(get_rows("cid", "sec", "entity-1", "employee_demographics", mock.MagicMock(), manager))++ flat = [row for batch in batches for row in batch]+ assert [r["_employee_id"] for r in flat] == ["e1", "e2"]+++class TestCultureAmpSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = CULTURE_AMP_ENDPOINTS[endpoint]+ response = culture_amp_source("cid", "sec", "entity-1", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ # Incremental streams defer the watermark (ordering undocumented).+ expected_sort = "desc" if config.incremental_fields else "asc"+ assert response.sort_mode == expected_sortdiff --git a/posthog/temporal/data_imports/sources/culture_amp/tests/test_culture_amp_source.py b/posthog/temporal/data_imports/sources/culture_amp/tests/test_culture_amp_source.pynew file mode 100644index 000000000000..99a0d1a4d50c--- /dev/null+++ b/posthog/temporal/data_imports/sources/culture_amp/tests/test_culture_amp_source.py@@ -0,0 +1,142 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.culture_amp.culture_amp import CultureAmpResumeConfig+from posthog.temporal.data_imports.sources.culture_amp.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.culture_amp.source import CultureAmpSource+from posthog.temporal.data_imports.sources.generated_configs import CultureAmpSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestCultureAmpSource:+ def setup_method(self):+ self.source = CultureAmpSource()+ self.team_id = 123+ self.config = CultureAmpSourceConfig(client_id="cid", client_secret="sec", account_id="entity-1")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CULTUREAMP++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "CultureAmp"+ assert config.label == "Culture Amp"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/culture_amp.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["client_id", "client_secret", "account_id"]++ def test_client_secret_field_is_secret_password(self):+ config = self.source.get_source_config+ secret_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "400 Client Error: Bad Request for url: https://api.cultureamp.com/v1/oauth2/token",+ "401 Client Error: Unauthorized for url: https://api.cultureamp.com/v1/oauth2/token",+ "403 Client Error: Forbidden for url: https://api.cultureamp.com/v1/employees",+ ],+ )+ 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",+ [+ "500 Server Error for url: https://api.cultureamp.com/v1/employees",+ # Mid-sync 401s on data endpoints are handled by token re-mint.+ "401 Client Error: Unauthorized for url: https://api.cultureamp.com/v1/employees",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(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)++ def test_get_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Only the performance streams expose the server-side after_date filter.+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}+ assert incremental == {"performance_cycles", "manager_reviews"}+ assert schemas["manager_reviews"].incremental_fields == INCREMENTAL_FIELDS["manager_reviews"]+ assert [f["field"] for f in schemas["performance_cycles"].incremental_fields] == ["processedAt"]+ assert schemas["employees"].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["employees"])+ assert len(schemas) == 1+ assert schemas[0].name == "employees"++ 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.culture_amp.source.validate_culture_amp_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 "employees read permission" in (error_message or "")+ mock_validate.assert_called_once_with("cid", "sec", "entity-1")++ 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 CultureAmpResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.culture_amp.source.culture_amp_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_culture_amp_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "manager_reviews"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_culture_amp_source.assert_called_once()+ kwargs = mock_culture_amp_source.call_args.kwargs+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "sec"+ assert kwargs["account_id"] == "entity-1"+ assert kwargs["endpoint"] == "manager_reviews"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"++ @mock.patch("posthog.temporal.data_imports.sources.culture_amp.source.culture_amp_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_culture_amp_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "employees"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_culture_amp_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex b9a6ba527dcf..424fdd8fc7d2 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -476,7 +476,9 @@ class CrunchbaseSourceConfig(config.Config):@config.configclass CultureAmpSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ account_id: str@config.config