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 sage_hr import source (#69372)

Tom Owers06f24c70566b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index e1ab1b421ff0..63381737d5ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -356,6 +356,7 @@ the row lists both.
| rss | HTTP | requests | ✅ |
| ruddr | HTTP | requests | ✅ |
| safetyculture | HTTP | requests | ✅ |
+| sage_hr | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| salesflare | HTTP | requests | ✅ |
| salesloft | HTTP | requests | ✅ |
@@ -756,7 +757,6 @@ doesn't conflict with concurrent PRs.
- rudderstack
- runpod
- safetyculture
-- sage_hr
- sage_intacct
- sailthru
- salesforce_marketing_cloud
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 013f4c63db5f..ee217727743e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -3239,7 +3239,8 @@ class SafetyCultureSourceConfig(config.Config):
@config.config
class SageHRSourceConfig(config.Config):
- pass
+ subdomain: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/canonical_descriptions.py
new file mode 100644
index 000000000000..ca0d0c79404d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/canonical_descriptions.py
@@ -0,0 +1,157 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Sage HR API docs (https://sagehr.docs.apiary.io). Partial coverage
+# is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "employees": {
+ "description": "An active employee, with their contact details, position, team, and employment dates.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the employee.",
+ "email": "The employee's email address.",
+ "first_name": "The employee's first name.",
+ "last_name": "The employee's last name.",
+ "picture_url": "URL of the employee's profile photo.",
+ "employment_start_date": "The date the employee's employment began.",
+ "date_of_birth": "The employee's date of birth.",
+ "team": "The name of the employee's team.",
+ "team_id": "The ID of the employee's team.",
+ "position": "The employee's job title.",
+ "position_id": "The ID of the employee's position.",
+ "reports_to_employee_id": "The employee ID of the person this employee reports to.",
+ "employee_number": "The employee's internal staff number.",
+ "employment_status": "The employee's employment status (e.g. Full-time).",
+ "nationality": "The employee's nationality.",
+ "country": "Two-letter ISO country code of the employee's address.",
+ },
+ },
+ "terminated_employees": {
+ "description": "A terminated (former) employee, with their identity fields and termination date.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the employee.",
+ "email": "The employee's email address.",
+ "first_name": "The employee's first name.",
+ "last_name": "The employee's last name.",
+ "termination_date": "The employee's last working day.",
+ "employment_start_date": "The date the employee's employment began.",
+ "employee_number": "The employee's internal staff number.",
+ "position": "The employee's job title at termination.",
+ },
+ },
+ "termination_reasons": {
+ "description": "A termination reason configured for the company (e.g. New job).",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the termination reason.",
+ "name": "The termination reason label.",
+ "code": "Optional short code for the reason.",
+ "type": "Whether the reason is voluntary or involuntary.",
+ },
+ },
+ "teams": {
+ "description": "A team in the company, with its managers and members.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the team.",
+ "name": "The team name.",
+ "manager_ids": "Employee IDs of the team's managers.",
+ "employee_ids": "Employee IDs of the team's members.",
+ },
+ },
+ "positions": {
+ "description": "A job position defined in the company.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the position.",
+ "title": "The position title.",
+ "description": "Free-text description of the position.",
+ "code": "Optional position code.",
+ },
+ },
+ "documents": {
+ "description": "A document stored in Sage HR, with its file metadata and sharing settings.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the document.",
+ "document_category_id": "The ID of the category the document belongs to.",
+ "description": "Free-text description of the document.",
+ "file_name": "The uploaded file's name.",
+ "file_content_type": "The uploaded file's MIME type.",
+ "file_size": "The uploaded file's size in bytes.",
+ "shared_with_everyone": "Whether the document is shared with everyone.",
+ "created_at": "When the document was created.",
+ "updated_at": "When the document was last updated.",
+ },
+ },
+ "document_categories": {
+ "description": "A document category, with the number of documents it contains.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the document category.",
+ "name": "The category name.",
+ "documents_count": "Number of documents in the category.",
+ },
+ },
+ "leave_requests": {
+ "description": "A time off request, with its policy, requester, dates, and approval state.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the time off request.",
+ "status": "Human-readable request status (e.g. Approved).",
+ "status_code": "Machine-readable request status (e.g. approved).",
+ "policy_id": "The ID of the time off policy the request is made under.",
+ "employee_id": "The ID of the requesting employee.",
+ "details": "Free-text reason or notes on the request.",
+ "is_multi_date": "Whether the request spans multiple days.",
+ "is_single_day": "Whether the request is for a single day.",
+ "is_part_of_day": "Whether the request covers only part of a day.",
+ "start_date": "The first day of the requested leave.",
+ "end_date": "The last day of the requested leave.",
+ "request_date": "When the request was submitted.",
+ "approval_date": "When the request was approved, if it has been.",
+ "hours": "Number of hours requested.",
+ },
+ },
+ "leave_policies": {
+ "description": "A time off policy (e.g. Vacation), with its accrual and allowance settings.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the time off policy.",
+ "name": "The policy name.",
+ "color": "Hex display color of the policy.",
+ "do_not_accrue": "Whether accrual is disabled for the policy.",
+ "unit": "Measurement unit of the policy (e.g. days).",
+ "default_allowance": "Default entitlement under the policy.",
+ "max_carryover": "Maximum amount that can be carried over.",
+ "accrue_type": "How the allowance accrues (e.g. yearly, no_tracking).",
+ },
+ },
+ "individual_allowances": {
+ "description": "Per-employee time off allowances: each employee's entitlement under each policy.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the employee the allowances belong to.",
+ "full_name": "The employee's full name.",
+ "eligibilities": "The employee's per-policy allowances (policy, quantity, unit, carryover).",
+ },
+ },
+ "onboarding_categories": {
+ "description": "An onboarding task category (e.g. General).",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the onboarding category.",
+ "title": "The category title.",
+ },
+ },
+ "offboarding_categories": {
+ "description": "An offboarding task category.",
+ "docs_url": "https://sagehr.docs.apiary.io",
+ "columns": {
+ "id": "The unique ID of the offboarding category.",
+ "title": "The category title.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py
new file mode 100644
index 000000000000..4ca99971ce0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/sage_hr.py
@@ -0,0 +1,304 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.settings import (
+ SAGE_HR_ENDPOINTS,
+ SageHREndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+# Credential validation is a single cheap probe; keep it snappy so source creation doesn't feel hung.
+VALIDATE_TIMEOUT_SECONDS = 15
+# Cheap collection endpoint used to confirm the subdomain + API key are genuine.
+DEFAULT_PROBE_PATH = "/employees"
+
+# Time off requests default to the current month unless an explicit `from`/`to` window is passed,
+# and the API rejects windows of 65 days or more — so a full sync walks fixed-size windows from a
+# start date predating any Sage HR (formerly CakeHR, launched 2013) account through to future
+# bookings. Sage HR doesn't publish rate limits, but ~100 mostly-empty window probes per sync is a
+# trivial request volume.
+LEAVE_WINDOW_START = "2010-01-01"
+LEAVE_WINDOW_DAYS = 60
+LEAVE_FUTURE_DAYS = 730
+
+# A single DNS label: letters, digits, hyphens. Rejects anything that could retarget the host
+# (slashes, `@`, dots) so the stored API key is only ever sent to `<subdomain>.sage.hr`.
+_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
+
+
+class SageHRRetryableError(Exception):
+ pass
+
+
+class SageHRResumeConfig:
+ # Next 1-indexed page to fetch (from the response `meta.next_page`). None means "start over".
+ next_page: int | None = None
+ # For the windowed leave_requests endpoint: ISO date of the window `next_page` belongs to.
+ window_from: str | None = None
+
+
+def normalize_subdomain(subdomain: str) -> str:
+ """Reduce user input to a bare, validated Sage HR subdomain label.
+
+ Accepts either the full host (``yourcompany.sage.hr``) or the bare subdomain
+ (``yourcompany``). Raises ``ValueError`` on anything that isn't a single DNS label so the
+ API key can never be retargeted away from ``<subdomain>.sage.hr``.
+ """
+ cleaned = subdomain.strip().removeprefix("https://").removeprefix("http://")
+ cleaned = cleaned.strip("/")
+ cleaned = cleaned.removesuffix(".sage.hr")
+ if not _SUBDOMAIN_RE.match(cleaned):
+ raise ValueError(
+ f"Invalid Sage HR company subdomain: {subdomain!r}. Enter just your subdomain, e.g. 'yourcompany' "
+ "for yourcompany.sage.hr."
+ )
+ return cleaned
+
+
+def _base_url(subdomain: str) -> str:
+ return f"https://{normalize_subdomain(subdomain)}.sage.hr/api"
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"X-Auth-Token": api_key, "Accept": "application/json"}
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{base_url}{path}"
+ return f"{base_url}{path}?{urlencode(params)}"
+
+
+def _extract_next_page(payload: dict[str, Any]) -> int | None:
+ # Collection responses carry a `meta` block: current_page, next_page, previous_page,
+ # total_pages, per_page, total_entries. `next_page` is null on the last page. Unpaginated
+ # endpoints omit `meta` entirely, which reads as a single page.
+ meta = payload.get("meta")
+ if not isinstance(meta, dict):
+ return None
+ next_page = meta.get("next_page")
+ return next_page if isinstance(next_page, int) else None
+
+
+@retry(
+ retry=retry_if_exception_type((SageHRRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], int | None]:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SageHRRetryableError(f"Sage HR API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Sage HR API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ payload = response.json()
+ # Collection endpoints wrap results in {"data": [...], "meta": {...}}.
+ if not isinstance(payload, dict) or not isinstance(payload.get("data"), list):
+ raise SageHRRetryableError(f"Sage HR returned an unexpected payload for {url}: {type(payload).__name__}")
+
+ return payload["data"], _extract_next_page(payload)
+
+
+def _leave_window_range() -> tuple[date, date]:
+ """Full date range the leave_requests sync covers: account prehistory through future bookings."""
+ today = datetime.now(UTC).date()
+ return date.fromisoformat(LEAVE_WINDOW_START), today + timedelta(days=LEAVE_FUTURE_DAYS)
+
+
+def _iter_windows(start: date, end: date) -> Iterator[tuple[date, date]]:
+ cursor = start
+ while cursor <= end:
+ window_end = min(cursor + timedelta(days=LEAVE_WINDOW_DAYS - 1), end)
+ yield cursor, window_end
+ cursor = window_end + timedelta(days=1)
+
+
+def _get_windowed_rows(
+ session: requests.Session,
+ base_url: str,
+ config: SageHREndpointConfig,
+ resume: SageHRResumeConfig | None,
+ resumable_source_manager: ResumableSourceManager[SageHRResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ start, end = _leave_window_range()
+ resume_from = date.fromisoformat(resume.window_from) if resume and resume.window_from else None
+ # The docs don't state whether `from`/`to` match on overlap or containment, so a request spanning
+ # a window boundary may come back from both windows. Full-refresh batches append without merging,
+ # so drop ids already yielded this sync. (After a mid-sync resume the set starts empty — a rare
+ # boundary duplicate then persists until the next successful full sync replaces the table.)
+ seen_ids: set[Any] = set()
+
+ for window_start, window_end in _iter_windows(start, end):
+ if resume_from is not None and window_start < resume_from:
+ continue
+
+ page = 1
+ if resume is not None and resume.next_page is not None and resume.window_from == window_start.isoformat():
+ page = resume.next_page
+
+ while True:
+ params = {"page": page, "from": window_start.isoformat(), "to": window_end.isoformat()}
+ items, next_page = _fetch_page(session, _build_url(base_url, config.path, params), logger)
+
+ fresh = []
+ for row in items:
+ # `id` is the declared primary key — fail loudly on a missing one rather than
+ # silently yielding rows the dedupe (and later merges) can't identify.
+ row_id = row["id"]
+ if row_id in seen_ids:
+ continue
+ seen_ids.add(row_id)
+ fresh.append(row)
+ if fresh:
+ yield fresh
+
+ # `next_page` is null on the last page; an empty or non-advancing page also terminates
+ # defensively so a bad meta block can never produce an infinite loop.
+ if not next_page or not items or next_page <= page:
+ break
+
+ page = next_page
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages
+ # are persisted).
+ resumable_source_manager.save_state(
+ SageHRResumeConfig(next_page=page, window_from=window_start.isoformat())
+ )
+
+ # Window exhausted — everything up to it has been yielded, so a resume can skip straight to
+ # the next window.
+ next_window_start = window_end + timedelta(days=1)
+ if next_window_start <= end:
+ resumable_source_manager.save_state(
+ SageHRResumeConfig(next_page=1, window_from=next_window_start.isoformat())
+ )
+
+
+def get_rows(
+ subdomain: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SageHRResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SAGE_HR_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ base_url = _base_url(subdomain)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ logger.debug(f"Sage HR: resuming {endpoint} from page={resume.next_page}, window={resume.window_from}")
+
+ if config.requires_date_window:
+ yield from _get_windowed_rows(session, base_url, config, resume, resumable_source_manager, logger)
+ return
+
+ if not config.paginated:
+ items, _ = _fetch_page(session, _build_url(base_url, config.path, {}), logger)
+ if items:
+ yield items
+ return
+
+ page = resume.next_page if (resume is not None and resume.next_page is not None) else 1
+ while True:
+ items, next_page = _fetch_page(session, _build_url(base_url, config.path, {"page": page}), logger)
+ if items:
+ yield items
+
+ # `next_page` is null on the last page; an empty or non-advancing page also terminates
+ # defensively so a bad meta block can never produce an infinite loop.
+ if not next_page or not items or next_page <= page:
+ break
+
+ page = next_page
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted).
+ resumable_source_manager.save_state(SageHRResumeConfig(next_page=page))
+
+
+def sage_hr_source(
+ subdomain: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SageHRResumeConfig],
+) -> SourceResponse:
+ config = SAGE_HR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ subdomain=subdomain,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(subdomain: str, api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single collection endpoint to validate the subdomain + API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ try:
+ url = _build_url(_base_url(subdomain), path, {"page": 1})
+ except ValueError as e:
+ return 0, str(e)
+
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(url, timeout=VALIDATE_TIMEOUT_SECONDS)
+ except Exception:
+ return 0, "Could not connect to Sage HR. Check the company subdomain and try again."
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if response.status_code == 404:
+ return 404, "Sage HR company subdomain not found. Use the subdomain from your Sage HR URL."
+
+ if not response.ok:
+ return response.status_code, f"Sage HR returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(subdomain: str, api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(subdomain, api_key)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid Sage HR API key. Make sure API access is enabled under Settings → Integrations → API."
+ if status == 403:
+ return (
+ False,
+ "Your Sage HR API key does not have access to this data. Check that API access is enabled under Settings → Integrations → API.",
+ )
+ return False, message or "Could not validate Sage HR credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/settings.py
new file mode 100644
index 000000000000..cfb335ce8d82
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/settings.py
@@ -0,0 +1,45 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class SageHREndpointConfig:
+ name: str
+ path: str
+ # Most collection endpoints paginate with a `page` query param and a `meta` block; a couple
+ # (policies, document categories) return everything in a single unpaginated response.
+ paginated: bool = True
+ # Time off requests only return the current month unless an explicit `from`/`to` window is
+ # passed, and the window is capped at 65 days — so a full sync must walk date windows.
+ requires_date_window: bool = False
+ # Sage HR resource identifiers are account-unique integers, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Sage HR API collection endpoints (https://sagehr.docs.apiary.io). All are full-refresh only:
+# no endpoint exposes an updated-since style server-side timestamp filter, so there is no cursor
+# to advance an incremental sync. The only date filter (`from`/`to` on time off requests) selects
+# by leave date range, not modification time, and is capped at 65 days per request.
+SAGE_HR_ENDPOINTS: dict[str, SageHREndpointConfig] = {
+ "employees": SageHREndpointConfig(name="employees", path="/employees"),
+ "terminated_employees": SageHREndpointConfig(name="terminated_employees", path="/terminated-employees"),
+ "termination_reasons": SageHREndpointConfig(name="termination_reasons", path="/termination-reasons"),
+ "teams": SageHREndpointConfig(name="teams", path="/teams"),
+ "positions": SageHREndpointConfig(name="positions", path="/positions"),
+ "documents": SageHREndpointConfig(name="documents", path="/documents"),
+ "document_categories": SageHREndpointConfig(
+ name="document_categories", path="/documents/categories", paginated=False
+ ),
+ "leave_requests": SageHREndpointConfig(
+ name="leave_requests", path="/leave-management/requests", requires_date_window=True
+ ),
+ "leave_policies": SageHREndpointConfig(name="leave_policies", path="/leave-management/policies", paginated=False),
+ "individual_allowances": SageHREndpointConfig(
+ name="individual_allowances", path="/leave-management/reports/individual-allowances"
+ ),
+ "onboarding_categories": SageHREndpointConfig(name="onboarding_categories", path="/onboarding/categories"),
+ "offboarding_categories": SageHREndpointConfig(name="offboarding_categories", path="/offboarding/categories"),
+}
+
+ENDPOINTS = tuple(SAGE_HR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/source.py
index b04a5a9165c0..caca4bedbb7d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/source.py
@@ -1,30 +1,147 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SageHRSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.sage_hr import (
+ SageHRResumeConfig,
+ sage_hr_source,
+ validate_credentials as validate_sage_hr_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.settings import (
+ ENDPOINTS,
+ SAGE_HR_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SageHRSource(SimpleSource[SageHRSourceConfig]):
+class SageHRSource(ResumableSource[SageHRSourceConfig, SageHRResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SAGEHR
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to `<subdomain>.sage.hr`, so changing the subdomain must re-require it.
+ return ["subdomain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SAGE_HR,
category=DataWarehouseSourceCategory.HR___RECRUITING,
label="Sage HR",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["cakehr", "hris"],
+ caption="""Enter your Sage HR company subdomain and API key to pull your HR data into the PostHog Data warehouse.
+
+An admin must first enable API access under **Settings → Integrations → API** in Sage HR, which generates the API key. Requests go to your own subdomain — for `https://yourcompany.sage.hr` the subdomain is `yourcompany`.""",
iconPath="/static/services/sage_hr.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/sage-hr",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Company subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="yourcompany",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # The URL carries the per-account subdomain, so match on the status prefix only.
+ return {
+ "401 Client Error: Unauthorized for url": "Your Sage HR API key is invalid or has been revoked. Regenerate it under Settings → Integrations → API, then reconnect.",
+ "403 Client Error: Forbidden for url": "Your Sage HR API key does not have access to this data. Check that API access is enabled under Settings → Integrations → API, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SageHRSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Sage HR exposes no updated-since style server-side
+ # filter, so there is no timestamp cursor to advance an incremental sync.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: SageHRSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates access to every schema.
+ return validate_sage_hr_credentials(config.subdomain, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SageHRResumeConfig]:
+ return ResumableSourceManager[SageHRResumeConfig](inputs, SageHRResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SageHRSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SageHRResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SAGE_HR_ENDPOINTS:
+ raise ValueError(f"Unknown Sage HR schema '{inputs.schema_name}'")
+
+ return sage_hr_source(
+ subdomain=config.subdomain,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py
new file mode 100644
index 000000000000..b0272f703e34
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr.py
@@ -0,0 +1,362 @@
+from collections.abc import Mapping
+from datetime import date
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr import sage_hr
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.sage_hr import (
+ SageHRResumeConfig,
+ SageHRRetryableError,
+ _iter_windows,
+ check_access,
+ get_rows,
+ normalize_subdomain,
+ sage_hr_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.settings import (
+ ENDPOINTS,
+ SAGE_HR_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = sage_hr._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SageHRResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SageHRResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SageHRResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SageHRResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestNormalizeSubdomain:
+ @parameterized.expand(
+ [
+ ("bare", "acme", "acme"),
+ ("full_host", "acme.sage.hr", "acme"),
+ ("https_prefix", "https://acme.sage.hr/", "acme"),
+ ("whitespace", " acme ", "acme"),
+ ("hyphenated", "acme-co", "acme-co"),
+ ]
+ )
+ def test_accepts_and_cleans_valid_input(self, _name: str, raw: str, expected: str) -> None:
+ assert normalize_subdomain(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("path_injection", "acme.sage.hr/../internal"),
+ ("other_domain", "evil.com"),
+ ("embedded_at", "[email protected]"),
+ ("empty", ""),
+ ("space_inside", "ac me"),
+ ]
+ )
+ def test_rejects_host_retargeting_input(self, _name: str, raw: str) -> None:
+ # The subdomain becomes the request host carrying the API key — anything that isn't a single
+ # DNS label must be rejected before a URL is built.
+ with pytest.raises(ValueError):
+ normalize_subdomain(raw)
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"data": []}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(SageHRRetryableError):
+ _fetch_page_unwrapped(session, "https://acme.sage.hr/api/employees?page=1", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "https://acme.sage.hr/api/employees?page=1", MagicMock())
+
+ def test_success_returns_items_and_next_page(self) -> None:
+ session = self._session_returning(200, {"data": [{"id": 1}], "meta": {"current_page": 1, "next_page": 2}})
+ items, next_page = _fetch_page_unwrapped(session, "https://acme.sage.hr/api/employees?page=1", MagicMock())
+ assert items == [{"id": 1}]
+ assert next_page == 2
+
+ @parameterized.expand(
+ [
+ ("null_next_page", {"data": [{"id": 1}], "meta": {"current_page": 2, "next_page": None}}),
+ ("missing_meta", {"data": [{"id": 1}]}),
+ ("non_dict_meta", {"data": [{"id": 1}], "meta": "nope"}),
+ ]
+ )
+ def test_last_or_unpaginated_page_yields_none_next_page(self, _name: str, body: dict) -> None:
+ session = self._session_returning(200, body)
+ items, next_page = _fetch_page_unwrapped(session, "https://acme.sage.hr/api/employees", MagicMock())
+ assert items == [{"id": 1}]
+ assert next_page is None
+
+ @parameterized.expand(
+ [
+ ("non_dict_body", [{"id": 1}]),
+ ("non_list_data", {"data": {"id": 1}}),
+ ]
+ )
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(SageHRRetryableError):
+ _fetch_page_unwrapped(session, "https://acme.sage.hr/api/employees", MagicMock())
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict], int | None]],
+ endpoint: str,
+ requested: list[str] | None = None,
+ ) -> list[dict]:
+ """Drive get_rows with _fetch_page faked by URL query string (sorted for determinism)."""
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> tuple[list[dict], int | None]:
+ parsed = urlparse(url)
+ key = "&".join(f"{k}={v[0]}" for k, v in sorted(parse_qs(parsed.query).items()))
+ if requested is not None:
+ requested.append(key)
+ return pages[key]
+
+ monkeypatch.setattr(sage_hr, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(sage_hr, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ subdomain="acme",
+ api_key="sage-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_no_next_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {"page=1": ([{"id": 1}, {"id": 2}], None)}, "employees")
+ assert rows == [{"id": 1}, {"id": 2}]
+ # `meta.next_page` is null, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_next_page_until_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {"page=1": ([{"id": 1}], 2), "page=2": ([{"id": 2}], None)}
+ rows = self._collect(manager, monkeypatch, pages, "employees")
+ assert rows == [{"id": 1}, {"id": 2}]
+ # State is saved after the first page (advancing to page 2), then the null next_page stops us.
+ assert [(s.next_page, s.window_from) for s in manager.saved] == [(2, None)]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(SageHRResumeConfig(next_page=2))
+ # Page 1 must never be fetched on resume.
+ pages = {"page=2": ([{"id": 2}], None)}
+ rows = self._collect(manager, monkeypatch, pages, "employees")
+ assert rows == [{"id": 2}]
+
+ @pytest.mark.parametrize(
+ "pages",
+ [
+ pytest.param({"page=1": ([], 2)}, id="empty_page_with_next"),
+ pytest.param({"page=1": ([{"id": 1}], 1)}, id="non_advancing_next_page"),
+ ],
+ )
+ def test_bad_meta_terminates_instead_of_looping(
+ self, pages: dict[str, tuple[list[dict], int | None]], monkeypatch: Any
+ ) -> None:
+ manager = _FakeResumableManager()
+ self._collect(manager, monkeypatch, pages, "employees")
+ assert manager.saved == []
+
+ def test_unpaginated_endpoint_fetches_once_without_page_param(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ requested: list[str] = []
+ rows = self._collect(manager, monkeypatch, {"": ([{"id": 1}], None)}, "leave_policies", requested)
+ assert rows == [{"id": 1}]
+ assert requested == [""]
+ assert manager.saved == []
+
+
+class TestWindowedLeaveRequests:
+ RANGE = (date(2024, 1, 1), date(2024, 3, 31))
+
+ def _collect(
+ self,
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict], int | None]],
+ requested: list[str] | None = None,
+ ) -> list[dict]:
+ monkeypatch.setattr(sage_hr, "_leave_window_range", lambda: self.RANGE)
+ return TestGetRows._collect(manager, monkeypatch, pages, "leave_requests", requested)
+
+ def test_iter_windows_are_contiguous_and_capped(self) -> None:
+ windows = list(_iter_windows(*self.RANGE))
+ assert windows[0][0] == self.RANGE[0]
+ assert windows[-1][1] == self.RANGE[1]
+ for window_start, window_end in windows:
+ # The API rejects `from`/`to` ranges of 65 days or more.
+ assert (window_end - window_start).days < 65
+ for (_, prev_end), (next_start, _) in zip(windows, windows[1:]):
+ assert (next_start - prev_end).days == 1
+
+ def test_walks_every_window_with_from_to_params(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ requested: list[str] = []
+ pages = {
+ "from=2024-01-01&page=1&to=2024-02-29": ([{"id": 1}], None),
+ "from=2024-03-01&page=1&to=2024-03-31": ([{"id": 2}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages, requested)
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert requested == list(pages.keys())
+ # Window advance is persisted so a resume skips the exhausted window.
+ assert [(s.next_page, s.window_from) for s in manager.saved] == [(1, "2024-03-01")]
+
+ def test_paginates_within_a_window_and_saves_state_after_yield(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ "from=2024-01-01&page=1&to=2024-02-29": ([{"id": 1}], 2),
+ "from=2024-01-01&page=2&to=2024-02-29": ([{"id": 2}], None),
+ "from=2024-03-01&page=1&to=2024-03-31": ([], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert [(s.next_page, s.window_from) for s in manager.saved] == [(2, "2024-01-01"), (1, "2024-03-01")]
+
+ def test_dedupes_rows_returned_by_adjacent_windows(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ # A request spanning the window boundary comes back from both windows; full-refresh batches
+ # append without merging, so the second occurrence must be dropped.
+ pages = {
+ "from=2024-01-01&page=1&to=2024-02-29": ([{"id": 1}, {"id": 7}], None),
+ "from=2024-03-01&page=1&to=2024-03-31": ([{"id": 7}, {"id": 2}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 1}, {"id": 7}, {"id": 2}]
+
+ def test_resumes_from_saved_window_and_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(SageHRResumeConfig(next_page=2, window_from="2024-03-01"))
+ # Earlier windows and page 1 of the resumed window must never be fetched.
+ pages = {"from=2024-03-01&page=2&to=2024-03-31": ([{"id": 2}], None)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 2}]
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(sage_hr, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @pytest.mark.parametrize(
+ "status, expected_status, expected_message",
+ [
+ (200, 200, None),
+ (401, 401, None),
+ (403, 403, None),
+ (404, 404, "Sage HR company subdomain not found. Use the subdomain from your Sage HR URL."),
+ (500, 500, "Sage HR returned HTTP 500"),
+ ],
+ )
+ def test_status_mapping(
+ self, status: int, expected_status: int, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ self._patch_session(monkeypatch, response)
+ assert check_access("acme", "sage-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("acme", "sage-key")
+ assert status == 0
+ assert message is not None and "Could not connect" in message
+
+ def test_invalid_subdomain_fails_without_network(self, monkeypatch: Any) -> None:
+ session = self._patch_session(monkeypatch, MagicMock())
+ status, message = check_access("evil.com/#", "sage-key")
+ assert status == 0
+ assert message is not None and "Invalid Sage HR company subdomain" in message
+ session.get.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (
+ 401,
+ False,
+ "Invalid Sage HR API key. Make sure API access is enabled under Settings → Integrations → API.",
+ ),
+ (
+ 403,
+ False,
+ "Your Sage HR API key does not have access to this data. Check that API access is enabled under Settings → Integrations → API.",
+ ),
+ (500, False, "Sage HR returned HTTP 500"),
+ ],
+ )
+ def test_validate_credentials(
+ self, status: int, expected_valid: bool, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ self._patch_session(monkeypatch, response)
+ assert validate_credentials("acme", "sage-key") == (expected_valid, expected_message)
+
+
+class TestSageHRSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = sage_hr_source(
+ subdomain="acme",
+ api_key="sage-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in SAGE_HR_ENDPOINTS.values())
+ assert set(SAGE_HR_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr_source.py
new file mode 100644
index 000000000000..10c7b6227942
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_hr/tests/test_sage_hr_source.py
@@ -0,0 +1,124 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SageHRSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.sage_hr import SageHRResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.source import SageHRSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSageHRSource:
+ def setup_method(self) -> None:
+ self.source = SageHRSource()
+ self.team_id = 123
+ self.config = SageHRSourceConfig(subdomain="acme", api_key="sage-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SAGEHR
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "SageHR"
+ assert config.label == "Sage HR"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Intentionally still hidden: the source lands unreleased until it has synced end-to-end
+ # against a live account.
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/sage-hr"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["subdomain", "api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_subdomain_is_a_connection_host_field(self) -> None:
+ # The API key is sent to `<subdomain>.sage.hr`, so retargeting the subdomain must force the
+ # editor to re-enter the key.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["employees"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "employees"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://acme.sage.hr/api/employees?page=1"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://other-co.sage.hr/api/teams?page=2"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://acme.sage.hr/api/employees"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://acme.sage.hr/api/teams"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.source.validate_sage_hr_credentials"
+ )
+ def test_validate_credentials_delegates_subdomain_and_key(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+ mock_validate.assert_called_once_with("acme", "sage-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SageHRResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sage_hr.source.sage_hr_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "employees"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["subdomain"] == "acme"
+ assert kwargs["api_key"] == "sage-key"
+ assert kwargs["endpoint"] == "employees"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Sage HR schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)