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 factorial import source (#66763)

Tom Owers5591bccb4e10
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 2de149370304..537656ceeea1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -111,6 +111,7 @@ the row lists both.
| emailoctopus | HTTP | requests | ✅ |
| eventbrite | HTTP | requests | ✅ |
| everhour | HTTP | requests | ✅ |
+| factorial | HTTP | requests + `rest_source.RESTClient` | ✅ |
| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
| financial_modelling | HTTP | requests | ✅ |
| finnhub | HTTP | requests | ✅ |
@@ -389,7 +390,6 @@ doesn't conflict with concurrent PRs.
- expensify
- ezofficeinventory
- facebook_pages
-- factorial
- fastbill
- fastly
- fauna
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.md
new file mode 100644
index 000000000000..9e91898783da
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.md
@@ -0,0 +1,72 @@
+# Factorial API inventory
+
+Source-local notes for the Factorial (HRIS) connector. See the official reference at
+<https://apidoc.factorialhr.com/>.
+
+## Connection
+
+- **Host:** single global host `https://api.factorialhr.com` (no per-account subdomains).
+- **Version:** dated path segment, pinned to `2025-04-01` → base `https://api.factorialhr.com/api/2025-04-01`.
+ Resources occasionally move between groups across versions, so the version is pinned in `factorial.py`.
+- **Auth:** `x-api-key: <key>` header (API key). OAuth2 is also supported by Factorial but not implemented
+ here — API key auth is fully supported for company/internal integrations and grants total account access.
+- **Resource path shape:** `/resources/<group>/<resource>` (e.g. `/resources/employees/employees`).
+
+## Pagination
+
+- Cursor pagination by record id. Params: `limit` (default & max 100), `after_id` (forward), `before_id`
+ (backward). Response envelope: `{"meta": {...}, "data": [...]}`.
+- `meta` carries `has_next_page`, `has_previous_page`, `start_cursor`, `end_cursor`, `total`, `limit`.
+- Forward paging: pass `after_id = meta.end_cursor` until `has_next_page` is false. Records come back in
+ ascending id order. Implemented by `FactorialCursorPaginator`.
+- No documented `sort` / `order` param; ordering is implied by the id cursor walk.
+
+## Incremental sync
+
+- Server-side `updated_after` is documented for only a narrow set of resources —
+ `project_management/flexible_time_records` and `project_management/subprojects`. It is **not** documented
+ on the higher-value people / time-off / attendance streams (Airbyte's connector confirms this: it filters
+ `updated_at` client-side everywhere except `shifts`).
+- Per the implementing-warehouse-sources guidance, a client-side cursor that still walks every page is not
+ incremental, and the two `updated_after` endpoints can't be curl-verified without a live API key. So every
+ endpoint currently ships **full refresh** (`INCREMENTAL_FIELDS = {}`). Promote `flexible_time_records` /
+ `subprojects` to incremental once the filter is verified against a live account with a future-date cutoff.
+- For genuine change tracking, Factorial also exposes `employee_updates/*` change-feed resources and webhooks
+ (`api_public/webhook_subscriptions`) — candidates for a future webhook-backed iteration.
+
+## Synced endpoints (`settings.py`)
+
+| Table | Path | Partition key |
+| --------------------- | ----------------------------------------------------- | ------------- |
+| employees | `/resources/employees/employees` | created_at |
+| teams | `/resources/teams/teams` | — |
+| team_memberships | `/resources/teams/memberships` | — |
+| locations | `/resources/locations/locations` | — |
+| legal_entities | `/resources/companies/legal_entities` | — |
+| contract_versions | `/resources/contracts/contract_versions` | created_at |
+| leaves | `/resources/timeoff/leaves` | created_at |
+| leave_types | `/resources/timeoff/leave_types` | — |
+| allowances | `/resources/timeoff/allowances` | — |
+| attendance_shifts | `/resources/attendance/shifts` | created_at |
+| expenses | `/resources/expenses/expenses` | created_at |
+| payroll_supplements | `/resources/payroll/supplements` | created_at |
+| flexible_time_records | `/resources/project_management/flexible_time_records` | created_at |
+| projects | `/resources/project_management/projects` | — |
+| candidates | `/resources/ats/candidates` | created_at |
+| job_postings | `/resources/ats/job_postings` | — |
+| applications | `/resources/ats/applications` | created_at |
+
+Primary key is the integer `id` on every list resource. Partition keys are `created_at` where the field is
+reliably present on every row (transactional records); lookup/config resources are left unpartitioned.
+
+## Rate limits
+
+- POST is documented at 200 req/min on `2025-*` endpoints. GET limits and rate-limit response headers are not
+ publicly documented. The tracked session's default retry handles transient `429`/`5xx`.
+
+## Verification status
+
+Endpoint paths, pagination, and the `updated_after` coverage were cross-referenced against the official docs
+and the Airbyte/Fivetran connector stream lists. They were **not** curl-verified against a live account (no
+API key available). The connection (host, version path, `x-api-key`, 401-on-bad-key) was confirmed with an
+unauthenticated curl returning `401`.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.py
new file mode 100644
index 000000000000..f656e20c6eb5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.py
@@ -0,0 +1,222 @@
+"""Canonical, documentation-sourced descriptions for Factorial endpoints and columns.
+
+Sourced from the official Factorial API reference (https://apidoc.factorialhr.com/). Keyed by the
+endpoint names in `settings.py` `FACTORIAL_ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced Factorial table. Columns absent here fall back to LLM enrichment, so partial coverage is fine.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://apidoc.factorialhr.com/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "employees": {
+ "description": "People employed at the company, with their personal and employment details.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the employee.",
+ "first_name": "Employee's first name.",
+ "last_name": "Employee's last name.",
+ "full_name": "Employee's full name.",
+ "email": "Employee's work email address.",
+ "birthday_on": "Employee's date of birth.",
+ "gender": "Employee's gender.",
+ "manager_id": "Identifier of the employee's manager.",
+ "legal_entity_id": "Identifier of the legal entity the employee belongs to.",
+ "location_id": "Identifier of the employee's primary workplace/location.",
+ "team_ids": "Identifiers of the teams the employee belongs to.",
+ "company_id": "Identifier of the company the employee belongs to.",
+ "terminated_on": "Date the employee was terminated, if applicable.",
+ "created_at": "Time at which the employee record was created.",
+ "updated_at": "Time at which the employee record was last updated.",
+ },
+ },
+ "teams": {
+ "description": "Teams used to group employees within the company.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the team.",
+ "name": "Name of the team.",
+ "description": "Description of the team.",
+ "employee_ids": "Identifiers of the employees in the team.",
+ "lead_ids": "Identifiers of the team leads.",
+ },
+ },
+ "team_memberships": {
+ "description": "Join records mapping employees to the teams they belong to.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the membership.",
+ "employee_id": "Identifier of the employee.",
+ "team_id": "Identifier of the team.",
+ "lead": "Whether the employee is a lead of the team.",
+ },
+ },
+ "locations": {
+ "description": "Workplaces/locations the company operates from, including their time zones.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the location.",
+ "name": "Name of the location.",
+ "country": "Country of the location.",
+ "timezone": "Time zone of the location.",
+ "company_id": "Identifier of the company the location belongs to.",
+ },
+ },
+ "legal_entities": {
+ "description": "Legal entities (companies) configured in the account.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the legal entity.",
+ "legal_name": "Registered legal name of the entity.",
+ "country": "Country the legal entity is registered in.",
+ "currency": "Default currency used by the legal entity.",
+ },
+ },
+ "contract_versions": {
+ "description": "Versions of an employee's contract; the latest holds the current job title, salary, and working hours.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the contract version.",
+ "employee_id": "Identifier of the employee the contract belongs to.",
+ "job_title": "Job title on this contract version.",
+ "salary_amount": "Salary amount on this contract version, in cents.",
+ "salary_frequency": "Frequency the salary is paid at.",
+ "starts_on": "Date this contract version starts.",
+ "ends_on": "Date this contract version ends, if applicable.",
+ "working_hours": "Contracted working hours.",
+ "created_at": "Time at which the contract version was created.",
+ "updated_at": "Time at which the contract version was last updated.",
+ },
+ },
+ "leaves": {
+ "description": "Individual time-off / absence records for employees.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the leave.",
+ "employee_id": "Identifier of the employee taking the leave.",
+ "company_id": "Identifier of the company.",
+ "leave_type_id": "Identifier of the leave type.",
+ "start_on": "First day of the leave.",
+ "finish_on": "Last day of the leave.",
+ "approved": "Whether the leave has been approved.",
+ "created_at": "Time at which the leave was created.",
+ "updated_at": "Time at which the leave was last updated.",
+ "deleted_at": "Time at which the leave was deleted, if applicable.",
+ },
+ },
+ "leave_types": {
+ "description": "Types of time off / absence configured for the company (e.g. holiday, sick leave).",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the leave type.",
+ "name": "Name of the leave type.",
+ "color": "Display color for the leave type.",
+ "approval_required": "Whether leaves of this type require approval.",
+ },
+ },
+ "allowances": {
+ "description": "Time-off allowance counters (the buckets of days/hours employees can take).",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the allowance.",
+ "name": "Name of the allowance.",
+ },
+ },
+ "attendance_shifts": {
+ "description": "Attendance shifts: clock-in/clock-out records for employees.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the shift.",
+ "employee_id": "Identifier of the employee.",
+ "clock_in": "Clock-in timestamp.",
+ "clock_out": "Clock-out timestamp.",
+ "day": "Calendar day the shift belongs to.",
+ "created_at": "Time at which the shift was created.",
+ "updated_at": "Time at which the shift was last updated.",
+ },
+ },
+ "expenses": {
+ "description": "Employee expenses submitted for reimbursement.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the expense.",
+ "employee_id": "Identifier of the employee who submitted the expense.",
+ "amount_cents": "Expense amount in cents.",
+ "currency": "Currency of the expense amount.",
+ "status": "Current status of the expense.",
+ "created_at": "Time at which the expense was created.",
+ "updated_at": "Time at which the expense was last updated.",
+ },
+ },
+ "payroll_supplements": {
+ "description": "Payroll supplements (one-off additions or deductions applied to payroll).",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the supplement.",
+ "employee_id": "Identifier of the employee.",
+ "amount_in_cents": "Supplement amount in cents.",
+ "description": "Description of the supplement.",
+ "created_at": "Time at which the supplement was created.",
+ "updated_at": "Time at which the supplement was last updated.",
+ },
+ },
+ "flexible_time_records": {
+ "description": "Flexible time records logged against projects (project time tracking).",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the time record.",
+ "employee_id": "Identifier of the employee.",
+ "date": "Date the time was recorded for.",
+ "imputed_minutes": "Minutes imputed to the record.",
+ "created_at": "Time at which the record was created.",
+ "updated_at": "Time at which the record was last updated.",
+ },
+ },
+ "projects": {
+ "description": "Projects used for time tracking.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "Name of the project.",
+ "status": "Current status of the project.",
+ },
+ },
+ "candidates": {
+ "description": "Candidates in the applicant tracking system (ATS).",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the candidate.",
+ "first_name": "Candidate's first name.",
+ "last_name": "Candidate's last name.",
+ "email": "Candidate's email address.",
+ "created_at": "Time at which the candidate was created.",
+ "updated_at": "Time at which the candidate was last updated.",
+ },
+ },
+ "job_postings": {
+ "description": "Job postings published in the applicant tracking system (ATS).",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the job posting.",
+ "title": "Title of the job posting.",
+ "status": "Current status of the job posting.",
+ "team_id": "Identifier of the team the posting belongs to.",
+ "location_id": "Identifier of the location for the posting.",
+ },
+ },
+ "applications": {
+ "description": "Applications linking candidates to job postings in the ATS.",
+ "docs_url": _DOCS,
+ "columns": {
+ "id": "Unique identifier for the application.",
+ "candidate_id": "Identifier of the candidate.",
+ "ats_job_posting_id": "Identifier of the job posting applied to.",
+ "phase_id": "Identifier of the current hiring phase.",
+ "created_at": "Time at which the application was created.",
+ "updated_at": "Time at which the application was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.py
new file mode 100644
index 000000000000..fd85d4fe7440
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.py
@@ -0,0 +1,195 @@
+import dataclasses
+from typing import Any, Optional
+
+from requests import Request, Response
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_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.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.settings import FACTORIAL_ENDPOINTS
+
+# Factorial uses a single global host (no per-account subdomains) and dated, version-pinned paths.
+# `2025-04-01` is a stable release within the currently supported version range; pinning avoids
+# silently picking up breaking changes (resources occasionally move between groups across versions).
+FACTORIAL_HOST = "https://api.factorialhr.com"
+API_VERSION = "2025-04-01"
+BASE_URL = f"{FACTORIAL_HOST}/api/{API_VERSION}"
+
+# Factorial caps `limit` at 100 records per page across list endpoints (the default is also 100).
+PAGE_SIZE = 100
+
+
+class FactorialResumeConfig:
+ # Opaque forward cursor (`meta.end_cursor`) passed back as `after_id` to fetch the next page.
+ after_id: str
+
+
+class FactorialCursorPaginator(BasePaginator):
+ """Cursor paginator for Factorial's ``{"meta": {...}, "data": [...]}`` envelope.
+
+ Factorial paginates forward by record id: each page returns a ``meta.end_cursor`` token that is
+ passed back as ``after_id`` to fetch the next page, and ``meta.has_next_page`` signals when to
+ stop. The cursor is an opaque (base64-encoded id) value, so we forward it verbatim. We also stop
+ on an empty page as a backstop, so a misreported ``has_next_page`` can never loop us forever.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._after_id: Optional[str] = None
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["limit"] = PAGE_SIZE
+ if self._after_id is not None:
+ request.params["after_id"] = self._after_id
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ meta: dict[str, Any] = {}
+ try:
+ body = response.json()
+ if isinstance(body, dict) and isinstance(body.get("meta"), dict):
+ meta = body["meta"]
+ except Exception:
+ meta = {}
+
+ end_cursor = meta.get("end_cursor")
+ if not meta.get("has_next_page") or not end_cursor or not data:
+ self._has_next_page = False
+ self._after_id = None
+ return
+
+ self._after_id = str(end_cursor)
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ if self._after_id is not None:
+ request.params["after_id"] = self._after_id
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if self._has_next_page and self._after_id is not None:
+ return {"after_id": self._after_id}
+ return None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ after_id = state.get("after_id")
+ if after_id is not None:
+ self._after_id = str(after_id)
+ self._has_next_page = True
+
+
+def get_resource(endpoint: str) -> EndpointResource:
+ config = FACTORIAL_ENDPOINTS[endpoint]
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": "replace",
+ "endpoint": {
+ # Every list endpoint wraps its records under a top-level `data` key.
+ "data_selector": "data",
+ "path": config.path,
+ "params": {},
+ },
+ "table_format": "delta",
+ }
+
+
+def factorial_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[FactorialResumeConfig],
+) -> SourceResponse:
+ endpoint_config = FACTORIAL_ENDPOINTS[endpoint]
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ # Factorial authenticates with the account-wide `x-api-key` header. Going through
+ # APIKeyAuth (rather than raw headers) registers the key for value-based log redaction.
+ "auth": {
+ "type": "api_key",
+ "api_key": api_key,
+ "name": "x-api-key",
+ "location": "header",
+ },
+ "paginator": FactorialCursorPaginator(),
+ "session": make_tracked_session(redact_values=(api_key,)),
+ },
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [get_resource(endpoint)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"after_id": resume_config.after_id}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when there's a next page to resume to; the Redis TTL handles cleanup once the
+ # sync finishes. Saving happens after each page is yielded, so a crash re-fetches the last
+ # page rather than skipping it (merge dedupes the re-pulled rows on the primary key).
+ if state and state.get("after_id"):
+ resumable_source_manager.save_state(FactorialResumeConfig(after_id=str(state["after_id"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ partition_key = endpoint_config.partition_key
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1 if partition_key else None,
+ partition_size=1 if partition_key else None,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="week" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
+ # Cursor pagination walks records in ascending id order, so pages arrive in a stable,
+ # forward-only sequence.
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # Probe the core Employees resource: every HRIS account has it, and an API key with no access
+ # would 401/403 here. Factorial API keys carry total account access, so there is no per-scope
+ # nuance to accept at source-create time the way OAuth-scoped sources need.
+ url = f"{BASE_URL}/resources/employees/employees"
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ url,
+ params={"limit": 1},
+ headers={"x-api-key": api_key},
+ timeout=10,
+ # `allow_redirects=False` as defense-in-depth — keeps the API key from being
+ # forwarded to a redirected host even though the base URL is hard-coded.
+ allow_redirects=False,
+ )
+ except Exception as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Factorial API key, or it does not have access to your account's data."
+ return False, f"Factorial returned an unexpected status code: {response.status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.py
new file mode 100644
index 000000000000..df47d8b00d48
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.py
@@ -0,0 +1,115 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class FactorialEndpointConfig:
+ name: str
+ # Path under the versioned base URL (e.g. "/resources/employees/employees"). Factorial groups
+ # resources as `/resources/<group>/<resource>`; the group can move between API versions, so the
+ # path is pinned to the version in `factorial.py`.
+ path: str
+ # Stable created-date field to partition by, or None to skip partitioning. Only set where
+ # `created_at` is reliably present on every row — Factorial returns it on transactional records
+ # (employees, leaves, shifts, expenses, …) but not on every lookup/config resource.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+# A focused, canonical HRIS stream set cross-referenced against the Airbyte/Fivetran Factorial
+# connectors: people & org structure, contracts, time off, attendance, expenses, payroll, project
+# time tracking, and recruiting (ATS). Every list resource is keyed by a unique integer `id`.
+FACTORIAL_ENDPOINTS: dict[str, FactorialEndpointConfig] = {
+ "employees": FactorialEndpointConfig(
+ name="employees",
+ path="/resources/employees/employees",
+ partition_key="created_at",
+ ),
+ "teams": FactorialEndpointConfig(
+ name="teams",
+ path="/resources/teams/teams",
+ ),
+ "team_memberships": FactorialEndpointConfig(
+ name="team_memberships",
+ path="/resources/teams/memberships",
+ ),
+ "locations": FactorialEndpointConfig(
+ name="locations",
+ path="/resources/locations/locations",
+ ),
+ "legal_entities": FactorialEndpointConfig(
+ name="legal_entities",
+ path="/resources/companies/legal_entities",
+ ),
+ "contract_versions": FactorialEndpointConfig(
+ name="contract_versions",
+ path="/resources/contracts/contract_versions",
+ partition_key="created_at",
+ ),
+ "leaves": FactorialEndpointConfig(
+ name="leaves",
+ path="/resources/timeoff/leaves",
+ partition_key="created_at",
+ ),
+ "leave_types": FactorialEndpointConfig(
+ name="leave_types",
+ path="/resources/timeoff/leave_types",
+ ),
+ "allowances": FactorialEndpointConfig(
+ name="allowances",
+ path="/resources/timeoff/allowances",
+ ),
+ "attendance_shifts": FactorialEndpointConfig(
+ name="attendance_shifts",
+ path="/resources/attendance/shifts",
+ partition_key="created_at",
+ ),
+ "expenses": FactorialEndpointConfig(
+ name="expenses",
+ path="/resources/expenses/expenses",
+ partition_key="created_at",
+ ),
+ "payroll_supplements": FactorialEndpointConfig(
+ name="payroll_supplements",
+ path="/resources/payroll/supplements",
+ partition_key="created_at",
+ ),
+ "flexible_time_records": FactorialEndpointConfig(
+ name="flexible_time_records",
+ path="/resources/project_management/flexible_time_records",
+ partition_key="created_at",
+ ),
+ "projects": FactorialEndpointConfig(
+ name="projects",
+ path="/resources/project_management/projects",
+ ),
+ "candidates": FactorialEndpointConfig(
+ name="candidates",
+ path="/resources/ats/candidates",
+ partition_key="created_at",
+ ),
+ "job_postings": FactorialEndpointConfig(
+ name="job_postings",
+ path="/resources/ats/job_postings",
+ ),
+ "applications": FactorialEndpointConfig(
+ name="applications",
+ path="/resources/ats/applications",
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(FACTORIAL_ENDPOINTS.keys())
+
+# Full refresh only. Factorial documents a server-side `updated_after` filter on only two of the
+# endpoints we sync — `project_management/flexible_time_records` and `project_management/subprojects`
+# — and not on the higher-value people/time-off/attendance streams (Airbyte's connector confirms this:
+# it filters `updated_at` client-side everywhere except `shifts`). Per the implementing-warehouse-sources
+# guidance, a "client-side cursor" that still walks every page is not incremental, so we ship every
+# endpoint as full refresh. The two `updated_after`-capable endpoints could be promoted to incremental
+# after curl-verifying (with a future-date cutoff) that the filter actually narrows results against a
+# live account — which requires a Factorial API key we don't have here.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/source.py
index 07a724b93bee..933b0179de49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/source.py
@@ -1,19 +1,43 @@
-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.factorial.factorial import (
+ FactorialResumeConfig,
+ factorial_source,
+ validate_credentials as validate_factorial_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.settings import (
+ ENDPOINTS,
+ FACTORIAL_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FactorialSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FactorialSource(SimpleSource[FactorialSourceConfig]):
+class FactorialSource(ResumableSource[FactorialSourceConfig, FactorialResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FACTORIAL
@@ -24,7 +48,88 @@ class FactorialSource(SimpleSource[FactorialSourceConfig]):
name=SchemaExternalDataSourceType.FACTORIAL,
category=DataWarehouseSourceCategory.HR___RECRUITING,
label="Factorial",
- iconPath="/static/services/factorial.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Factorial API key to sync your HR, time-off, attendance, payroll, and recruiting data into the PostHog Data warehouse.
+
+Create an API key in your Factorial account under **Settings > API keys** (or **Integrations > Public API**). The key grants read access to your company's data across every table listed below.""",
+ iconPath="/static/services/factorial.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/factorial",
+ fields=cast(
+ list[FieldType],
+ [
+ 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.factorial.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked Factorial API key surfaces as an HTTPError when the RESTClient
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop
+ # the sync with an actionable message.
+ "401 Client Error": "Invalid or revoked Factorial API key. Create a new key in your Factorial account settings and reconnect.",
+ "403 Client Error": "Your Factorial API key does not have access to this data. Check the key's permissions and reconnect.",
+ "Unauthorized for url": "Invalid or revoked Factorial API key. Create a new key in your Factorial account settings and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: FactorialSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # No endpoint advertises a curl-verified server-side timestamp filter yet, so every
+ # schema is full refresh only (INCREMENTAL_FIELDS is empty — see settings.py).
+ supports_incremental=(fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,
+ supports_append=fields is not None,
+ incremental_fields=fields or [],
+ should_sync_default=FACTORIAL_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: FactorialSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_factorial_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FactorialResumeConfig]:
+ return ResumableSourceManager[FactorialResumeConfig](inputs, FactorialResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FactorialSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FactorialResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return factorial_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.py
new file mode 100644
index 000000000000..dda2863f7d67
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.py
@@ -0,0 +1,301 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.factorial import (
+ BASE_URL,
+ PAGE_SIZE,
+ FactorialCursorPaginator,
+ FactorialResumeConfig,
+ factorial_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.settings import (
+ ENDPOINTS,
+ FACTORIAL_ENDPOINTS,
+)
+
+_SESSION_FACTORY = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.factorial.factorial.make_tracked_session"
+)
+
+
+def _full_page() -> list[dict[str, Any]]:
+ return [{"id": i} for i in range(PAGE_SIZE)]
+
+
+def _meta_response(meta: dict[str, Any]) -> MagicMock:
+ response = MagicMock()
+ response.json.return_value = {"meta": meta, "data": []}
+ return response
+
+
+class TestFactorialCursorPaginator:
+ def test_initial_state(self) -> None:
+ paginator = FactorialCursorPaginator()
+ assert paginator.has_next_page is True
+
+ def test_init_request_emits_limit_only_when_fresh(self) -> None:
+ paginator = FactorialCursorPaginator()
+ request = Request(method="GET", url=f"{BASE_URL}/resources/employees/employees")
+ paginator.init_request(request)
+ assert request.params["limit"] == PAGE_SIZE
+ assert "after_id" not in request.params
+
+ def test_advances_after_id_on_non_terminal_page(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.update_state(_meta_response({"has_next_page": True, "end_cursor": "Mjc="}), _full_page())
+ assert paginator.has_next_page is True
+
+ request = Request(method="GET", url=f"{BASE_URL}/resources/employees/employees")
+ paginator.update_request(request)
+ assert request.params["after_id"] == "Mjc="
+
+ def test_stops_when_has_next_page_false(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.update_state(_meta_response({"has_next_page": False, "end_cursor": "Mjc="}), _full_page())
+ assert paginator.has_next_page is False
+
+ def test_stops_when_no_end_cursor(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.update_state(_meta_response({"has_next_page": True}), _full_page())
+ assert paginator.has_next_page is False
+
+ def test_stops_on_empty_page_even_if_api_claims_more(self) -> None:
+ # A misreported has_next_page must never loop us forever on an empty page.
+ paginator = FactorialCursorPaginator()
+ paginator.update_state(_meta_response({"has_next_page": True, "end_cursor": "Mjc="}), [])
+ assert paginator.has_next_page is False
+
+ def test_get_resume_state_when_next_page(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.update_state(_meta_response({"has_next_page": True, "end_cursor": "Mjc="}), _full_page())
+ assert paginator.get_resume_state() == {"after_id": "Mjc="}
+
+ def test_get_resume_state_none_on_terminal_page(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.update_state(_meta_response({"has_next_page": False}), [])
+ assert paginator.get_resume_state() is None
+
+ def test_set_resume_state_round_trip(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.set_resume_state({"after_id": "MTY="})
+ assert paginator.has_next_page is True
+
+ request = Request(method="GET", url=f"{BASE_URL}/resources/employees/employees")
+ paginator.init_request(request)
+ assert request.params["after_id"] == "MTY="
+ assert request.params["limit"] == PAGE_SIZE
+
+ def test_set_resume_state_ignores_missing_cursor(self) -> None:
+ paginator = FactorialCursorPaginator()
+ paginator.set_resume_state({})
+ request = Request(method="GET", url=f"{BASE_URL}/resources/employees/employees")
+ paginator.init_request(request)
+ assert "after_id" not in request.params
+
+
+class TestGetResource:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_resource_shape(self, endpoint: str) -> None:
+ resource = get_resource(endpoint)
+ config = FACTORIAL_ENDPOINTS[endpoint]
+
+ assert resource["name"] == endpoint
+ assert resource["table_name"] == endpoint
+ assert resource["write_disposition"] == "replace"
+ assert resource["table_format"] == "delta"
+
+ endpoint_def = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint_def["path"] == config.path
+ assert endpoint_def["path"].startswith("/resources/")
+ # Every Factorial list endpoint wraps records under the top-level `data` key.
+ assert endpoint_def["data_selector"] == "data"
+
+
+class TestSourceResponsePartitioning:
+ def _build(self, endpoint: str) -> Any:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ with patch(_SESSION_FACTORY):
+ return factorial_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ @pytest.mark.parametrize(
+ "endpoint",
+ [e for e, c in FACTORIAL_ENDPOINTS.items() if c.partition_key],
+ )
+ def test_partitioned_endpoints_use_datetime_partitioning(self, endpoint: str) -> None:
+ response = self._build(endpoint)
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_format == "week"
+ assert response.sort_mode == "asc"
+
+ @pytest.mark.parametrize(
+ "endpoint",
+ [e for e, c in FACTORIAL_ENDPOINTS.items() if not c.partition_key],
+ )
+ def test_unpartitioned_endpoints_skip_partitioning(self, endpoint: str) -> None:
+ response = self._build(endpoint)
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ assert response.partition_count is None
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_primary_keys_are_id(self, endpoint: str) -> None:
+ response = self._build(endpoint)
+ assert response.primary_keys == ["id"]
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestFactorialSourceResumeBehavior:
+ """End-to-end resume behaviour of ``factorial_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(_SESSION_FACTORY) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source = factorial_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ list(cast(Iterable[Any], source.items()))
+ return mock_session, sent_params
+
+ def _page_body(self, items: list[dict[str, Any]], meta: dict[str, Any]) -> dict[str, Any]:
+ return {"data": items, "meta": meta}
+
+ def test_fresh_run_saves_cursor_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(self._page_body(_full_page(), {"has_next_page": True, "end_cursor": "Mjc="})),
+ _make_http_response(self._page_body([{"id": 999}], {"has_next_page": False, "end_cursor": None})),
+ ]
+ _, sent_params = self._drive("employees", manager, responses)
+
+ # First request starts without a cursor; the second carries the advanced after_id.
+ assert "after_id" not in sent_params[0]
+ assert sent_params[1].get("after_id") == "Mjc="
+ assert all(p.get("limit") == PAGE_SIZE for p in sent_params)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [FactorialResumeConfig(after_id="Mjc=")]
+
+ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = FactorialResumeConfig(after_id="MTY=")
+
+ responses = [
+ _make_http_response(self._page_body([{"id": 17}], {"has_next_page": False, "end_cursor": None})),
+ ]
+ _, sent_params = self._drive("employees", manager, responses)
+
+ assert sent_params[0].get("after_id") == "MTY="
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(self._page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),
+ ]
+ self._drive("employees", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(self._page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),
+ ]
+ self._drive("employees", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:
+ with patch(_SESSION_FACTORY) as MockSession:
+ mock_session = MockSession.return_value
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session.get.return_value = response
+
+ valid, error = validate_credentials("test-key")
+ assert valid is expected_valid
+ if expected_valid:
+ assert error is None
+ else:
+ assert error is not None
+
+ def test_probes_employees_endpoint_with_api_key_header(self) -> None:
+ with patch(_SESSION_FACTORY) as MockSession:
+ mock_session = MockSession.return_value
+ response = MagicMock()
+ response.status_code = 200
+ mock_session.get.return_value = response
+
+ validate_credentials("test-key")
+
+ call = mock_session.get.call_args
+ assert call.args[0] == f"{BASE_URL}/resources/employees/employees"
+ assert call.kwargs["headers"] == {"x-api-key": "test-key"}
+ assert call.kwargs["params"] == {"limit": 1}
+ assert call.kwargs["allow_redirects"] is False
+
+ def test_network_error_returns_message(self) -> None:
+ with patch(_SESSION_FACTORY) as MockSession:
+ MockSession.return_value.get.side_effect = Exception("boom")
+ valid, error = validate_credentials("test-key")
+ assert valid is False
+ assert error == "boom"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial_source.py
new file mode 100644
index 000000000000..341dd10c579a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial_source.py
@@ -0,0 +1,152 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.factorial import FactorialResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.source import FactorialSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FactorialSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "employees",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestFactorialSource:
+ def setup_method(self) -> None:
+ self.source = FactorialSource()
+ self.team_id = 123
+ self.config = FactorialSourceConfig(api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.FACTORIAL
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Factorial"
+ assert config.label == "Factorial"
+ # Shipping behind the unreleased flag while in alpha: hidden from users until verified live.
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/factorial"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ (api_key_field,) = config.fields
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog (no I/O in get_schemas), so the public docs can render the
+ # Supported tables section.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "Unauthorized for url"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_all_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No endpoint has a curl-verified server-side filter yet, so every schema is full refresh only.
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append 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=["leaves"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "leaves"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ def test_get_documented_tables_renders_catalog(self) -> None:
+ # Drives the public-docs <SourceTables /> path: static catalog + canonical descriptions.
+ tables = self.source.get_documented_tables()
+ names = {t["name"] for t in tables}
+ assert names == set(ENDPOINTS)
+ leaves = next(t for t in tables if t["name"] == "leaves")
+ assert leaves["description"]
+ assert leaves["sync_methods"] == ["Full refresh"]
+ assert leaves["primary_keys"] == [] # detected_primary_keys is unset for static schemas
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ # Every documented table must map to a real endpoint, else the description is dead weight.
+ assert set(descriptions).issubset(set(ENDPOINTS))
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ ((True, None), True, None),
+ (
+ (False, "Invalid Factorial API key, or it does not have access to your account's data."),
+ False,
+ "Invalid Factorial API key, or it does not have access to your account's data.",
+ ),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.factorial.source.validate_factorial_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("test-key")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FactorialResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.factorial.source.factorial_source")
+ def test_source_for_pipeline_passes_arguments(self, mock_factorial_source: mock.MagicMock) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = _make_inputs(schema_name="leaves", team_id=99, job_id="job-xyz")
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_factorial_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="leaves",
+ team_id=99,
+ job_id="job-xyz",
+ resumable_source_manager=manager,
+ )
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 fdb323711d27..fa7b8886ecad 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
@@ -1090,7 +1090,7 @@ class FacebookPagesSourceConfig(config.Config):
@config.config
class FactorialSourceConfig(config.Config):
- pass
+ api_key: str
@config.config