: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(warehouse_sources): add HiBob history and candidates tables (#111307)
Tom Owersd796f44a64c0
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.mdindex 1580c6f5f9af..621227d737a1 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@@ -4043,18 +4043,18 @@ Note: learn.hex.tech renders the reference client-side from Docusaurus; the oper## HiBob — **thin**-Today (3): `employees`, `tasks`, `time_off_calendars`+Today (7): `candidates`, `employee_employment`, `employee_lifecycle`, `employee_salaries`, `employees`, `tasks`, `time_off_calendars`Diffed against: <https://apidocs.hibob.com/reference/get_tasks>- [x] `POST /timeoff/calendars/employees/search` — the holiday calendar resolved per employee (employment override or site default); fans out over employee ids, full refresh (medium)-- [ ] `GET /bulk/people/lifecycle` — employee lifecycle state transitions (hire, promotion, termination) — the core HR history table (high)-- [ ] `GET /bulk/people/employment` — employment history rows per employee (contract, manager, site changes) rather than only current state (high)-- [ ] `GET /bulk/people/salaries` — compensation history, the headline HR analytics dataset (high)+- [x] `GET /bulk/people/lifecycle` — employee lifecycle state transitions (hire, promotion, termination) — the core HR history table (high)+- [x] `GET /bulk/people/employment` — employment history rows per employee (contract, manager, site changes) rather than only current state (high)+- [x] `GET /bulk/people/salaries` — compensation history, the headline HR analytics dataset (high)- [ ] `GET /timeoff/requests/changes` — time off request event stream plus GET /timeoff/employees/{id}/balance for balances (high)- [ ] `POST /attendance/entries/search` — clock in/out entries; also /attendance/daily-breakdown/search and /attendance/summaries/search for rollups (high)- [ ] `GET /company/named-lists` — lookup table resolving the list-value field ids stored on every employee record (high)-- [ ] `POST /hiring/candidates/search` — recruiting pipeline entities, unreachable today (high)+- [x] `POST /hiring/candidates/search` — recruiting pipeline entities, unreachable today (high)- [ ] `POST /hiring/applications/search` — application rows joining candidates to job openings — the recruiting funnel fact table (high)- [ ] `GET /job-catalog/job-roles and /job-catalog/job-families` — lookup tables resolving role and family ids carried on employee records (high)- [ ] `GET /payroll/history` — payroll runs over time, plus POST /people/actual-payments/search (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/canonical_descriptions.pyindex aa45b2b683c1..04af8d305f4c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/canonical_descriptions.py@@ -54,4 +54,88 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"siteId": "Identifier of the employee's site, or null when they have no site.",},},+ "employee_lifecycle": {+ "description": "One row per entry in each employee's lifecycle table: the history of status changes such as hire, leave, and termination.",+ "docs_url": "https://apidocs.hibob.com/reference/get_bulk-people-lifecycle",+ "columns": {+ "employeeId": "Identifier of the employee the entry belongs to.",+ "id": "Identifier of the lifecycle entry, unique within the employee's lifecycle table.",+ "effectiveDate": "The date this entry becomes effective.",+ "endEffectiveDate": "For entries that are no longer active, the date this entry stopped being effective.",+ "status": "The employee's lifecycle status from this entry onwards.",+ "employeeStatus": "The employee's access status, derived automatically from the lifecycle status.",+ "workChangeType": "ID of the change type value for this entry.",+ "reasonType": "ID of the lifecycle reason type list entry.",+ "leaveReason": "The reason for a leave, when the entry records one.",+ "isCurrent": "True when this is the entry that is currently in effect.",+ "creationDate": "The date this entry was created.",+ "modificationDate": "The date this entry was last modified.",+ "change": "Details of the last change and the ID of the user who updated this entry.",+ "customColumns": "Values of any custom columns defined on the table.",+ },+ },+ "employee_employment": {+ "description": "One row per entry in each employee's employment table: the history of contract, employment type, and working pattern.",+ "docs_url": "https://apidocs.hibob.com/reference/get_bulk-people-employment",+ "columns": {+ "employeeId": "Identifier of the employee the entry belongs to.",+ "id": "Identifier of the employment entry, unique within the employee's employment table.",+ "reason": "The reason for this change.",+ "effectiveDate": "The date this entry becomes effective.",+ "endEffectiveDate": "For entries that are no longer active, the date this entry stopped being effective.",+ "contract": "The contract, such as Full-Time, Part-Time, or Shifts.",+ "type": "The employment type, such as Permanent, Temporary, Apprentice, Contractor, or a custom value.",+ "salaryPayType": "The salary pay type: Salaries or Hourly.",+ "flsaCode": "The FLSA code: Exempt or Non-Exempt.",+ "weeklyHours": "Weekly hours, based on the actual working pattern.",+ "fte": "The FTE percentage for this entry, calculated from the working pattern.",+ "actualWorkingPattern": "The working pattern in effect for this entry.",+ "calendarId": "Identifier of the selected holiday calendar.",+ "calendarName": "Name of the selected holiday calendar.",+ "isCurrent": "True when this is the entry that is currently in effect.",+ "modificationDate": "The date this entry was last modified.",+ },+ },+ "employee_salaries": {+ "description": "One row per entry in each employee's salary (payroll) table: the history of base pay.",+ "docs_url": "https://apidocs.hibob.com/reference/get_bulk-people-salaries",+ "columns": {+ "employeeId": "Identifier of the employee the entry belongs to.",+ "id": "Identifier of the salary entry, unique within the employee's salary table.",+ "base": "The base salary amount and its currency.",+ "payPeriod": "The period the base salary covers: Annual, Hourly, Daily, Weekly, or Monthly.",+ "payFrequency": "How often the salary is paid: Monthly, Semi Monthly, Weekly, or Bi-Weekly.",+ "effectiveDate": "The date this entry becomes effective.",+ "endEffectiveDate": "For entries that are no longer active, the date this entry stopped being effective.",+ "activeEffectiveDate": "The active effective date for this entry.",+ "workChangeType": "ID of the change type value for this entry.",+ "isCurrent": "True when this is the entry that is currently in effect.",+ "creationDate": "The date this entry was created.",+ "modificationDate": "The date this entry was last modified.",+ "change": "Details of the last change and the ID of the user who updated this entry.",+ "customColumns": "Values of any custom columns defined on the table.",+ },+ },+ "candidates": {+ "description": "A candidate in Bob Hiring, with their contact details, background, and the job openings they applied to.",+ "docs_url": "https://apidocs.hibob.com/reference/post_hiring-candidates-search",+ "columns": {+ "id": "Unique identifier for the candidate.",+ "firstName": "The candidate's first name.",+ "lastName": "The candidate's last name.",+ "email": "The candidate's email address.",+ "phone": "The candidate's phone number.",+ "title": "The candidate's professional title.",+ "country": "The candidate's country.",+ "city": "The candidate's city.",+ "education": "Education history entries.",+ "experience": "Work experience entries.",+ "employeeId": "Identifier of the Bob employee record, if the candidate was hired.",+ "sourceId": "Identifier of the source the candidate came from.",+ "sourceType": "The type of source the candidate came from.",+ "jobOpeningsToApplicationIds": "The job openings the candidate applied to, with the matching application ids.",+ "anonymizedAt": "When the candidate's data was anonymized, if it was.",+ "modificationDate": "Timestamp of the last modification to this candidate record.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/hibob.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/hibob.pyindex 97dc639860cc..ba8c91e281ad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/hibob.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/hibob.py@@ -1,4 +1,4 @@-from collections.abc import Iterator+from collections.abc import Callable, Iterable, Iteratorfrom typing import Anyfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -8,12 +8,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.hibob.settings import (HIBOB_ENDPOINTS,TIME_OFF_CALENDARS,+ HiBobEndpointConfig,)HIBOB_BASE_URL = "https://api.hibob.com"@@ -50,6 +53,47 @@ def _leaf_key(key: str) -> str:return key.rsplit("/", 1)[-1] if "/" in key else key+def _leaf_keys_page(page: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [{_leaf_key(key): value for key, value in item.items()} for item in page]+++def _employee_history_page(page: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Flatten bulk table results (`{employeeId, values: [...]}` per employee) into one row per entry."""+ rows: list[dict[str, Any]] = []+ for result in page:+ employee_id = result.get("employeeId")+ for value in result.get("values") or []:+ # The spec types each item as a `{values, restricted_columns}` wrapper, while the+ # single-employee table endpoints return bare entries, so accept both shapes.+ entries = value["values"] if isinstance(value.get("values"), list) else [value]+ rows.extend({**entry, "employeeId": employee_id} for entry in entries)+ return rows+++PAGE_MAPPERS: dict[str, Callable[[list[dict[str, Any]]], list[dict[str, Any]]]] = {+ "employee_history": _employee_history_page,+ "pointer_keys": _leaf_keys_page,+}+++def _map_pages(+ pages: Iterable[list[dict[str, Any]]], mapper: Callable[[list[dict[str, Any]]], list[dict[str, Any]]]+) -> Iterator[list[dict[str, Any]]]:+ for page in pages:+ yield mapper(page)+++def _paginator(config: HiBobEndpointConfig) -> BasePaginator:+ if config.cursor_location is None:+ return SinglePagePaginator()+ return JSONResponseCursorPaginator(+ cursor_path="response_metadata.next_cursor",+ cursor_param="cursor",+ param_location=config.cursor_location,+ raise_on_repeated_cursor=True,+ )++def _iter_employee_ids(session: Any) -> Iterator[str]:employees_config = HIBOB_ENDPOINTS["employees"]response = session.post(@@ -83,7 +127,7 @@ def _search_employee_calendars(session: Any, path: str, employee_ids: list[str])items = data.get("items", [])if items:- yield [{_leaf_key(key): value for key, value in item.items()} for item in items]+ yield _leaf_keys_page(items)cursor = (data.get("response_metadata") or {}).get("next_cursor")if not cursor:@@ -120,7 +164,7 @@ def hibob_source(return SourceResponse(name=endpoint,items=lambda: _time_off_calendars_rows(service_user_id, service_user_token, config.path),- primary_keys=[config.primary_key],+ primary_keys=list(config.primary_keys),partition_count=1,partition_size=1,sort_mode="asc",@@ -137,14 +181,16 @@ def hibob_source("data_selector": config.data_key,}if config.body is not None:- api_endpoint["json"] = config.body+ # Copy, because the cursor paginator writes the cursor into the request body.+ api_endpoint["json"] = {**config.body}+ if config.params is not None:+ api_endpoint["params"] = config.paramsrest_config: RESTAPIConfig = {"client": {"base_url": HIBOB_BASE_URL,"auth": {"type": "http_basic", "username": service_user_id, "password": service_user_token},- # Both shipped endpoints return their full result set in one response.- "paginator": SinglePagePaginator(),+ "paginator": _paginator(config),},"resources": [{@@ -155,11 +201,12 @@ def hibob_source(}resource = rest_api_resource(rest_config, team_id, job_id, None)+ mapper = PAGE_MAPPERS.get(config.row_shape)return SourceResponse(name=endpoint,- items=lambda: resource,- primary_keys=[config.primary_key],+ items=(lambda: _map_pages(resource, mapper)) if mapper else (lambda: resource),+ primary_keys=list(config.primary_keys),partition_count=1,partition_size=1,sort_mode="asc",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/settings.pyindex 2ee53419334f..e55d1ec4498f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/settings.py@@ -4,7 +4,7 @@ from typing import Literal, Optionalfrom products.warehouse_sources.backend.types import IncrementalField-@dataclass+@dataclass(frozen=True)class HiBobEndpointConfig:name: strpath: str@@ -13,9 +13,69 @@ class HiBobEndpointConfig:# HiBob's primary employee read is a POST-for-read with a JSON body.method: Literal["GET", "POST"] = "GET"body: Optional[dict] = None- primary_key: str = "id"+ params: Optional[dict] = None+ primary_keys: tuple[str, ...] = ("id",)+ # Where the cursor goes on the next request. None means the endpoint returns everything in one response.+ cursor_location: Optional[Literal["query", "json"]] = None+ # "employee_history": rows are nested per employee under `values` and need flattening.+ # "pointer_keys": rows are keyed by JSON pointers (e.g. `/candidate/id`) and need leaf keys.+ row_shape: Literal["flat", "employee_history", "pointer_keys"] = "flat"+# Max page size the cursor-paginated bulk tables and hiring searches accept.+BULK_PAGE_LIMIT = 200++# History entry ids are only documented as unique within one employee's table.+HISTORY_PRIMARY_KEYS = ("employeeId", "id")++CANDIDATE_FIELDS = (+ "/candidate/id",+ "/candidate/firstName",+ "/candidate/lastName",+ "/candidate/email",+ "/candidate/phone",+ "/candidate/title",+ "/candidate/address",+ "/candidate/photo",+ "/candidate/languages",+ "/candidate/skills",+ "/candidate/socialMedia",+ "/candidate/socialMediaLinkedIn",+ "/candidate/socialMediaFacebook",+ "/candidate/socialMediaInstagram",+ "/candidate/socialMediaThreads",+ "/candidate/socialMediaTwitter",+ "/candidate/socialMediaYouTube",+ "/candidate/socialMediaMedium",+ "/candidate/socialMediaGitHub",+ "/candidate/socialMediaReddit",+ "/candidate/socialMediaXing",+ "/candidate/socialMediaPersonalWebsite",+ "/candidate/country",+ "/candidate/city",+ "/candidate/region",+ "/candidate/education",+ "/candidate/experience",+ "/candidate/employeeId",+ "/candidate/externalUserId",+ "/candidate/importExternalId",+ "/candidate/sourceId",+ "/candidate/sourceEffectiveDate",+ "/candidate/extendConsentDueDate",+ "/candidate/extendedConsentRequestedAt",+ "/candidate/anonymizedAt",+ "/candidate/jobOpeningsToApplicationIds",+ "/candidate/dataDownloadFileId",+ "/candidate/dataDownloadRequestedAt",+ "/candidate/dataDeletionRequestedAt",+ "/candidate/dataDownloadedAt",+ "/candidate/sourceType",+ "/candidate/sourceApplicationId",+ "/candidate/sourceInstanceId",+ "/candidate/meetingBotEnabled",+ "/candidate/modificationDate",+)+# Name of the employee time-off calendars stream. It fans out over employee ids# (the search endpoint resolves the holiday calendar per employee), so it needs# bespoke transport rather than the shared single-page path — routed by name in@@ -26,6 +86,8 @@ TIME_OFF_CALENDARS = "time_off_calendars"# Fivetran re-imports most tables every sync), so every stream is an honest# full refresh. The time off changes endpoint has a `since` param but its rows# carry no verifiable per-change timestamp to use as a watermark — deferred.+# Candidates search accepts a `modificationDate` filter, but neither its value+# format nor the result order is documented — deferred.HIBOB_ENDPOINTS: dict[str, HiBobEndpointConfig] = {"employees": HiBobEndpointConfig(name="employees",@@ -47,7 +109,44 @@ HIBOB_ENDPOINTS: dict[str, HiBobEndpointConfig] = {data_key="items",method="POST",# One resolved calendar per employee, so the employee id is table-wide unique.- primary_key="employeeId",+ primary_keys=("employeeId",),+ ),+ "employee_lifecycle": HiBobEndpointConfig(+ name="employee_lifecycle",+ path="/v1/bulk/people/lifecycle",+ data_key="results",+ params={"limit": BULK_PAGE_LIMIT},+ primary_keys=HISTORY_PRIMARY_KEYS,+ cursor_location="query",+ row_shape="employee_history",+ ),+ "employee_employment": HiBobEndpointConfig(+ name="employee_employment",+ path="/v1/bulk/people/employment",+ data_key="results",+ params={"limit": BULK_PAGE_LIMIT},+ primary_keys=HISTORY_PRIMARY_KEYS,+ cursor_location="query",+ row_shape="employee_history",+ ),+ "employee_salaries": HiBobEndpointConfig(+ name="employee_salaries",+ path="/v1/bulk/people/salaries",+ data_key="results",+ params={"limit": BULK_PAGE_LIMIT},+ primary_keys=HISTORY_PRIMARY_KEYS,+ cursor_location="query",+ row_shape="employee_history",+ ),+ "candidates": HiBobEndpointConfig(+ name="candidates",+ path="/v1/hiring/candidates/search",+ data_key="items",+ method="POST",+ # The search returns only the fields requested, so ask for every documented candidate field.+ body={"fields": list(CANDIDATE_FIELDS), "filters": [], "limit": BULK_PAGE_LIMIT},+ cursor_location="json",+ row_shape="pointer_keys",),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/tests/test_hibob.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/tests/test_hibob.pyindex a5967397d841..a44085809764 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/tests/test_hibob.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hibob/tests/test_hibob.py@@ -39,7 +39,7 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,"method": request.method,"url": request.url,"params": dict(request.params or {}),- "json": request.json,+ "json": dict(request.json) if request.json is not None else None,"auth": request.auth,})@@ -139,6 +139,108 @@ class TestGetRows:assert session.send.call_count == 1+class TestEmployeeHistoryTables:+ @pytest.mark.parametrize(+ "endpoint, path",+ [+ ("employee_lifecycle", "/v1/bulk/people/lifecycle"),+ ("employee_employment", "/v1/bulk/people/employment"),+ ("employee_salaries", "/v1/bulk/people/salaries"),+ ],+ )+ @pytest.mark.parametrize(+ "values_page_1, values_page_2",+ [+ ([{"id": 1, "status": "hired"}, {"id": 2, "status": "employed"}], [{"id": 1, "status": "hired"}]),+ (+ [{"values": [{"id": 1, "status": "hired"}, {"id": 2, "status": "employed"}], "restricted_columns": {}}],+ [{"values": [{"id": 1, "status": "hired"}]}],+ ),+ ],+ ids=["bare_entries", "wrapped_entries"],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_flattens_entries_per_employee_and_follows_query_cursor(+ self, MockSession, endpoint, path, values_page_1, values_page_2+ ) -> None:+ session = MockSession.return_value+ captured = _wire(+ session,+ [+ _response(+ {+ "results": [{"employeeId": "e1", "values": values_page_1}],+ "response_metadata": {"next_cursor": "c2"},+ }+ ),+ _response(+ {+ "results": [{"employeeId": "e2", "values": values_page_2}, {"employeeId": "e3", "values": []}],+ "response_metadata": {"next_cursor": None},+ }+ ),+ ],+ )++ response = hibob_source("service-id", "token", endpoint, team_id=1, job_id="j")+ rows = _rows(response)++ assert rows == [+ {"id": 1, "status": "hired", "employeeId": "e1"},+ {"id": 2, "status": "employed", "employeeId": "e1"},+ {"id": 1, "status": "hired", "employeeId": "e2"},+ ]+ assert response.primary_keys == ["employeeId", "id"]+ assert [(c["method"], c["url"]) for c in captured] == [("GET", f"https://api.hibob.com{path}")] * 2+ assert captured[0]["params"] == {"limit": 200}+ assert captured[1]["params"] == {"limit": 200, "cursor": "c2"}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_rejects_repeated_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"results": [], "response_metadata": {"next_cursor": "stalled"}}),+ _response({"results": [], "response_metadata": {"next_cursor": "stalled"}}),+ ],+ )++ with pytest.raises(ValueError, match="repeated cursor"):+ _rows(hibob_source("service-id", "token", "employee_lifecycle", team_id=1, job_id="j"))+++class TestCandidates:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_posts_body_cursor_and_normalizes_pointer_keys(self, MockSession) -> None:+ session = MockSession.return_value+ captured = _wire(+ session,+ [+ _response(+ {+ "items": [{"/candidate/id": 7, "/candidate/firstName": "Ada"}],+ "response_metadata": {"next_cursor": "c2"},+ }+ ),+ _response({"items": [{"/candidate/id": 8}], "response_metadata": {"next_cursor": None}}),+ ],+ )++ rows = _rows(hibob_source("service-id", "token", "candidates", team_id=1, job_id="j"))++ assert rows == [{"id": 7, "firstName": "Ada"}, {"id": 8}]+ assert [(c["method"], c["url"]) for c in captured] == [+ ("POST", "https://api.hibob.com/v1/hiring/candidates/search")+ ] * 2+ assert "cursor" not in captured[0]["json"]+ assert "/candidate/modificationDate" in captured[0]["json"]["fields"]+ assert captured[1]["json"]["cursor"] == "c2"+ # The next sync must not start from the previous sync's cursor.+ body = HIBOB_ENDPOINTS["candidates"].body+ assert body is not None and "cursor" not in body++class TestTimeOffCalendars:"""The calendars stream fans out over employee ids (POST search), so it hand-rolls its ownsession.post calls rather than riding the shared rest_client."""@@ -244,7 +346,7 @@ class TestHiBobSourceResponse:response = hibob_source("service-id", "token", endpoint, team_id=1, job_id="j")assert response.name == endpoint- assert response.primary_keys == [config.primary_key]+ assert response.primary_keys == list(config.primary_keys)assert response.sort_mode == "asc"assert response.partition_mode is Noneassert response.partition_keys is None