: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 greenhouse import source (#61654)
Tom Owers0684956ac1eb
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 89abe51dcd5f..97cde4749688 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -77,6 +77,7 @@ the row lists both.| google_sheets | HTTP (vendor SDK) | gspread | ✅ || granola | HTTP | requests | ✅ || gorgias | HTTP | requests | ✅ |+| greenhouse | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ || intercom | HTTP | requests + `rest_source.RESTClient` | ✅ || klaviyo | HTTP | requests | ✅ |@@ -188,7 +189,6 @@ doesn't conflict with concurrent PRs.- gong- google_analytics- google_drive-- greenhouse- helpscout- iterablediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 1f50473249cf..2e79462484b8 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -444,7 +444,7 @@ class GranolaSourceConfig(config.Config):@config.configclass GreenhouseSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/greenhouse/greenhouse.py b/posthog/temporal/data_imports/sources/greenhouse/greenhouse.pynew file mode 100644index 000000000000..3fcb86fd259a--- /dev/null+++ b/posthog/temporal/data_imports/sources/greenhouse/greenhouse.py@@ -0,0 +1,197 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests # used for exception types in the tenacity retry predicate+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.greenhouse.settings import GREENHOUSE_ENDPOINTS, GreenhouseEndpointConfig++GREENHOUSE_BASE_URL = "https://harvest.greenhouse.io/v1"+REQUEST_TIMEOUT_SECONDS = 60+# Harvest's documented maximum page size. Fewer requests keeps us comfortably under the+# per-10-second rate limit advertised via the `X-RateLimit-*` response headers.+PAGE_SIZE = 500+++class GreenhouseRetryableError(Exception):+ pass+++class GreenhouseResumeConfig:+ # Harvest paginates with RFC 5988 `Link` headers. We persist the full `rel="next"` URL+ # (it already carries `per_page` plus any timestamp filter) so a resumed run continues+ # from the same page rather than restarting the stream.+ next_url: str+++def _auth(api_key: str) -> tuple[str, str]:+ # Harvest uses HTTP Basic auth with the API key as the username and a blank password.+ return (api_key, "")+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor value as the ISO 8601 string Harvest's `*_after` filters expect."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00.000Z")+ return str(value)+++def validate_credentials(+ api_key: str, path: str = "/candidates", accept_forbidden: bool = True+) -> tuple[bool, str | None]:+ """Probe a Harvest endpoint to confirm the API key is genuine.++ Harvest keys are scoped per-resource: a valid key may still 403 on an endpoint it wasn't+ granted. At source-create time (``accept_forbidden=True``) we treat 403 as success so users+ can connect with keys scoped only to the endpoints they want; per-schema checks pass+ ``accept_forbidden=False`` to surface a missing-scope error for that specific endpoint.+ """+ url = f"{GREENHOUSE_BASE_URL}{path}"+ session = make_tracked_session()+ try:+ response = session.get(url, auth=_auth(api_key), params={"per_page": 1}, timeout=10)+ except Exception as e:+ return False, str(e)+ finally:+ session.close()++ if response.status_code == 200:+ return True, None++ if response.status_code == 403:+ if accept_forbidden:+ return True, None+ return False, "Your Greenhouse API key does not have permission to access this endpoint."++ if response.status_code == 401:+ return False, "Invalid Greenhouse API key. Please check your key and try again."++ return False, f"Greenhouse API returned an unexpected status code: {response.status_code}"+++def _build_initial_params(+ config: GreenhouseEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"per_page": PAGE_SIZE}++ if should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None:+ filter_param = config.incremental_filter_params.get(incremental_field)+ if filter_param:+ # Harvest's `*_after` filters are inclusive — merge dedupes the boundary rows.+ params[filter_param] = _format_datetime(db_incremental_field_last_value)++ return params+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GreenhouseResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = GREENHOUSE_ENDPOINTS[endpoint]+ session = make_tracked_session()++ base_params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ next_url: str | None = resume_config.next_url if resume_config else None+ if next_url:+ logger.debug(f"Greenhouse: resuming {endpoint} from saved page URL")++ @retry(+ retry=retry_if_exception_type((GreenhouseRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(url: str, params: dict[str, Any] | None) -> requests.Response:+ response = session.get(url, auth=_auth(api_key), params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise GreenhouseRetryableError(+ f"Greenhouse API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ logger.error(f"Greenhouse API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response++ try:+ while True:+ if next_url:+ # The `Link` URL already encodes per_page + filters; sending params again would+ # duplicate the query string, so we follow it verbatim.+ response = fetch_page(next_url, None)+ else:+ response = fetch_page(f"{GREENHOUSE_BASE_URL}{config.path}", base_params)++ items = response.json()+ if items:+ yield items++ next_url = response.links.get("next", {}).get("url")+ if not next_url:+ break++ # Save state after yielding so a crash re-yields the last batch (merge dedupes on+ # the primary key) rather than skipping it.+ resumable_source_manager.save_state(GreenhouseResumeConfig(next_url=next_url))+ finally:+ session.close()+++def greenhouse_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GreenhouseResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = GREENHOUSE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Harvest orders list results by `id`, not by the timestamp cursor, so there is no way+ # to request ascending-by-cursor ordering. We keep `asc` (the watermark advances to the+ # max cursor value seen) and rely on the resumable `Link` cursor to make in-run retries+ # safe; merge semantics dedupe re-fetched rows.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/greenhouse/settings.py b/posthog/temporal/data_imports/sources/greenhouse/settings.pynew file mode 100644index 000000000000..536e5f3b3776--- /dev/null+++ b/posthog/temporal/data_imports/sources/greenhouse/settings.py@@ -0,0 +1,185 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class GreenhouseEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable field used for datetime partitioning. Must never be a field that mutates over an+ # object's lifetime (so `created_at`, never `updated_at`). Left as ``None`` for the small+ # reference endpoints whose objects don't expose a creation timestamp.+ partition_key: Optional[str] = None+ # Maps an advertised incremental field name to the Harvest query param that filters it+ # server-side (e.g. `updated_at` -> `updated_after`). Only populated for endpoints with a+ # genuine documented server-side timestamp filter.+ incremental_filter_params: dict[str, str] = field(default_factory=dict)+++def _datetime_incremental_field(name: str) -> IncrementalField:+ # Harvest returns timestamps as ISO 8601 strings (e.g. "2019-01-01T00:00:00.000Z"), so the+ # cursor is stored and compared as a datetime — no normalization needed on the rows.+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Core Greenhouse Harvest (recruiting) objects. The major streams expose documented+# `updated_after` / `created_after` server-side filters and ship incremental; the small+# reference endpoints (departments, offices, sources, rejection/close reasons) have no+# timestamp filter and ship full refresh. Per-parent fan-out streams (activity feeds,+# per-application interviews/scorecards) are intentionally deferred to a later pass.+GREENHOUSE_ENDPOINTS: dict[str, GreenhouseEndpointConfig] = {+ "candidates": GreenhouseEndpointConfig(+ name="candidates",+ path="/candidates",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "applications": GreenhouseEndpointConfig(+ name="applications",+ path="/applications",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("last_activity_at"),+ _datetime_incremental_field("created_at"),+ ],+ # `/applications` does not document `updated_after`; it exposes `last_activity_after`+ # (filters `last_activity_at`) and `created_after` instead.+ incremental_filter_params={+ "last_activity_at": "last_activity_after",+ "created_at": "created_after",+ },+ ),+ "jobs": GreenhouseEndpointConfig(+ name="jobs",+ path="/jobs",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "job_posts": GreenhouseEndpointConfig(+ name="job_posts",+ path="/job_posts",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "offers": GreenhouseEndpointConfig(+ name="offers",+ path="/offers",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "scorecards": GreenhouseEndpointConfig(+ name="scorecards",+ path="/scorecards",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "scheduled_interviews": GreenhouseEndpointConfig(+ name="scheduled_interviews",+ path="/scheduled_interviews",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "users": GreenhouseEndpointConfig(+ name="users",+ path="/users",+ primary_keys=["id"],+ partition_key="created_at",+ incremental_fields=[+ _datetime_incremental_field("updated_at"),+ _datetime_incremental_field("created_at"),+ ],+ incremental_filter_params={+ "updated_at": "updated_after",+ "created_at": "created_after",+ },+ ),+ "departments": GreenhouseEndpointConfig(+ name="departments",+ path="/departments",+ primary_keys=["id"],+ ),+ "offices": GreenhouseEndpointConfig(+ name="offices",+ path="/offices",+ primary_keys=["id"],+ ),+ "sources": GreenhouseEndpointConfig(+ name="sources",+ path="/sources",+ primary_keys=["id"],+ ),+ "rejection_reasons": GreenhouseEndpointConfig(+ name="rejection_reasons",+ path="/rejection_reasons",+ primary_keys=["id"],+ ),+ "close_reasons": GreenhouseEndpointConfig(+ name="close_reasons",+ path="/close_reasons",+ primary_keys=["id"],+ ),+}++ENDPOINTS = tuple(GREENHOUSE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GREENHOUSE_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/greenhouse/source.py b/posthog/temporal/data_imports/sources/greenhouse/source.pyindex bbfab387ff6e..1c4a35103f10 100644--- a/posthog/temporal/data_imports/sources/greenhouse/source.py+++ b/posthog/temporal/data_imports/sources/greenhouse/source.py@@ -1,19 +1,35 @@-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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import GreenhouseSourceConfig+from posthog.temporal.data_imports.sources.greenhouse.greenhouse import (+ GreenhouseResumeConfig,+ greenhouse_source,+ validate_credentials as validate_greenhouse_credentials,+)+from posthog.temporal.data_imports.sources.greenhouse.settings import (+ ENDPOINTS,+ GREENHOUSE_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class GreenhouseSource(SimpleSource[GreenhouseSourceConfig]):+class GreenhouseSource(ResumableSource[GreenhouseSourceConfig, GreenhouseResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GREENHOUSE@@ -23,7 +39,90 @@ class GreenhouseSource(SimpleSource[GreenhouseSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.GREENHOUSE,label="Greenhouse",- iconPath="/static/services/greenhouse.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Greenhouse Harvest API key to automatically pull your Greenhouse recruiting data into the PostHog Data warehouse.++You can create a Harvest API key in Greenhouse under **Configure → Dev Center → API Credential Management**.++Grant the key read (`GET`) access to the resources you want to sync — for example **Candidates**, **Applications**, **Jobs**, **Job Posts**, **Offers**, **Scorecards**, **Scheduled Interviews**, and **Users**.""",+ iconPath="/static/services/greenhouse.png",+ docsUrl="https://posthog.com/docs/cdp/sources/greenhouse",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: GreenhouseSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [schema for schema in schemas if schema.name in names_set]++ return schemas++ def validate_credentials(+ self, config: GreenhouseSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # At source-create (`schema_name is None`) accept a 403 — the key may legitimately be+ # scoped only to the endpoints the user wants. For a per-schema check, probe that+ # endpoint and surface a missing-scope error.+ if schema_name is not None and schema_name in GREENHOUSE_ENDPOINTS:+ return validate_greenhouse_credentials(+ config.api_key, path=GREENHOUSE_ENDPOINTS[schema_name].path, accept_forbidden=False+ )++ return validate_greenhouse_credentials(config.api_key, accept_forbidden=True)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://harvest.greenhouse.io": "Your Greenhouse API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url: https://harvest.greenhouse.io": "Your Greenhouse API key does not have the required permissions. Please grant read access to this resource and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GreenhouseResumeConfig]:+ return ResumableSourceManager[GreenhouseResumeConfig](inputs, GreenhouseResumeConfig)++ def source_for_pipeline(+ self,+ config: GreenhouseSourceConfig,+ resumable_source_manager: ResumableSourceManager[GreenhouseResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return greenhouse_source(+ api_key=config.api_key,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.py b/posthog/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.pynew file mode 100644index 000000000000..4376a2e18835--- /dev/null+++ b/posthog/temporal/data_imports/sources/greenhouse/tests/test_greenhouse.py@@ -0,0 +1,232 @@+import json+import dataclasses+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from posthog.temporal.data_imports.sources.greenhouse.greenhouse import (+ GREENHOUSE_ENDPOINTS,+ PAGE_SIZE,+ GreenhouseResumeConfig,+ _build_initial_params,+ _format_datetime,+ greenhouse_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.greenhouse.settings import ENDPOINTS+++def _make_response(body: Any, status_code: int = 200, next_url: str | None = None) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ if next_url is not None:+ # RFC 5988 Link header, as Harvest returns it. requests parses this into `resp.links`.+ resp.headers["Link"] = f'<{next_url}>; rel="next"'+ return resp+++class TestFormatDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"), # naive -> treated as UTC+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("already-a-string", "already-a-string"),+ ],+ )+ def test_format_datetime(self, value: object, expected: str) -> None:+ assert _format_datetime(value) == expected++ def test_no_plus_zero_offset(self) -> None:+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+++class TestBuildInitialParams:+ def test_full_refresh_only_sets_per_page(self) -> None:+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["departments"], False, None, None)+ assert params == {"per_page": PAGE_SIZE}++ def test_first_incremental_sync_has_no_filter(self) -> None:+ # No watermark yet -> pull everything, only per_page is set.+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, None, "updated_at")+ assert params == {"per_page": PAGE_SIZE}++ def test_incremental_filter_maps_updated_at_to_updated_after(self) -> None:+ watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, watermark, "updated_at")+ assert params == {"per_page": PAGE_SIZE, "updated_after": "2026-03-04T02:58:14.000Z"}++ def test_incremental_filter_uses_chosen_cursor_field(self) -> None:+ watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, watermark, "created_at")+ assert params == {"per_page": PAGE_SIZE, "created_after": "2026-03-04T02:58:14.000Z"}++ def test_applications_uses_last_activity_after(self) -> None:+ watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["applications"], True, watermark, "last_activity_at")+ assert params == {"per_page": PAGE_SIZE, "last_activity_after": "2026-03-04T02:58:14.000Z"}++ def test_unknown_cursor_field_is_ignored(self) -> None:+ watermark = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ params = _build_initial_params(GREENHOUSE_ENDPOINTS["candidates"], True, watermark, "somethingElse")+ assert params == {"per_page": PAGE_SIZE}+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, accept_forbidden, expected_valid",+ [+ (200, True, True),+ (200, False, True),+ (401, True, False),+ (401, False, False),+ (403, True, True), # source-create: a scoped key may legitimately 403+ (403, False, False), # per-schema check: missing scope is an error+ (500, True, False),+ ],+ )+ @patch("posthog.temporal.data_imports.sources.greenhouse.greenhouse.make_tracked_session")+ def test_status_code_mapping(+ self, mock_session_factory: MagicMock, status_code: int, accept_forbidden: bool, expected_valid: bool+ ) -> None:+ mock_session = mock_session_factory.return_value+ mock_session.get.return_value = _make_response({}, status_code=status_code)++ is_valid, error = validate_credentials("test_key", accept_forbidden=accept_forbidden)++ assert is_valid is expected_valid+ assert (error is None) is expected_valid++ @patch("posthog.temporal.data_imports.sources.greenhouse.greenhouse.make_tracked_session")+ def test_network_error_is_not_valid(self, mock_session_factory: MagicMock) -> None:+ mock_session_factory.return_value.get.side_effect = Exception("boom")+ is_valid, error = validate_credentials("test_key")+ assert is_valid is False+ assert error == "boom"+++class TestGreenhouseSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_primary_keys_match_settings(self, endpoint: str) -> None:+ response = greenhouse_source("key", endpoint, MagicMock(), MagicMock())+ assert response.primary_keys == GREENHOUSE_ENDPOINTS[endpoint].primary_keys++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_partitioning_only_when_partition_key_present(self, endpoint: str) -> None:+ response = greenhouse_source("key", endpoint, MagicMock(), MagicMock())+ partition_key = GREENHOUSE_ENDPOINTS[endpoint].partition_key++ if partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_partition_key_is_never_updated_at(self, endpoint: str) -> None:+ assert GREENHOUSE_ENDPOINTS[endpoint].partition_key not in ("updated_at", "last_activity_at")++ def test_sort_mode_is_ascending(self) -> None:+ assert greenhouse_source("key", "candidates", MagicMock(), MagicMock()).sort_mode == "asc"+++class TestGreenhousePaginationAndResume:+ """Drive ``get_rows`` (via ``greenhouse_source``) with a mocked HTTP session."""++ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response]+ ) -> tuple[list[tuple[str, dict[str, Any] | None]], list[Any]]:+ """Returns (per-request (url, params) tuples, batches yielded by the source)."""+ sent: list[tuple[str, dict[str, Any] | None]] = []+ yielded: list[Any] = []+ response_iter = iter(responses)++ def fake_get(url: str, *_args: Any, **kwargs: Any) -> Response:+ sent.append((url, kwargs.get("params")))+ return next(response_iter)++ with patch("posthog.temporal.data_imports.sources.greenhouse.greenhouse.make_tracked_session") as mock_factory:+ mock_factory.return_value.get.side_effect = fake_get++ response = greenhouse_source("key", endpoint, MagicMock(), manager)+ yielded.extend(cast(Iterable[Any], response.items()))++ return sent, yielded++ def test_fresh_run_follows_link_header(self) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ next_url = "https://harvest.greenhouse.io/v1/candidates?per_page=500&page=2"+ responses = [+ _make_response([{"id": 1}], next_url=next_url),+ _make_response([{"id": 2}]), # no Link header -> last page+ ]++ sent, yielded = self._drive("candidates", manager, responses)++ # First request hits the path with params; second follows the Link URL verbatim (no params).+ assert sent[0][0] == "https://harvest.greenhouse.io/v1/candidates"+ assert sent[0][1] == {"per_page": PAGE_SIZE}+ assert sent[1] == (next_url, None)++ flat = [row for batch in yielded for row in batch]+ assert flat == [{"id": 1}, {"id": 2}]++ def test_saves_next_url_after_each_non_terminal_page(self) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ url2 = "https://harvest.greenhouse.io/v1/jobs?per_page=500&page=2"+ url3 = "https://harvest.greenhouse.io/v1/jobs?per_page=500&page=3"+ responses = [+ _make_response([{"id": 1}], next_url=url2),+ _make_response([{"id": 2}], next_url=url3),+ _make_response([{"id": 3}]),+ ]+ self._drive("jobs", manager, responses)++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [GreenhouseResumeConfig(next_url=url2), GreenhouseResumeConfig(next_url=url3)]++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ self._drive("jobs", manager, [_make_response([{"id": 1}])])+ manager.save_state.assert_not_called()++ def test_resume_seeds_first_request_with_saved_next_url(self) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = True+ saved_url = "https://harvest.greenhouse.io/v1/candidates?per_page=500&page=5"+ manager.load_state.return_value = GreenhouseResumeConfig(next_url=saved_url)++ sent, _ = self._drive("candidates", manager, [_make_response([{"id": 9}])])++ assert sent[0] == (saved_url, None)++ def test_empty_page_yields_nothing_and_stops(self) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ sent, yielded = self._drive("jobs", manager, [_make_response([])])+ assert yielded == []+ assert len(sent) == 1+++class TestResumeConfigSerialization:+ def test_round_trip(self) -> None:+ cfg = GreenhouseResumeConfig(next_url="https://harvest.greenhouse.io/v1/candidates?page=3")+ reconstituted = GreenhouseResumeConfig(**json.loads(json.dumps(dataclasses.asdict(cfg))))+ assert reconstituted == cfgdiff --git a/posthog/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.py b/posthog/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.pynew file mode 100644index 000000000000..b98f8e55c5a7--- /dev/null+++ b/posthog/temporal/data_imports/sources/greenhouse/tests/test_greenhouse_source.py@@ -0,0 +1,162 @@+import pytest+from unittest import mock++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.generated_configs import GreenhouseSourceConfig+from posthog.temporal.data_imports.sources.greenhouse.greenhouse import GreenhouseResumeConfig+from posthog.temporal.data_imports.sources.greenhouse.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.greenhouse.source import GreenhouseSource++from products.data_warehouse.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {+ "candidates",+ "applications",+ "jobs",+ "job_posts",+ "offers",+ "scorecards",+ "scheduled_interviews",+ "users",+}+FULL_REFRESH_ENDPOINTS = {"departments", "offices", "sources", "rejection_reasons", "close_reasons"}+++class TestGreenhouseSource:+ def setup_method(self) -> None:+ self.source = GreenhouseSource()+ self.team_id = 123+ self.config = GreenhouseSourceConfig(api_key="test_api_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.GREENHOUSE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Greenhouse"+ assert config.label == "Greenhouse"+ assert config.releaseStatus == "alpha"+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/greenhouse.png"+ assert len(config.fields) == 1++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ @pytest.mark.parametrize(+ "expected_key",+ [+ "401 Client Error: Unauthorized for url: https://harvest.greenhouse.io",+ "403 Client Error: Forbidden for url: https://harvest.greenhouse.io",+ ],+ )+ def test_non_retryable_errors_includes_greenhouse_key(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_non_retryable_errors_matches_observed_error_message(self) -> None:+ observed = "401 Client Error: Unauthorized for url: https://harvest.greenhouse.io/v1/candidates?per_page=500"+ assert any(key in observed for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.lever.co/v1/opportunities",+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ ],+ )+ def test_non_retryable_errors_does_not_match_other_vendors(self, other_vendor_error: str) -> None:+ assert not any(key in other_vendor_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_split(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ appendable = {schema.name for schema in schemas if schema.supports_append}++ assert incremental == INCREMENTAL_ENDPOINTS+ assert appendable == INCREMENTAL_ENDPOINTS++ @pytest.mark.parametrize("endpoint", sorted(FULL_REFRESH_ENDPOINTS))+ def test_reference_endpoints_are_full_refresh(self, endpoint: str) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=[endpoint])+ assert len(schemas) == 1+ assert schemas[0].supports_incremental is False+ assert schemas[0].incremental_fields == []++ def test_candidates_advertises_created_and_updated_cursors(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["candidates"])+ fields = {field["field"] for field in schemas[0].incremental_fields}+ assert fields == {"created_at", "updated_at"}++ def test_applications_advertises_last_activity_cursor(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["applications"])+ fields = {field["field"] for field in schemas[0].incremental_fields}+ assert fields == {"created_at", "last_activity_at"}++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @mock.patch("posthog.temporal.data_imports.sources.greenhouse.source.validate_greenhouse_credentials")+ def test_validate_credentials_at_source_create_accepts_forbidden(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)++ is_valid, error = self.source.validate_credentials(self.config, self.team_id, schema_name=None)++ assert is_valid is True+ assert error is None+ mock_validate.assert_called_once_with("test_api_key", accept_forbidden=True)++ @mock.patch("posthog.temporal.data_imports.sources.greenhouse.source.validate_greenhouse_credentials")+ def test_validate_credentials_per_schema_probes_endpoint_path(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)++ self.source.validate_credentials(self.config, self.team_id, schema_name="candidates")++ mock_validate.assert_called_once_with("test_api_key", path="/candidates", accept_forbidden=False)++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is GreenhouseResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.greenhouse.source.greenhouse_source")+ def test_source_for_pipeline_passes_incremental_inputs(self, mock_greenhouse_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "candidates"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"+ inputs.incremental_field = "updated_at"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_greenhouse_source.call_args.kwargs+ assert kwargs["api_key"] == "test_api_key"+ assert kwargs["endpoint"] == "candidates"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"+ assert kwargs["incremental_field"] == "updated_at"++ @mock.patch("posthog.temporal.data_imports.sources.greenhouse.source.greenhouse_source")+ def test_source_for_pipeline_drops_last_value_when_not_incremental(+ self, mock_greenhouse_source: mock.MagicMock+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "departments"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00.000Z"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_greenhouse_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None