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 workable import source (#65657)

Tom Owers585a749a4d2d
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 4134d13b7906..42eeca4264c3 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -191,6 +191,7 @@ the row lists both.
| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| webflow | HTTP | requests | ✅ |
| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| workable | HTTP | requests | ✅ |
| workos | HTTP | requests + `rest_source.RESTClient` | ✅ |
| wrike | HTTP | requests | ✅ |
| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -688,7 +689,6 @@ doesn't conflict with concurrent PRs.
- when_i_work
- wikipedia_pageviews
- wordpress
-- workable
- workday
- workflowmax
- workramp
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index e2be0bb93cc4..26927bc1f0fe 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -3307,7 +3307,8 @@ class WorkOSSourceConfig(config.Config):
@config.config
class WorkableSourceConfig(config.Config):
- pass
+ subdomain: str
+ api_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/workable/canonical_descriptions.py b/posthog/temporal/data_imports/sources/workable/canonical_descriptions.py
new file mode 100644
index 000000000000..5a81c3e5df9d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/workable/canonical_descriptions.py
@@ -0,0 +1,77 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Descriptions taken from the Workable SPI v3 docs (https://workable.readme.io/reference). Columns not
+# covered here fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "jobs": {
+ "description": "Jobs (open positions) in your Workable account.",
+ "docs_url": "https://workable.readme.io/reference/jobs",
+ "columns": {
+ "id": "Unique identifier for the job.",
+ "title": "Job title.",
+ "full_title": "Job title including the job code suffix.",
+ "shortcode": "System-generated short code for the job, used in public job URLs.",
+ "code": "Job code as set by the account.",
+ "state": "Current state of the job (draft, published, archived, closed).",
+ "department": "Department the job belongs to.",
+ "url": "URL of the job in Workable.",
+ "application_url": "URL where candidates apply to the job.",
+ "shortlink": "Public short link to the job posting.",
+ "location": "Location details for the job.",
+ "created_at": "Timestamp the job was created.",
+ "updated_at": "Timestamp the job was last updated.",
+ },
+ },
+ "candidates": {
+ "description": "Candidates (applicants) across the account's jobs.",
+ "docs_url": "https://workable.readme.io/reference/job-candidates-index",
+ "columns": {
+ "id": "Unique identifier for the candidate.",
+ "name": "Candidate's full name.",
+ "firstname": "Candidate's first name.",
+ "lastname": "Candidate's last name.",
+ "headline": "Candidate's professional headline.",
+ "job": "The job the candidate applied to (shortcode and title).",
+ "stage": "Current pipeline stage of the candidate.",
+ "disqualified": "Whether the candidate has been disqualified.",
+ "disqualification_reason": "Reason the candidate was disqualified, if any.",
+ "sourced": "Whether the candidate was sourced rather than having applied.",
+ "profile_url": "URL of the candidate's profile in Workable.",
+ "email": "Candidate's email address.",
+ "domain": "Source domain the candidate came from.",
+ "created_at": "Timestamp the candidate was created.",
+ "updated_at": "Timestamp the candidate was last updated.",
+ },
+ },
+ "members": {
+ "description": "Members (users) of your Workable account.",
+ "docs_url": "https://workable.readme.io/reference/members",
+ "columns": {
+ "id": "Unique identifier for the member.",
+ "name": "Member's full name.",
+ "headline": "Member's headline.",
+ "email": "Member's email address.",
+ "role": "Member's recruiting role.",
+ "active": "Whether the member is active.",
+ },
+ },
+ "recruiters": {
+ "description": "External recruiters associated with your Workable account.",
+ "docs_url": "https://workable.readme.io/reference/recruiters",
+ "columns": {
+ "id": "Unique identifier for the recruiter.",
+ "name": "Recruiter's full name.",
+ "email": "Recruiter's email address.",
+ },
+ },
+ "stages": {
+ "description": "Stages of your account's recruitment pipeline.",
+ "docs_url": "https://workable.readme.io/reference/stages",
+ "columns": {
+ "slug": "Unique token identifying the stage.",
+ "name": "Stage name.",
+ "kind": "Stage type (e.g. sourced, applied, interview, offer, hired).",
+ "position": "Zero-based position of the stage in the pipeline.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/workable/settings.py b/posthog/temporal/data_imports/sources/workable/settings.py
new file mode 100644
index 000000000000..20100396c96c
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/workable/settings.py
@@ -0,0 +1,85 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# Workable caps `limit` at 100 (default 50) across the list endpoints.
+PAGE_SIZE = 100
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class WorkableEndpointConfig:
+ name: str
+ # Path under the `/spi/v3` base (e.g. `/jobs`).
+ path: str
+ # Key the result array is nested under in the JSON response (e.g. `{"jobs": [...]}`).
+ data_key: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation timestamp used for datetime partitioning. Never `updated_at` — partitions
+ # must not rewrite on every sync. `None` when the resource has no creation timestamp.
+ partition_key: Optional[str] = None
+ # Only `True` when the endpoint exposes a genuine server-side `<field>_after` time filter.
+ supports_incremental: bool = False
+
+
+# Account-level list endpoints. These mirror the canonical Workable connector stream set
+# (jobs, candidates, members, recruiters, stages). All return `{<data_key>: [...]}` and the
+# paginated ones carry a sibling `{"paging": {"next": "<full url>"}}`.
+WORKABLE_ENDPOINTS: dict[str, WorkableEndpointConfig] = {
+ "jobs": WorkableEndpointConfig(
+ name="jobs",
+ path="/jobs",
+ data_key="jobs",
+ primary_keys=["id"],
+ partition_key="created_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],
+ ),
+ "candidates": WorkableEndpointConfig(
+ name="candidates",
+ path="/candidates",
+ data_key="candidates",
+ primary_keys=["id"],
+ partition_key="created_at",
+ supports_incremental=True,
+ incremental_fields=[_datetime_field("updated_at"), _datetime_field("created_at")],
+ ),
+ # Members, recruiters, and stages are small account-level reference collections with no
+ # server-side time filter (and stages/recruiters have no pagination at all), so they're
+ # full refresh only.
+ "members": WorkableEndpointConfig(
+ name="members",
+ path="/members",
+ data_key="members",
+ primary_keys=["id"],
+ ),
+ "recruiters": WorkableEndpointConfig(
+ name="recruiters",
+ path="/recruiters",
+ data_key="recruiters",
+ primary_keys=["id"],
+ ),
+ # Stages are keyed by `slug` — the stage object has no `id`.
+ "stages": WorkableEndpointConfig(
+ name="stages",
+ path="/stages",
+ data_key="stages",
+ primary_keys=["slug"],
+ ),
+}
+
+ENDPOINTS = tuple(WORKABLE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in WORKABLE_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/workable/source.py b/posthog/temporal/data_imports/sources/workable/source.py
index 988987bd02b8..b218dcd39b49 100644
--- a/posthog/temporal/data_imports/sources/workable/source.py
+++ b/posthog/temporal/data_imports/sources/workable/source.py
@@ -1,20 +1,33 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import WorkableSourceConfig
+from posthog.temporal.data_imports.sources.workable.settings import ENDPOINTS, INCREMENTAL_FIELDS, WORKABLE_ENDPOINTS
+from posthog.temporal.data_imports.sources.workable.workable import (
+ WorkableResumeConfig,
+ validate_credentials as validate_workable_credentials,
+ workable_source,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class WorkableSource(SimpleSource[WorkableSourceConfig]):
+class WorkableSource(ResumableSource[WorkableSourceConfig, WorkableResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WORKABLE
@@ -25,7 +38,123 @@ class WorkableSource(SimpleSource[WorkableSourceConfig]):
name=SchemaExternalDataSourceType.WORKABLE,
category=DataWarehouseSourceCategory.HR___RECRUITING,
label="Workable",
- iconPath="/static/services/workable.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Workable account subdomain and an SPI access token to pull your Workable recruiting data into the PostHog Data warehouse.
+
+You can create an access token in your Workable account under **Settings > Integrations > Access Tokens** (admins only). Grant the following read scopes:
+- `r_jobs`
+- `r_candidates`
+""",
+ iconPath="/static/services/workable.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/workable",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Account subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your-company",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored token is sent to https://<subdomain>.workable.com, so retargeting `subdomain`
+ # must re-require the token to prevent exfiltration to an attacker-controlled host.
+ return ["subdomain"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad/expired/revoked token surfaces as an HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Match the stable status text plus the per-account host prefix.
+ "401 Client Error: Unauthorized for url: https://": "Your Workable access token is invalid or has expired. Create a new token in your Workable account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://": "Your Workable access token is missing the read scopes needed to sync this data (e.g. r_jobs, r_candidates). Grant them in your Workable account settings, then reconnect.",
+ "Invalid Workable subdomain": "The Workable subdomain is invalid. Use just the account subdomain from https://<subdomain>.workable.com.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.workable.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: WorkableSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = WORKABLE_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+
+ schemas = [_build_schema(endpoint) 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: WorkableSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Probe the specific schema's endpoint when given, otherwise a cheap `/jobs` probe.
+ path = WORKABLE_ENDPOINTS[schema_name].path if schema_name in WORKABLE_ENDPOINTS else "/jobs"
+
+ try:
+ status_code, ok = validate_workable_credentials(config.subdomain, config.api_token, path)
+ except ValueError as e:
+ return False, str(e)
+
+ if ok:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid Workable access token"
+ if status_code == 403:
+ # A 403 is a valid token missing a scope. At source-create (no schema_name) accept it —
+ # users may only grant scopes for the endpoints they want. Reject it for a specific schema.
+ if schema_name is None:
+ return True, None
+ return False, f"Your Workable access token is missing the scope required to sync '{schema_name}'"
+ return False, "Unable to validate Workable credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WorkableResumeConfig]:
+ return ResumableSourceManager[WorkableResumeConfig](inputs, WorkableResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: WorkableSourceConfig,
+ resumable_source_manager: ResumableSourceManager[WorkableResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return workable_source(
+ subdomain=config.subdomain,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/workable/tests/test_workable.py b/posthog/temporal/data_imports/sources/workable/tests/test_workable.py
new file mode 100644
index 000000000000..451352e07acd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/workable/tests/test_workable.py
@@ -0,0 +1,271 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.workable import workable
+from posthog.temporal.data_imports.sources.workable.settings import PAGE_SIZE, WORKABLE_ENDPOINTS
+from posthog.temporal.data_imports.sources.workable.workable import (
+ WorkableResumeConfig,
+ WorkableRetryableError,
+ _build_initial_url,
+ _format_datetime,
+ _sort_mode_for,
+ _validate_subdomain,
+ get_rows,
+ validate_credentials,
+ workable_source,
+)
+
+
+class TestValidateSubdomain:
+ @parameterized.expand(
+ [
+ ("simple", "groove-tech", "groove-tech"),
+ ("alnum", "company123", "company123"),
+ ("single_char", "a", "a"),
+ ("trims_whitespace", " acme ", "acme"),
+ ]
+ )
+ def test_valid_subdomains(self, _name: str, value: str, expected: str) -> None:
+ assert _validate_subdomain(value) == expected
+
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("dot_injection", "evil.com/"),
+ ("slash", "acme/foo"),
+ ("at_sign", "user@host"),
+ ("leading_hyphen_ok_but_dot_not", "a.b"),
+ ("trailing_hyphen", "acme-"),
+ ("leading_hyphen", "-acme"),
+ ("space_inside", "ac me"),
+ ]
+ )
+ def test_invalid_subdomains_raise(self, _name: str, value: str) -> None:
+ with pytest.raises(ValueError):
+ _validate_subdomain(value)
+
+
+class TestFormatDatetime:
+ @parameterized.expand(
+ [
+ ("aware", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_only", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "already-a-cursor", "already-a-cursor"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+
+class TestBuildInitialUrl:
+ def test_full_refresh_only_has_limit(self) -> None:
+ url = _build_initial_url(
+ "acme",
+ "members",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert url == f"https://acme.workable.com/spi/v3/members?limit={PAGE_SIZE}"
+
+ def test_incremental_adds_updated_after_by_default(self) -> None:
+ url = _build_initial_url(
+ "acme",
+ "candidates",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field=None,
+ )
+ assert "updated_after=2026-01-02T03%3A04%3A05Z" in url
+
+ def test_incremental_honors_chosen_created_at_field(self) -> None:
+ url = _build_initial_url(
+ "acme",
+ "candidates",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert "created_after=" in url
+ assert "updated_after=" not in url
+
+ def test_full_refresh_endpoint_ignores_incremental_filter(self) -> None:
+ # `members` is full refresh — a stray incremental value must not produce a time filter.
+ url = _build_initial_url(
+ "acme",
+ "members",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ assert "_after" not in url
+
+
+class TestSortMode:
+ @parameterized.expand(
+ [
+ ("created_at_is_asc", "candidates", True, "created_at", "asc"),
+ ("updated_at_is_desc", "candidates", True, "updated_at", "desc"),
+ ("default_field_is_desc", "candidates", True, None, "desc"),
+ ("non_incremental_run_is_asc", "candidates", False, "updated_at", "asc"),
+ ("full_refresh_endpoint_is_asc", "members", True, "updated_at", "asc"),
+ ]
+ )
+ def test_sort_mode(
+ self, _name: str, endpoint: str, use_incremental: bool, field: str | None, expected: str
+ ) -> None:
+ assert _sort_mode_for(endpoint, use_incremental, field) == expected
+
+
+class _FakeResumableManager:
+ """In-memory stand-in for ResumableSourceManager."""
+
+ def __init__(self, state: WorkableResumeConfig | None = None) -> None:
+ self.state = state
+ self.saved: list[WorkableResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> WorkableResumeConfig | None:
+ return self.state
+
+ def save_state(self, data: WorkableResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], **kwargs: Any) -> list[dict]:
+ def fake_fetch(_session: Any, url: str, _logger: Any) -> dict:
+ return pages[url]
+
+ monkeypatch.setattr(workable, "_fetch_page", fake_fetch)
+ rows: list[dict] = []
+ for batch in get_rows(
+ subdomain="acme",
+ api_token="tok",
+ endpoint=kwargs.get("endpoint", "candidates"),
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=kwargs.get("should_use_incremental_field", False),
+ db_incremental_field_last_value=kwargs.get("db_incremental_field_last_value"),
+ incremental_field=kwargs.get("incremental_field"),
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestGetRows:
+ def test_yields_items_and_follows_paging_next(self, monkeypatch: Any) -> None:
+ first = f"https://acme.workable.com/spi/v3/candidates?limit={PAGE_SIZE}"
+ second = "https://www.workable.com/spi/v3/accounts/acme/candidates?limit=100&since_id=2"
+ pages = {
+ first: {"candidates": [{"id": "1"}], "paging": {"next": second}},
+ second: {"candidates": [{"id": "2"}], "paging": {}},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages)
+ assert [r["id"] for r in rows] == ["1", "2"]
+
+ def test_saves_state_after_yielding_each_page_with_more_pages(self, monkeypatch: Any) -> None:
+ first = f"https://acme.workable.com/spi/v3/candidates?limit={PAGE_SIZE}"
+ second = "https://www.workable.com/spi/v3/accounts/acme/candidates?limit=100&since_id=2"
+ pages = {
+ first: {"candidates": [{"id": "1"}], "paging": {"next": second}},
+ second: {"candidates": [{"id": "2"}], "paging": {}},
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, pages)
+ # State saved once (after page 1, which had a next); not after the final page.
+ assert [s.next_url for s in manager.saved] == [second]
+
+ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:
+ resume_url = "https://www.workable.com/spi/v3/accounts/acme/candidates?limit=100&since_id=99"
+ pages = {resume_url: {"candidates": [{"id": "99"}], "paging": {}}}
+ manager = _FakeResumableManager(state=WorkableResumeConfig(next_url=resume_url))
+ rows = _collect(manager, monkeypatch, pages)
+ # The initial URL is never fetched — we pick up from the saved cursor.
+ assert [r["id"] for r in rows] == ["99"]
+
+ def test_empty_page_terminates(self, monkeypatch: Any) -> None:
+ first = f"https://acme.workable.com/spi/v3/stages?limit={PAGE_SIZE}"
+ pages: dict[str, Any] = {first: {"stages": [], "paging": {}}}
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, endpoint="stages")
+ assert rows == []
+
+
+class TestFetchPage:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status)
+ # Disable tenacity's real sleeps so the retries don't slow the test down.
+ workable._fetch_page.retry.sleep = lambda *_args, **_kwargs: None # type: ignore[attr-defined]
+ with pytest.raises(WorkableRetryableError):
+ workable._fetch_page(session, "https://acme.workable.com/spi/v3/jobs", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_non_retryable_statuses_raise_http_error(self, _name: str, status: int) -> None:
+ response = MagicMock(status_code=status, ok=False, text="nope")
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=response)
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(requests.HTTPError):
+ workable._fetch_page(session, "https://acme.workable.com/spi/v3/jobs", MagicMock())
+
+
+class TestWorkableSource:
+ @parameterized.expand(list(WORKABLE_ENDPOINTS.keys()))
+ def test_source_response_primary_keys_and_partitioning(self, endpoint: str) -> None:
+ config = WORKABLE_ENDPOINTS[endpoint]
+ response = workable_source(
+ subdomain="acme",
+ api_token="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_partition_keys_are_stable_creation_fields(self) -> None:
+ # Never partition on a mutable field like updated_at.
+ for config in WORKABLE_ENDPOINTS.values():
+ assert config.partition_key in (None, "created_at")
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True, (200, True)),
+ ("unauthorized", 401, False, (401, False)),
+ ("forbidden", 403, False, (403, False)),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, ok: bool, expected: tuple[int, bool]) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status, ok=ok)
+ with mock.patch.object(workable, "make_tracked_session", lambda **_kwargs: session):
+ assert validate_credentials("acme", "tok") == expected
+
+ def test_transport_error_returns_zero(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch.object(workable, "make_tracked_session", lambda **_kwargs: session):
+ assert validate_credentials("acme", "tok") == (0, False)
+
+ def test_invalid_subdomain_raises(self) -> None:
+ with pytest.raises(ValueError):
+ validate_credentials("evil.com/", "tok")
diff --git a/posthog/temporal/data_imports/sources/workable/tests/test_workable_source.py b/posthog/temporal/data_imports/sources/workable/tests/test_workable_source.py
new file mode 100644
index 000000000000..8f74c320429c
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/workable/tests/test_workable_source.py
@@ -0,0 +1,160 @@
+from typing import Any
+
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import WorkableSourceConfig
+from posthog.temporal.data_imports.sources.workable import source as source_module
+from posthog.temporal.data_imports.sources.workable.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.workable.source import WorkableSource
+from posthog.temporal.data_imports.sources.workable.workable import WorkableResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config() -> WorkableSourceConfig:
+ return WorkableSourceConfig(subdomain="acme", api_token="tok")
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert WorkableSource().source_type == ExternalDataSourceType.WORKABLE
+
+ def test_config_basics(self) -> None:
+ config = WorkableSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.HR___RECRUITING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Stays hidden from users until the source is signed off.
+ assert config.unreleasedSource is True
+
+ def test_fields(self) -> None:
+ field_names = {f.name for f in WorkableSource().get_source_config.fields}
+ assert field_names == {"subdomain", "api_token"}
+
+ def test_subdomain_is_a_connection_host_field(self) -> None:
+ # Retargeting the subdomain must re-require the token (it's where the token is sent).
+ assert WorkableSource().connection_host_fields == ["subdomain"]
+
+ def test_api_token_field_is_secret(self) -> None:
+ token_field = next(f for f in WorkableSource().get_source_config.fields if f.name == "api_token")
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.secret is True
+
+
+class TestSchemas:
+ def test_lists_all_endpoints(self) -> None:
+ names = {s.name for s in WorkableSource().get_schemas(_config(), team_id=1)}
+ assert names == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("jobs", True),
+ ("candidates", True),
+ ("members", False),
+ ("recruiters", False),
+ ("stages", False),
+ ]
+ )
+ def test_incremental_support_per_endpoint(self, endpoint: str, expected_incremental: bool) -> None:
+ schemas = {s.name: s for s in WorkableSource().get_schemas(_config(), team_id=1)}
+ assert schemas[endpoint].supports_incremental is expected_incremental
+ assert schemas[endpoint].supports_append is expected_incremental
+
+ def test_incremental_endpoints_offer_updated_and_created(self) -> None:
+ schemas = {s.name: s for s in WorkableSource().get_schemas(_config(), team_id=1)}
+ fields = {f["field"] for f in schemas["candidates"].incremental_fields}
+ assert fields == {"updated_at", "created_at"}
+
+ def test_names_filter(self) -> None:
+ schemas = WorkableSource().get_schemas(_config(), team_id=1, names=["jobs"])
+ assert [s.name for s in schemas] == ["jobs"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ # (status, ok, schema_name, expected_valid)
+ ("ok_create", 200, True, None, True),
+ ("ok_schema", 200, True, "candidates", True),
+ ("unauthorized_create", 401, False, None, False),
+ ("unauthorized_schema", 401, False, "candidates", False),
+ # 403 = valid token missing a scope: accepted at create, rejected for a specific schema.
+ ("forbidden_create_accepted", 403, False, None, True),
+ ("forbidden_schema_rejected", 403, False, "candidates", False),
+ ]
+ )
+ def test_credential_status_mapping(
+ self, _name: str, status: int, ok: bool, schema_name: str | None, expected_valid: bool
+ ) -> None:
+ with mock.patch.object(source_module, "validate_workable_credentials", lambda *_a, **_k: (status, ok)):
+ valid, _msg = WorkableSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert valid is expected_valid
+
+ def test_invalid_subdomain_is_a_failure(self) -> None:
+ def _raise(*_a: Any, **_k: Any) -> Any:
+ raise ValueError("Invalid Workable subdomain")
+
+ with mock.patch.object(source_module, "validate_workable_credentials", _raise):
+ valid, msg = WorkableSource().validate_credentials(_config(), team_id=1)
+ assert valid is False
+ assert "subdomain" in (msg or "")
+
+
+class TestMisc:
+ def test_non_retryable_errors_cover_auth(self) -> None:
+ errors = WorkableSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = WorkableSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is WorkableResumeConfig
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ descriptions = WorkableSource().get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ def test_source_for_pipeline_plumbs_arguments(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "response"
+
+ monkeypatch.setattr(source_module, "workable_source", fake_source)
+
+ inputs = MagicMock()
+ inputs.schema_name = "candidates"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ inputs.incremental_field = "updated_at"
+ manager = MagicMock()
+
+ result: Any = WorkableSource().source_for_pipeline(_config(), manager, inputs)
+ assert result == "response"
+ assert captured["subdomain"] == "acme"
+ assert captured["api_token"] == "tok"
+ assert captured["endpoint"] == "candidates"
+ assert captured["incremental_field"] == "updated_at"
+ assert captured["db_incremental_field_last_value"] == "2026-01-01"
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+ monkeypatch.setattr(source_module, "workable_source", lambda **kwargs: captured.update(kwargs))
+
+ inputs = MagicMock()
+ inputs.schema_name = "members"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ inputs.incremental_field = None
+
+ WorkableSource().source_for_pipeline(_config(), MagicMock(), inputs)
+ assert captured["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/workable/workable.py b/posthog/temporal/data_imports/sources/workable/workable.py
new file mode 100644
index 000000000000..b504aa2349aa
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/workable/workable.py
@@ -0,0 +1,218 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+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 urllib3.util.retry import Retry
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SortMode, SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.workable.settings import PAGE_SIZE, WORKABLE_ENDPOINTS
+
+# Workable account subdomains are DNS labels — letters, digits and hyphens. Validating this before
+# building the URL prevents host injection (e.g. a `subdomain` of `evil.com/` would otherwise retarget
+# the request and exfiltrate the stored token).
+_SUBDOMAIN_RE = re.compile(r"^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$")
+
+DEFAULT_TIMEOUT = 60
+RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
+
+# Maps the incremental cursor column to Workable's server-side time filter param. The column is
+# `updated_at` / `created_at`; the filter is `updated_after` / `created_after`.
+_TIME_FILTER_PARAM = {"updated_at": "updated_after", "created_at": "created_after"}
+
+
+class WorkableRetryableError(Exception):
+ pass
+
+
+class WorkableResumeConfig:
+ # Full `paging.next` URL to fetch next. `None` means start the endpoint from its first page.
+ next_url: str | None = None
+
+
+def _validate_subdomain(subdomain: str) -> str:
+ subdomain = (subdomain or "").strip()
+ if not _SUBDOMAIN_RE.match(subdomain):
+ raise ValueError(
+ "Invalid Workable subdomain. Use just the account subdomain from "
+ "https://<subdomain>.workable.com (letters, digits and hyphens only)."
+ )
+ return subdomain
+
+
+def _base_url(subdomain: str) -> str:
+ return f"https://{_validate_subdomain(subdomain)}.workable.com/spi/v3"
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental cursor value as an ISO 8601 UTC timestamp with a `Z` suffix."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ return str(value)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_initial_url(
+ subdomain: str,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> str:
+ config = WORKABLE_ENDPOINTS[endpoint]
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:
+ # `updated_after` / `created_after` are the documented server-side filters. Honor the user's
+ # chosen cursor field; default to `updated_at` so edits to existing rows are picked up.
+ field_name = incremental_field or "updated_at"
+ filter_param = _TIME_FILTER_PARAM.get(field_name, "updated_after")
+ params[filter_param] = _format_datetime(db_incremental_field_last_value)
+
+ return f"{_base_url(subdomain)}{config.path}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type((WorkableRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ # Workable allows ~10 requests / 10s and returns HTTP 429 past that. Back off well clear of the
+ # window (≈2, 4, 8, 16s) rather than reading the X-Rate-Limit-Reset header, which keeps the retry
+ # logic simple while still self-healing.
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, timeout=DEFAULT_TIMEOUT)
+
+ if response.status_code in RETRYABLE_STATUSES:
+ raise WorkableRetryableError(f"Workable API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Workable API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ subdomain: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WorkableResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = WORKABLE_ENDPOINTS[endpoint]
+ # Tenacity owns retries (so it can honor the tight rate limit), so disable the adapter's own
+ # status/transport retries to avoid retrying twice. One session is reused across every page so
+ # the connection is kept alive.
+ session = make_tracked_session(headers=_get_headers(api_token), retry=Retry(total=0), redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_url:
+ url = resume.next_url
+ logger.debug(f"Workable: resuming {endpoint} from {url}")
+ else:
+ url = _build_initial_url(
+ subdomain, endpoint, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ while True:
+ data = _fetch_page(session, url, logger)
+ items = data.get(config.data_key, [])
+ # `paging.next` is a full URL that already carries the cursor params. Follow it verbatim.
+ next_url = data.get("paging", {}).get("next")
+
+ if items:
+ yield items
+ # Save state AFTER yielding so a crash re-yields the last page (merge dedupes on the
+ # primary key) rather than skipping it. Only save when more pages remain.
+ if next_url:
+ resumable_source_manager.save_state(WorkableResumeConfig(next_url=next_url))
+
+ if not next_url:
+ break
+ url = next_url
+
+
+def _sort_mode_for(endpoint: str, should_use_incremental_field: bool, incremental_field: str | None) -> SortMode:
+ """Pick the order the pipeline should assume rows arrive in.
+
+ Workable paginates by `since_id` (ascending id, which tracks ascending `created_at`); it has no
+ way to sort by `updated_at`. So when the cursor field is `created_at`, rows genuinely arrive in
+ ascending cursor order and the watermark can advance per batch (`asc`). When the cursor is
+ `updated_at`, arrival order is unrelated to the cursor, so we use `desc` — which defers the
+ watermark commit to sync completion — to avoid advancing past unsynced rows on a partial failure.
+ """
+ if not should_use_incremental_field or not WORKABLE_ENDPOINTS[endpoint].supports_incremental:
+ return "asc"
+ return "asc" if incremental_field == "created_at" else "desc"
+
+
+def workable_source(
+ subdomain: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WorkableResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = WORKABLE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ subdomain=subdomain,
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode=_sort_mode_for(endpoint, should_use_incremental_field, incremental_field),
+ )
+
+
+def validate_credentials(subdomain: str, api_token: str, path: str = "/jobs") -> tuple[int, bool]:
+ """Probe a Workable endpoint. Returns ``(status_code, ok)``; ``status_code`` is ``0`` on a transport error."""
+ try:
+ url = f"{_base_url(subdomain)}{path}?{urlencode({'limit': 1})}"
+ response = make_tracked_session(
+ headers=_get_headers(api_token), retry=Retry(total=0), redact_values=(api_token,)
+ ).get(url, timeout=DEFAULT_TIMEOUT)
+ return response.status_code, response.ok
+ except ValueError:
+ # Invalid subdomain — surface as a non-transport failure.
+ raise
+ except Exception:
+ return 0, False