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): add lever applications, offers, interviews and feedback tables (#114508)

Tom Owers6cb26c364f97
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 0f4c22bb6198..1ed24cb2431f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5113,14 +5113,14 @@ Note: LACRM's v2 API is RPC-shaped (single POST endpoint with a Function name),
## Lever — gaps
-Today (8): `archive_reasons`, `opportunities`, `postings`, `requisitions`, `sources`, `stages`, `tags`, `users`
+Today (12): `applications`, `archive_reasons`, `feedback`, `interviews`, `offers`, `opportunities`, `postings`, `requisitions`, `sources`, `stages`, `tags`, `users`
Diffed against: <https://hire.lever.co/developer/documentation>
-- [ ] `opportunities/{id}/feedback` — interview scorecards and ratings - the core hiring-quality signal, missing entirely (high)
-- [ ] `opportunities/{id}/interviews` — scheduled interview records with panel/interviewer and timing, needed for funnel and scheduling analysis (high)
-- [ ] `candidates/{id}/applications (+ /applications/deleted)` — links a candidate/opportunity to a specific posting; the join table behind apply-to-hire funnels (high)
-- [ ] `opportunities/{id}/offers` — offer records with salary/status - offer acceptance rate is a headline recruiting metric (high)
+- [x] `opportunities/{id}/feedback` — interview scorecards and ratings - the core hiring-quality signal, missing entirely (high) — synced as `feedback`
+- [x] `opportunities/{id}/interviews` — scheduled interview records with panel/interviewer and timing, needed for funnel and scheduling analysis (high) — synced as `interviews`
+- [x] `candidates/{id}/applications (+ /applications/deleted)` — links a candidate/opportunity to a specific posting; the join table behind apply-to-hire funnels (high) — synced as `applications` through `GET /opportunities?expand=applications`, the route Lever recommends over the deprecated per-candidate endpoint; `/applications/deleted` is not synced because it requires 30-day windows with no documented start
+- [x] `opportunities/{id}/offers` — offer records with salary/status - offer acceptance rate is a headline recruiting metric (high) — synced as `offers`
- [ ] `disposition_stages` — lookup resolving the disposition/stage codes carried on archived opportunities (medium)
- [ ] `audit_events` — state-transition history for candidates, postings and users; the only source of change-over-time in Lever (medium)
- [ ] `opportunities/{id}/notes` — recruiter activity volume per candidate (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/canonical_descriptions.py
index 4abeee79f0ca..a9fcd98c320f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/canonical_descriptions.py
@@ -96,6 +96,75 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"text": "The stage's display name.",
},
},
+ "applications": {
+ "description": "A candidate's application to a job posting. Each opportunity has at most one application.",
+ "docs_url": "https://hire.lever.co/developer/documentation#applications",
+ "columns": {
+ "id": "Unique identifier for the application.",
+ "opportunityId": "ID of the opportunity the application belongs to.",
+ "createdAt": "When the application was created in Lever (epoch seconds).",
+ "type": "How the application was created: posting, user, or referral.",
+ "posting": "ID of the job posting the candidate applied to.",
+ "postingOwner": "ID of the posting owner at the time the candidate applied.",
+ "postingHiringManager": "ID of the posting's hiring manager at the time the candidate applied.",
+ "user": "For referral applications, ID of the user who made the referral.",
+ },
+ },
+ "offers": {
+ "description": "An offer sent to a candidate for an opportunity, with its status and offer fields.",
+ "docs_url": "https://hire.lever.co/developer/documentation#offers",
+ "columns": {
+ "id": "Unique identifier for the offer.",
+ "opportunity_id": "ID of the opportunity the offer belongs to.",
+ "createdAt": "When the offer was created in Lever (epoch seconds).",
+ "creator": "ID of the user who created the offer.",
+ "status": "Offer status: draft, approval-sent, approved, sent, sent-manually, opened, denied, or signed.",
+ "fields": "Standard and custom offer fields, each with its text, identifier, and value.",
+ "signatures": "Signature details for the candidate and company signers.",
+ "sentDocument": "Details of the offer document sent to the candidate.",
+ "signedDocument": "Details of the signed offer document, if anyone signed it.",
+ },
+ },
+ "interviews": {
+ "description": "A scheduled interview for an opportunity, with its interviewers, time, and location.",
+ "docs_url": "https://hire.lever.co/developer/documentation#interviews",
+ "columns": {
+ "id": "Unique identifier for the interview.",
+ "opportunity_id": "ID of the opportunity the interview belongs to.",
+ "panel": "ID of the interview panel that contains the interview.",
+ "subject": "Interview subject.",
+ "interviewers": "Interviewers, each with their user ID, name, email, and feedback template.",
+ "timezone": "Time zone in which the interview was scheduled.",
+ "createdAt": "When the interview was created in Lever (epoch seconds).",
+ "date": "When the interview is scheduled to occur (epoch milliseconds).",
+ "duration": "Interview duration in minutes.",
+ "location": "Interview location, such as a room name or phone number.",
+ "feedbackForms": "IDs of the feedback forms associated with the interview.",
+ "user": "ID of the user who created the interview.",
+ "stage": "ID of the stage the candidate was in when the interview was scheduled.",
+ "canceledAt": "When the interview was canceled (epoch milliseconds), or null.",
+ "postings": "IDs of the job postings the interview is associated with.",
+ },
+ },
+ "feedback": {
+ "description": "A completed feedback form (scorecard) for an opportunity, usually submitted after an interview.",
+ "docs_url": "https://hire.lever.co/developer/documentation#feedback",
+ "columns": {
+ "id": "Unique identifier for the feedback form.",
+ "opportunity_id": "ID of the opportunity the feedback belongs to.",
+ "type": "Form type: interview, assignment, or share.",
+ "text": "Form title.",
+ "baseTemplateId": "ID of the form template this form was completed from.",
+ "fields": "Form fields with their answers, including scores and ratings.",
+ "user": "ID of the user who completed and submitted the feedback.",
+ "panel": "ID of the interview panel the feedback is associated with.",
+ "interview": "ID of the interview the feedback was submitted for.",
+ "createdAt": "When the form was created (epoch seconds).",
+ "updatedAt": "When the form was last updated (epoch seconds), or null.",
+ "completedAt": "When the form was completed (epoch milliseconds).",
+ "deletedAt": "When the form was deleted (epoch milliseconds).",
+ },
+ },
"sources": {
"description": "A source through which candidates are added to Lever, keyed by its unique text value.",
"docs_url": "https://hire.lever.co/developer/documentation#sources",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/lever.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/lever.py
index e0ccff231a7b..279cf053db5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/lever.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/lever.py
@@ -1,5 +1,6 @@
import dataclasses
-from typing import Any, Optional
+from collections.abc import Callable
+from typing import Any, Optional, cast
from requests import Request, Response
@@ -9,7 +10,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -41,6 +47,18 @@ def _normalize_item(item: dict[str, Any]) -> dict[str, Any]:
return item
+def _explode_nested_rows(rows_field: str) -> Callable[[dict[str, Any]], list[dict[str, Any]]]:
+ def _explode(item: dict[str, Any]) -> list[dict[str, Any]]:
+ rows = item.get(rows_field) or []
+ for row in rows:
+ if not isinstance(row, dict):
+ # An unexpanded id means Lever ignored `expand`; fail rather than sync an empty table.
+ raise ValueError(f"Lever: expected expanded {rows_field} objects but got {type(row).__name__}")
+ return [_normalize_item(row) for row in rows]
+
+ return _explode
+
+
class LeverPaginator(BasePaginator):
"""Cursor pagination for Lever.
@@ -122,7 +140,7 @@ def _build_initial_params(
db_incremental_field_last_value: Any,
incremental_field: str | None,
) -> dict[str, Any]:
- params: dict[str, Any] = {"limit": config.page_size}
+ params: dict[str, Any] = {"limit": config.page_size, **config.params}
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)
@@ -134,6 +152,49 @@ def _build_initial_params(
return params
+def _client_config(api_key: str, endpoint: str) -> ClientConfig:
+ return {
+ "base_url": LEVER_BASE_URL,
+ # Lever uses HTTP Basic auth with the API key as the username and a blank password.
+ # Supplying it through the framework auth keeps it off logged URLs/bodies.
+ "auth": {"type": "http_basic", "username": api_key, "password": ""},
+ "paginator": LeverPaginator(endpoint),
+ }
+
+
+def _fanout_source(api_key: str, config: LeverEndpointConfig, team_id: int, job_id: str) -> SourceResponse:
+ assert config.fanout is not None
+ # No resume: completed parents would be checkpointed one id each, which grows without bound
+ # on large accounts, and the parent listing is re-fetched each run anyway.
+ resource = cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=LEVER_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=_client_config(api_key, config.name),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"data_selector": "data"},
+ child_endpoint_extra={"data_selector": "data"},
+ ),
+ ).add_map(_normalize_item)
+
+ return SourceResponse(
+ name=config.name,
+ items=lambda: resource,
+ 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",
+ )
+
+
def lever_source(
api_key: str,
endpoint: str,
@@ -146,18 +207,15 @@ def lever_source(
) -> SourceResponse:
config = LEVER_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _fanout_source(api_key, config, team_id, job_id)
+
params = _build_initial_params(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": LEVER_BASE_URL,
- # Lever uses HTTP Basic auth with the API key as the username and a blank password.
- # Supplying it through the framework auth keeps it off logged URLs/bodies.
- "auth": {"type": "http_basic", "username": api_key, "password": ""},
- "paginator": LeverPaginator(endpoint),
- },
+ "client": _client_config(api_key, endpoint),
"resource_defaults": {},
"resources": [
{
@@ -168,7 +226,9 @@ def lever_source(
"data_selector": "data",
},
# Convert Lever's epoch-millisecond timestamps to epoch seconds per row.
- "data_map": _normalize_item,
+ "data_map": _explode_nested_rows(config.nested_rows_field)
+ if config.nested_rows_field
+ else _normalize_item,
}
],
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py
index 1513a95f8644..8f7878ec0140 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py
@@ -1,10 +1,13 @@
from dataclasses import dataclass, field
-from typing import Optional
+from typing import Any, Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class LeverEndpointConfig:
name: str
path: str
@@ -18,6 +21,11 @@ class LeverEndpointConfig:
# 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
+ default_incremental_field: Optional[str] = None
+ params: dict[str, Any] = field(default_factory=dict)
+ # Rows live in this array field of each listed object rather than at the top level of `data`.
+ nested_rows_field: Optional[str] = None
+ fanout: Optional[DependentEndpointConfig] = None
def _timestamp_incremental_field(name: str) -> IncrementalField:
@@ -32,11 +40,25 @@ def _timestamp_incremental_field(name: str) -> IncrementalField:
}
+def _opportunity_fanout() -> DependentEndpointConfig:
+ return DependentEndpointConfig(
+ parent_name="opportunities",
+ resolve_param="opportunity_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "opportunity_id"},
+ # The child only needs each opportunity's id, so skip the rest of the payload.
+ parent_params={"include": "id"},
+ # An opportunity deleted between the listing and its child fetch 404s.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ )
+
+
# 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.
+# incremental sync. Everything else is full refresh. The per-opportunity children have no
+# timestamp filter, and the opportunity `updated_at` filter does not track changes to them,
+# so they fan out over every opportunity on each sync.
LEVER_ENDPOINTS: dict[str, LeverEndpointConfig] = {
"opportunities": LeverEndpointConfig(
name="opportunities",
@@ -52,6 +74,37 @@ LEVER_ENDPOINTS: dict[str, LeverEndpointConfig] = {
"updatedAt": "updated_at_start",
},
),
+ # The per-opportunity applications endpoint is deprecated; Lever points to listing
+ # opportunities with `expand=applications` instead. Each opportunity has at most one.
+ "applications": LeverEndpointConfig(
+ name="applications",
+ path="/opportunities",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ params={"expand": "applications", "include": "applications"},
+ nested_rows_field="applications",
+ ),
+ "offers": LeverEndpointConfig(
+ name="offers",
+ path="/opportunities/{opportunity_id}/offers",
+ primary_keys=["opportunity_id", "id"],
+ partition_key="createdAt",
+ fanout=_opportunity_fanout(),
+ ),
+ "interviews": LeverEndpointConfig(
+ name="interviews",
+ path="/opportunities/{opportunity_id}/interviews",
+ primary_keys=["opportunity_id", "id"],
+ partition_key="createdAt",
+ fanout=_opportunity_fanout(),
+ ),
+ "feedback": LeverEndpointConfig(
+ name="feedback",
+ path="/opportunities/{opportunity_id}/feedback",
+ primary_keys=["opportunity_id", "id"],
+ partition_key="createdAt",
+ fanout=_opportunity_fanout(),
+ ),
"postings": LeverEndpointConfig(
name="postings",
path="/postings",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/tests/test_lever.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/tests/test_lever.py
index f26a0bb1fe5e..717d24f6be5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lever/tests/test_lever.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lever/tests/test_lever.py
@@ -47,34 +47,36 @@ def _make_manager(resume_state: LeverResumeConfig | None = None) -> mock.MagicMo
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session, returning a list that captures each request's params AT SEND TIME.
+def _wire(session: mock.MagicMock, responses: list[Response]) -> tuple[list[dict[str, Any]], list[str]]:
+ """Wire a mock session, returning each request's params and URL captured AT SEND TIME.
``request.params`` is a single dict mutated in place across pages, so inspecting it after the
run shows only the final state — snapshot a copy when each request is prepared instead.
"""
session.headers = {}
param_snapshots: list[dict[str, Any]] = []
+ urls: list[str] = []
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
+ urls.append(request.url)
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
session.send.side_effect = responses
- return param_snapshots
+ return param_snapshots, urls
def _drive(endpoint: str, manager: mock.MagicMock, responses: list[Response], **kwargs: Any):
- """Run ``lever_source`` against a mocked session and return (param snapshots, yielded batches)."""
+ """Run ``lever_source`` against a mocked session and return (param snapshots, yielded batches, URLs)."""
with mock.patch(CLIENT_SESSION_PATCH) as MockSession:
session = MockSession.return_value
- params = _wire(session, responses)
+ params, urls = _wire(session, responses)
source_response = lever_source(
"key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs
)
yielded = list(cast("Iterable[Any]", source_response.items()))
- return params, yielded
+ return params, yielded, urls
class TestBuildInitialParams:
@@ -134,7 +136,7 @@ class TestLeverPaginationAndResume:
_page([{"id": "o2", "createdAt": 1700000005000}], False),
]
- sent_params, yielded = _drive("opportunities", manager, responses)
+ sent_params, yielded, _ = _drive("opportunities", manager, responses)
# First request has no offset; second request uses the saved offset token.
assert sent_params[0].get("offset") is None
@@ -153,7 +155,7 @@ class TestLeverPaginationAndResume:
manager = _make_manager(LeverResumeConfig(offset="saved_offset"))
responses = [_page([{"id": "o5"}], False)]
- sent_params, _ = _drive("opportunities", manager, responses)
+ sent_params, _, _ = _drive("opportunities", manager, responses)
assert sent_params[0].get("offset") == "saved_offset"
@@ -169,6 +171,68 @@ class TestLeverPaginationAndResume:
manager.save_state.assert_not_called()
+class TestLeverOpportunityChildren:
+ @pytest.mark.parametrize("endpoint", ["offers", "interviews", "feedback"])
+ def test_fans_out_per_opportunity_and_tags_rows_with_parent(self, endpoint: str) -> None:
+ responses = [
+ _page([{"id": "opp1"}], True, "parent_2"),
+ _page([{"id": "c1", "createdAt": 1700000000000}], True, "child_2"),
+ _page([{"id": "c2", "createdAt": 1700000005000}], False),
+ _page([{"id": "opp2"}, {"id": "opp_deleted"}], False),
+ _page([{"id": "c1", "createdAt": 1700000010000}], False),
+ _make_response({"code": "NotFound"}, status_code=404),
+ ]
+
+ sent_params, yielded, urls = _drive(endpoint, _make_manager(), responses)
+
+ assert [url.removeprefix("https://api.lever.co/v1") for url in urls] == [
+ "/opportunities",
+ f"/opportunities/opp1/{endpoint}",
+ f"/opportunities/opp1/{endpoint}",
+ "/opportunities",
+ f"/opportunities/opp2/{endpoint}",
+ f"/opportunities/opp_deleted/{endpoint}",
+ ]
+ assert sent_params[0] == {"limit": 100, "include": "id"}
+ assert sent_params[2].get("offset") == "child_2"
+ assert sent_params[3].get("offset") == "parent_2"
+ assert [row for batch in yielded for row in batch] == [
+ {"id": "c1", "createdAt": 1700000000, "opportunity_id": "opp1"},
+ {"id": "c2", "createdAt": 1700000005, "opportunity_id": "opp1"},
+ {"id": "c1", "createdAt": 1700000010, "opportunity_id": "opp2"},
+ ]
+
+
+class TestLeverApplications:
+ def test_flattens_expanded_applications_from_opportunities(self) -> None:
+ responses = [
+ _page(
+ [
+ {"applications": [{"id": "a1", "opportunityId": "o1", "createdAt": 1700000000000}]},
+ {"applications": []},
+ ],
+ True,
+ "offset_2",
+ ),
+ _page([{"applications": [{"id": "a2", "opportunityId": "o2", "createdAt": 1700000005000}]}], False),
+ ]
+
+ sent_params, yielded, urls = _drive("applications", _make_manager(), responses)
+
+ assert urls[0] == "https://api.lever.co/v1/opportunities"
+ assert sent_params[0] == {"limit": 100, "expand": "applications", "include": "applications"}
+ assert [row for batch in yielded for row in batch] == [
+ {"id": "a1", "opportunityId": "o1", "createdAt": 1700000000},
+ {"id": "a2", "opportunityId": "o2", "createdAt": 1700000005},
+ ]
+
+ def test_unexpanded_application_ids_fail_loudly(self) -> None:
+ responses = [_page([{"applications": ["a1"]}], False)]
+
+ with pytest.raises(ValueError, match="expected expanded applications objects"):
+ _drive("applications", _make_manager(), responses)
+
+
class TestResumeConfigSerialization:
def test_round_trip(self) -> None:
cfg = LeverResumeConfig(offset="abc123")