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 lever import source (#61151)

Tom Owersbd10424854ff
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 78e5e7e7cc21..d8a9f98b039b 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -65,6 +65,7 @@ the row lists both.
| hubspot | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
+| lever | HTTP | requests | ✅ |
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
| mailjet | HTTP | requests | ✅ |
@@ -177,7 +178,6 @@ doesn't conflict with concurrent PRs.
- jira
- kafka
- launchdarkly
-- lever
- mailerlite
- marketo
- microsoft_teams
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 005593fda272..4ea74c7ecc8f 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -458,7 +458,7 @@ class LaunchDarklySourceConfig(config.Config):
@config.config
class LeverSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/lever/lever.py b/posthog/temporal/data_imports/sources/lever/lever.py
new file mode 100644
index 000000000000..5f8d87354998
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lever/lever.py
@@ -0,0 +1,183 @@
+import dataclasses
+from collections.abc import Iterator
+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.lever.settings import LEVER_ENDPOINTS, LeverEndpointConfig
+
+LEVER_BASE_URL = "https://api.lever.co/v1"
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Lever returns these top-level fields as Unix-epoch milliseconds. We store them as epoch
+# seconds (int) so datetime partitioning and incremental watermarks behave like the other
+# epoch-based sources (Clerk, Stripe).
+_TIMESTAMP_FIELDS = ("createdAt", "updatedAt")
+
+
+class LeverRetryableError(Exception):
+ pass
+
+
+class LeverResumeConfig:
+ # Lever paginates with an opaque `offset` token returned as `next` in each response.
+ offset: str
+
+
+def _auth(api_key: str) -> tuple[str, str]:
+ # Lever uses HTTP Basic auth with the API key as the username and a blank password.
+ return (api_key, "")
+
+
+def _normalize_item(item: dict[str, Any]) -> dict[str, Any]:
+ for ts_field in _TIMESTAMP_FIELDS:
+ value = item.get(ts_field)
+ if isinstance(value, int):
+ # Integer division keeps the int64 type that delta tables expect.
+ item[ts_field] = value // 1000
+ return item
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ url = f"{LEVER_BASE_URL}/postings"
+ session = make_tracked_session()
+ try:
+ response = session.get(url, auth=_auth(api_key), params={"limit": 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 in (401, 403):
+ return False, "Invalid Lever API key. Please check your key and try again."
+
+ return False, f"Lever API returned an unexpected status code: {response.status_code}"
+
+
+def _build_initial_params(
+ config: LeverEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": config.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:
+ # The stored watermark is epoch seconds; Lever's timestamp filters expect
+ # milliseconds. `_start` filters are inclusive — merge dedupes the boundary rows.
+ params[filter_param] = int(db_incremental_field_last_value) * 1000
+
+ return params
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LeverResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = LEVER_ENDPOINTS[endpoint]
+ url = f"{LEVER_BASE_URL}{config.path}"
+ 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
+ offset: str | None = resume_config.offset if resume_config else None
+ if offset:
+ logger.debug(f"Lever: resuming {endpoint} from offset token")
+
+ @retry(
+ retry=retry_if_exception_type((LeverRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(params: dict[str, Any]) -> dict[str, Any]:
+ 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 LeverRetryableError(f"Lever API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Lever API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ try:
+ while True:
+ params = dict(base_params)
+ if offset:
+ params["offset"] = offset
+
+ data = fetch_page(params)
+
+ items = data.get("data", [])
+ if items:
+ yield [_normalize_item(item) for item in items]
+
+ if not data.get("hasNext"):
+ break
+
+ next_offset = data.get("next")
+ if not next_offset:
+ # Lever signalled more pages (`hasNext`) but gave us no cursor to fetch
+ # them. Breaking here would silently truncate the sync, so fail loudly and
+ # let the pipeline retry instead of completing with partial data.
+ raise Exception(f"Lever: hasNext was true but no next offset token returned for endpoint={endpoint}")
+
+ # Save state after yielding so a crash re-yields the last batch (merge dedupes
+ # on the primary key) rather than skipping it.
+ offset = next_offset
+ resumable_source_manager.save_state(LeverResumeConfig(offset=offset))
+ finally:
+ session.close()
+
+
+def lever_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LeverResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = LEVER_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,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/lever/settings.py b/posthog/temporal/data_imports/sources/lever/settings.py
new file mode 100644
index 000000000000..10b8a331eb6f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lever/settings.py
@@ -0,0 +1,100 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class LeverEndpointConfig:
+ 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 `createdAt`, never `updatedAt`).
+ partition_key: Optional[str] = None
+ # Maps an advertised incremental field name to the Lever query param that filters it
+ # server-side (e.g. `updatedAt` -> `updated_at_start`). Only populated for endpoints
+ # with a genuine server-side timestamp filter.
+ incremental_filter_params: dict[str, str] = field(default_factory=dict)
+ page_size: int = 100 # Lever default and maximum is 100
+
+
+def _timestamp_incremental_field(name: str) -> IncrementalField:
+ # Lever returns timestamps as Unix-epoch milliseconds. We normalize them to epoch
+ # seconds (stored as integers), matching the convention used by the other epoch-based
+ # sources (Clerk, Stripe) so datetime partitioning and incremental watermarks line up.
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.Integer,
+ }
+
+
+# Only `opportunities` exposes documented server-side timestamp filters
+# (`created_at_start` / `updated_at_start`), so it is the only endpoint shipped with
+# incremental sync. Everything else is full refresh. Per-opportunity fan-out streams
+# (interviews, feedback, offers, notes, referrals) and the descending-ordered
+# `audit_events` stream are intentionally deferred — see source.py / the PR notes.
+LEVER_ENDPOINTS: dict[str, LeverEndpointConfig] = {
+ "opportunities": LeverEndpointConfig(
+ name="opportunities",
+ path="/opportunities",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ incremental_fields=[
+ _timestamp_incremental_field("createdAt"),
+ _timestamp_incremental_field("updatedAt"),
+ ],
+ incremental_filter_params={
+ "createdAt": "created_at_start",
+ "updatedAt": "updated_at_start",
+ },
+ ),
+ "postings": LeverEndpointConfig(
+ name="postings",
+ path="/postings",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ ),
+ "users": LeverEndpointConfig(
+ name="users",
+ path="/users",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ ),
+ "requisitions": LeverEndpointConfig(
+ name="requisitions",
+ path="/requisitions",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ ),
+ "archive_reasons": LeverEndpointConfig(
+ name="archive_reasons",
+ path="/archive_reasons",
+ primary_keys=["id"],
+ ),
+ "stages": LeverEndpointConfig(
+ name="stages",
+ path="/stages",
+ primary_keys=["id"],
+ ),
+ # `/sources` and `/tags` return objects keyed by their unique `text` value (no `id`).
+ "sources": LeverEndpointConfig(
+ name="sources",
+ path="/sources",
+ primary_keys=["text"],
+ ),
+ "tags": LeverEndpointConfig(
+ name="tags",
+ path="/tags",
+ primary_keys=["text"],
+ ),
+}
+
+ENDPOINTS = tuple(LEVER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in LEVER_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/lever/source.py b/posthog/temporal/data_imports/sources/lever/source.py
index 9e9a48d18494..5a9e8c36faa6 100644
--- a/posthog/temporal/data_imports/sources/lever/source.py
+++ b/posthog/temporal/data_imports/sources/lever/source.py
@@ -1,19 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from 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, 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 LeverSourceConfig
+from posthog.temporal.data_imports.sources.lever.lever import (
+ LeverResumeConfig,
+ lever_source,
+ validate_credentials as validate_lever_credentials,
+)
+from posthog.temporal.data_imports.sources.lever.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LeverSource(SimpleSource[LeverSourceConfig]):
+class LeverSource(ResumableSource[LeverSourceConfig, LeverResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LEVER
@@ -23,7 +35,81 @@ class LeverSource(SimpleSource[LeverSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.LEVER,
label="Lever",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Lever API key to automatically pull your Lever recruiting data into the PostHog Data warehouse.
+
+You can generate an API key in your Lever account under **Settings → Integrations and API → API Credentials**.
+
+The key has full read access to your account's data; no individual scopes need to be granted.""",
iconPath="/static/services/lever.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/lever",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: LeverSourceConfig,
+ 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: LeverSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_lever_credentials(config.api_key)
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.lever.co": "Your Lever API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.lever.co": "Your Lever API key does not have the required permissions. Please check the key and try again.",
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LeverResumeConfig]:
+ return ResumableSourceManager[LeverResumeConfig](inputs, LeverResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LeverSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LeverResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return lever_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/lever/tests/test_lever.py b/posthog/temporal/data_imports/sources/lever/tests/test_lever.py
new file mode 100644
index 000000000000..7b1ce3bf5b54
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lever/tests/test_lever.py
@@ -0,0 +1,233 @@
+import json
+import dataclasses
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from posthog.temporal.data_imports.sources.lever.lever import (
+ LEVER_ENDPOINTS,
+ LeverResumeConfig,
+ _build_initial_params,
+ _normalize_item,
+ lever_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.lever.settings import ENDPOINTS
+
+
+def _make_response(body: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _page(items: list[dict[str, Any]], has_next: bool, next_offset: str | None = None) -> dict[str, Any]:
+ body: dict[str, Any] = {"data": items, "hasNext": has_next}
+ if next_offset is not None:
+ body["next"] = next_offset
+ return body
+
+
+class TestNormalizeItem:
+ @pytest.mark.parametrize(
+ "item, expected",
+ [
+ ({"id": "a", "createdAt": 1700000000000}, {"id": "a", "createdAt": 1700000000}),
+ (
+ {"id": "a", "createdAt": 1700000000000, "updatedAt": 1700000005000},
+ {"id": "a", "createdAt": 1700000000, "updatedAt": 1700000005},
+ ),
+ ({"id": "a"}, {"id": "a"}), # no timestamp fields -> untouched
+ ({"id": "a", "createdAt": None}, {"id": "a", "createdAt": None}), # null preserved
+ ],
+ )
+ def test_milliseconds_converted_to_seconds(self, item: dict[str, Any], expected: dict[str, Any]) -> None:
+ assert _normalize_item(item) == expected
+
+
+class TestBuildInitialParams:
+ def test_full_refresh_only_sets_limit(self) -> None:
+ params = _build_initial_params(LEVER_ENDPOINTS["users"], False, None, None)
+ assert params == {"limit": 100}
+
+ def test_first_incremental_sync_has_no_filter(self) -> None:
+ # No watermark yet (initial sync) -> pull everything, only limit is set.
+ params = _build_initial_params(LEVER_ENDPOINTS["opportunities"], True, None, "updatedAt")
+ assert params == {"limit": 100}
+
+ def test_incremental_filter_converts_seconds_to_milliseconds(self) -> None:
+ params = _build_initial_params(LEVER_ENDPOINTS["opportunities"], True, 1700000000, "updatedAt")
+ assert params == {"limit": 100, "updated_at_start": 1700000000000}
+
+ def test_incremental_filter_uses_chosen_cursor_field(self) -> None:
+ params = _build_initial_params(LEVER_ENDPOINTS["opportunities"], True, 1700000000, "createdAt")
+ assert params == {"limit": 100, "created_at_start": 1700000000000}
+
+ def test_unknown_cursor_field_is_ignored(self) -> None:
+ params = _build_initial_params(LEVER_ENDPOINTS["opportunities"], True, 1700000000, "somethingElse")
+ assert params == {"limit": 100}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @patch("posthog.temporal.data_imports.sources.lever.lever.make_tracked_session")
+ def test_status_code_mapping(self, mock_session_factory, status_code: int, 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")
+
+ assert is_valid is expected_valid
+ if expected_valid:
+ assert error is None
+ else:
+ assert error is not None
+
+ @patch("posthog.temporal.data_imports.sources.lever.lever.make_tracked_session")
+ def test_network_error_is_not_valid(self, mock_session_factory) -> None:
+ mock_session = mock_session_factory.return_value
+ mock_session.get.side_effect = Exception("boom")
+
+ is_valid, error = validate_credentials("test_key")
+
+ assert is_valid is False
+ assert error == "boom"
+
+
+class TestLeverSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_primary_keys_match_settings(self, endpoint: str) -> None:
+ response = lever_source("key", endpoint, MagicMock(), MagicMock())
+ assert response.primary_keys == LEVER_ENDPOINTS[endpoint].primary_keys
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_partitioning_only_when_partition_key_present(self, endpoint: str) -> None:
+ response = lever_source("key", endpoint, MagicMock(), MagicMock())
+ partition_key = LEVER_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
+
+ def test_partition_key_is_never_updated_at(self) -> None:
+ for endpoint in ENDPOINTS:
+ assert LEVER_ENDPOINTS[endpoint].partition_key != "updatedAt"
+
+ def test_sort_mode_is_ascending(self) -> None:
+ response = lever_source("key", "opportunities", MagicMock(), MagicMock())
+ assert response.sort_mode == "asc"
+
+
+class TestLeverPaginationAndResume:
+ """Drive ``get_rows`` (via ``lever_source``) with a mocked HTTP session."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[list[dict[str, Any]], list[Any]]:
+ """Returns (params sent per request, batches yielded by the source)."""
+ sent_params: list[dict[str, Any]] = []
+ yielded: list[Any] = []
+ response_iter = iter(responses)
+
+ def fake_get(url: str, *_args: Any, **kwargs: Any) -> Response:
+ sent_params.append(dict(kwargs.get("params", {})))
+ return next(response_iter)
+
+ with patch("posthog.temporal.data_imports.sources.lever.lever.make_tracked_session") as mock_factory:
+ mock_factory.return_value.get.side_effect = fake_get
+
+ response = lever_source("key", endpoint, MagicMock(), manager)
+ yielded.extend(cast(Iterable[Any], response.items()))
+
+ return sent_params, yielded
+
+ def test_fresh_run_paginates_and_normalizes(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_response(_page([{"id": "o1", "createdAt": 1700000000000}], True, "offset_2")),
+ _make_response(_page([{"id": "o2", "createdAt": 1700000005000}], False)),
+ ]
+
+ sent_params, yielded = self._drive("opportunities", manager, responses)
+
+ # First request has no offset; second request uses the saved offset token.
+ assert sent_params[0].get("offset") is None
+ assert sent_params[1].get("offset") == "offset_2"
+
+ # Timestamps were converted ms -> seconds in the yielded rows.
+ flat = [row for batch in yielded for row in batch]
+ assert flat == [
+ {"id": "o1", "createdAt": 1700000000},
+ {"id": "o2", "createdAt": 1700000005},
+ ]
+
+ def test_saves_offset_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_response(_page([{"id": "o1"}], True, "offset_2")),
+ _make_response(_page([{"id": "o2"}], True, "offset_3")),
+ _make_response(_page([{"id": "o3"}], False)),
+ ]
+ self._drive("opportunities", manager, responses)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [LeverResumeConfig(offset="offset_2"), LeverResumeConfig(offset="offset_3")]
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ responses = [_make_response(_page([{"id": "only"}], False))]
+ self._drive("opportunities", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_resume_seeds_first_request_with_saved_offset(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = LeverResumeConfig(offset="saved_offset")
+
+ responses = [_make_response(_page([{"id": "o5"}], False))]
+ sent_params, _ = self._drive("opportunities", manager, responses)
+
+ assert sent_params[0].get("offset") == "saved_offset"
+
+ def test_hasnext_without_next_token_raises(self) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ # hasNext is True but no `next` token -> fail loudly rather than silently
+ # truncating the sync with partial data.
+ responses = [_make_response(_page([{"id": "o1"}], True))]
+ with pytest.raises(Exception, match="hasNext was true but no next offset token"):
+ self._drive("opportunities", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+
+class TestResumeConfigSerialization:
+ def test_round_trip(self) -> None:
+ cfg = LeverResumeConfig(offset="abc123")
+ reconstituted = LeverResumeConfig(**json.loads(json.dumps(dataclasses.asdict(cfg))))
+ assert reconstituted == cfg
diff --git a/posthog/temporal/data_imports/sources/lever/tests/test_lever_source.py b/posthog/temporal/data_imports/sources/lever/tests/test_lever_source.py
new file mode 100644
index 000000000000..657936fdaab7
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lever/tests/test_lever_source.py
@@ -0,0 +1,155 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.generated_configs import LeverSourceConfig
+from posthog.temporal.data_imports.sources.lever.lever import LeverResumeConfig
+from posthog.temporal.data_imports.sources.lever.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.lever.source import LeverSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"opportunities"}
+
+
+class TestLeverSource:
+ def setup_method(self):
+ self.source = LeverSource()
+ self.team_id = 123
+ self.config = LeverSourceConfig(api_key="test_api_key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LEVER
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Lever"
+ assert config.label == "Lever"
+ assert config.releaseStatus == "alpha"
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/lever.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://api.lever.co",
+ "403 Client Error: Forbidden for url: https://api.lever.co",
+ ],
+ )
+ def test_non_retryable_errors_includes_lever_key(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_non_retryable_errors_matches_observed_error_message(self):
+ observed_error = "401 Client Error: Unauthorized for url: https://api.lever.co/v1/opportunities?limit=100"
+ 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",
+ "401 Client Error: Unauthorized for url: https://api.clerk.com/v1/users",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_other_vendors(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_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_only_opportunities_is_incremental(self):
+ 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
+
+ def test_opportunities_advertises_created_and_updated_cursors(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["opportunities"])
+ assert len(schemas) == 1
+
+ fields = {field["field"] for field in schemas[0].incremental_fields}
+ assert fields == {"createdAt", "updatedAt"}
+
+ 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"
+ assert schemas[0].supports_incremental is False
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_error",
+ [
+ ((True, None), True, None),
+ (
+ (False, "Invalid Lever API key. Please check your key and try again."),
+ False,
+ "Invalid Lever API key. Please check your key and try again.",
+ ),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.lever.source.validate_lever_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_error):
+ mock_validate.return_value = mock_return
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error == expected_error
+ mock_validate.assert_called_once_with(self.config.api_key)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is LeverResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.lever.source.lever_source")
+ def test_source_for_pipeline_passes_incremental_inputs(self, mock_lever_source):
+ manager = mock.MagicMock()
+ inputs = mock.MagicMock()
+ inputs.schema_name = "opportunities"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = "updatedAt"
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_lever_source.assert_called_once()
+ kwargs = mock_lever_source.call_args.kwargs
+ assert kwargs["api_key"] == "test_api_key"
+ assert kwargs["endpoint"] == "opportunities"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+ assert kwargs["incremental_field"] == "updatedAt"
+
+ @mock.patch("posthog.temporal.data_imports.sources.lever.source.lever_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_lever_source):
+ manager = mock.MagicMock()
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_lever_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None